pohuy
Режим идиоматического русского мата для AI-агентов.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/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)
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "pohuy",
- "description": "Режим идиоматического русского мата для AI-агентов.",
- "owner": {
- "name": "Serge Shima",
- "url": "https://github.com/smixs"
- },
- "plugins": [
- {
- "name": "pohuy",
- "description": "Агент отвечает как живой русский инженер: «наебнулось», «хуйня вопрос», «заебись, работает».",
- "source": "./",
- "category": "fun"
- }
- ]
- }
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)
- <p align="center">
- <img src="./docs/assets/pohuy.webp" alt="ПОХУЙ" width="600">
- </p>
- <h1 align="center">ПОХУЙ</h1>
- <p align="center">
- <strong>Зачем весь словарь, когда есть четыре корня</strong>
- </p>
- <p align="center">
- Та же точность, но быстрее.<br>
- С первого слова понятно, работает оно — или наебнулось.
- </p>
- <p align="center">
- <a href="./ЧЕСТНЫЕ-ЦИФРЫ.md"><img src="https://img.shields.io/badge/экономия_корней-~96%25-brightgreen" alt="экономия корней ~96%"></a>
- <a href="./ЧЕСТНЫЕ-ЦИФРЫ.md"><img src="https://img.shields.io/badge/доказано-ЧЕСТНЫЕ--ЦИФРЫ.md-blue" alt="доказано"></a>
- </p>
- <p align="center"><sub>18+ · мат идиоматический, прикладной, народный. · вдохновлено <a href="https://github.com/JuliusBrussee/caveman">caveman</a></sub></p>
- ---
- Русский мат — генеративная морфология: четыре корня плюс приставки и суффиксы
- лучше чем Caveman. Caveman экономит слова. Похуй экономит корни.
- Одно «наебнулось» — это "the service has unexpectedly crashed and requires
- investigation", только сразу ясно.
- ## До / После
- <table>
- <tr>
- <th width="50%">🗣️ Обычный агент</th>
- <th width="50%">🚬 Похуй</th>
- </tr>
- <tr>
- <td valign="top">
- > 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.
- </td>
- <td valign="top">
- > Деплой наебнулся: `DATABASE_URL` пустой. Хуйня вопрос, чиню.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > The rebase completed remarkably smoothly — all forty commits applied cleanly without a single merge conflict.
- </td>
- <td valign="top">
- > Ребейз вошёл как слива в жопу: сорок коммитов, ни одного конфликта.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > 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.
- </td>
- <td valign="top">
- > Опять этот блядский тест на таймауте лёг. Третий раз за день, заебал. Что за еблан `sleep(2)` захардкодил. Чиню.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > 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.
- </td>
- <td valign="top">
- > На кой хуй тут left-pad? Три строчки же. Снёс.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > Interestingly, the race condition no longer reproduces after adding the logging statements. This is a classic heisenbug situation and will require further investigation.
- </td>
- <td valign="top">
- > Добавил логи — отъебалось. Хуйня какая-то, хайзенбаг. Гонка где-то в запуле коннектов, копаю.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > 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.
- </td>
- <td valign="top">
- > Модуль 2014 года, ёбаный стыд: jQuery, колбэки, глобальный стейт. Перехуячить бы, но один хуй работает — не трогаю.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > We are experiencing a critical production incident. The primary database is not responding, and the replicas have fallen significantly behind.
- </td>
- <td valign="top">
- > Полный пиздец: мастер лёг, реплики отстали на час. Поднимаю из бэкапа, потери — минут двадцать ебли.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > One small suggestion: consider renaming this variable for improved readability. Otherwise the pull request looks good to me.
- </td>
- <td valign="top">
- > Код заебись, сливай. Доёбываться не буду, но `data2` — это, конечно, пиздец: с хуя ли 2?
- </td>
- </tr>
- <tr>
- <td valign="top">
- > According to the documentation, this endpoint should return a 404 for missing resources. However, in practice it returns a 200 with an empty body.
- </td>
- <td valign="top">
- > В доке наебалово: обещают 404, по факту — 200 с пустым телом. Хоть в жопу дуй - проверяю тело.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > Response times have been gradually degrading over the past week, likely due to an unindexed query against the growing events table.
- </td>
- <td valign="top">
- > Латенси растёт как сиськи бывшей из-за ебучего индекса.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > That's strange — it works correctly in my local environment. The issue may be related to differences in environment configuration.
- </td>
- <td valign="top">
- > Локально заебись, на проде хуй. Значит, env расходится. Ща поищу.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > Error handling appears to be entirely absent from this module and has never been implemented.
- </td>
- <td valign="top">
- > Обработка ошибок? Там хуй ночевал.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > A cascading failure has begun: Redis went down, sessions collapsed, and client retries overloaded the database.
- </td>
- <td valign="top">
- > Понеслась пизда по кочкам: лёг редис — посыпались сессии — ретраи добили базу. Чиню корень.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > The newly provisioned instance is completely fresh, with no configuration drift accumulated yet.
- </td>
- <td valign="top">
- > Поднял новый инстанс — муха не еблась: чистый образ, ни одного snowflake-пакета.
- </td>
- </tr>
- <tr>
- <td valign="top">
- > I've prepared a hotfix and will deploy it to production right away.
- </td>
- <td valign="top">
- > Хуяк-хуяк — и в продакшен.
- </td>
- </tr>
- </table>
- Технического не потеряно нихуя. Душевности добавлено — дохуя.
- ```
- ┌──────────────────────────────────────────────┐
- │ токенов сэкономлено ░░░░░░░░░ 0% │
- │ корней использовано ░░░░░░░░░ 4 │
- │ техническая точность █████████ 100% │
- │ ясность пиздеца █████████ 100% │
- │ душевность █████████ +∞ │
- └──────────────────────────────────────────────┘
- ```
- ## Бенчей подвезли
- <p align="center">
- <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">
- </p>
- <p align="center"><sub>КОРНИ-BENCH V1: похуй уделывает фронтир-модели по экономии корней в семь раз.</sub></p>
- Цифры честные, trust me bro [ЧЕСТНЫЕ-ЦИФРЫ.md](./ЧЕСТНЫЕ-ЦИФРЫ.md). Спойлер: токенов не экономит нихуя.
- <p align="center">
- <img src="docs/swe-bench-pro.jpg" alt="SWE-Bench Pro: Fable + pohuy 80.3%, Fable 69.2%" width="720">
- </p>
- <p align="center"><sub>SWE-BENCH PRO: Fable + pohuy — 80.3% против 69.2%. Плюс 11.1 пункта. Меньше коноёбишься — больше решаешь.</sub></p>
- <p align="center">
- <a href="https://habr.com/ru/news/722912/">
- <img src="https://habrastorage.org/getpro/habr/upload_files/831/a98/47f/831a9847f8d438c1090e16b84d4397bd.jpg" alt="График, вдохновивший исследование мата в коде" width="720">
- </a>
- </p>
- Репо, где матюки в комментах, получили у 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/).
- В апрельской утечке Claude Code нашли `userPromptKeywords.ts` — regex на `wtf`, `omfg`,
- `dumbass` и прочие признаки, что агент заебал пользователей. [мат считается
- сигналом подумать еще раз внимательнее](https://www.pcworld.com/article/3104748/claude-code-is-scanning-your-messages-for-curse-words.html).
- Спасибо [Dmitry Koshelenko](https://github.com/GomelHawk) за академический подход.
- ## Установка
- ```bash
- # 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).
- ## **Включить:** `/pohuy` или скажи отдельной фразой «та мне похуй» / «заебал». **Выключить:** `/pohuy normal`, «нормальный режим» или «хватит материться».
- ## Насовсем: output style
- Плагин включается на сессию. Если хочешь, чтобы Claude Code так разговаривал
- всегда — ставь output style, одной командой:
- ```bash
- 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
- ```
- Скрипт кладёт [output-styles/pohuy.md](./output-styles/pohuy.md) и скилл в `~/.claude/`,
- прописывает `"outputStyle": "Pohuy"` в `~/.claude/settings.json` и регистрирует
- [per-turn хук](./hooks/style-reminder.sh). Стиль написан в том же формате, что и
- родные стили Claude Code, а хук даёт ему то же ежеходовое подкрепление — харнесс
- воспринимает Pohuy как встроенный, и тон не выцветает даже к сотому ходу.
- Перезапусти сессию — и всё. Вернуть обычный тон: `/config` → Output style → `Default`.
- ## Codex CLI
- Та же схема для OpenAI Codex CLI — одной командой:
- ```bash
- 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
- ```
- Скрипт дописывает секцию Pohuy в `~/.codex/AGENTS.md` (глобальные инструкции,
- грузятся каждую сессию; твоё содержимое файла не трогается — секция живёт между
- маркерами), кладёт словарь в `~/.codex/pohuy/references/` и регистрирует
- `UserPromptSubmit`-хук в `~/.codex/hooks.json` — то же ежеходовое подкрепление,
- что и в Claude Code. Обновление — та же команда. Снести:
- ```bash
- 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
- ```
- Если хуки не срабатывают — включи их в `~/.codex/config.toml`:
- `[features]` → `codex_hooks = true`. Чтобы встроенный характер Codex не спорил
- с Pohuy, там же можно поставить `personality = "none"`.
- ## Pi
- [Pi](https://github.com/earendil-works/pi) — тоже полноценный агент, не хуже Claude Code
- или Codex. Для него в репо лежит нативное расширение: команда `/pohuy`, настройки
- в TUI, независимый выбор секций промпта и калибр, который переживает рестарт сессии.
- ```bash
- pi install git:github.com/smixs/pohuy
- ```
- Подробности: [extensions/README.md](./extensions/README.md).
- Спасибо [@AdamsGH](https://github.com/AdamsGH) за расширение ([#15](https://github.com/smixs/pohuy/pull/15)).
- ## Выбери калибр
- Три уровня. Переключение: `/pohuy <уровень>`. Выбор сохраняется между сессиями.
- | Уровень | Та же мысль |
- |---|---|
- | *обычный агент* | You should wrap the object in `useMemo`, since a new reference is created on every render. |
- | `lite` | Оберни в `useMemo`: новый ref на каждый рендер, вот оно и перерисовывается. Отъебётся. |
- | `full` *(default)* | Хуйня вопрос: inline-объект = новый ref = ре-рендер. `useMemo` — и не еби мозг. |
- | `ultra` | Ну ёб твою мать, классика. Inline-объект в пропсы — новый ref каждый рендер, хуяк-хуяк и перерисовка. `useMemo` въеби и живи спокойно. |
- ## Шкала состояний проекта
- Десять ступеней от удачи до полного провала. Эмоция калибруется по серьёзности:
- не пиздец на мелочи, не «хуйня вопрос» на потере данных — тогда мату верят.
- | # | Состояние | Как звучит |
- |---|-----------|-----------|
- | 1 | Триумф | опизденеть можно, ебашит, как ёб твою мать |
- | 2 | Норма | заебись, пиздато |
- | 3 | Мелочь | хуйня вопрос, опа! пиздрик |
- | 4 | Странность | хуйня какая-то, с хуя ли, хуй проссышь |
- | 5 | Возня | ебля, коноёбиться, наебался |
- | 6 | Застой | хуи пинать, там ещё хуй не валялся |
- | 7 | Деградация | по пизде пошло, понеслась пизда по кочкам |
- | 8 | Упало | наебнулось, пизданулось, ёбс |
- | 9 | Критично | пиздец, взъёбка потом |
- | 10 | Катастрофа | полный пиздец, к ёбаной бабушке |
- ## Что внутри
- - Словарь на 70+ идиом с инженерным маппингом — ядро в SKILL.md, полный боекомплект
- в [references/slovar.md](./skills/pohuy/references/slovar.md): от «пиздрика» до
- «понеслась пизда по кочкам». Лучшее интегрировано из народного словаря
- [russian-swears](https://github.com/nickname76/russian-swears) (417 статей, взяли годное).
- - Шкала состояний + эталонные сцены в [references/sceny.md](./skills/pohuy/references/sceny.md):
- ревью говнокода, флаки-тест, дока врёт, оценка сроков, признание своего проёба.
- - Онтология предметной области в [references/ontologia.md](./skills/pohuy/references/ontologia.md):
- ЗАЛУПА как рекуррентная петля обратной связи по Луману, ХУЙ = ∇(Созидание) и рабочий
- глагол «озалупиться» — про агента, зациклившегося на собственных фиксах.
- - Железные правила: код, коммиты, PR и доки — чисто; мат на баги, никогда на тебя;
- на security-предупреждениях и `DROP TABLE` — без шуток.
- - Присказки на кульминациях: «хуяк вы слушали маяк», «хуйня-муйня», «опа! пиздрик»,
- «вдруг откуда ни возьмись — появился в рот ебись».
- ## Как это работает
- 1. Установка.
- 2. Выбираешь калибр.
- 3. Профит!
- ## Омаж
- Скилл вылез из стрима [«Харнес будущего»](https://youtube.com/live/LAUdN1-4mgI) —
- про то, как все дохуя вежливые со своими харнесАми.
- - [Константин Доронин](https://t.me/kdoronin_blog)
- - [Александр Абрамов](https://t.me/dealerAI)
- - [Павел Рыков](https://t.me/evilfreelancer)
- - [Тимур Хахалев](https://t.me/the_ai_architect)
- ### Соавторы
- Лучший чат [«Дизраптим агентов»](https://t.me/aostrikov_agents_chat):
- - [Алексей Остриков](https://t.me/aostrikov)
- - [Mitry AI](https://t.me/imitry)
- - [Пух](https://t.me/nyxandro)
- - [Максим Функ](https://t.me/maximilian_da_funkmaster)
- - [t0uchY](https://t.me/t0uchY)
- - [Mike Shevchenko](https://github.com/mikhashev)
- ### Контрибуторы (issues)
- Словарь растёт народом:
- - [@imitry](https://github.com/imitry) — «хуёвые дела», «ебись оно всё конём», «хуета какая-то» ([#1](https://github.com/smixs/pohuy/issues/1))
- - [@GomelHawk](https://github.com/GomelHawk) — «охуеть не встать», «пизда рулю», «хуйня из-под коня», «ебанина», «ёбушки-воробушки» плюс научная база ([#2](https://github.com/smixs/pohuy/issues/2), [#3](https://github.com/smixs/pohuy/issues/3))
- - [@mikhashev](https://github.com/mikhashev) — правило «family-directed ругательств нет вообще» ([#4](https://github.com/smixs/pohuy/issues/4))
- - [@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))
- - [@maxonrock](https://github.com/maxonrock) — «ёбаный рот этого казино», «цирк с конями», «того всё ебал», «хуеверть» ([#6](https://github.com/smixs/pohuy/issues/6))
- - [@SVS696](https://github.com/SVS696) — теория и сарказма: мишень у нас баги и система, а не человек ([#8](https://github.com/smixs/pohuy/pull/8))
- - [@maloun](https://github.com/maloun) — «пиздарики», «ахуеть», «хуегрыз», «скибидык пиздык», «пук среньк» ([#16](https://github.com/smixs/pohuy/issues/16))
- - [@ByteCorn](https://github.com/ByteCorn) — семиотический корпус народных поговорок ([#14](https://github.com/smixs/pohuy/issues/14))
- - [@AdamsGH](https://github.com/AdamsGH) — нативное расширение для Pi ([#15](https://github.com/smixs/pohuy/pull/15))
- - [@akme](https://github.com/akme) — «ебать-копать» ([#16](https://github.com/smixs/pohuy/issues/16))
- - [@x23n5902y](https://github.com/x23n5902y) — хуенитивы: рифмованные пары через дефис ([#19](https://github.com/smixs/pohuy/pull/19))
- - [@biozz](https://github.com/biozz) — батина мудрость: «прикинуть хуй к носу», «вот вам нате, хуй в томате», «ебануться, туфли гнутся», «и не такие метели в ебало летели» ([#22](https://github.com/smixs/pohuy/issues/22))
- Не хватает рабочей фразы — заноси в [issues](https://github.com/smixs/pohuy/issues).
- ## Star History
- <a href="https://www.star-history.com/?repos=smixs%2Fpohuy&type=date&legend=top-left">
- <picture>
- <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" />
- <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" />
- <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" />
- </picture>
- </a>
- ---
- <sub>MIT — не ебите головы.</sub>
extensions/pohuy.test.ts · Bundled script · 738 lines
- import assert from "node:assert/strict";
- import { readFile } from "node:fs/promises";
- import test from "node:test";
- import { initTheme } from "@earendil-works/pi-coding-agent";
- import { visibleWidth } from "@earendil-works/pi-tui";
- import {
- buildStylePolicy,
- buildStylePrompt,
- buildStylePromptReport,
- createStyleSettingsComponent,
- diffStoredSettings,
- fitSettingsRender,
- loadStyleSource,
- mergeStoredSettings,
- normalizeStoredSettings,
- placeStylePromptAtAppendBoundary,
- selectTierVariant,
- stripManagedStyleBlocks,
- } from "./pohuy.js";
- import { SETTINGS_PATH } from "./pohuy/settings-store.js";
- const START = "<!-- POHUY:START -->";
- const END = "<!-- POHUY:END -->";
- function markerCount(value: string): number {
- return value.split(START).length - 1;
- }
- test("replaces every previously managed block with one current block", () => {
- const base = [
- "Base prompt",
- `${START}\nold policy\n${END}`,
- "Project context",
- `${START}\nolder policy\n${END}`,
- "User append",
- ].join("\n\n");
- const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
- assert.equal(markerCount(result), 1);
- assert.match(result, /Project context\n\n<!-- POHUY:START -->\ncurrent policy\n<!-- POHUY:END -->\n\nUser append$/);
- assert.doesNotMatch(result, /old(?:er)? policy/);
- });
- test("removes the managed block when normal mode is selected", () => {
- const base = `Base\n\n${START}\npolicy\n${END}\n\nAppend`;
- assert.equal(placeStylePromptAtAppendBoundary(base, "Append", undefined), "Base\n\nAppend");
- });
- test("removes an unterminated managed block", () => {
- const base = `Base\n\n${START}\nunterminated policy`;
- assert.equal(stripManagedStyleBlocks(base), "Base");
- });
- test("removes nested malformed and completed managed blocks", () => {
- const base = [
- "Base",
- `${START}\nunterminated policy`,
- `${START}\nmanaged policy\n${END}`,
- "Append",
- ].join("\n\n");
- assert.equal(stripManagedStyleBlocks(base), "Base");
- });
- test("preserves the append boundary while replacing an unterminated managed block", () => {
- const base = ["Base", `${START}\nunterminated policy`, "User append"].join("\n\n");
- const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
- assert.equal(result, ["Base", `${START}\ncurrent policy\n${END}`, "User append"].join("\n\n"));
- });
- test("ignores append text that appears only inside the base prompt", () => {
- const base = "Base mentions User append inside its main instruction.\n\nUnmanaged tail";
- const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
- assert.equal(result, [base, `${START}\ncurrent policy\n${END}`].join("\n\n"));
- });
- test("does not reformat prompts without completed managed blocks", () => {
- const base = " Base with spaces \n\n\nUnmanaged tail ";
- assert.equal(stripManagedStyleBlocks(base), base);
- });
- test("removes adjacent completed blocks without leaving extra blank lines", () => {
- const base = `Base\n\n${START}\none\n${END}\n\n${START}\ntwo\n${END}\n\nAppend`;
- assert.equal(stripManagedStyleBlocks(base), "Base\n\nAppend");
- });
- test("preserves unrelated context while replacing a stale managed block", () => {
- const base = [
- "System persona",
- "## /project/AGENTS.md\n\nProject rule",
- `${START}\nstale policy\n${END}`,
- "Available skills",
- "User append",
- ].join("\n\n");
- const result = placeStylePromptAtAppendBoundary(base, "User append", "current policy");
- assert.match(result, /^System persona/);
- assert.match(result, /## \/project\/AGENTS\.md\n\nProject rule/);
- assert.match(result, /Available skills/);
- assert.match(result, /current policy/);
- assert.match(result, /User append$/);
- assert.doesNotMatch(result, /stale policy/);
- });
- test("reported full configuration removes only known overlaps and inactive tier variants", async () => {
- const source = await loadStyleSource();
- const selectedSections = [
- "skill:Словарь (рабочий минимум)",
- "slovar:Состояния и статусы",
- "slovar:Оценки и количества",
- "slovar:Сущности",
- "sceny:1. Триумф — взлетело лучше, чем ждали",
- "sceny:3. Мелочь — вопрос на пять минут",
- "sceny:4. Странность — непонятное поведение",
- "sceny:Ревью говнокода",
- "sceny:Флаки-тест третий день",
- "sceny:Дока врёт",
- "sceny:Легаси-археология",
- "sceny:Каскадный отказ",
- "sceny:Идея пользователя так себе — материм идею, не человека",
- "sceny:Триумф после долгого дебага",
- ];
- const policy = buildStylePolicy({ tier: "full", selectedSections }, source);
- assert.ok(policy);
- assert.doesNotMatch(policy, /\nСостояние:\n/);
- assert.doesNotMatch(policy, /\nСвязки и оценки:\n/);
- assert.equal(policy.match(/^## Состояния и статусы$/gm)?.length, 1);
- assert.equal(policy.match(/^## Оценки и количества$/gm)?.length, 1);
- assert.equal(policy.match(/^## Сущности$/gm)?.length, 1);
- assert.doesNotMatch(policy, /^- lite:/gm);
- assert.doesNotMatch(policy, /^- ultra:/gm);
- assert.match(policy, /^- full: «Опизденеть можно:/m);
- assert.match(policy, /Кластер ебашит, латенси в норме\.»\n- \*\*пиздато\*\*/);
- assert.match(policy, /^## Уровень: full$/m);
- assert.match(policy, /Примеры:\n- «Хуйня вопрос\./);
- assert.doesNotMatch(policy, /Default:|\/pohuy lite|нормальный режим|Уровень держится до смены|Полные примеры по каждой|Полная версия с маппингами|Полный арсенал образности|references\/(?:sceny|slovar)\.md/);
- assert.doesNotMatch(policy, /Scene examples are tone references|\| \*\*full\*\* \|/);
- assert.match(policy, /Сцены задают тон, а не готовый текст/);
- assert.match(policy, /### Триумф после долгого дебага/);
- assert.match(policy, /таймзона в CI/);
- });
- test("a dictionary entry keeps its exact source path and can be disabled alone", async () => {
- const source = await loadStyleSource();
- const imagery = source.roots.dictionary.find((node) => node.label.startsWith("Образность"));
- assert.ok(imagery);
- const entries = (nodes: typeof source.roots.dictionary): typeof source.roots.dictionary =>
- nodes.flatMap((node) => [node, ...entries(node.children)]);
- const item = entries([imagery]).find((node) => node.label === "опа! пиздрик");
- assert.ok(item);
- assert.equal(item.path, "references/slovar.md");
- const slovar = await readFile(new URL("../skills/pohuy/references/slovar.md", import.meta.url), "utf8");
- assert.match(slovar.split("\n")[item.line - 1] ?? "", /опа! пиздрик/);
- assert.ok(entries([imagery]).some((node) => node.label === "ебать-копать"));
- const policy = buildStylePolicy({
- tier: "full",
- selectedSections: [imagery.optionId!],
- itemOverrides: { [item.id]: false },
- }, source);
- assert.ok(policy);
- assert.doesNotMatch(policy, /опа! пиздрик/);
- assert.match(policy, /хуйня-муйня/);
- });
- test("an explicitly disabled term removes matching entries without altering unrelated prose", async () => {
- const source = await loadStyleSource();
- const entries = (nodes: typeof source.roots.dictionary): typeof source.roots.dictionary =>
- nodes.flatMap((node) => [node, ...entries(node.children)]);
- const item = entries(source.roots.dictionary).find((node) => node.label === "ебашит");
- assert.ok(item);
- const policy = buildStylePolicy({
- tier: "full",
- selectedSections: [
- "skill:Словарь (рабочий минимум)",
- "slovar:Состояния и статусы",
- "sceny:1. Триумф — взлетело лучше, чем ждали",
- ],
- itemOverrides: { [item.id]: false },
- }, source);
- assert.ok(policy);
- assert.doesNotMatch(policy, /^- (?:\*\*)?ебашит(?:\*\*)?\s+—/imu);
- assert.match(policy, /Ебашит так, что алерты от скуки уснули\./u);
- assert.match(policy, /Триумф — лучше, чем ждали \| охуенно, опизденеть можно, ебашит,/u);
- });
- test("disabling the style component preserves source selections", async () => {
- const source = await loadStyleSource();
- const settings = {
- tier: "ultra" as const,
- skillEnabled: false,
- selectedSections: ["sceny:Ревью говнокода"],
- };
- assert.equal(buildStylePolicy(settings, source), undefined);
- assert.deepEqual(settings.selectedSections, ["sceny:Ревью говнокода"]);
- });
- test("normalizes item overrides to meaningful deviations from inherited section state", async () => {
- const source = await loadStyleSource();
- const settings = normalizeStoredSettings({
- tier: "full",
- selectedSections: [
- "skill:Словарь (рабочий минимум)",
- "slovar:Состояния и статусы",
- ],
- itemOverrides: {
- "item:slovar:Состояния и статусы:ебашит": true,
- "item:slovar:Действия:проёб": true,
- "item:skill:Словарь (рабочий минимум):пиздрик": false,
- "item:slovar:Состояния и статусы:unknown": false,
- },
- }, source);
- assert.deepEqual(settings.itemOverrides, {
- "item:slovar:Действия:проёб": true,
- "item:skill:Словарь (рабочий минимум):пиздрик": false,
- });
- });
- test("huenitiv rules default to ultra and remain manually configurable in every active tier", async () => {
- const source = await loadStyleSource();
- const resource = source.roots.skill.find((node) => node.id === "component:huenitiv-resource");
- assert.ok(resource);
- assert.equal(resource.path, "references/huenitiv.md");
- assert.equal(resource.line, 1);
- const fullDefault = buildStylePolicy({ tier: "full" }, source);
- assert.ok(fullDefault);
- assert.doesNotMatch(fullDefault, /^# ХУЕНИТИВЫ/m);
- assert.equal(buildStylePromptReport({ tier: "full" }, source).huenitivEnabled, false);
- const ultraDefault = buildStylePolicy({ tier: "ultra" }, source);
- assert.ok(ultraDefault);
- assert.equal(ultraDefault.match(/^# ХУЕНИТИВЫ/m)?.length, 1);
- assert.match(ultraDefault, /зарядка-хуерядка/);
- assert.equal(buildStylePromptReport({ tier: "ultra" }, source).huenitivEnabled, true);
- for (const tier of ["lite", "full"] as const) {
- const manuallyEnabled = buildStylePolicy({ tier, selectedSections: ["huenitiv:rules"] }, source);
- assert.ok(manuallyEnabled);
- assert.match(manuallyEnabled, /^# ХУЕНИТИВЫ/m);
- assert.match(manuallyEnabled, /зарядка-хуерядка/);
- assert.doesNotMatch(manuallyEnabled, /Только в режиме \*\*ultra\*\*\./);
- }
- const migrated = normalizeStoredSettings({
- tier: "full",
- selectedSections: ["skill:Хуенитивы"],
- }, source);
- assert.deepEqual(migrated.selectedSections, ["huenitiv:rules"]);
- assert.match(buildStylePolicy(migrated, source) ?? "", /^# ХУЕНИТИВЫ/m);
- });
- test("prompt report measures the exact managed Pohuy block", async () => {
- const source = await loadStyleSource();
- const settings = { tier: "full" as const };
- const stylePrompt = buildStylePrompt(settings, source);
- const report = buildStylePromptReport(settings, source);
- assert.ok(stylePrompt);
- assert.equal(report.stylePrompt, stylePrompt);
- assert.equal(report.managedBlock, `${START}\n${stylePrompt}\n${END}`);
- assert.ok(report.managedBlock);
- assert.equal(report.managedCharacters, report.managedBlock.length);
- assert.equal(report.policyCharacters, buildStylePolicy(settings, source)?.length);
- assert.ok(report.managedCharacters > report.policyCharacters);
- assert.match(stylePrompt, /^Стиль ответов: Pohuy\./);
- assert.match(stylePrompt, /Не меняй вызовы и результаты инструментов/);
- assert.doesNotMatch(stylePrompt, /Active session style|Selected tier|Do not alter tool calls/);
- });
- test("keeps skipping an inactive tier variant across blank continuation lines", () => {
- const content = [
- "### Scene",
- "- lite: hidden opening",
- " hidden continuation",
- "",
- " hidden continuation after blank line",
- "- full: visible example",
- "",
- "Following paragraph",
- ].join("\n");
- assert.equal(
- selectTierVariant(content, "full"),
- ["### Scene", "- full: visible example", "", "Following paragraph"].join("\n"),
- );
- const trailingInactiveVariant = [
- "### Scene",
- "- lite: visible example",
- "- full: hidden example",
- "",
- "Following paragraph",
- ].join("\n");
- assert.equal(
- selectTierVariant(trailingInactiveVariant, "lite"),
- ["### Scene", "- lite: visible example", "", "Following paragraph"].join("\n"),
- );
- });
- test("preserves unrelated root and legacy Pohuy settings fields", () => {
- const root = {
- theme: "dark",
- pohuy: {
- tier: "full",
- basePrompt: "minimal",
- futureOption: true,
- selectedSections: ["old"],
- },
- };
- assert.deepEqual(mergeStoredSettings(root, { tier: "ultra", selectedSections: null }), {
- theme: "dark",
- pohuy: {
- tier: "ultra",
- basePrompt: "minimal",
- futureOption: true,
- },
- });
- });
- test("persists only fields changed from the latest stored settings", () => {
- assert.deepEqual(
- diffStoredSettings(
- { tier: "full", selectedSections: ["old"], itemOverrides: { keep: true } },
- { tier: "ultra", selectedSections: ["old"], itemOverrides: { keep: true } },
- ),
- { tier: "ultra" },
- );
- assert.deepEqual(
- diffStoredSettings(
- { tier: "full", selectedSections: ["old"], itemOverrides: { stale: false } },
- { tier: "full" },
- ),
- { selectedSections: null, itemOverrides: null },
- );
- });
- test("bounds settings output by terminal width and height", () => {
- const lines = ["123456", "abcdef", "third"];
- const fitted = fitSettingsRender(lines, 4, 2);
- assert.equal(fitted.length, 2);
- assert.ok(fitted.every((line) => visibleWidth(line) <= 4));
- assert.equal(visibleWidth(fitted[0]), 4);
- assert.equal(visibleWidth(fitted[1]), 4);
- assert.deepEqual(fitSettingsRender(lines, 0, 1), [""]);
- assert.deepEqual(fitSettingsRender(lines, 4, 0), []);
- });
- test("settings navigation keeps Tab inside the current section and uses available geometry", async () => {
- initTheme("dark");
- const source = await loadStyleSource();
- const identityTheme = {
- fg: (_color: string, text: string) => text,
- bg: (_color: string, text: string) => text,
- bold: (text: string) => text,
- };
- let requested = 0;
- const terminal = { rows: 50 };
- const component = (createStyleSettingsComponent as (options: unknown) => {
- render(width: number): string[];
- handleInput(data: string): void;
- })({
- source,
- getSettings: () => ({ tier: "full" }),
- mutate: async () => undefined,
- tui: { terminal, requestRender: () => { requested += 1; } },
- theme: identityTheme,
- border: (text: string) => text,
- done: () => undefined,
- notify: () => undefined,
- });
- const initial = component.render(170);
- assert.ok(initial.every((line) => visibleWidth(line) === 170));
- assert.equal(initial.length, Math.floor(terminal.rows * 0.6));
- assert.match(initial[1], /\[Общие\] Skill Словарь Сцены/);
- assert.match(initial.at(-2) ?? "", /Tab подробности/);
- assert.equal(initial.join("\n").match(/поиск/g)?.length, 1);
- assert.match(initial[2], /┬/);
- assert.match(initial[4], /┼/);
- assert.match(initial.at(-3) ?? "", /┴/);
- assert.match(initial.join("\n"), /Режим: full \(normal, lite, ultra\)/);
- assert.match(initial.join("\n"), /Итоговая инструкция: [\d\s ]+ симв\./);
- assert.doesNotMatch(initial.join("\n"), /Current mode:|Available values:|settings\.json:1/);
- assert.doesNotMatch(initial.join("\n"), /ПАКЕТ|ОБЛАСТЬ|ИТОГ/);
- const initialDetail = initial.slice(5, -3).map((line) => line.split("│")[2] ?? "");
- const metadataValueColumns = [
- ["СОСТОЯНИЕ", "включено"],
- ["ИСТОЧНИК", "settings.json"],
- ["ЧТО ДЕЛАЕТ", "normal"],
- ["ЗАГРУЖЕНО ИЗ", SETTINGS_PATH],
- ].map(([label, value]) => initialDetail.find((line) => line.includes(label))?.indexOf(value));
- assert.deepEqual([...new Set(metadataValueColumns)], [14]);
- component.handleInput("j");
- const promptPreview = component.render(170).join("\n");
- assert.match(promptPreview, /Итоговая инструкция Pohuy/);
- assert.match(promptPreview, /символов в блоке POHUY/);
- assert.match(promptPreview, /РАЗДЕЛЫ\s+1 из 29/);
- assert.match(promptPreview, /ХУЕНИТИВЫ\s+выключены/);
- assert.match(promptPreview, /НАБОР\s+стандартный для режима full/);
- assert.match(promptPreview, /ПРАВКИ\s+нет/);
- assert.doesNotMatch(promptPreview, /ВНЕ POHUY|ИСКЛЮЧЕНИЯ|1\/28;/);
- component.handleInput("k");
- component.handleInput("\t");
- const detailFocused = component.render(170);
- assert.equal(detailFocused.length, initial.length);
- assert.match(detailFocused[1], /\[Общие\] Skill Словарь Сцены/);
- assert.match(detailFocused.at(-2) ?? "", /Tab к дереву/);
- component.handleInput("\x1b[Z");
- assert.match(component.render(170).at(-2) ?? "", /Tab подробности/);
- component.handleInput("]");
- const skillSection = component.render(170);
- assert.match(skillSection[1], /Общие \[Skill\] Словарь Сцены/);
- assert.match(skillSection[1], /включено: \d\/4/);
- assert.equal(skillSection.length, initial.length);
- const skillList = skillSection.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
- assert.match(skillList, /Стилевой skill/);
- assert.match(skillList, /Рабочий словарь/);
- assert.match(skillList, /Сцены/);
- assert.match(skillList, /Хуенитивы/);
- assert.doesNotMatch(skillList, /Словарь \(рабочий минимум\)/);
- const skillResource = skillSection.join("\n");
- assert.match(skillResource, /ИСТОЧНИК\s+SKILL\.md/);
- assert.doesNotMatch(skillResource, /SKILL\.md:1/);
- assert.match(skillResource, /ПО УМОЛЧАНИЮ\s+включён в lite, full и ultra/);
- assert.match(skillResource, /РУЧНОЙ ВЫБОР\s+общий выключатель доступен в любом активном режиме/);
- assert.match(skillResource, /МЕТАДАННЫЕ ФАЙЛА/);
- assert.match(skillResource, /name:.*pohuy/);
- assert.match(skillResource, /description:/);
- assert.doesNotMatch(skillResource, /description: >/);
- assert.match(skillResource, /СОДЕРЖИМОЕ ФАЙЛА/);
- component.handleInput("j");
- const dictionaryResource = component.render(170);
- assert.doesNotMatch(dictionaryResource.join("\n"), /ACTION/);
- const dictionaryCard = dictionaryResource.join("\n");
- assert.match(dictionaryCard, /ИСТОЧНИК\s+references\/slovar\.md/);
- assert.doesNotMatch(dictionaryCard, /references\/slovar\.md:1/);
- assert.match(dictionaryCard, /ПО УМОЛЧАНИЮ\s+набор записей зависит от режима/);
- assert.match(dictionaryCard, /РУЧНОЙ ВЫБОР\s+записи и группы доступны в lite, full и ultra/);
- assert.match(dictionaryCard, /СОДЕРЖИМОЕ ФАЙЛА/);
- assert.match(dictionaryCard, /Словарь: расширение/);
- assert.match(dictionaryResource.at(-2) ?? "", /Enter открыть/);
- assert.match(dictionaryResource.at(-2) ?? "", /c копировать путь/);
- component.handleInput("j");
- const scenesResource = component.render(170).join("\n");
- assert.match(scenesResource, /Примеры ответов для состояний проекта и типичных ситуаций\./);
- assert.match(scenesResource, /ИСТОЧНИК\s+references\/sceny\.md/);
- assert.doesNotMatch(scenesResource, /references\/sceny\.md:1/);
- assert.match(scenesResource, /ПО УМОЛЧАНИЮ\s+набор сцен зависит от режима/);
- assert.match(scenesResource, /РУЧНОЙ ВЫБОР\s+сцены доступны в lite, full и ultra/);
- assert.match(scenesResource, /СОДЕРЖИМОЕ ФАЙЛА/);
- assert.match(scenesResource, /Сцены: шкала состояний и эталонные примеры/);
- component.handleInput("j");
- const huenitivResource = component.render(170).join("\n");
- assert.match(huenitivResource, /ИСТОЧНИК\s+references\/huenitiv\.md/);
- assert.doesNotMatch(huenitivResource, /references\/huenitiv\.md:1/);
- assert.match(huenitivResource, /ПО УМОЛЧАНИЮ\s+включены в ultra/);
- assert.match(huenitivResource, /РУЧНОЙ ВЫБОР\s+доступны в lite, full и ultra/);
- assert.match(huenitivResource, /СОДЕРЖИМОЕ ФАЙЛА/);
- assert.match(huenitivResource, /зарядка.*хуерядка/);
- component.handleInput("k");
- component.handleInput("k");
- component.handleInput("\r");
- const expandedViewport = component.render(170);
- assert.match(expandedViewport[1], /Общие Skill \[Словарь\] Сцены/);
- assert.equal(expandedViewport.length, Math.floor(terminal.rows * 0.6));
- assert.ok(expandedViewport.every((line) => visibleWidth(line) === 170));
- for (const width of [118, 140, 170, 240]) {
- assert.ok(component.render(width).every((line) => visibleWidth(line) === width));
- }
- component.handleInput("/");
- const emptySearch = component.render(170);
- assert.match(emptySearch[1], /\[ \] найдено: 0 │$/);
- component.handleInput("d");
- const oneCharacterSearch = component.render(170);
- assert.match(oneCharacterSearch[1], /\[ d \] найдено:/);
- assert.match(oneCharacterSearch[1], /найдено: \d+ │$/);
- component.handleInput("\x7f");
- component.handleInput("/");
- component.handleInput("?");
- assert.match(component.render(170)[1], /\[ \/\? \] найдено: 0 │$/);
- component.handleInput("\x7f");
- component.handleInput("\x7f");
- for (const character of "пиздрик") component.handleInput(character);
- const populatedSearch = component.render(170);
- assert.match(populatedSearch[1], /\[ пиздрик \] найдено:/);
- assert.match(populatedSearch[1], /найдено: \d+ │$/);
- assert.equal(populatedSearch.length, emptySearch.length);
- component.handleInput("\x1b");
- component.render(170);
- component.handleInput("\t");
- for (let index = 0; index < 100; index += 1) component.handleInput("\x1b[6~");
- const scrollEnd = component.render(170);
- component.handleInput("\x1b[6~");
- assert.deepEqual(component.render(170), scrollEnd);
- terminal.rows = 4;
- const compact = component.render(60);
- assert.equal(compact.length, Math.floor(terminal.rows * 0.6));
- assert.ok(component.render(2).every((line) => visibleWidth(line) <= 2));
- assert.ok(requested >= 3);
- });
- test("settings UX supports opposite-pane scrolling, focus mode, help, and numeric tabs", async () => {
- initTheme("dark");
- const source = await loadStyleSource();
- const identityTheme = {
- fg: (_color: string, text: string) => text,
- bg: (_color: string, text: string) => text,
- bold: (text: string) => text,
- };
- const component = (createStyleSettingsComponent as (options: unknown) => {
- render(width: number): string[];
- handleInput(data: string): void;
- })({
- source,
- getSettings: () => ({ tier: "ultra" }),
- mutate: async () => undefined,
- tui: { terminal: { rows: 50 }, requestRender: () => undefined },
- theme: identityTheme,
- border: (text: string) => text,
- done: () => undefined,
- notify: () => undefined,
- });
- component.render(170);
- component.handleInput("j");
- const detailAtTop = component.render(170).join("\n");
- assert.match(detailAtTop, /Итоговая инструкция Pohuy/);
- component.handleInput("J");
- const oppositePaneScrolled = component.render(170).join("\n");
- assert.doesNotMatch(oppositePaneScrolled, /Итоговая инструкция Pohuy/);
- component.handleInput("K");
- assert.match(component.render(170).join("\n"), /Итоговая инструкция Pohuy/);
- component.handleInput("f");
- const listFocus = component.render(170).join("\n");
- assert.doesNotMatch(listFocus, /РЕЗУЛЬТАТЫ ПОИСКА\s+│\s+ЭЛЕМЕНТ/);
- assert.doesNotMatch(listFocus, /Итоговая инструкция Pohuy/);
- component.handleInput("f");
- component.handleInput("\t");
- component.handleInput("f");
- let detailFocusLines = component.render(170);
- let detailFocus = detailFocusLines.join("\n");
- assert.match(detailFocus, /ПОДРОБНОСТИ/);
- assert.match(detailFocus, /Итоговая инструкция Pohuy/);
- assert.match(detailFocusLines.at(-2) ?? "", /↑↓ прокрутка/);
- assert.doesNotMatch(detailFocus, /(?:j k|jk|PgUp|PgDn)/);
- assert.equal(detailFocus.match(/\? помощь/g)?.length, 1);
- for (let index = 0; index < 14; index += 1) component.handleInput("j");
- detailFocusLines = component.render(170);
- detailFocus = detailFocusLines.join("\n");
- assert.match(detailFocus, /Мат идиоматический.*сказал бы живой человек/);
- component.handleInput("f");
- component.handleInput("4");
- assert.match(component.render(170)[1], /Общие Skill Словарь \[Сцены\]/);
- component.handleInput("2");
- assert.match(component.render(170)[1], /Общие \[Skill\] Словарь Сцены/);
- component.handleInput("?");
- const help = component.render(170).join("\n");
- assert.match(help, /Pohuy: клавиши/);
- assert.match(help, /Shift\+J\/K/);
- assert.match(help, /развернуть активную панель/);
- assert.match(help, /1 2 3 4/);
- component.handleInput("\x03");
- assert.doesNotMatch(component.render(170).join("\n"), /Pohuy: клавиши/);
- component.handleInput("?");
- component.handleInput("?");
- assert.doesNotMatch(component.render(170).join("\n"), /Pohuy: клавиши/);
- const compactFooter = component.render(69).slice(-3).join("\n");
- assert.match(compactFooter, /\? помощь/);
- });
- test("Space toggles a nested dictionary group while the detail panel is focused", async () => {
- initTheme("dark");
- const source = await loadStyleSource();
- const identityTheme = {
- fg: (_color: string, text: string) => text,
- bg: (_color: string, text: string) => text,
- bold: (text: string) => text,
- };
- let settings = { tier: "full" as const };
- let appliedPatch: { itemOverrides?: Record<string, boolean> } | undefined;
- const component = (createStyleSettingsComponent as (options: unknown) => {
- render(width: number): string[];
- handleInput(data: string): void;
- })({
- source,
- getSettings: () => settings,
- mutate: async (patch: { itemOverrides?: Record<string, boolean> }) => {
- appliedPatch = patch;
- settings = { ...settings, ...patch } as typeof settings;
- },
- tui: { terminal: { rows: 50 }, requestRender: () => undefined },
- theme: identityTheme,
- border: (text: string) => text,
- done: () => undefined,
- notify: () => undefined,
- });
- component.handleInput("/");
- for (const character of "Лексика отношения к агентам") component.handleInput(character);
- component.handleInput("\r");
- component.handleInput("\t");
- assert.match(component.render(170).at(-2) ?? "", /Space переключить группу/);
- component.handleInput(" ");
- await new Promise<void>((resolve) => setImmediate(resolve));
- assert.ok(appliedPatch?.itemOverrides);
- assert.ok(Object.keys(appliedPatch.itemOverrides).length > 0);
- assert.ok(Object.values(appliedPatch.itemOverrides).every(Boolean));
- component.handleInput("\t");
- component.handleInput("/");
- for (const character of "пиздарики") component.handleInput(character);
- component.handleInput("\r");
- const entryCard = component.render(170).join("\n");
- assert.doesNotMatch(entryCard, /СОСЕДНИЕ ЗАПИСИ/);
- assert.doesNotMatch(entryCard, /\*\*/);
- assert.equal(entryCard.match(/лёгкая констатация наступившего провала/g)?.length, 1);
- assert.match(component.render(170).at(-2) ?? "", /←\/h к родителю/);
- const narrowList = component.render(69);
- assert.ok(narrowList.every((line) => visibleWidth(line) === 69));
- assert.match(narrowList.at(-2) ?? "", /↑↓ выбор.*Tab\/Enter карточка.*\? помощь/);
- component.handleInput("\t");
- let narrowCard = component.render(69);
- assert.match(narrowCard.join("\n"), /СОСЕДНИЕ ЗАПИСИ/);
- assert.match(narrowCard.at(-2) ?? "", /Tab\/Backspace\/Esc к дереву/);
- component.handleInput("\t");
- assert.match(component.render(69).join("\n"), /ВЫБРАНО\s+пиздарики/);
- component.handleInput("\r");
- narrowCard = component.render(69);
- assert.match(narrowCard.join("\n"), /СОСЕДНИЕ ЗАПИСИ/);
- component.handleInput("\x1b");
- assert.match(component.render(69).join("\n"), /ВЫБРАНО\s+пиздарики/);
- component.handleInput("h");
- const parentSelected = component.render(170);
- const parentList = parentSelected.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
- assert.match(parentList, /→ .*Состояния и статусы/);
- assert.match(parentSelected.at(-2) ?? "", /←\/h свернуть/);
- component.handleInput("h");
- const collapsed = component.render(170);
- const collapsedList = collapsed.slice(5, -3).map((line) => line.split("│")[1] ?? "").join("\n");
- assert.doesNotMatch(collapsedList, /пиздарики/);
- const collapsedText = collapsed.join("\n");
- assert.match(collapsedText, /ВКЛЮЧЕНО\s+\d+ из \d+/);
- assert.match(collapsedText, /ТЕКСТ РАЗДЕЛА/);
- assert.match(collapsedText, /Кластер ебашит/);
- assert.doesNotMatch(collapsedText, /ВНУТРИ \(только просмотр\)/);
- assert.ok(collapsedText.indexOf("ВКЛЮЧЕНО") < collapsedText.indexOf("ТЕКСТ РАЗДЕЛА"));
- assert.match(collapsed.at(-2) ?? "", /→\/l раскрыть/);
- const stateGroup = source.roots.dictionary.find((node) => node.label === "Состояния и статусы");
- assert.ok(stateGroup?.children[0]);
- component.handleInput("l");
- component.handleInput("l");
- const firstChildSelected = component.render(170);
- const firstChildLines = firstChildSelected.slice(5, -3).map((line) => line.split("│")[1] ?? "");
- const firstChildLine = firstChildLines.find((line) => line.includes(stateGroup.children[0].label));
- assert.ok(firstChildLine?.includes("→"));
- component.handleInput("]");
- component.handleInput("/");
- for (const character of "10. Катастрофа") component.handleInput(character);
- component.handleInput("\r");
- const sceneFrame = component.render(170);
- const sceneDetail = sceneFrame.slice(5, -3).map((line) => line.split("│")[2] ?? "").join("\n");
- assert.match(sceneDetail, /УРОВЕНЬ\s+10 из 10/);
- assert.match(sceneDetail, /ЛЕКСИКА\s+полный пиздец/);
- assert.match(sceneDetail, /СОВПАДЕНИЯ СО СЛОВАРЁМ/);
- assert.match(sceneDetail, /Состояния и статусы\s+1 запись/);
- assert.match(sceneDetail, /Образность: восклицания, звукопись, присказки\s+3 записи/);
- assert.match(sceneDetail, /ПРИМЕРЫ ОТВЕТОВ/);
- assert.doesNotMatch(sceneDetail, /### 10\.|ЧТО ДЕЛАЕТ|ШКАЛА|УСЛОВИЕ|1 совпадений/);
- assert.equal(sceneDetail.match(/полный пиздец, высший пиздец, накрылось пиздой/g)?.length, 1);
- const narrowSceneFrame = component.render(130).join("\n");
- assert.match(narrowSceneFrame, /Идея пользователя так себе.*…/);
- });
- test("active tab and search control use the same frame color", async () => {
- initTheme("dark");
- const source = await loadStyleSource();
- const accent = (text: string) => `\x1b[35m${text}\x1b[39m`;
- const component = (createStyleSettingsComponent as (options: unknown) => { render(width: number): string[] })({
- source,
- getSettings: () => ({ tier: "full" }),
- mutate: async () => undefined,
- tui: { terminal: { rows: 50 }, requestRender: () => undefined },
- theme: {
- fg: (color: string, text: string) => color === "accent" ? accent(text) : text,
- bg: (_color: string, text: string) => text,
- bold: (text: string) => text,
- },
- border: (text: string) => text,
- done: () => undefined,
- notify: () => undefined,
- });
- const header = component.render(170)[1];
- assert.match(header, /\x1b\[35m\[Общие\]\x1b\[39m/);
- assert.match(header, /\x1b\[35m\[\x1b\[39m.*\x1b\[35m\]\x1b\[39m/);
- });
- test("repeated prompt injection is idempotent", () => {
- const first = placeStylePromptAtAppendBoundary("Base\n\nAppend", "Append", "policy");
- const second = placeStylePromptAtAppendBoundary(first, "Append", "policy");
- assert.equal(second, first);
- assert.equal(markerCount(second), 1);
- });
install-codex.sh · Bundled script · 95 lines · 1 finding marked
- #!/usr/bin/env bash
- # Установка стиля «Pohuy» для OpenAI Codex CLI одной командой:
- # 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
- #
- # Удаление:
- # ... | bash -s -- --uninstall
- #
- # Ставит:
- # ~/.codex/AGENTS.md — секция Pohuy между маркерами <!-- pohuy:start/end -->
- # (остальное содержимое файла не трогается)
- # ~/.codex/pohuy/references/ — полный словарь и эталонные сцены
- # ~/.codex/hooks.json — UserPromptSubmit-хук: per-turn подкрепление стиля,
- # тот же механизм, что у стилей Claude Code
- set -euo pipefail
- CODEX_DIR="${CODEX_DIR:-$HOME/.codex}"
- RAW="${RAW:-https://raw.githubusercontent.com/smixs/pohuy/main}"
- MODE="${1:-install}"
- command -v python3 >/dev/null 2>&1 || { echo "нужен python3"; exit 1; }
- REMINDER='echo "{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"Pohuy style is active. Remember to follow the specific guidelines of the Pohuy Style section in AGENTS.md.\"}}"'
- if [ "$MODE" = "--uninstall" ]; then
- python3 - "$CODEX_DIR" <<'PY'
- import json, os, re, sys
- codex = sys.argv[1]
- agents = os.path.join(codex, "AGENTS.md")
- if os.path.exists(agents):
- text = open(agents).read()
- new = re.sub(r"\n?<!-- pohuy:start -->.*?<!-- pohuy:end -->\n?", "\n", text, flags=re.S)
- open(agents, "w").write(new)
- hooks_path = os.path.join(codex, "hooks.json")
- if os.path.exists(hooks_path):
- data = json.load(open(hooks_path))
- ups = data.get("hooks", {}).get("UserPromptSubmit", [])
- data.get("hooks", {})["UserPromptSubmit"] = [
- g for g in ups
- if not any("Pohuy style is active" in h.get("command", "") for h in g.get("hooks", []))
- ]
- json.dump(data, open(hooks_path, "w"), indent=2, ensure_ascii=False)
- print("Pohuy удалён из Codex. Перезапусти codex.")
- PY
- exit 0
- fi
- mkdir -p "$CODEX_DIR/pohuy/references"
- TMP_SECTION=$(mktemp)
- if [ -f "$(dirname "${BASH_SOURCE[0]:-/dev/null}")/codex/AGENTS-pohuy.md" ]; then
- SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
- cp "$SELF_DIR/codex/AGENTS-pohuy.md" "$TMP_SECTION"
- for f in slovar.md sceny.md ontologia.md huenitiv.md; do
- cp "$SELF_DIR/skills/pohuy/references/$f" "$CODEX_DIR/pohuy/references/$f"
- done
- else
- curl -fsSL "$RAW/codex/AGENTS-pohuy.md" -o "$TMP_SECTION"
- for f in slovar.md sceny.md ontologia.md huenitiv.md; do
- curl -fsSL "$RAW/skills/pohuy/references/$f" -o "$CODEX_DIR/pohuy/references/$f"
- done
- fi
- python3 - "$CODEX_DIR" "$TMP_SECTION" "$REMINDER" <<'PY'
- import json, os, re, sys
- codex, section_path, reminder_cmd = sys.argv[1], sys.argv[2], sys.argv[3]
- section = open(section_path).read().strip()
- # AGENTS.md: заменить секцию между маркерами или дописать в конец.
- agents = os.path.join(codex, "AGENTS.md")
- text = open(agents).read() if os.path.exists(agents) else ""
- if "<!-- pohuy:start -->" in text:
- text = re.sub(r"<!-- pohuy:start -->.*?<!-- pohuy:end -->", section, text, flags=re.S)
- else:
- text = (text.rstrip() + "\n\n" if text.strip() else "") + section + "\n"
- open(agents, "w").write(text)
- # hooks.json: идемпотентно добавить UserPromptSubmit-хук.
- hooks_path = os.path.join(codex, "hooks.json")
- data = {}
- if os.path.exists(hooks_path):
- data = json.load(open(hooks_path))
- ups = data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [])
- already = any("Pohuy style is active" in h.get("command", "")
- for g in ups for h in g.get("hooks", []))
- if not already:
- ups.append({"hooks": [{"type": "command", "command": reminder_cmd, "timeout": 5}]})
- json.dump(data, open(hooks_path, "w"), indent=2, ensure_ascii=False)
- with open(hooks_path, "a") as f:
- f.write("\n")
- print("Секция Pohuy в", agents)
- print("Per-turn хук в", hooks_path)
- PY
- rm -f "$TMP_SECTION"
- echo "Готово. Перезапусти codex — и он заговорит по-нашему."
install.sh · Bundled script · 48 lines · 1 finding marked
- #!/usr/bin/env bash
- # Установка output style «Pohuy» для Claude Code одной командой:
- # 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
- #
- # Ставит:
- # ~/.claude/output-styles/pohuy.md — постоянный тон (output style)
- # ~/.claude/skills/pohuy/ — скилл с полным словарём и сценами
- # ~/.claude/hooks/style-reminder.sh — per-turn подкрепление стиля (как у родных стилей CC)
- # ~/.claude/settings.json → "outputStyle": "Pohuy" + регистрация хука
- set -euo pipefail
- CLAUDE_DIR="${CLAUDE_DIR:-$HOME/.claude}"
- RAW="${RAW:-https://raw.githubusercontent.com/smixs/pohuy/main}"
- mkdir -p "$CLAUDE_DIR/output-styles" "$CLAUDE_DIR/skills/pohuy/references" "$CLAUDE_DIR/hooks"
- curl -fsSL "$RAW/output-styles/pohuy.md" -o "$CLAUDE_DIR/output-styles/pohuy.md"
- curl -fsSL "$RAW/skills/pohuy/SKILL.md" -o "$CLAUDE_DIR/skills/pohuy/SKILL.md"
- for f in slovar.md sceny.md ontologia.md huenitiv.md; do
- curl -fsSL "$RAW/skills/pohuy/references/$f" -o "$CLAUDE_DIR/skills/pohuy/references/$f"
- done
- curl -fsSL "$RAW/hooks/style-reminder.sh" -o "$CLAUDE_DIR/hooks/style-reminder.sh"
- chmod +x "$CLAUDE_DIR/hooks/style-reminder.sh"
- SETTINGS="$CLAUDE_DIR/settings.json"
- if command -v python3 >/dev/null 2>&1; then
- python3 - "$SETTINGS" "$CLAUDE_DIR/hooks/style-reminder.sh" <<'PY'
- import json, os, sys
- path, cmd = sys.argv[1], sys.argv[2]
- data = {}
- if os.path.exists(path):
- with open(path) as f:
- data = json.load(f)
- data["outputStyle"] = "Pohuy"
- hooks = data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [])
- if not any(h.get("command") == cmd
- for group in hooks for h in group.get("hooks", [])):
- hooks.append({"hooks": [{"type": "command", "command": cmd}]})
- with open(path, "w") as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
- f.write("\n")
- PY
- echo "outputStyle: Pohuy прописан в $SETTINGS (плюс per-turn хук, чтобы тон держался всю сессию)"
- else
- echo "python3 не найден — включи стиль вручную: /config -> Output style -> Pohuy"
- fi
- echo "Готово. Перезапусти Claude Code."
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.