refactor(skills): переработан скилл codex-review

- Зачем:
  - скилл работал только с планами; нужна поддержка ревью кода и автодетект режима.
- Что:
  - добавлен автодетект режима: plan, code, code-vs-plan.
  - три отдельных промпта для каждого режима ревью.
  - модель обновлена на gpt-5.4, reasoning effort = high.
  - исправлен сбор diff (условный, не перезаписывающий).
  - инструкции переведены на русский, промпты к Codex оставлены на английском.
  - добавлен вывод пути к файлу плана для открытия в IDE.
  - явные правила парсинга аргументов (model:..., reasoning level, путь к файлу).
- Проверка:
  - /codex-review в Claude Code.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
ddadminandClaude Opus 4.6 committed 2026-03-31 09:40:41 +03:00
1 parent 9b05b4ab82
commit bdccd889fe
1 file changed
+196 -94
+196 -94
View File
@@ -1,44 +1,132 @@
---
name: codex-review
description: Send the current plan to OpenAI Codex CLI for iterative review. Claude and Codex go back-and-forth until Codex approves the plan.
description: Ревью плана или кода через OpenAI Codex. Автодетект режима, итеративные правки до одобрения.
user_invocable: true
---
# Codex Plan Review (Iterative)
# Итеративное ревью через Codex
Send the current implementation plan to OpenAI Codex for review. Claude revises the plan based on Codex's feedback and re-submits until Codex approves. Max 5 rounds.
Отправляет текущую работу в OpenAI Codex на adversarial-ревью. Автоматически определяет, что ревьюить: **план** или **код**. Claude правит по замечаниям Codex и переотправляет до одобрения. Максимум 5 раундов.
---
## When to Invoke
## Когда вызывать
- When the user runs `/codex-review` during or after plan mode
- When the user wants a second opinion on a plan from a different model
- `/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:`)
## Agent Instructions
## Инструкции
When invoked, perform the following iterative review loop:
### Шаг 1: Определить режим ревью
### Step 1: Generate Session ID
Определи, что ревьюить, по контексту и аргументам:
Generate a unique ID to avoid conflicts with other concurrent Claude Code sessions:
**Автодетект (без явного аргумента):**
1. Проверь `git diff --stat` и `git diff --cached --stat` на наличие изменений кода.
2. Проверь, есть ли план в текущем контексте разговора (из plan mode, задач или обсуждения).
| Изменения кода? | План в контексте? | Режим |
|----------------|-------------------|-------|
| Нет | Да | **plan** — ревью плана |
| Да | Да | **code-vs-plan** — ревью реализации против плана |
| Да | Нет | **code** — ревью изменений кода |
| Нет | Нет | Спросить пользователя, что ревьюить |
**Явные аргументы** имеют приоритет над автодетектом: `plan`, `code` или путь к файлу.
### Шаг 2: Сгенерировать Session ID
```bash
REVIEW_ID=$(uuidgen | tr '[:upper:]' '[:lower:]' | head -c 8)
```
Use this for all temp file paths: `/tmp/claude-plan-${REVIEW_ID}.md` and `/tmp/codex-review-${REVIEW_ID}.md`.
### Шаг 3: Подготовить материал для ревью
### Step 2: Capture the Plan
**Ревью плана:**
Write the current plan to the session-scoped temporary file. The plan is whatever implementation plan exists in the current conversation context (from plan mode, or a plan discussed in chat).
- Если план уже существует как файл (в `project/`, memory или где-то в репо) — использовать путь напрямую. НЕ копировать.
- Если план только в контексте разговора — записать в `/tmp/claude-plan-${REVIEW_ID}.md`.
- **Обязательно вывести путь к файлу плана пользователю**, чтобы он мог открыть его в IDE:
`📄 План для ревью: <путь-к-файлу>`
1. Write the full plan content to `/tmp/claude-plan-${REVIEW_ID}.md`
2. If there is no plan in the current context, ask the user what they want reviewed
**Ревью кода:**
### Step 3: Initial Review (Round 1)
Собрать diff в порядке приоритета (использовать первый непустой):
Run Codex CLI in non-interactive mode to review the plan:
```bash
# 1. Unstaged changes
git diff > /tmp/claude-diff-${REVIEW_ID}.diff
# 2. Если пусто — staged changes
if [ ! -s /tmp/claude-diff-${REVIEW_ID}.diff ]; then
git diff --cached > /tmp/claude-diff-${REVIEW_ID}.diff
fi
# 3. Если пусто — все коммиты ветки относительно main
if [ ! -s /tmp/claude-diff-${REVIEW_ID}.diff ]; then
git diff main...HEAD > /tmp/claude-diff-${REVIEW_ID}.diff
fi
```
Если diff всё равно пуст — нет изменений для ревью, сообщить пользователю.
**Ревью кода против плана:** подготовить и путь к плану, И diff.
### Шаг 4: Сформировать промпт и запустить первый раунд
Сформируй промпт в зависимости от режима:
**Промпт для ревью плана:**
```
Review the implementation plan in <plan-path>. 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?
```
**Промпт для ревью кода:**
```
Review the code changes in <diff-path>. You can also read the full files in the repo for context. 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?
```
**Промпт для ревью кода против плана:**
```
Review the code changes in <diff-path> against the implementation plan in <plan-path>.
You can also read the full files in the repo for context. 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
codex exec \
@@ -46,129 +134,143 @@ codex exec \
-c model_reasoning_effort=high \
-s read-only \
-o /tmp/codex-review-${REVIEW_ID}.md \
"Review the implementation plan in /tmp/claude-plan-${REVIEW_ID}.md. 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?
"ПРОМПТ"
```
Be specific and actionable. If the plan is solid and ready to implement, end your review with exactly: VERDICT: APPROVED
**Пример для режима plan** (план в файле `project/TODO.md`):
```bash
codex exec \
-m gpt-5.4 \
-c model_reasoning_effort=high \
-s read-only \
-o /tmp/codex-review-${REVIEW_ID}.md \
"Review the implementation plan in project/TODO.md. Focus on:
1. Correctness — will this plan achieve the stated goals?
...
If changes are needed, end with exactly: VERDICT: REVISE"
```
**Capture the Codex session ID** from the output line that says `session id: <uuid>`. Store this as `CODEX_SESSION_ID`. You MUST use this exact ID to resume in subsequent rounds (do NOT use `--last`, which would grab the wrong session if multiple reviews are running concurrently).
**Пример для режима code** (diff в temp-файле):
**Notes:**
- Use `-m gpt-5.4` with `-c model_reasoning_effort=high` as defaults. If the user specifies a different model or reasoning level (e.g., `/codex-review gpt-5.4` or `/codex-review xhigh`), override accordingly.
- Use `-s read-only` so Codex can read the codebase for context but cannot modify anything.
- Use `-o` to capture the output to a file for reliable reading.
### Step 4: Read Review & Check Verdict
1. Read `/tmp/codex-review-${REVIEW_ID}.md`
2. Present Codex's review to the user:
```
## Codex Review — Round N (model: gpt-5.4)
[Codex's feedback here]
```bash
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 /tmp/claude-diff-${REVIEW_ID}.diff. You can also read the full files in the repo for context. Focus on:
1. Bugs — logic errors, off-by-one, null handling, race conditions
...
If changes are needed, end with exactly: VERDICT: REVISE"
```
3. Check the verdict:
- If **VERDICT: APPROVED** → go to Step 7 (Done)
- If **VERDICT: REVISE** → go to Step 5 (Revise & Re-submit)
- If no clear verdict but feedback is all positive / no actionable items → treat as approved
- If max rounds (5) reached → go to Step 7 with a note that max rounds hit
**После запуска:** сохрани Codex session ID из строки вывода `session id: <uuid>` → переменная `CODEX_SESSION_ID`.
### Step 5: Revise the Plan
**Примечания:**
- Модель по умолчанию: `gpt-5.4` с `model_reasoning_effort=high`. Пользователь может переопределить через аргументы.
- Всегда `-s read-only` — Codex не должен писать файлы.
- `-o` для захвата вывода в файл.
Based on Codex's feedback:
### Шаг 5: Прочитать ревью и проверить вердикт
1. **Revise the plan** — address each issue Codex raised. Update the plan content in the conversation context and rewrite `/tmp/claude-plan-${REVIEW_ID}.md` with the revised version.
2. **Briefly summarize** what you changed for the user:
1. Прочитать `/tmp/codex-review-${REVIEW_ID}.md`
2. Показать пользователю:
```
### Revisions (Round N)
- [What was changed and why, one bullet per Codex issue addressed]
## Codex Review — Раунд N (режим: <plan|code|code-vs-plan>, модель: gpt-5.4)
[Отзыв Codex]
```
3. Inform the user what's happening: "Sending revised plan back to Codex for re-review..."
3. Проверить вердикт:
- **VERDICT: APPROVED** → перейти к Шагу 8 (Готово)
- **VERDICT: REVISE** → перейти к Шагу 6 (Правки)
- Нет явного вердикта, но всё позитивно → считать одобренным
- Достигнут максимум (5 раундов) → перейти к Шагу 8 с пометкой
### Step 6: Re-submit to Codex (Rounds 2-5)
### Шаг 6: Внести правки
Resume the existing Codex session so it has full context of the prior review:
По замечаниям Codex:
**Для ревью плана:** исправить план — адресовать каждое замечание. Обновить файл плана (или temp-файл). Показать пользователю:
```
### Правки (Раунд N)
- [Что изменено и почему, один пункт на замечание]
```
**Для ревью кода:** исправить код напрямую — редактировать файлы, запустить тесты если применимо. Показать пользователю:
```
### Исправления (Раунд N)
- [Что исправлено и почему, один пункт на замечание]
```
**Пропустить** правку, если она противоречит явным требованиям пользователя — отметить это для пользователя.
### Шаг 7: Переотправить в Codex (Раунды 2-5)
Продолжить существующую сессию Codex:
```bash
codex exec resume ${CODEX_SESSION_ID} \
"I've revised the plan based on your feedback. The updated plan is in /tmp/claude-plan-${REVIEW_ID}.md.
"I've revised based on your feedback.
Here's what I changed:
[List the specific changes made]
[List the specific changes]
Please re-review. If the plan is now solid and ready to implement, end with: VERDICT: APPROVED
If more changes are needed, end with: VERDICT: REVISE" 2>&1 | tail -80
Please re-review. End with VERDICT: APPROVED or VERDICT: REVISE" 2>&1 | tail -200
```
**Note:** `codex exec resume` does NOT support `-o` flag. Capture output from stdout instead (pipe through `tail` to skip startup lines). Read the Codex response directly from the command output.
**Примечание:** `codex exec resume` НЕ поддерживает `-o`. Вывод читается из stdout. `tail -200` отсекает служебные строки запуска, но сохраняет длинные ответы.
Then go back to **Step 4** (Read Review & Check Verdict).
Если resume не сработал (сессия истекла) — сделать свежий `codex exec` с контекстом предыдущих раундов в промпте.
**Important:** If `resume ${CODEX_SESSION_ID}` fails (e.g., session expired), fall back to a fresh `codex exec` call with context about the prior rounds included in the prompt.
Вернуться к **Шагу 5**.
### Step 7: Present Final Result
Once approved (or max rounds reached):
### Шаг 8: Итоговый результат
**Одобрено:**
```
## Codex Review — Final (model: gpt-5.4)
## Codex Review — Итог (режим: <режим>, модель: gpt-5.4)
**Status:** ✅ Approved after N round(s)
**Статус:** ✅ Одобрено после N раунд(ов)
[Final Codex feedback / approval message]
[Итоговый отзыв]
---
**The plan has been reviewed and approved by Codex. Ready for your approval to implement.**
**Проверено и одобрено Codex. Ожидает вашего решения.**
```
If max rounds were reached without approval:
**Достигнут максимум раундов:**
```
## Codex Review — Final (model: gpt-5.4)
## Codex Review — Итог (режим: <режим>, модель: gpt-5.4)
**Status:** ⚠️ Max rounds (5) reached — not fully approved
**Статус:** ⚠️ Достигнут максимум (5 раундов) — не полностью одобрено
**Remaining concerns:**
[List unresolved issues from last review]
**Оставшиеся замечания:**
[Нерешённые вопросы]
---
**Codex still has concerns. Review the remaining items and decide whether to proceed or continue refining.**
**У Codex остались замечания. Просмотрите их и решите, как действовать дальше.**
```
### Step 8: Cleanup
### Шаг 9: Очистка
Remove the session-scoped temporary files:
```bash
rm -f /tmp/claude-plan-${REVIEW_ID}.md /tmp/codex-review-${REVIEW_ID}.md
rm -f /tmp/claude-plan-${REVIEW_ID}.md /tmp/claude-diff-${REVIEW_ID}.diff /tmp/codex-review-${REVIEW_ID}.md
```
## Loop Summary
НЕ удалять файлы планов, которые существовали до ревью (только temp-файлы, созданные этим скиллом).
```
Round 1: Claude sends plan → Codex reviews → REVISE?
Round 2: Claude revises → Codex re-reviews (resume session) → REVISE?
Round 3: Claude revises → Codex re-reviews (resume session) → APPROVED ✅
```
## Правила
Max 5 rounds. Each round preserves Codex's conversation context via session resume.
## Rules
- Claude **actively revises the plan** based on Codex feedback between rounds — this is NOT just passing messages, Claude should make real improvements
- Default model is `gpt-5.4`. Accept model override from the user's arguments (e.g., `/codex-review o4-mini`)
- Always use read-only sandbox mode — Codex should never write files
- Max 5 review rounds to prevent infinite loops
- Show the user each round's feedback and revisions so they can follow along
- If Codex CLI is not installed or fails, inform the user and suggest `npm install -g @openai/codex`
- If a revision contradicts the user's explicit requirements, skip that revision and note it for the user
- Claude **активно правит** по замечаниям Codex — это НЕ просто передача сообщений
- Автодетект режима ревью по контексту; аргументы пользователя имеют приоритет
- Предпочитать существующие файлы, не создавать лишние копии
- Всегда read-only sandbox — Codex никогда не пишет файлы
- Максимум 5 раундов для защиты от бесконечных циклов
- Показывать пользователю отзывы и правки каждого раунда
- Если Codex CLI не установлен или упал — сообщить пользователю: `npm install -g @openai/codex`
- Если правка противоречит явным требованиям пользователя — пропустить и объяснить почему