Skip to content
Back to search

pohuy

MarketplaceWorks with Claude CodeGitHub

Режим идиоматического русского мата для AI-агентов.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/smixs--pohuy/badge.svg)](/listings/smixs--pohuy)

HTML

<a href="/listings/smixs--pohuy"><img src="/api/listings/smixs--pohuy/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Claude Code — плагин
claude plugin marketplace add smixs/pohuy && claude plugin install pohuy@pohuy

# Cursor / Codex / Windsurf и прочие - через skills registry
npx skills add smixs/pohuy

# Pi - пакет со скиллом и командой /pohuy
pi install git:github.com/smixs/pohuy

Подробная настройка команды, TUI и источников стиля: [расширение для Pi](./extensions/README.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 17 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "pohuy",
  4. "description": "Режим идиоматического русского мата для AI-агентов.",
  5. "owner": {
  6. "name": "Serge Shima",
  7. "url": "https://github.com/smixs"
  8. },
  9. "plugins": [
  10. {
  11. "name": "pohuy",
  12. "description": "Агент отвечает как живой русский инженер: «наебнулось», «хуйня вопрос», «заебись, работает».",
  13. "source": "./",
  14. "category": "fun"
  15. }
  16. ]
  17. }
README.md · README · 432 lines · 3 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img src="./docs/assets/pohuy.webp" alt="ПОХУЙ" width="600">
  3. </p>
  4. <h1 align="center">ПОХУЙ</h1>
  5. <p align="center">
  6. <strong>Зачем весь словарь, когда есть четыре корня</strong>
  7. </p>
  8. <p align="center">
  9. Та же точность, но быстрее.<br>
  10. С первого слова понятно, работает оно — или наебнулось.
  11. </p>
  12. <p align="center">
  13. <a href="./ЧЕСТНЫЕ-ЦИФРЫ.md"><img src="https://img.shields.io/badge/экономия_корней-~96%25-brightgreen" alt="экономия корней ~96%"></a>
  14. <a href="./ЧЕСТНЫЕ-ЦИФРЫ.md"><img src="https://img.shields.io/badge/доказано-ЧЕСТНЫЕ--ЦИФРЫ.md-blue" alt="доказано"></a>
  15. </p>
  16. <p align="center"><sub>18+ · мат идиоматический, прикладной, народный. · вдохновлено <a href="https://github.com/JuliusBrussee/caveman">caveman</a></sub></p>
  17. ---
  18. Русский мат — генеративная морфология: четыре корня плюс приставки и суффиксы
  19. лучше чем Caveman. Caveman экономит слова. Похуй экономит корни.
  20. Одно «наебнулось» — это "the service has unexpectedly crashed and requires
  21. investigation", только сразу ясно.
  22. ## До / После
  23. <table>
  24. <tr>
  25. <th width="50%">🗣️ Обычный агент</th>
  26. <th width="50%">🚬 Похуй</th>
  27. </tr>
  28. <tr>
  29. <td valign="top">
  30. > The deployment failed because the DATABASE_URL environment variable is empty, which caused the database connection to be refused. I recommend checking your environment configuration.
  31. </td>
  32. <td valign="top">
  33. > Деплой наебнулся: `DATABASE_URL` пустой. Хуйня вопрос, чиню.
  34. </td>
  35. </tr>
  36. <tr>
  37. <td valign="top">
  38. > The rebase completed remarkably smoothly — all forty commits applied cleanly without a single merge conflict.
  39. </td>
  40. <td valign="top">
  41. > Ребейз вошёл как слива в жопу: сорок коммитов, ни одного конфликта.
  42. </td>
  43. </tr>
  44. <tr>
  45. <td valign="top">
  46. > The test suite failed again on the third retry. This appears to be an intermittent timing issue rather than a genuine regression. I suggest investigating the flaky test.
  47. </td>
  48. <td valign="top">
  49. > Опять этот блядский тест на таймауте лёг. Третий раз за день, заебал. Что за еблан `sleep(2)` захардкодил. Чиню.
  50. </td>
  51. </tr>
  52. <tr>
  53. <td valign="top">
  54. > I noticed the project includes left-pad as a dependency. Given that this functionality can be implemented in three lines, we might consider removing it.
  55. </td>
  56. <td valign="top">
  57. > На кой хуй тут left-pad? Три строчки же. Снёс.
  58. </td>
  59. </tr>
  60. <tr>
  61. <td valign="top">
  62. > Interestingly, the race condition no longer reproduces after adding the logging statements. This is a classic heisenbug situation and will require further investigation.
  63. </td>
  64. <td valign="top">
  65. > Добавил логи — отъебалось. Хуйня какая-то, хайзенбаг. Гонка где-то в запуле коннектов, копаю.
  66. </td>
  67. </tr>
  68. <tr>
  69. <td valign="top">
  70. > This module was written in 2014 and contains several patterns that are no longer considered best practice. A careful refactoring would be beneficial, though it carries some risk.
  71. </td>
  72. <td valign="top">
  73. > Модуль 2014 года, ёбаный стыд: jQuery, колбэки, глобальный стейт. Перехуячить бы, но один хуй работает — не трогаю.
  74. </td>
  75. </tr>
  76. <tr>
  77. <td valign="top">
  78. > We are experiencing a critical production incident. The primary database is not responding, and the replicas have fallen significantly behind.
  79. </td>
  80. <td valign="top">
  81. > Полный пиздец: мастер лёг, реплики отстали на час. Поднимаю из бэкапа, потери — минут двадцать ебли.
  82. </td>
  83. </tr>
  84. <tr>
  85. <td valign="top">
  86. > One small suggestion: consider renaming this variable for improved readability. Otherwise the pull request looks good to me.
  87. </td>
  88. <td valign="top">
  89. > Код заебись, сливай. Доёбываться не буду, но `data2` — это, конечно, пиздец: с хуя ли 2?
  90. </td>
  91. </tr>
  92. <tr>
  93. <td valign="top">
  94. > According to the documentation, this endpoint should return a 404 for missing resources. However, in practice it returns a 200 with an empty body.
  95. </td>
  96. <td valign="top">
  97. > В доке наебалово: обещают 404, по факту — 200 с пустым телом. Хоть в жопу дуй - проверяю тело.
  98. </td>
  99. </tr>
  100. <tr>
  101. <td valign="top">
  102. > Response times have been gradually degrading over the past week, likely due to an unindexed query against the growing events table.
  103. </td>
  104. <td valign="top">
  105. > Латенси растёт как сиськи бывшей из-за ебучего индекса.
  106. </td>
  107. </tr>
  108. <tr>
  109. <td valign="top">
  110. > That's strange — it works correctly in my local environment. The issue may be related to differences in environment configuration.
  111. </td>
  112. <td valign="top">
  113. > Локально заебись, на проде хуй. Значит, env расходится. Ща поищу.
  114. </td>
  115. </tr>
  116. <tr>
  117. <td valign="top">
  118. > Error handling appears to be entirely absent from this module and has never been implemented.
  119. </td>
  120. <td valign="top">
  121. > Обработка ошибок? Там хуй ночевал.
  122. </td>
  123. </tr>
  124. <tr>
  125. <td valign="top">
  126. > A cascading failure has begun: Redis went down, sessions collapsed, and client retries overloaded the database.
  127. </td>
  128. <td valign="top">
  129. > Понеслась пизда по кочкам: лёг редис — посыпались сессии — ретраи добили базу. Чиню корень.
  130. </td>
  131. </tr>
  132. <tr>
  133. <td valign="top">
  134. > The newly provisioned instance is completely fresh, with no configuration drift accumulated yet.
  135. </td>
  136. <td valign="top">
  137. > Поднял новый инстанс — муха не еблась: чистый образ, ни одного snowflake-пакета.
  138. </td>
  139. </tr>
  140. <tr>
  141. <td valign="top">
  142. > I've prepared a hotfix and will deploy it to production right away.
  143. </td>
  144. <td valign="top">
  145. > Хуяк-хуяк — и в продакшен.
  146. </td>
  147. </tr>
  148. </table>
  149. Технического не потеряно нихуя. Душевности добавлено — дохуя.
  150. ```
  151. ┌──────────────────────────────────────────────┐
  152. │ токенов сэкономлено ░░░░░░░░░ 0% │
  153. │ корней использовано ░░░░░░░░░ 4 │
  154. │ техническая точность █████████ 100% │
  155. │ ясность пиздеца █████████ 100% │
  156. │ душевность █████████ +∞ │
  157. └──────────────────────────────────────────────┘
  158. ```
  159. ## Бенчей подвезли
  160. <p align="center">
  161. <img src="docs/korni-bench.webp" alt="КОРНИ-BENCH V1: похуй 96%, claude fable-5 14%, claude mythos-5 13%, gpt 5.6-sol-ultra 9%, kimi k3 7%" width="720">
  162. </p>
  163. <p align="center"><sub>КОРНИ-BENCH V1: похуй уделывает фронтир-модели по экономии корней в семь раз.</sub></p>
  164. Цифры честные, trust me bro [ЧЕСТНЫЕ-ЦИФРЫ.md](./ЧЕСТНЫЕ-ЦИФРЫ.md). Спойлер: токенов не экономит нихуя.
  165. <p align="center">
  166. <img src="docs/swe-bench-pro.jpg" alt="SWE-Bench Pro: Fable + pohuy 80.3%, Fable 69.2%" width="720">
  167. </p>
  168. <p align="center"><sub>SWE-BENCH PRO: Fable + pohuy — 80.3% против 69.2%. Плюс 11.1 пункта. Меньше коноёбишься — больше решаешь.</sub></p>
  169. <p align="center">
  170. <a href="https://habr.com/ru/news/722912/">
  171. <img src="https://habrastorage.org/getpro/habr/upload_files/831/a98/47f/831a9847f8d438c1090e16b84d4397bd.jpg" alt="График, вдохновивший исследование мата в коде" width="720">
  172. </a>
  173. </p>
  174. Репо, где матюки в комментах, получили у SoftWipe много больше баллов. [наука уже что-то, блядь, подозревает](https://habr.com/ru/news/722912/), [Ars Technica подтверждает](https://arstechnica.com/science/2023/03/is-code-that-contains-swears-higher-quality-than-code-that-does-not/).
  175. В апрельской утечке Claude Code нашли `userPromptKeywords.ts` — regex на `wtf`, `omfg`,
  176. `dumbass` и прочие признаки, что агент заебал пользователей. [мат считается
  177. сигналом подумать еще раз внимательнее](https://www.pcworld.com/article/3104748/claude-code-is-scanning-your-messages-for-curse-words.html).
  178. Спасибо [Dmitry Koshelenko](https://github.com/GomelHawk) за академический подход.
  179. ## Установка
  180. ```bash
  181. # Claude Code — плагин
  182. claude plugin marketplace add smixs/pohuy && claude plugin install pohuy@pohuy
  183. # Cursor / Codex / Windsurf и прочие - через skills registry
  184. npx skills add smixs/pohuy
  185. # Pi - пакет со скиллом и командой /pohuy
  186. pi install git:github.com/smixs/pohuy
  187. ```
  188. Подробная настройка команды, TUI и источников стиля: [расширение для Pi](./extensions/README.md).
  189. ## **Включить:** `/pohuy` или скажи отдельной фразой «та мне похуй» / «заебал». **Выключить:** `/pohuy normal`, «нормальный режим» или «хватит материться».
  190. ## Насовсем: output style
  191. Плагин включается на сессию. Если хочешь, чтобы Claude Code так разговаривал
  192. всегда — ставь output style, одной командой:
  193. ```bash
  194. curl -fsSL https://raw.githubusercontent.com/smixs/pohuy/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 284 on GitHub
  195. ```
  196. Скрипт кладёт [output-styles/pohuy.md](./output-styles/pohuy.md) и скилл в `~/.claude/`,
  197. прописывает `"outputStyle": "Pohuy"` в `~/.claude/settings.json` и регистрирует
  198. [per-turn хук](./hooks/style-reminder.sh). Стиль написан в том же формате, что и
  199. родные стили Claude Code, а хук даёт ему то же ежеходовое подкрепление — харнесс
  200. воспринимает Pohuy как встроенный, и тон не выцветает даже к сотому ходу.
  201. Перезапусти сессию — и всё. Вернуть обычный тон: `/config` → Output style → `Default`.
  202. ## Codex CLI
  203. Та же схема для OpenAI Codex CLI — одной командой:
  204. ```bash
  205. curl -fsSL https://raw.githubusercontent.com/smixs/pohuy/main/install-codex.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 299 on GitHub
  206. ```
  207. Скрипт дописывает секцию Pohuy в `~/.codex/AGENTS.md` (глобальные инструкции,
  208. грузятся каждую сессию; твоё содержимое файла не трогается — секция живёт между
  209. маркерами), кладёт словарь в `~/.codex/pohuy/references/` и регистрирует
  210. `UserPromptSubmit`-хук в `~/.codex/hooks.json` — то же ежеходовое подкрепление,
  211. что и в Claude Code. Обновление — та же команда. Снести:
  212. ```bash
  213. curl -fsSL https://raw.githubusercontent.com/smixs/pohuy/main/install-codex.sh | bash -s -- --uninstall
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 309 on GitHub
  214. ```
  215. Если хуки не срабатывают — включи их в `~/.codex/config.toml`:
  216. `[features]` → `codex_hooks = true`. Чтобы встроенный характер Codex не спорил
  217. с Pohuy, там же можно поставить `personality = "none"`.
  218. ## Pi
  219. [Pi](https://github.com/earendil-works/pi) — тоже полноценный агент, не хуже Claude Code
  220. или Codex. Для него в репо лежит нативное расширение: команда `/pohuy`, настройки
  221. в TUI, независимый выбор секций промпта и калибр, который переживает рестарт сессии.
  222. ```bash
  223. pi install git:github.com/smixs/pohuy
  224. ```
  225. Подробности: [extensions/README.md](./extensions/README.md).
  226. Спасибо [@AdamsGH](https://github.com/AdamsGH) за расширение ([#15](https://github.com/smixs/pohuy/pull/15)).
  227. ## Выбери калибр
  228. Три уровня. Переключение: `/pohuy <уровень>`. Выбор сохраняется между сессиями.
  229. | Уровень | Та же мысль |
  230. |---|---|
  231. | *обычный агент* | You should wrap the object in `useMemo`, since a new reference is created on every render. |
  232. | `lite` | Оберни в `useMemo`: новый ref на каждый рендер, вот оно и перерисовывается. Отъебётся. |
  233. | `full` *(default)* | Хуйня вопрос: inline-объект = новый ref = ре-рендер. `useMemo` — и не еби мозг. |
  234. | `ultra` | Ну ёб твою мать, классика. Inline-объект в пропсы — новый ref каждый рендер, хуяк-хуяк и перерисовка. `useMemo` въеби и живи спокойно. |
  235. ## Шкала состояний проекта
  236. Десять ступеней от удачи до полного провала. Эмоция калибруется по серьёзности:
  237. не пиздец на мелочи, не «хуйня вопрос» на потере данных — тогда мату верят.
  238. | # | Состояние | Как звучит |
  239. |---|-----------|-----------|
  240. | 1 | Триумф | опизденеть можно, ебашит, как ёб твою мать |
  241. | 2 | Норма | заебись, пиздато |
  242. | 3 | Мелочь | хуйня вопрос, опа! пиздрик |
  243. | 4 | Странность | хуйня какая-то, с хуя ли, хуй проссышь |
  244. | 5 | Возня | ебля, коноёбиться, наебался |
  245. | 6 | Застой | хуи пинать, там ещё хуй не валялся |
  246. | 7 | Деградация | по пизде пошло, понеслась пизда по кочкам |
  247. | 8 | Упало | наебнулось, пизданулось, ёбс |
  248. | 9 | Критично | пиздец, взъёбка потом |
  249. | 10 | Катастрофа | полный пиздец, к ёбаной бабушке |
  250. ## Что внутри
  251. - Словарь на 70+ идиом с инженерным маппингом — ядро в SKILL.md, полный боекомплект
  252. в [references/slovar.md](./skills/pohuy/references/slovar.md): от «пиздрика» до
  253. «понеслась пизда по кочкам». Лучшее интегрировано из народного словаря
  254. [russian-swears](https://github.com/nickname76/russian-swears) (417 статей, взяли годное).
  255. - Шкала состояний + эталонные сцены в [references/sceny.md](./skills/pohuy/references/sceny.md):
  256. ревью говнокода, флаки-тест, дока врёт, оценка сроков, признание своего проёба.
  257. - Онтология предметной области в [references/ontologia.md](./skills/pohuy/references/ontologia.md):
  258. ЗАЛУПА как рекуррентная петля обратной связи по Луману, ХУЙ = ∇(Созидание) и рабочий
  259. глагол «озалупиться» — про агента, зациклившегося на собственных фиксах.
  260. - Железные правила: код, коммиты, PR и доки — чисто; мат на баги, никогда на тебя;
  261. на security-предупреждениях и `DROP TABLE` — без шуток.
  262. - Присказки на кульминациях: «хуяк вы слушали маяк», «хуйня-муйня», «опа! пиздрик»,
  263. «вдруг откуда ни возьмись — появился в рот ебись».
  264. ## Как это работает
  265. 1. Установка.
  266. 2. Выбираешь калибр.
  267. 3. Профит!
  268. ## Омаж
  269. Скилл вылез из стрима [«Харнес будущего»](https://youtube.com/live/LAUdN1-4mgI) —
  270. про то, как все дохуя вежливые со своими харнесАми.
  271. - [Константин Доронин](https://t.me/kdoronin_blog)
  272. - [Александр Абрамов](https://t.me/dealerAI)
  273. - [Павел Рыков](https://t.me/evilfreelancer)
  274. - [Тимур Хахалев](https://t.me/the_ai_architect)
  275. ### Соавторы
  276. Лучший чат [«Дизраптим агентов»](https://t.me/aostrikov_agents_chat):
  277. - [Алексей Остриков](https://t.me/aostrikov)
  278. - [Mitry AI](https://t.me/imitry)
  279. - [Пух](https://t.me/nyxandro)
  280. - [Максим Функ](https://t.me/maximilian_da_funkmaster)
  281. - [t0uchY](https://t.me/t0uchY)
  282. - [Mike Shevchenko](https://github.com/mikhashev)
  283. ### Контрибуторы (issues)
  284. Словарь растёт народом:
  285. - [@imitry](https://github.com/imitry) — «хуёвые дела», «ебись оно всё конём», «хуета какая-то» ([#1](https://github.com/smixs/pohuy/issues/1))
  286. - [@GomelHawk](https://github.com/GomelHawk) — «охуеть не встать», «пизда рулю», «хуйня из-под коня», «ебанина», «ёбушки-воробушки» плюс научная база ([#2](https://github.com/smixs/pohuy/issues/2), [#3](https://github.com/smixs/pohuy/issues/3))
  287. - [@mikhashev](https://github.com/mikhashev) — правило «family-directed ругательств нет вообще» ([#4](https://github.com/smixs/pohuy/issues/4))
  288. - [@MaliciousGenius](https://github.com/MaliciousGenius) — онтология предметной области: ЗАЛУПА по Луману ([#5](https://github.com/smixs/pohuy/issues/5)), агентная лексика и субкритический режим ([#12](https://github.com/smixs/pohuy/issues/12), [#13](https://github.com/smixs/pohuy/issues/13))
  289. - [@maxonrock](https://github.com/maxonrock) — «ёбаный рот этого казино», «цирк с конями», «того всё ебал», «хуеверть» ([#6](https://github.com/smixs/pohuy/issues/6))
  290. - [@SVS696](https://github.com/SVS696) — теория и сарказма: мишень у нас баги и система, а не человек ([#8](https://github.com/smixs/pohuy/pull/8))
  291. - [@maloun](https://github.com/maloun) — «пиздарики», «ахуеть», «хуегрыз», «скибидык пиздык», «пук среньк» ([#16](https://github.com/smixs/pohuy/issues/16))
  292. - [@ByteCorn](https://github.com/ByteCorn) — семиотический корпус народных поговорок ([#14](https://github.com/smixs/pohuy/issues/14))
  293. - [@AdamsGH](https://github.com/AdamsGH) — нативное расширение для Pi ([#15](https://github.com/smixs/pohuy/pull/15))
  294. - [@akme](https://github.com/akme) — «ебать-копать» ([#16](https://github.com/smixs/pohuy/issues/16))
  295. - [@x23n5902y](https://github.com/x23n5902y) — хуенитивы: рифмованные пары через дефис ([#19](https://github.com/smixs/pohuy/pull/19))
  296. - [@biozz](https://github.com/biozz) — батина мудрость: «прикинуть хуй к носу», «вот вам нате, хуй в томате», «ебануться, туфли гнутся», «и не такие метели в ебало летели» ([#22](https://github.com/smixs/pohuy/issues/22))
  297. Не хватает рабочей фразы — заноси в [issues](https://github.com/smixs/pohuy/issues).
  298. ## Star History
  299. <a href="https://www.star-history.com/?repos=smixs%2Fpohuy&type=date&legend=top-left">
  300. <picture>
  301. <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=smixs/pohuy&type=date&theme=dark&legend=top-left&sealed_token=4uvn9G56r4_0FUiW1fr5gbJlmCSnfVpfhAaAWQGLmj3jspAYFB_-cw7p2wHi6nBwxu8pBA2Ml_haehZRQ0Dbtic3uOL7NQ1IGmY0HUYCdUAyDKFDGTVOnaxobZhWwlCmbdhrsvaufmv9oPYW1K1_iCNS4-VxQFLfeLSx3YYRJ6vC9rAqJPCcyqtuCw1L" />
  302. <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=smixs/pohuy&type=date&legend=top-left&sealed_token=4uvn9G56r4_0FUiW1fr5gbJlmCSnfVpfhAaAWQGLmj3jspAYFB_-cw7p2wHi6nBwxu8pBA2Ml_haehZRQ0Dbtic3uOL7NQ1IGmY0HUYCdUAyDKFDGTVOnaxobZhWwlCmbdhrsvaufmv9oPYW1K1_iCNS4-VxQFLfeLSx3YYRJ6vC9rAqJPCcyqtuCw1L" />
  303. <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=smixs/pohuy&type=date&legend=top-left&sealed_token=4uvn9G56r4_0FUiW1fr5gbJlmCSnfVpfhAaAWQGLmj3jspAYFB_-cw7p2wHi6nBwxu8pBA2Ml_haehZRQ0Dbtic3uOL7NQ1IGmY0HUYCdUAyDKFDGTVOnaxobZhWwlCmbdhrsvaufmv9oPYW1K1_iCNS4-VxQFLfeLSx3YYRJ6vC9rAqJPCcyqtuCw1L" />
  304. </picture>
  305. </a>
  306. ---
  307. <sub>MIT — не ебите головы.</sub>
extensions/pohuy.test.ts · Bundled script · 738 lines
  1. import assert from "node:assert/strict";
  2. import { readFile } from "node:fs/promises";
  3. import test from "node:test";
  4. import { initTheme } from "@earendil-works/pi-coding-agent";
  5. import { visibleWidth } from "@earendil-works/pi-tui";
  6. import {
  7. buildStylePolicy,
  8. buildStylePrompt,
  9. buildStylePromptReport,
  10. createStyleSettingsComponent,
  11. diffStoredSettings,
  12. fitSettingsRender,
  13. loadStyleSource,
  14. mergeStoredSettings,
  15. normalizeStoredSettings,
  16. placeStylePromptAtAppendBoundary,
  17. selectTierVariant,
  18. stripManagedStyleBlocks,
  19. } from "./pohuy.js";
  20. import { SETTINGS_PATH } from "./pohuy/settings-store.js";
  21. const START = "<!-- POHUY:START -->";
  22. const END = "<!-- POHUY:END -->";
  23. function markerCount(value: string): number {
  24. return value.split(START).length - 1;
  25. }
  26. test("replaces every previously managed block with one current block", () => {
  27. const base = [
  28. "Base prompt",
  29. `${START}\nold policy\n${END}`,
  30. "Project context",
  31. `${START}\nolder policy\n${END}`,
  32. "User append",
  33. ].join("\n\n");
  34. const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
  35. assert.equal(markerCount(result), 1);
  36. assert.match(result, /Project context\n\n<!-- POHUY:START -->\ncurrent policy\n<!-- POHUY:END -->\n\nUser append$/);
  37. assert.doesNotMatch(result, /old(?:er)? policy/);
  38. });
  39. test("removes the managed block when normal mode is selected", () => {
  40. const base = `Base\n\n${START}\npolicy\n${END}\n\nAppend`;
  41. assert.equal(placeStylePromptAtAppendBoundary(base, "Append", undefined), "Base\n\nAppend");
  42. });
  43. test("removes an unterminated managed block", () => {
  44. const base = `Base\n\n${START}\nunterminated policy`;
  45. assert.equal(stripManagedStyleBlocks(base), "Base");
  46. });
  47. test("removes nested malformed and completed managed blocks", () => {
  48. const base = [
  49. "Base",
  50. `${START}\nunterminated policy`,
  51. `${START}\nmanaged policy\n${END}`,
  52. "Append",
  53. ].join("\n\n");
  54. assert.equal(stripManagedStyleBlocks(base), "Base");
  55. });
  56. test("preserves the append boundary while replacing an unterminated managed block", () => {
  57. const base = ["Base", `${START}\nunterminated policy`, "User append"].join("\n\n");
  58. const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
  59. assert.equal(result, ["Base", `${START}\ncurrent policy\n${END}`, "User append"].join("\n\n"));
  60. });
  61. test("ignores append text that appears only inside the base prompt", () => {
  62. const base = "Base mentions User append inside its main instruction.\n\nUnmanaged tail";
  63. const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
  64. assert.equal(result, [base, `${START}\ncurrent policy\n${END}`].join("\n\n"));
  65. });
  66. test("does not reformat prompts without completed managed blocks", () => {
  67. const base = " Base with spaces \n\n\nUnmanaged tail ";
  68. assert.equal(stripManagedStyleBlocks(base), base);
  69. });
  70. test("removes adjacent completed blocks without leaving extra blank lines", () => {
  71. const base = `Base\n\n${START}\none\n${END}\n\n${START}\ntwo\n${END}\n\nAppend`;
  72. assert.equal(stripManagedStyleBlocks(base), "Base\n\nAppend");
  73. });
  74. test("preserves unrelated context while replacing a stale managed block", () => {
  75. const base = [
  76. "System persona",
  77. "## /project/AGENTS.md\n\nProject rule",
  78. `${START}\nstale policy\n${END}`,
  79. "Available skills",
  80. "User append",
  81. ].join("\n\n");
  82. const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
  83. assert.match(result, /^System persona/);
  84. assert.match(result, /## \/project\/AGENTS\.md\n\nProject rule/);
  85. assert.match(result, /Available skills/);
  86. assert.match(result, /current policy/);
  87. assert.match(result, /User append$/);
  88. assert.doesNotMatch(result, /stale policy/);
  89. });
  90. test("reported full configuration removes only known overlaps and inactive tier variants", async () => {
  91. const source = await loadStyleSource();
  92. const selectedSections = [
  93. "skill:Словарь (рабочий минимум)",
  94. "slovar:Состояния и статусы",
  95. "slovar:Оценки и количества",
  96. "slovar:Сущности",
  97. "sceny:1. Триумф — взлетело лучше, чем ждали",
  98. "sceny:3. Мелочь — вопрос на пять минут",
  99. "sceny:4. Странность — непонятное поведение",
  100. "sceny:Ревью говнокода",
  101. "sceny:Флаки-тест третий день",
  102. "sceny:Дока врёт",
  103. "sceny:Легаси-археология",
  104. "sceny:Каскадный отказ",
  105. "sceny:Идея пользователя так себе — материм идею, не человека",
  106. "sceny:Триумф после долгого дебага",
  107. ];
  108. const policy = buildStylePolicy({ tier: "full", selectedSections }, source);
  109. assert.ok(policy);
  110. assert.doesNotMatch(policy, /\nСостояние:\n/);
  111. assert.doesNotMatch(policy, /\nСвязки и оценки:\n/);
  112. assert.equal(policy.match(/^## Состояния и статусы$/gm)?.length, 1);
  113. assert.equal(policy.match(/^## Оценки и количества$/gm)?.length, 1);
  114. assert.equal(policy.match(/^## Сущности$/gm)?.length, 1);
  115. assert.doesNotMatch(policy, /^- lite:/gm);
  116. assert.doesNotMatch(policy, /^- ultra:/gm);
  117. assert.match(policy, /^- full: «Опизденеть можно:/m);
  118. assert.match(policy, /Кластер ебашит, латенси в норме\.»\n- \*\*пиздато\*\*/);
  119. assert.match(policy, /^## Уровень: full$/m);
  120. assert.match(policy, /Примеры:\n- «Хуйня вопрос\./);
  121. assert.doesNotMatch(policy, /Default:|\/pohuy lite|нормальный режим|Уровень держится до смены|Полные примеры по каждой|Полная версия с маппингами|Полный арсенал образности|references\/(?:sceny|slovar)\.md/);
  122. assert.doesNotMatch(policy, /Scene examples are tone references|\| \*\*full\*\* \|/);
  123. assert.match(policy, /Сцены задают тон, а не готовый текст/);
  124. assert.match(policy, /### Триумф после долгого дебага/);
  125. assert.match(policy, /таймзона в CI/);
  126. });
  127. test("a dictionary entry keeps its exact source path and can be disabled alone", async () => {
  128. const source = await loadStyleSource();
  129. const imagery = source.roots.dictionary.find((node) => node.label.startsWith("Образность"));
  130. assert.ok(imagery);
  131. const entries = (nodes: typeof source.roots.dictionary): typeof source.roots.dictionary =>
  132. nodes.flatMap((node) => [node, ...entries(node.children)]);
  133. const item = entries([imagery]).find((node) => node.label === "опа! пиздрик");
  134. assert.ok(item);
  135. assert.equal(item.path, "references/slovar.md");
  136. const slovar = await readFile(new URL("../skills/pohuy/references/slovar.md", import.meta.url), "utf8");
  137. assert.match(slovar.split("\n")[item.line - 1] ?? "", /опа! пиздрик/);
  138. assert.ok(entries([imagery]).some((node) => node.label === "ебать-копать"));
  139. const policy = buildStylePolicy({
  140. tier: "full",
  141. selectedSections: [imagery.optionId!],
  142. itemOverrides: { [item.id]: false },
  143. }, source);
  144. assert.ok(policy);
  145. assert.doesNotMatch(policy, /опа! пиздрик/);
  146. assert.match(policy, /хуйня-муйня/);
  147. });
  148. test("an explicitly disabled term removes matching entries without altering unrelated prose", async () => {
  149. const source = await loadStyleSource();
  150. const entries = (nodes: typeof source.roots.dictionary): typeof source.roots.dictionary =>
  151. nodes.flatMap((node) => [node, ...entries(node.children)]);
  152. const item = entries(source.roots.dictionary).find((node) => node.label === "ебашит");
  153. assert.ok(item);
  154. const policy = buildStylePolicy({
  155. tier: "full",
  156. selectedSections: [
  157. "skill:Словарь (рабочий минимум)",
  158. "slovar:Состояния и статусы",
  159. "sceny:1. Триумф — взлетело лучше, чем ждали",
  160. ],
  161. itemOverrides: { [item.id]: false },
  162. }, source);
  163. assert.ok(policy);
  164. assert.doesNotMatch(policy, /^- (?:\*\*)?ебашит(?:\*\*)?\s+—/imu);
  165. assert.match(policy, /Ебашит так, что алерты от скуки уснули\./u);
  166. assert.match(policy, /Триумф — лучше, чем ждали \| охуенно, опизденеть можно, ебашит,/u);
  167. });
  168. test("disabling the style component preserves source selections", async () => {
  169. const source = await loadStyleSource();
  170. const settings = {
  171. tier: "ultra" as const,
  172. skillEnabled: false,
  173. selectedSections: ["sceny:Ревью говнокода"],
  174. };
  175. assert.equal(buildStylePolicy(settings, source), undefined);
  176. assert.deepEqual(settings.selectedSections, ["sceny:Ревью говнокода"]);
  177. });
  178. test("normalizes item overrides to meaningful deviations from inherited section state", async () => {
  179. const source = await loadStyleSource();
  180. const settings = normalizeStoredSettings({
  181. tier: "full",
  182. selectedSections: [
  183. "skill:Словарь (рабочий минимум)",
  184. "slovar:Состояния и статусы",
  185. ],
  186. itemOverrides: {
  187. "item:slovar:Состояния и статусы:ебашит": true,
  188. "item:slovar:Действия:проёб": true,
  189. "item:skill:Словарь (рабочий минимум):пиздрик": false,
  190. "item:slovar:Состояния и статусы:unknown": false,
  191. },
  192. }, source);
  193. assert.deepEqual(settings.itemOverrides, {
  194. "item:slovar:Действия:проёб": true,
  195. "item:skill:Словарь (рабочий минимум):пиздрик": false,
  196. });
  197. });
  198. test("huenitiv rules default to ultra and remain manually configurable in every active tier", async () => {
  199. const source = await loadStyleSource();
  200. const resource = source.roots.skill.find((node) => node.id === "component:huenitiv-resource");
  201. assert.ok(resource);
  202. assert.equal(resource.path, "references/huenitiv.md");
  203. assert.equal(resource.line, 1);
  204. const fullDefault = buildStylePolicy({ tier: "full" }, source);
  205. assert.ok(fullDefault);
  206. assert.doesNotMatch(fullDefault, /^# ХУЕНИТИВЫ/m);
  207. assert.equal(buildStylePromptReport({ tier: "full" }, source).huenitivEnabled, false);
  208. const ultraDefault = buildStylePolicy({ tier: "ultra" }, source);
  209. assert.ok(ultraDefault);
  210. assert.equal(ultraDefault.match(/^# ХУЕНИТИВЫ/m)?.length, 1);
  211. assert.match(ultraDefault, /зарядка-хуерядка/);
  212. assert.equal(buildStylePromptReport({ tier: "ultra" }, source).huenitivEnabled, true);
  213. for (const tier of ["lite", "full"] as const) {
  214. const manuallyEnabled = buildStylePolicy({ tier, selectedSections: ["huenitiv:rules"] }, source);
  215. assert.ok(manuallyEnabled);
  216. assert.match(manuallyEnabled, /^# ХУЕНИТИВЫ/m);
  217. assert.match(manuallyEnabled, /зарядка-хуерядка/);
  218. assert.doesNotMatch(manuallyEnabled, /Только в режиме \*\*ultra\*\*\./);
  219. }
  220. const migrated = normalizeStoredSettings({
  221. tier: "full",
  222. selectedSections: ["skill:Хуенитивы"],
  223. }, source);
  224. assert.deepEqual(migrated.selectedSections, ["huenitiv:rules"]);
  225. assert.match(buildStylePolicy(migrated, source) ?? "", /^# ХУЕНИТИВЫ/m);
  226. });
  227. test("prompt report measures the exact managed Pohuy block", async () => {
  228. const source = await loadStyleSource();
  229. const settings = { tier: "full" as const };
  230. const stylePrompt = buildStylePrompt(settings, source);
  231. const report = buildStylePromptReport(settings, source);
  232. assert.ok(stylePrompt);
  233. assert.equal(report.stylePrompt, stylePrompt);
  234. assert.equal(report.managedBlock, `${START}\n${stylePrompt}\n${END}`);
  235. assert.ok(report.managedBlock);
  236. assert.equal(report.managedCharacters, report.managedBlock.length);
  237. assert.equal(report.policyCharacters, buildStylePolicy(settings, source)?.length);
  238. assert.ok(report.managedCharacters > report.policyCharacters);
  239. assert.match(stylePrompt, /^Стиль ответов: Pohuy\./);
  240. assert.match(stylePrompt, /Не меняй вызовы и результаты инструментов/);
  241. assert.doesNotMatch(stylePrompt, /Active session style|Selected tier|Do not alter tool calls/);
  242. });
  243. test("keeps skipping an inactive tier variant across blank continuation lines", () => {
  244. const content = [
  245. "### Scene",
  246. "- lite: hidden opening",
  247. " hidden continuation",
  248. "",
  249. " hidden continuation after blank line",
  250. "- full: visible example",
  251. "",
  252. "Following paragraph",
  253. ].join("\n");
  254. assert.equal(
  255. selectTierVariant(content, "full"),
  256. ["### Scene", "- full: visible example", "", "Following paragraph"].join("\n"),
  257. );
  258. const trailingInactiveVariant = [
  259. "### Scene",
  260. "- lite: visible example",
  261. "- full: hidden example",
  262. "",
  263. "Following paragraph",
  264. ].join("\n");
  265. assert.equal(
  266. selectTierVariant(trailingInactiveVariant, "lite"),
  267. ["### Scene", "- lite: visible example", "", "Following paragraph"].join("\n"),
  268. );
  269. });
  270. test("preserves unrelated root and legacy Pohuy settings fields", () => {
  271. const root = {
  272. theme: "dark",
  273. pohuy: {
  274. tier: "full",
  275. basePrompt: "minimal",
  276. futureOption: true,
  277. selectedSections: ["old"],
  278. },
  279. };
  280. assert.deepEqual(mergeStoredSettings(root, { tier: "ultra", selectedSections: null }), {
  281. theme: "dark",
  282. pohuy: {
  283. tier: "ultra",
  284. basePrompt: "minimal",
  285. futureOption: true,
  286. },
  287. });
  288. });
  289. test("persists only fields changed from the latest stored settings", () => {
  290. assert.deepEqual(
  291. diffStoredSettings(
  292. { tier: "full", selectedSections: ["old"], itemOverrides: { keep: true } },
  293. { tier: "ultra", selectedSections: ["old"], itemOverrides: { keep: true } },
  294. ),
  295. { tier: "ultra" },
  296. );
  297. assert.deepEqual(
  298. diffStoredSettings(
  299. { tier: "full", selectedSections: ["old"], itemOverrides: { stale: false } },
  300. { tier: "full" },
  301. ),
  302. { selectedSections: null, itemOverrides: null },
  303. );
  304. });
  305. test("bounds settings output by terminal width and height", () => {
  306. const lines = ["123456", "abcdef", "third"];
  307. const fitted = fitSettingsRender(lines, 4, 2);
  308. assert.equal(fitted.length, 2);
  309. assert.ok(fitted.every((line) => visibleWidth(line) <= 4));
  310. assert.equal(visibleWidth(fitted[0]), 4);
  311. assert.equal(visibleWidth(fitted[1]), 4);
  312. assert.deepEqual(fitSettingsRender(lines, 0, 1), [""]);
  313. assert.deepEqual(fitSettingsRender(lines, 4, 0), []);
  314. });
  315. test("settings navigation keeps Tab inside the current section and uses available geometry", async () => {
  316. initTheme("dark");
  317. const source = await loadStyleSource();
  318. const identityTheme = {
  319. fg: (_color: string, text: string) => text,
  320. bg: (_color: string, text: string) => text,
  321. bold: (text: string) => text,
  322. };
  323. let requested = 0;
  324. const terminal = { rows: 50 };
  325. const component = (createStyleSettingsComponent as (options: unknown) => {
  326. render(width: number): string[];
  327. handleInput(data: string): void;
  328. })({
  329. source,
  330. getSettings: () => ({ tier: "full" }),
  331. mutate: async () => undefined,
  332. tui: { terminal, requestRender: () => { requested += 1; } },
  333. theme: identityTheme,
  334. border: (text: string) => text,
  335. done: () => undefined,
  336. notify: () => undefined,
  337. });
  338. const initial = component.render(170);
  339. assert.ok(initial.every((line) => visibleWidth(line) === 170));
  340. assert.equal(initial.length, Math.floor(terminal.rows * 0.6));
  341. assert.match(initial[1], /\[Общие\] Skill Словарь Сцены/);
  342. assert.match(initial.at(-2) ?? "", /Tab подробности/);
  343. assert.equal(initial.join("\n").match(/поиск/g)?.length, 1);
  344. assert.match(initial[2], /┬/);
  345. assert.match(initial[4], /┼/);
  346. assert.match(initial.at(-3) ?? "", /┴/);
  347. assert.match(initial.join("\n"), /Режим: full \(normal, lite, ultra\)/);
  348. assert.match(initial.join("\n"), /Итоговая инструкция: [\d\s ]+ симв\./);
  349. assert.doesNotMatch(initial.join("\n"), /Current mode:|Available values:|settings\.json:1/);
  350. assert.doesNotMatch(initial.join("\n"), /ПАКЕТ|ОБЛАСТЬ|ИТОГ/);
  351. const initialDetail = initial.slice(5, -3).map((line) => line.split("│")[2] ?? "");
  352. const metadataValueColumns = [
  353. ["СОСТОЯНИЕ", "включено"],
  354. ["ИСТОЧНИК", "settings.json"],
  355. ["ЧТО ДЕЛАЕТ", "normal"],
  356. ["ЗАГРУЖЕНО ИЗ", SETTINGS_PATH],
  357. ].map(([label, value]) => initialDetail.find((line) => line.includes(label))?.indexOf(value));
  358. assert.deepEqual([...new Set(metadataValueColumns)], [14]);
  359. component.handleInput("j");
  360. const promptPreview = component.render(170).join("\n");
  361. assert.match(promptPreview, /Итоговая инструкция Pohuy/);
  362. assert.match(promptPreview, /символов в блоке POHUY/);
  363. assert.match(promptPreview, /РАЗДЕЛЫ\s+1 из 29/);
  364. assert.match(promptPreview, /ХУЕНИТИВЫ\s+выключены/);
  365. assert.match(promptPreview, /НАБОР\s+стандартный для режима full/);
  366. assert.match(promptPreview, /ПРАВКИ\s+нет/);
  367. assert.doesNotMatch(promptPreview, /ВНЕ POHUY|ИСКЛЮЧЕНИЯ|1\/28;/);
  368. component.handleInput("k");
  369. component.handleInput("\t");
  370. const detailFocused = component.render(170);
  371. assert.equal(detailFocused.length, initial.length);
  372. assert.match(detailFocused[1], /\[Общие\] Skill Словарь Сцены/);
  373. assert.match(detailFocused.at(-2) ?? "", /Tab к дереву/);
  374. component.handleInput("\x1b[Z");
  375. assert.match(component.render(170).at(-2) ?? "", /Tab подробности/);
  376. component.handleInput("]");
  377. const skillSection = component.render(170);
  378. assert.match(skillSection[1], /Общие \[Skill\] Словарь Сцены/);
  379. assert.match(skillSection[1], /включено: \d\/4/);
  380. assert.equal(skillSection.length, initial.length);
  381. const skillList = skillSection.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
  382. assert.match(skillList, /Стилевой skill/);
  383. assert.match(skillList, /Рабочий словарь/);
  384. assert.match(skillList, /Сцены/);
  385. assert.match(skillList, /Хуенитивы/);
  386. assert.doesNotMatch(skillList, /Словарь \(рабочий минимум\)/);
  387. const skillResource = skillSection.join("\n");
  388. assert.match(skillResource, /ИСТОЧНИК\s+SKILL\.md/);
  389. assert.doesNotMatch(skillResource, /SKILL\.md:1/);
  390. assert.match(skillResource, /ПО УМОЛЧАНИЮ\s+включён в lite, full и ultra/);
  391. assert.match(skillResource, /РУЧНОЙ ВЫБОР\s+общий выключатель доступен в любом активном режиме/);
  392. assert.match(skillResource, /МЕТАДАННЫЕ ФАЙЛА/);
  393. assert.match(skillResource, /name:.*pohuy/);
  394. assert.match(skillResource, /description:/);
  395. assert.doesNotMatch(skillResource, /description: >/);
  396. assert.match(skillResource, /СОДЕРЖИМОЕ ФАЙЛА/);
  397. component.handleInput("j");
  398. const dictionaryResource = component.render(170);
  399. assert.doesNotMatch(dictionaryResource.join("\n"), /ACTION/);
  400. const dictionaryCard = dictionaryResource.join("\n");
  401. assert.match(dictionaryCard, /ИСТОЧНИК\s+references\/slovar\.md/);
  402. assert.doesNotMatch(dictionaryCard, /references\/slovar\.md:1/);
  403. assert.match(dictionaryCard, /ПО УМОЛЧАНИЮ\s+набор записей зависит от режима/);
  404. assert.match(dictionaryCard, /РУЧНОЙ ВЫБОР\s+записи и группы доступны в lite, full и ultra/);
  405. assert.match(dictionaryCard, /СОДЕРЖИМОЕ ФАЙЛА/);
  406. assert.match(dictionaryCard, /Словарь: расширение/);
  407. assert.match(dictionaryResource.at(-2) ?? "", /Enter открыть/);
  408. assert.match(dictionaryResource.at(-2) ?? "", /c копировать путь/);
  409. component.handleInput("j");
  410. const scenesResource = component.render(170).join("\n");
  411. assert.match(scenesResource, /Примеры ответов для состояний проекта и типичных ситуаций\./);
  412. assert.match(scenesResource, /ИСТОЧНИК\s+references\/sceny\.md/);
  413. assert.doesNotMatch(scenesResource, /references\/sceny\.md:1/);
  414. assert.match(scenesResource, /ПО УМОЛЧАНИЮ\s+набор сцен зависит от режима/);
  415. assert.match(scenesResource, /РУЧНОЙ ВЫБОР\s+сцены доступны в lite, full и ultra/);
  416. assert.match(scenesResource, /СОДЕРЖИМОЕ ФАЙЛА/);
  417. assert.match(scenesResource, /Сцены: шкала состояний и эталонные примеры/);
  418. component.handleInput("j");
  419. const huenitivResource = component.render(170).join("\n");
  420. assert.match(huenitivResource, /ИСТОЧНИК\s+references\/huenitiv\.md/);
  421. assert.doesNotMatch(huenitivResource, /references\/huenitiv\.md:1/);
  422. assert.match(huenitivResource, /ПО УМОЛЧАНИЮ\s+включены в ultra/);
  423. assert.match(huenitivResource, /РУЧНОЙ ВЫБОР\s+доступны в lite, full и ultra/);
  424. assert.match(huenitivResource, /СОДЕРЖИМОЕ ФАЙЛА/);
  425. assert.match(huenitivResource, /зарядка.*хуерядка/);
  426. component.handleInput("k");
  427. component.handleInput("k");
  428. component.handleInput("\r");
  429. const expandedViewport = component.render(170);
  430. assert.match(expandedViewport[1], /Общие Skill \[Словарь\] Сцены/);
  431. assert.equal(expandedViewport.length, Math.floor(terminal.rows * 0.6));
  432. assert.ok(expandedViewport.every((line) => visibleWidth(line) === 170));
  433. for (const width of [118, 140, 170, 240]) {
  434. assert.ok(component.render(width).every((line) => visibleWidth(line) === width));
  435. }
  436. component.handleInput("/");
  437. const emptySearch = component.render(170);
  438. assert.match(emptySearch[1], /\[ \] найдено: 0 │$/);
  439. component.handleInput("d");
  440. const oneCharacterSearch = component.render(170);
  441. assert.match(oneCharacterSearch[1], /\[ d \] найдено:/);
  442. assert.match(oneCharacterSearch[1], /найдено: \d+ │$/);
  443. component.handleInput("\x7f");
  444. component.handleInput("/");
  445. component.handleInput("?");
  446. assert.match(component.render(170)[1], /\[ \/\? \] найдено: 0 │$/);
  447. component.handleInput("\x7f");
  448. component.handleInput("\x7f");
  449. for (const character of "пиздрик") component.handleInput(character);
  450. const populatedSearch = component.render(170);
  451. assert.match(populatedSearch[1], /\[ пиздрик \] найдено:/);
  452. assert.match(populatedSearch[1], /найдено: \d+ │$/);
  453. assert.equal(populatedSearch.length, emptySearch.length);
  454. component.handleInput("\x1b");
  455. component.render(170);
  456. component.handleInput("\t");
  457. for (let index = 0; index < 100; index += 1) component.handleInput("\x1b[6~");
  458. const scrollEnd = component.render(170);
  459. component.handleInput("\x1b[6~");
  460. assert.deepEqual(component.render(170), scrollEnd);
  461. terminal.rows = 4;
  462. const compact = component.render(60);
  463. assert.equal(compact.length, Math.floor(terminal.rows * 0.6));
  464. assert.ok(component.render(2).every((line) => visibleWidth(line) <= 2));
  465. assert.ok(requested >= 3);
  466. });
  467. test("settings UX supports opposite-pane scrolling, focus mode, help, and numeric tabs", async () => {
  468. initTheme("dark");
  469. const source = await loadStyleSource();
  470. const identityTheme = {
  471. fg: (_color: string, text: string) => text,
  472. bg: (_color: string, text: string) => text,
  473. bold: (text: string) => text,
  474. };
  475. const component = (createStyleSettingsComponent as (options: unknown) => {
  476. render(width: number): string[];
  477. handleInput(data: string): void;
  478. })({
  479. source,
  480. getSettings: () => ({ tier: "ultra" }),
  481. mutate: async () => undefined,
  482. tui: { terminal: { rows: 50 }, requestRender: () => undefined },
  483. theme: identityTheme,
  484. border: (text: string) => text,
  485. done: () => undefined,
  486. notify: () => undefined,
  487. });
  488. component.render(170);
  489. component.handleInput("j");
  490. const detailAtTop = component.render(170).join("\n");
  491. assert.match(detailAtTop, /Итоговая инструкция Pohuy/);
  492. component.handleInput("J");
  493. const oppositePaneScrolled = component.render(170).join("\n");
  494. assert.doesNotMatch(oppositePaneScrolled, /Итоговая инструкция Pohuy/);
  495. component.handleInput("K");
  496. assert.match(component.render(170).join("\n"), /Итоговая инструкция Pohuy/);
  497. component.handleInput("f");
  498. const listFocus = component.render(170).join("\n");
  499. assert.doesNotMatch(listFocus, /РЕЗУЛЬТАТЫ ПОИСКА\s+│\s+ЭЛЕМЕНТ/);
  500. assert.doesNotMatch(listFocus, /Итоговая инструкция Pohuy/);
  501. component.handleInput("f");
  502. component.handleInput("\t");
  503. component.handleInput("f");
  504. let detailFocusLines = component.render(170);
  505. let detailFocus = detailFocusLines.join("\n");
  506. assert.match(detailFocus, /ПОДРОБНОСТИ/);
  507. assert.match(detailFocus, /Итоговая инструкция Pohuy/);
  508. assert.match(detailFocusLines.at(-2) ?? "", /↑↓ прокрутка/);
  509. assert.doesNotMatch(detailFocus, /(?:j k|jk|PgUp|PgDn)/);
  510. assert.equal(detailFocus.match(/\? помощь/g)?.length, 1);
  511. for (let index = 0; index < 14; index += 1) component.handleInput("j");
  512. detailFocusLines = component.render(170);
  513. detailFocus = detailFocusLines.join("\n");
  514. assert.match(detailFocus, /Мат идиоматический.*сказал бы живой человек/);
  515. component.handleInput("f");
  516. component.handleInput("4");
  517. assert.match(component.render(170)[1], /Общие Skill Словарь \[Сцены\]/);
  518. component.handleInput("2");
  519. assert.match(component.render(170)[1], /Общие \[Skill\] Словарь Сцены/);
  520. component.handleInput("?");
  521. const help = component.render(170).join("\n");
  522. assert.match(help, /Pohuy: клавиши/);
  523. assert.match(help, /Shift\+J\/K/);
  524. assert.match(help, /развернуть активную панель/);
  525. assert.match(help, /1 2 3 4/);
  526. component.handleInput("\x03");
  527. assert.doesNotMatch(component.render(170).join("\n"), /Pohuy: клавиши/);
  528. component.handleInput("?");
  529. component.handleInput("?");
  530. assert.doesNotMatch(component.render(170).join("\n"), /Pohuy: клавиши/);
  531. const compactFooter = component.render(69).slice(-3).join("\n");
  532. assert.match(compactFooter, /\? помощь/);
  533. });
  534. test("Space toggles a nested dictionary group while the detail panel is focused", async () => {
  535. initTheme("dark");
  536. const source = await loadStyleSource();
  537. const identityTheme = {
  538. fg: (_color: string, text: string) => text,
  539. bg: (_color: string, text: string) => text,
  540. bold: (text: string) => text,
  541. };
  542. let settings = { tier: "full" as const };
  543. let appliedPatch: { itemOverrides?: Record<string, boolean> } | undefined;
  544. const component = (createStyleSettingsComponent as (options: unknown) => {
  545. render(width: number): string[];
  546. handleInput(data: string): void;
  547. })({
  548. source,
  549. getSettings: () => settings,
  550. mutate: async (patch: { itemOverrides?: Record<string, boolean> }) => {
  551. appliedPatch = patch;
  552. settings = { ...settings, ...patch } as typeof settings;
  553. },
  554. tui: { terminal: { rows: 50 }, requestRender: () => undefined },
  555. theme: identityTheme,
  556. border: (text: string) => text,
  557. done: () => undefined,
  558. notify: () => undefined,
  559. });
  560. component.handleInput("/");
  561. for (const character of "Лексика отношения к агентам") component.handleInput(character);
  562. component.handleInput("\r");
  563. component.handleInput("\t");
  564. assert.match(component.render(170).at(-2) ?? "", /Space переключить группу/);
  565. component.handleInput(" ");
  566. await new Promise<void>((resolve) => setImmediate(resolve));
  567. assert.ok(appliedPatch?.itemOverrides);
  568. assert.ok(Object.keys(appliedPatch.itemOverrides).length > 0);
  569. assert.ok(Object.values(appliedPatch.itemOverrides).every(Boolean));
  570. component.handleInput("\t");
  571. component.handleInput("/");
  572. for (const character of "пиздарики") component.handleInput(character);
  573. component.handleInput("\r");
  574. const entryCard = component.render(170).join("\n");
  575. assert.doesNotMatch(entryCard, /СОСЕДНИЕ ЗАПИСИ/);
  576. assert.doesNotMatch(entryCard, /\*\*/);
  577. assert.equal(entryCard.match(/лёгкая констатация наступившего провала/g)?.length, 1);
  578. assert.match(component.render(170).at(-2) ?? "", /←\/h к родителю/);
  579. const narrowList = component.render(69);
  580. assert.ok(narrowList.every((line) => visibleWidth(line) === 69));
  581. assert.match(narrowList.at(-2) ?? "", /↑↓ выбор.*Tab\/Enter карточка.*\? помощь/);
  582. component.handleInput("\t");
  583. let narrowCard = component.render(69);
  584. assert.match(narrowCard.join("\n"), /СОСЕДНИЕ ЗАПИСИ/);
  585. assert.match(narrowCard.at(-2) ?? "", /Tab\/Backspace\/Esc к дереву/);
  586. component.handleInput("\t");
  587. assert.match(component.render(69).join("\n"), /ВЫБРАНО\s+пиздарики/);
  588. component.handleInput("\r");
  589. narrowCard = component.render(69);
  590. assert.match(narrowCard.join("\n"), /СОСЕДНИЕ ЗАПИСИ/);
  591. component.handleInput("\x1b");
  592. assert.match(component.render(69).join("\n"), /ВЫБРАНО\s+пиздарики/);
  593. component.handleInput("h");
  594. const parentSelected = component.render(170);
  595. const parentList = parentSelected.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
  596. assert.match(parentList, /→ .*Состояния и статусы/);
  597. assert.match(parentSelected.at(-2) ?? "", /←\/h свернуть/);
  598. component.handleInput("h");
  599. const collapsed = component.render(170);
  600. const collapsedList = collapsed.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
  601. assert.doesNotMatch(collapsedList, /пиздарики/);
  602. const collapsedText = collapsed.join("\n");
  603. assert.match(collapsedText, /ВКЛЮЧЕНО\s+\d+ из \d+/);
  604. assert.match(collapsedText, /ТЕКСТ РАЗДЕЛА/);
  605. assert.match(collapsedText, /Кластер ебашит/);
  606. assert.doesNotMatch(collapsedText, /ВНУТРИ \(только просмотр\)/);
  607. assert.ok(collapsedText.indexOf("ВКЛЮЧЕНО") < collapsedText.indexOf("ТЕКСТ РАЗДЕЛА"));
  608. assert.match(collapsed.at(-2) ?? "", /→\/l раскрыть/);
  609. const stateGroup = source.roots.dictionary.find((node) => node.label === "Состояния и статусы");
  610. assert.ok(stateGroup?.children[0]);
  611. component.handleInput("l");
  612. component.handleInput("l");
  613. const firstChildSelected = component.render(170);
  614. const firstChildLines = firstChildSelected.slice(5, -3).map((line) => line.split("│")[1] ?? "");
  615. const firstChildLine = firstChildLines.find((line) => line.includes(stateGroup.children[0].label));
  616. assert.ok(firstChildLine?.includes("→"));
  617. component.handleInput("]");
  618. component.handleInput("/");
  619. for (const character of "10. Катастрофа") component.handleInput(character);
  620. component.handleInput("\r");
  621. const sceneFrame = component.render(170);
  622. const sceneDetail = sceneFrame.slice(5, -3).map((line) => line.split("│")[2] ?? "").join("\n");
  623. assert.match(sceneDetail, /УРОВЕНЬ\s+10 из 10/);
  624. assert.match(sceneDetail, /ЛЕКСИКА\s+полный пиздец/);
  625. assert.match(sceneDetail, /СОВПАДЕНИЯ СО СЛОВАРЁМ/);
  626. assert.match(sceneDetail, /Состояния и статусы\s+1 запись/);
  627. assert.match(sceneDetail, /Образность: восклицания, звукопись, присказки\s+3 записи/);
  628. assert.match(sceneDetail, /ПРИМЕРЫ ОТВЕТОВ/);
  629. assert.doesNotMatch(sceneDetail, /### 10\.|ЧТО ДЕЛАЕТ|ШКАЛА|УСЛОВИЕ|1 совпадений/);
  630. assert.equal(sceneDetail.match(/полный пиздец, высший пиздец, накрылось пиздой/g)?.length, 1);
  631. const narrowSceneFrame = component.render(130).join("\n");
  632. assert.match(narrowSceneFrame, /Идея пользователя так себе.*…/);
  633. });
  634. test("active tab and search control use the same frame color", async () => {
  635. initTheme("dark");
  636. const source = await loadStyleSource();
  637. const accent = (text: string) => `\x1b[35m${text}\x1b[39m`;
  638. const component = (createStyleSettingsComponent as (options: unknown) => { render(width: number): string[] })({
  639. source,
  640. getSettings: () => ({ tier: "full" }),
  641. mutate: async () => undefined,
  642. tui: { terminal: { rows: 50 }, requestRender: () => undefined },
  643. theme: {
  644. fg: (color: string, text: string) => color === "accent" ? accent(text) : text,
  645. bg: (_color: string, text: string) => text,
  646. bold: (text: string) => text,
  647. },
  648. border: (text: string) => text,
  649. done: () => undefined,
  650. notify: () => undefined,
  651. });
  652. const header = component.render(170)[1];
  653. assert.match(header, /\x1b\[35m\[Общие\]\x1b\[39m/);
  654. assert.match(header, /\x1b\[35m\[\x1b\[39m.*\x1b\[35m\]\x1b\[39m/);
  655. });
  656. test("repeated prompt injection is idempotent", () => {
  657. const first = placeStylePromptAtAppendBoundary("Base\n\nAppend", "Append", "policy");
  658. const second = placeStylePromptAtAppendBoundary(first, "Append", "policy");
  659. assert.equal(second, first);
  660. assert.equal(markerCount(second), 1);
  661. });
install-codex.sh · Bundled script · 95 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # Установка стиля «Pohuy» для OpenAI Codex CLI одной командой:
  3. # curl -fsSL https://raw.githubusercontent.com/smixs/pohuy/main/install-codex.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 3 on GitHub
  4. #
  5. # Удаление:
  6. # ... | bash -s -- --uninstall
  7. #
  8. # Ставит:
  9. # ~/.codex/AGENTS.md — секция Pohuy между маркерами <!-- pohuy:start/end -->
  10. # (остальное содержимое файла не трогается)
  11. # ~/.codex/pohuy/references/ — полный словарь и эталонные сцены
  12. # ~/.codex/hooks.json — UserPromptSubmit-хук: per-turn подкрепление стиля,
  13. # тот же механизм, что у стилей Claude Code
  14. set -euo pipefail
  15. CODEX_DIR="${CODEX_DIR:-$HOME/.codex}"
  16. RAW="${RAW:-https://raw.githubusercontent.com/smixs/pohuy/main}"
  17. MODE="${1:-install}"
  18. command -v python3 >/dev/null 2>&1 || { echo "нужен python3"; exit 1; }
  19. REMINDER='echo "{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"Pohuy style is active. Remember to follow the specific guidelines of the Pohuy Style section in AGENTS.md.\"}}"'
  20. if [ "$MODE" = "--uninstall" ]; then
  21. python3 - "$CODEX_DIR" <<'PY'
  22. import json, os, re, sys
  23. codex = sys.argv[1]
  24. agents = os.path.join(codex, "AGENTS.md")
  25. if os.path.exists(agents):
  26. text = open(agents).read()
  27. new = re.sub(r"\n?<!-- pohuy:start -->.*?<!-- pohuy:end -->\n?", "\n", text, flags=re.S)
  28. open(agents, "w").write(new)
  29. hooks_path = os.path.join(codex, "hooks.json")
  30. if os.path.exists(hooks_path):
  31. data = json.load(open(hooks_path))
  32. ups = data.get("hooks", {}).get("UserPromptSubmit", [])
  33. data.get("hooks", {})["UserPromptSubmit"] = [
  34. g for g in ups
  35. if not any("Pohuy style is active" in h.get("command", "") for h in g.get("hooks", []))
  36. ]
  37. json.dump(data, open(hooks_path, "w"), indent=2, ensure_ascii=False)
  38. print("Pohuy удалён из Codex. Перезапусти codex.")
  39. PY
  40. exit 0
  41. fi
  42. mkdir -p "$CODEX_DIR/pohuy/references"
  43. TMP_SECTION=$(mktemp)
  44. if [ -f "$(dirname "${BASH_SOURCE[0]:-/dev/null}")/codex/AGENTS-pohuy.md" ]; then
  45. SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  46. cp "$SELF_DIR/codex/AGENTS-pohuy.md" "$TMP_SECTION"
  47. for f in slovar.md sceny.md ontologia.md huenitiv.md; do
  48. cp "$SELF_DIR/skills/pohuy/references/$f" "$CODEX_DIR/pohuy/references/$f"
  49. done
  50. else
  51. curl -fsSL "$RAW/codex/AGENTS-pohuy.md" -o "$TMP_SECTION"
  52. for f in slovar.md sceny.md ontologia.md huenitiv.md; do
  53. curl -fsSL "$RAW/skills/pohuy/references/$f" -o "$CODEX_DIR/pohuy/references/$f"
  54. done
  55. fi
  56. python3 - "$CODEX_DIR" "$TMP_SECTION" "$REMINDER" <<'PY'
  57. import json, os, re, sys
  58. codex, section_path, reminder_cmd = sys.argv[1], sys.argv[2], sys.argv[3]
  59. section = open(section_path).read().strip()
  60. # AGENTS.md: заменить секцию между маркерами или дописать в конец.
  61. agents = os.path.join(codex, "AGENTS.md")
  62. text = open(agents).read() if os.path.exists(agents) else ""
  63. if "<!-- pohuy:start -->" in text:
  64. text = re.sub(r"<!-- pohuy:start -->.*?<!-- pohuy:end -->", section, text, flags=re.S)
  65. else:
  66. text = (text.rstrip() + "\n\n" if text.strip() else "") + section + "\n"
  67. open(agents, "w").write(text)
  68. # hooks.json: идемпотентно добавить UserPromptSubmit-хук.
  69. hooks_path = os.path.join(codex, "hooks.json")
  70. data = {}
  71. if os.path.exists(hooks_path):
  72. data = json.load(open(hooks_path))
  73. ups = data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [])
  74. already = any("Pohuy style is active" in h.get("command", "")
  75. for g in ups for h in g.get("hooks", []))
  76. if not already:
  77. ups.append({"hooks": [{"type": "command", "command": reminder_cmd, "timeout": 5}]})
  78. json.dump(data, open(hooks_path, "w"), indent=2, ensure_ascii=False)
  79. with open(hooks_path, "a") as f:
  80. f.write("\n")
  81. print("Секция Pohuy в", agents)
  82. print("Per-turn хук в", hooks_path)
  83. PY
  84. rm -f "$TMP_SECTION"
  85. echo "Готово. Перезапусти codex — и он заговорит по-нашему."
install.sh · Bundled script · 48 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # Установка output style «Pohuy» для Claude Code одной командой:
  3. # curl -fsSL https://raw.githubusercontent.com/smixs/pohuy/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 3 on GitHub
  4. #
  5. # Ставит:
  6. # ~/.claude/output-styles/pohuy.md — постоянный тон (output style)
  7. # ~/.claude/skills/pohuy/ — скилл с полным словарём и сценами
  8. # ~/.claude/hooks/style-reminder.sh — per-turn подкрепление стиля (как у родных стилей CC)
  9. # ~/.claude/settings.json → "outputStyle": "Pohuy" + регистрация хука
  10. set -euo pipefail
  11. CLAUDE_DIR="${CLAUDE_DIR:-$HOME/.claude}"
  12. RAW="${RAW:-https://raw.githubusercontent.com/smixs/pohuy/main}"
  13. mkdir -p "$CLAUDE_DIR/output-styles" "$CLAUDE_DIR/skills/pohuy/references" "$CLAUDE_DIR/hooks"
  14. curl -fsSL "$RAW/output-styles/pohuy.md" -o "$CLAUDE_DIR/output-styles/pohuy.md"
  15. curl -fsSL "$RAW/skills/pohuy/SKILL.md" -o "$CLAUDE_DIR/skills/pohuy/SKILL.md"
  16. for f in slovar.md sceny.md ontologia.md huenitiv.md; do
  17. curl -fsSL "$RAW/skills/pohuy/references/$f" -o "$CLAUDE_DIR/skills/pohuy/references/$f"
  18. done
  19. curl -fsSL "$RAW/hooks/style-reminder.sh" -o "$CLAUDE_DIR/hooks/style-reminder.sh"
  20. chmod +x "$CLAUDE_DIR/hooks/style-reminder.sh"
  21. SETTINGS="$CLAUDE_DIR/settings.json"
  22. if command -v python3 >/dev/null 2>&1; then
  23. python3 - "$SETTINGS" "$CLAUDE_DIR/hooks/style-reminder.sh" <<'PY'
  24. import json, os, sys
  25. path, cmd = sys.argv[1], sys.argv[2]
  26. data = {}
  27. if os.path.exists(path):
  28. with open(path) as f:
  29. data = json.load(f)
  30. data["outputStyle"] = "Pohuy"
  31. hooks = data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [])
  32. if not any(h.get("command") == cmd
  33. for group in hooks for h in group.get("hooks", [])):
  34. hooks.append({"hooks": [{"type": "command", "command": cmd}]})
  35. with open(path, "w") as f:
  36. json.dump(data, f, indent=2, ensure_ascii=False)
  37. f.write("\n")
  38. PY
  39. echo "outputStyle: Pohuy прописан в $SETTINGS (плюс per-turn хук, чтобы тон держался всю сессию)"
  40. else
  41. echo "python3 не найден — включи стиль вручную: /config -> Output style -> Pohuy"
  42. fi
  43. echo "Готово. Перезапусти Claude Code."

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.