From 7c130253b138041177e520dea250c71bbaa70576 Mon Sep 17 00:00:00 2001 From: Dmitrii Date: Fri, 3 Apr 2026 18:25:46 +0300 Subject: [PATCH] chore: initial import of codex-review skill Baseline copy of the working codex-review SKILL.md from dotfiles before adversarial prompt rewrite and rebranding. Co-Authored-By: Claude Opus 4.6 (1M context) --- LICENSE | 190 +++++++++++++++++++++++++++++++ SKILL.md | 340 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 530 insertions(+) create mode 100644 LICENSE create mode 100644 SKILL.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d194d51 --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2025 Dmitrii Dementev + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..3b82ca6 --- /dev/null +++ b/SKILL.md @@ -0,0 +1,340 @@ +--- +name: codex-review +description: Ревью плана или кода через OpenAI Codex. Автодетект режима, итеративные правки до одобрения. +user_invocable: true +--- + +# Итеративное ревью через Codex + +Отправляет текущую работу в OpenAI Codex на adversarial-ревью. Автоматически определяет, что ревьюить: **план** или **код**. Claude правит по замечаниям Codex и переотправляет до одобрения. Максимум 5 раундов. + +--- + +## Когда вызывать + +- `/codex-review` — автодетект что ревьюить +- `/codex-review plan` — принудительно ревью плана +- `/codex-review code` — принудительно ревью кода +- `/codex-review <путь-к-файлу>` — ревью конкретного файла (аргумент содержит `/` или `.`) +- Переопределение reasoning: `/codex-review xhigh` или `/codex-review low` (одно из: `none`, `low`, `medium`, `high`, `xhigh`) +- Переопределение модели: `/codex-review model:gpt-5.3-codex` (аргумент с префиксом `model:`) + +## Инструкции + +> **Плейсхолдеры:** `${REVIEW_ID}`, `${CODEX_SESSION_ID}` и `${BASE_BRANCH}` в шагах ниже — это шаблонные плейсхолдеры, НЕ shell-переменные. Подставляй литеральные значения напрямую в каждый tool call. + +### Шаг 1: Определить режим ревью + +Определи, что ревьюить. Проверяй в порядке приоритета: + +**1. Явный аргумент** (`plan`, `code`, путь к файлу) → использовать его. + - Для `plan` → пропустить все git-проверки, перейти к шагу 2 (только REVIEW_ID). + +**2. Claude Code Plan Mode** — если в контексте есть системное сообщение "Plan mode is active" → режим = `plan`, пропустить git. В Plan Mode код не редактируется, поэтому code/code-vs-plan невозможны. + +**3. Автодетект** (без явного аргумента, вне Plan Mode): + +1. Проверь наличие изменений кода (любой непустой — значит есть): + - `git diff --name-only` — unstaged + - `git diff --cached --name-only` — staged + - `git diff --name-only ${BASE_BRANCH}...HEAD` — коммиты ветки +2. Проверь, есть ли план в текущем контексте разговора (из plan mode, задач или обсуждения). + +| Изменения кода? | План в контексте? | Режим | +|----------------|-------------------|-------| +| Нет | Да | **plan** — ревью плана | +| Да | Да | **code-vs-plan** — ревью реализации против плана | +| Да | Нет | **code** — ревью изменений кода | +| Нет | Нет | Спросить пользователя, что ревьюить | + +### Шаг 2: Сгенерировать Session ID и определить base branch + +Сгенерируй уникальный `REVIEW_ID` самостоятельно, формат: `{unix_timestamp}-{случайное_4значное_число}`. +Пример: `1711872000-4821`. **НЕ используй bash** — подставляй значение напрямую в команды следующих шагов. + +**Определение base branch (только для режимов `code` и `code-vs-plan`):** + +Для режима `plan` — пропустить определение base branch, перейти к шагу 3. + +Для остальных режимов определи base branch репозитория: + +```bash +git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|refs/remotes/origin/||' +``` + +Если команда вернула пустой результат (remote HEAD не настроен), используй fallback: + +```bash +git rev-parse --verify main 2>/dev/null && echo main || echo master +``` + +Сохрани результат как `BASE_BRANCH` — используется в `git diff ${BASE_BRANCH}...HEAD` далее. + +### Шаг 3: Подготовить материал для ревью + +**Ревью плана:** + +- Если план уже существует как файл (в `project/`, plan file от Plan Mode, memory или где-то в репо) — использовать путь напрямую. НЕ копировать. В Claude Code Plan Mode план всегда является файлом. +- Если план только в контексте разговора (вне Plan Mode) — записать через **Write tool** в `/tmp/claude-plan-${REVIEW_ID}.md`. +- **Обязательно вывести путь к файлу плана пользователю**, чтобы он мог открыть его в IDE: + `📄 План для ревью: <путь-к-файлу>` + +**Ревью кода:** + +Собери список изменённых файлов: + +1. `git diff --name-only` — unstaged changes +2. `git diff --cached --name-only` — staged changes + +Объедини unstaged + staged (уникальные пути). Если оба пусты: + +3. `git diff --name-only ${BASE_BRANCH}...HEAD` — коммиты ветки (fallback) + +Branch берётся ТОЛЬКО когда нет локальных изменений — иначе контекст раздувается. +Для branch в промпте указывай команду `git diff ${BASE_BRANCH}...HEAD` (полный diff). + +Codex имеет доступ к репо и сам прочитает полный diff и файлы. +В промпт (шаг 4) передай список файлов и какие git diff команды запускать. + +**Много файлов (> 50):** если объединённый список превышает 50 путей, +передай в промпт только git-команды без списка файлов — Codex разберётся сам. + +Если все источники пусты — нет изменений для ревью, сообщи пользователю. + +**Ревью кода против плана:** подготовить путь к плану И собрать список изменённых файлов (как выше). + +### Шаг 4: Сформировать промпт и запустить первый раунд + +Сформируй промпт в зависимости от режима: + +**Промпт для ревью плана:** +``` +Review the implementation plan in . Focus on: +1. Correctness — will this plan achieve the stated goals? +2. Risks — what could go wrong? Edge cases? Data loss? +3. Missing steps — is anything forgotten? +4. Alternatives — is there a simpler or better approach? +5. Security — any security concerns? +``` + +**Промпт для ревью кода (<= 50 файлов):** +``` +Review the code changes in this repo. Changed files: + +<список файлов из --name-only> + +Changes include: . +Run to see the full diffs. Focus on: +1. Bugs — logic errors, off-by-one, null handling, race conditions +2. Edge cases — what inputs or states could break this? +3. Style — does the code follow existing project conventions? +4. Security — injection, credential exposure, unsafe operations +5. Tests — is the change adequately tested? +``` + +**Промпт для ревью кода (> 50 файлов):** +``` +Review the code changes in this repo. +Changes include: . +Run to see changed files and full diffs. Focus on: +1. Bugs — ... +(те же 5 пунктов) +``` + +**Промпт для ревью кода против плана:** +``` +Review the code changes in this repo against the implementation plan in . +Changed files: + +<список файлов или пусто если > 50> + +Changes include: <тип>. +Run to see the full diffs. Focus on: +1. Completeness — does the implementation cover all plan steps? +2. Deviations — where does the code differ from the plan? Are deviations justified? +3. Bugs — logic errors, edge cases, null handling +4. Security — injection, credential exposure, unsafe operations +5. Missing — what from the plan is not yet implemented? +``` + +**Все промпты заканчиваются:** +``` +Be specific and actionable. Reference file paths and line numbers where possible. + +If the work is solid and ready, end your review with exactly: VERDICT: APPROVED +If changes are needed, end with exactly: VERDICT: REVISE +``` + +**Запуск Codex — шаблон команды:** + +Флаги: +- `-m gpt-5.4` — модель (переопределяется аргументом `model:...`) +- `-c model_reasoning_effort=high` — глубина рассуждения (переопределяется аргументом `xhigh`, `low` и т.д.) +- `-s read-only` — Codex только читает, не пишет +- `-o /tmp/codex-review-${REVIEW_ID}.md` — файл для записи ответа + +```bash +timeout 600 codex exec \ + -m gpt-5.4 \ + -c model_reasoning_effort=high \ + -s read-only \ + -o /tmp/codex-review-${REVIEW_ID}.md \ + "ПРОМПТ" +``` + +**Важно:** +- Всегда оборачивай `codex exec` в `timeout 600` (10 минут). Если Codex зависнет — команда завершится с кодом 124. +- Используй параметр `timeout: 620000` в Bash tool для запаса. +- Команда **синхронная**: когда она вернулась, файл `-o` уже готов. **НЕ** используй poll-loop (`while/sleep`). +- Если exit code = 124 (таймаут) — сообщи пользователю и предложи повторить. + +**Пример для режима code** (unstaged изменения в двух файлах): + +```bash +timeout 600 codex exec \ + -m gpt-5.4 \ + -c model_reasoning_effort=high \ + -s read-only \ + -o /tmp/codex-review-${REVIEW_ID}.md \ + "Review the code changes in this repo. Changed files: + +agents/.agents/skills/codex-review/SKILL.md +TODO.md + +Changes include: unstaged changes. +Run git diff to see the full diffs. Focus on: +1. Bugs — logic errors, off-by-one, null handling, race conditions +... +If changes are needed, end with exactly: VERDICT: REVISE" +``` + +**После запуска:** найди в выводе строку `session id: ` и сохрани значение как `CODEX_SESSION_ID` — оно нужно для `resume` в последующих раундах. + +**Примечания:** +- Модель по умолчанию: `gpt-5.4` с `model_reasoning_effort=high`. Пользователь может переопределить через аргументы. +- Всегда `-s read-only` — Codex не должен писать файлы. +- `-o` для захвата вывода в файл. **НЕ** запускай в background — команда сама вернёт управление. + +### Шаг 5: Прочитать ревью и проверить вердикт + +1. Прочитать `/tmp/codex-review-${REVIEW_ID}.md` +2. Показать пользователю: + +``` +## Codex Review — Раунд N (режим: , модель: gpt-5.4) + +[Отзыв Codex] +``` + +3. Проверить вердикт: + - **VERDICT: APPROVED** → перейти к Шагу 8 (Готово) + - **VERDICT: REVISE** → перейти к Шагу 6 (Правки) + - Нет явного вердикта, но всё позитивно → считать одобренным + - Достигнут максимум (5 раундов) → перейти к Шагу 8 с пометкой + +### Шаг 6: Внести правки + +По замечаниям Codex: + +**Для ревью плана:** исправить план — адресовать каждое замечание. Обновить файл плана (или temp-файл). Показать пользователю: + +``` +### Правки (Раунд N) +- [Что изменено и почему, один пункт на замечание] +``` + +**Для ревью кода:** исправить код напрямую — редактировать файлы, запустить тесты если применимо. Показать пользователю: + +``` +### Исправления (Раунд N) +- [Что исправлено и почему, один пункт на замечание] +``` + +**Пропустить** правку, если она противоречит явным требованиям пользователя — отметить это для пользователя. + +### Шаг 7: Переотправить в Codex (Раунды 2-5) + +**Resume — основной путь.** Экономит токены и сохраняет контекст сессии Codex. Свежий `codex exec` без resume — **аварийный fallback**, расходует значительно больше токенов. Использовать только при ошибке resume. + +1. Запусти resume с подавлением stderr (`2>/dev/null`): + +```bash +timeout 600 codex exec resume ${CODEX_SESSION_ID} \ + "I've revised based on your feedback. + +Here's what I changed: +[Список правок] + +Please re-review. End with VERDICT: APPROVED or VERDICT: REVISE" 2>/dev/null +``` + +Используй `timeout: 620000` в параметрах Bash tool. + +**Почему `2>/dev/null`:** `codex exec` по дизайну разделяет потоки — progress/metadata → stderr, финальный ответ модели → stdout. Подавление stderr даёт чистый вывод без CLI-шума. Результат Bash tool = только ревью. + +2. Проверь результат по exit code: + - **exit 0** — успех. stdout содержит чистое ревью. Показать пользователю напрямую (Write в файл и Read **не нужны**). Проверить VERDICT: последняя непустая строка stdout = `VERDICT: APPROVED` или `VERDICT: REVISE`. Если вердикт отсутствует → вывод мог быть обрезан, перейти к Fallback. Далее применить обработку вердикта из Шага 5 (APPROVED → Шаг 8, REVISE → Шаг 6). + - **exit 124** — таймаут. Сообщи пользователю: "Codex не ответил за 10 минут" и предложи повторить. + - **другой exit code** — сообщи пользователю: "Resume не удался (exit code N)". Перейди к Fallback. Диагностика без stderr недоступна — не пытайся парсить stdout как ошибку. + +**Fallback** — если `resume` не сработал (сессия истекла, session ID не захвачен, ошибка): + +1. Собрать список изменённых файлов (аналогично Шагу 3). +2. Запустить свежий `codex exec -o` с описанием предыдущих раундов в промпте. + +Вернуться к **Шагу 5**. + +### Шаг 8: Итоговый результат + +**Одобрено:** +``` +## Codex Review — Итог (режим: <режим>, модель: gpt-5.4) + +**Статус:** ✅ Одобрено после N раунд(ов) + +[Итоговый отзыв] + +--- +**Проверено и одобрено Codex. Ожидает вашего решения.** +``` + +**Достигнут максимум раундов:** +``` +## Codex Review — Итог (режим: <режим>, модель: gpt-5.4) + +**Статус:** ⚠️ Достигнут максимум (5 раундов) — не полностью одобрено + +**Оставшиеся замечания:** +[Нерешённые вопросы] + +--- +**У Codex остались замечания. Просмотрите их и решите, как действовать дальше.** +``` + +### Шаг 9: Очистка + +**В Claude Code Plan Mode:** пропустить любой cleanup (включая deferred). rm вызовет permission prompt. Файлы подчистятся при следующем вызове вне Plan Mode. + +**Вне Plan Mode:** + +```bash +rm -f /tmp/claude-plan-${REVIEW_ID}.md /tmp/codex-review-${REVIEW_ID}.md +``` + +Если пользователь отклонил rm — продолжить без ошибки. + +НЕ удалять файлы планов, которые существовали до ревью (только temp-файлы, созданные этим скиллом). Старые temp-файлы от предыдущих сессий безвредны в /tmp и очистятся ОС при перезагрузке. + +## Правила + +- Claude **активно правит** по замечаниям Codex — это НЕ просто передача сообщений +- Автодетект режима ревью по контексту; аргументы пользователя имеют приоритет +- При явном аргументе `plan` или в Claude Code Plan Mode: пропускать git-проверки и определение base branch +- Resume — основной путь для повторных раундов. Свежий exec — аварийный fallback (дорогой по токенам) +- Cleanup — best-effort: в Plan Mode пропускать, при отказе продолжать без ошибки +- Предпочитать существующие файлы, не создавать лишние копии +- Всегда read-only sandbox — Codex никогда не пишет файлы +- Максимум 5 раундов для защиты от бесконечных циклов +- Показывать пользователю отзывы и правки каждого раунда +- Если Codex CLI не установлен или упал — сообщить пользователю: `npm install -g @openai/codex` +- Если правка противоречит явным требованиям пользователя — пропустить и объяснить почему