| name | implement-review |
| description | Review loop for staged changes. Detects content type, prepares a review request for Codex (Terminal-relay manual default, opt-in Auto-terminal codex-exec subprocess, or IDE plugin), categorizes feedback, revises, and iterates. Works for code, papers, proposals, or any text-based output. |
Implement-Review
Overview
A review loop for staged changes. Claude Code detects the content type, sends the changes to one or more reviewers, categorizes the feedback, revises, and iterates. Codex is the primary reviewer via three channels: terminal relay (manual copy-paste, default on every platform), Auto-terminal (opt-in codex exec subprocess dispatch), or IDE plugin. Other reviewers (Copilot, Gemini, Claude Code, etc.) are driven ad-hoc by the user through their own UI and only need to honor the Review-<AgentName>.md save contract defined in Phase 1c. Cross-vendor exception: when Claude Code is unavailable and Codex (or the user) is the primary implementer, the Auto-terminal channel can dispatch GitHub Copilot CLI as the reviewer through a parallel dispatch-copilot backend (opt-in; see Codex Channels > Auto-terminal Copilot backend). Bare /implement-review auto is unchanged and still selects Codex.
When to plan-review first
Any complex task benefits from a plan review BEFORE execution, not only writing or code. Plan-first catches architectural holes while they are still cheap to fix. The scope includes: system design, refactors, paper outlines, proposal structure, data-pipeline redesigns, multi-stage debugging strategies, teaching / curriculum planning, release-process changes, migration plans, and anything else where the shape of the work precedes and constrains the execution.
Plan-review is a Phase 0 before the staged-change loop below. If the user asks for a plan review, or if the task clearly meets the signals below, do not apply the staged-change prerequisite in Phase 1 yet. Tell the reviewer to read the plan file directly (or paste the plan contents via the terminal path when the reviewer cannot access the file) and critique the design, not git diff --cached. After the plan has no High findings and no new design blockers, execute the work and resume the normal staged-output review flow at Prerequisites / Phase 1.
When to plan-first
Signals that the round-trip pays off:
- Blast radius is large -- multiple files, cross-cutting concerns, shared state, multiple stakeholders, or the organizing structure of a deliverable.
- Irreversible once executed -- publishes, submissions, deployments, immutable packages, paper submissions, external commitments.
- History shows a pattern -- "got the structure wrong, redo next cycle" has happened on this track before.
- Uncertainty in the approach -- the user is weighing alternatives and wants the design validated, not the execution reviewed.
- Context is unfamiliar -- new codebase, domain, audience, agency, collaborator workflow, or external constraint set, where a wrong assumption can shape the rest of the work.
When to skip plan-first
- Change is small, local, reversible.
- The design is already worked out and only execution feedback is wanted.
- Plan and execution would be the same artifact (three-line bug fix, one-sentence footnote).
Process
- Write the plan to a scratch file
PLAN-<identifier>.md in the most natural location for the task (repo root for code, paper-repo root for Overleaf-style docs, a local scratch directory beside the deliverable for tasks that do not live in git). If the plan lands inside a git worktree, add it to .git/info/exclude so git add -A does not accidentally stage it; outside git, keep it as a clearly named scratch file outside the final deliverable and delete it after review.
- Content varies by task but at minimum include: purpose, non-goals, structure, regression or failure analysis, validation plan, open questions. Keep it terse -- 1 to 3 pages.
- Send the plan through a plan-review prompt (not the staged-change template). Make clear this is a pre-execution design review and that the plan file path or pasted contents are what the reviewer should read; instruct the reviewer to critique the design rather than to run
git diff --cached. Use the normal "Save your complete review to Review-.md" save-contract from Phase 1c.
- Reviewer must answer the scope-challenge questions (see "Adversarial scope challenge" below) before any in-scope correctness review.
- Iterate until the review has no High findings and no new design blockers.
- Then execute (code, draft, revise, deploy).
- Run the normal review cycle on the staged output. It is typically smaller because the architecture was already validated.
- After the work ships or is submitted, delete the PLAN file.
Adversarial scope challenge (mandatory in plan-review)
Plan-review must be adversarial about plan purpose and shape, not about low-probability edge cases. The single biggest plan-review failure mode in this maintainer's history was not "the plan had a bug" — it was "the plan's scope was over-conservative, deferring user value across an extra release cycle worth of process tax." Examples:
- Conservative scope (
v0.5.7 = ref bump only; defer compact to v0.6.0) → the user's real projects would have stayed on large AGENTS.md files for another release cycle. The apparent product ask was a one-line bundled manifest flip, but existing-consumer delivery also required bundled-default drift detection in aa plus real-project upgrade tests. The scope challenge should force reviewers to price both parts: user value now, and the smallest code path that actually delivers it.
- Conservative deferrals also defer the validation that proves the next-step works in real consumers, so the next release inherits the same uncertainty plus a longer review chain.
The plan-review prompt must instruct the reviewer to take an explicit position on:
- Why this exact scope? What user pain (or user opportunity) does THIS scope close? Could a strictly smaller scope close most of it? Could a marginally larger scope close all of it for low marginal cost?
- Are deferrals justified? Every "out of scope / deferred to vNext" carries process tax: another full plan-review + implement + execution-review + CI + publish cycle. Quantify the deferral. If the deferred axis is 1 line of code and the user pain is real, the deferral is probably wrong.
- Is this plan the simplest path? Are there simpler approaches the plan didn't consider — including doing nothing if the user pain is hypothetical?
Plan-review must not default to "no blocker, ready to implement" on the first round when scope is multi-axis or when the plan defers a user-facing axis. The reviewer must either raise a scope challenge OR explicitly state why the scope is calibrated. Skipping the explicit position on these three questions counts as an incomplete review.
Anti-patterns the reviewer must NOT pursue:
- Edge-case fishing: "what if user has unusual config Y?" — only matters when realistic probability × impact > review cost.
- Process ritual: "should this also do Z?" without grounding in user pain or opportunity.
- Adversarial-for-its-own-sake: rejecting plans whose scope IS calibrated, or proposing scope expansion that adds cost without proportional user benefit.
The Phase 1c prompt template Scope-challenge focus: line below carries this contract into every plan-review send.
Illustrative examples (not exhaustive; the category is less important than the pattern)
- System / code: hook or infra design, cross-cutting refactor, state-file schema, cross-platform behavior, release runbook revisions.
- Research output: paper outline with specific aims, contribution claims before methods is written, figure-placement vs argument flow, reviewer response strategy, experiment design across multiple methods, ablation plan.
- Proposal: full outline (aims alignment with merit-review criteria), budget-narrative coupling, broader-impacts framing.
- Operational: migration plan, incident-response playbook, data-pipeline redesign.
- Administrative / teaching: course syllabus structure, lab policy document, committee process design.
The point is not which category -- it is whether the shape of the work precedes and constrains the execution.
Empirical note
In the agent-config 0.1.9 release cycle, two plan-review rounds caught a High-severity design flaw before implementation. The later execution-review rounds were limited to documentation and test polish, avoiding a likely post-ship hotfix.
Codex Channels
Three paths to Codex are supported. Default is Terminal-relay (manual copy-paste). Auto-terminal (codex exec subprocess) is opt-in via the trigger rules in Path selection below. Plugin is user-initiated. The skill picks the channel based on those rules.
Terminal path (default)
The user has a Codex interactive terminal window open alongside Claude Code. Claude Code prepares a copy-pasteable review prompt (summary, diff, lens, round number) and presents it as a fenced text block. The user copies it into the Codex terminal, then relays the feedback back to Claude Code.
Auto-terminal path (opt-in, codex exec subprocess)
When the user opts in via the trigger rules in Path selection below, Claude Code dispatches Codex via codex exec --sandbox danger-full-access as a background subprocess (Bash on POSIX, a transient <state-dir>/run-codex.cmd helper invoked through cmd /c on Windows; see the Script contract invariants subsection for the rationale). The dispatch script writes the prompt to a per-dispatch temp file under %TEMP% / $TMPDIR, feeds it on stdin (codex exec -), and emits a state-dir path to stdout for Phase 2 to consume. Codex writes its review to Review-Codex.md per the save contract; the same Phase 1d auto-watch fires on file appearance.
Trust model and the sandbox flag: Auto-terminal aligns its trust model with Terminal-relay by passing --sandbox danger-full-access to codex exec. In Terminal-relay the user is typing into their own Codex window with full fs / network / shell access; in Auto-terminal Claude Code starts the same Codex on the user's behalf, so granting the same access keeps the two channels behaviorally equivalent. The sandbox flag is also a hard requirement for the channel to work on Windows: Codex 0.130.0's default workspace-write sandbox runner hits CreateProcessAsUserW failed: 1312 when Codex spawns its own git / grep / pwsh subprocesses, which makes the review come back as "could not access files" and surfaces through Phase 2.0 Check 7 / 8 / Substance-2 as a tool-sandbox failure. Scope discipline (review-only, save findings to Review-Codex.md, no commits / pushes / branch operations) is enforced at the prompt level, identical to how Terminal-relay enforces it. For CI / shared / multi-tenant environments where this trust posture is too broad, set CODEX_DISPATCH_SANDBOX to a stricter mode (workspace-write / read-only); the dispatch script honors the env var.
The primary Auto-terminal dispatch preserves the byte-identical prompt invariant with Terminal-relay: the assembled prompt bytes are the same regardless of channel. The extra -c developer_instructions=... value is a Codex CLI configuration argument, separate from the review prompt on stdin, so it does not change those bytes. The dispatch script must NOT call codex exec review, codex exec review --uncommitted, or any other Codex exec subcommand, because those carry Codex's own built-in review prompt template which would compete with the skill's lens-aware prompts. The embedded-diff retry described below is the explicit exception: it is used only after a health-checked Auto-terminal run shows that Codex's own shell tool cannot inspect the repo, usually because CODEX_DISPATCH_SANDBOX has been narrowed in a CI / sandbox-strict environment, but also for the same class of failure if a future Codex version regresses under the relaxed default sandbox.
The Auto-terminal path requires codex on PATH. Probe before dispatch; if absent, warn and downgrade to Terminal-relay for the round. On non-zero codex exec exit, timeout, or stdin-pipe failure (rare on Windows with PowerShell quirks or Bitdefender input-stream interception), downgrade to Terminal-relay for that round; do NOT add a truncated positional-argument fallback, which would break the prompt invariant. Sticky downgrade applies session-wide once Auto-terminal fails: subsequent rounds default to Terminal-relay until the user re-opts-in explicitly.
Auto-terminal has no incremental-checkpoint guarantee. The save contract requires a complete per-round review published atomically, but it does not require intermediate checkpoints. The Codex dispatcher snapshots the prior review mtime and propagates codex exec's exit code, and it does not validate that a fresh review was published. A child that exits 0 without saving therefore leaves <state-dir>/tail and no fresh review, which Phase 2 health checks 1 through 3 reject as missing, stale, or wrong-round. That rejection costs a full Codex run.
Configuration boundary: the dispatched Codex does NOT inherit the user's config.toml. Under the default MCP isolation, the dispatch script passes --ignore-user-config and re-passes -c model_reasoning_effort=$CODEX_DISPATCH_REASONING (default xhigh). Independently of that isolation choice, every dispatch passes a separate -c developer_instructions=... argument telling the child reviewer to skip bootstrap and shared configuration refresh commands and to use the configuration already on disk. The child still reads and follows AGENTS.md; all other project instructions, including the agent-style banned-word list and any NSF rules, remain in force. Everything else in ~/.codex/config.toml is dropped for the dispatched run: model (so the review runs on Codex's built-in default model, not the user's configured one), service_tier, [features].fast_mode, and any custom provider settings. This is a deliberate consequence of the MCP-isolation fix, not an oversight, but it is easy to misread: a user who has tuned config.toml for maximum reasoning will find that none of it reaches their reviews, and the only user-controlled config knob that does is CODEX_DISPATCH_REASONING. To raise the dispatched reasoning effort, set that variable rather than editing config.toml. To hand the dispatched run the full user config instead, set CODEX_DISPATCH_ISOLATE_MCP=off, which is the documented opt-out and also restores the user's MCP servers and plugins.
Reasoning effort is a one-way ratchet: xhigh is the floor, not a target. The dispatching agent may raise a single round to max by passing CODEX_DISPATCH_REASONING=max on that dispatch when it judges the change under review hard enough to earn deeper reasoning: changes that span mirrored copies of one file, touch caching or state lifetime, or would fail silently rather than loudly. It must never pass a value below xhigh. Raising the tier is not free: it roughly doubles wall-clock, so raise the dispatch timeout in the same step, or the round is killed before it writes anything. The asymmetry is deliberate. An agent choosing how hard to review its own work creates a self-grading loop, and its confidence is highest exactly where a quiet error hides. Its discretion therefore runs upward only, so the worst case is a round that was not deepened rather than one that was weakened.
Depth against another round: when the budget would buy either one deeper round or two at the floor, prefer another round while the artifact is still changing. The later round reads the revised state and carries the prior findings with it, so its budget is spent on what the last round actually produced. Raise the tier for the closing round, or when the change is subtle enough that a first read is unlikely to reach it. The relative yield of the two has not been measured, so treat this as a default rather than a finding.
Python interpreter resolution and the verification contract: Before it creates dispatch state or spends a Codex round, dispatch-codex finds a working Python interpreter in this order: ANYWHERE_AGENTS_PYTHON; project .venv or venv; the activated VIRTUAL_ENV; active and discovered conda or Miniforge roots and environments; py -3; then every python3 and python entry on PATH. A configured but broken ANYWHERE_AGENTS_PYTHON is a hard preflight failure. Every candidate must run an isolated probe, return an absolute sys.executable, pass the nonempty-file and non-WindowsApps checks, and execute successfully again through the resolved path. The dispatcher writes the absolute path to <state-dir>/python-interpreter and includes it in the child developer_instructions; the reviewer must use that exact path for Python commands. Resolving nothing at all is a degradation rather than a dispatch failure: the dispatcher warns on stderr, omits the marker file so its absence is unambiguous, tells the reviewer that no interpreter was pre-resolved, and proceeds. The probe exists to keep a reviewer from claiming verification it never ran, and check 10 enforces that independently by refusing a PASS or BLOCK verdict without a VERIFIED status. Reviews also run on repositories whose verification is not Python at all, so a missing interpreter must not make those repositories unreviewable.
PowerShell 7 (pwsh) resolution: The probe enumerates PATH only because Codex's tool router shells out to pwsh by name. It rejects a candidate when its path contains WindowsApps or when the file has zero length. This is a structural check rather than an execution probe because a Microsoft Store App Execution Alias succeeds from an interactive shell and fails only under the dispatched spawn context, where it dies with NTSTATUS 0xC0000142 (-1073741502) in about 30 ms and is retried indefinitely. The dispatcher writes a resolved absolute path to <state-dir>/pwsh-interpreter and names it in the child developer_instructions. Finding nothing is a soft degradation that tells the reviewer to prefer bash, Windows PowerShell 5.1 (powershell.exe), or plain git, as it does for a missing Python interpreter. The Copilot and Claude reviewer backends pass no developer instructions today, so they carry neither the Python nor the pwsh probe; extension to those backends is deferred.
Every saved review must include one standalone Verification status: VERIFIED or Verification status: UNVERIFIED line. VERIFIED is permitted only after at least one relevant verification command completed, and Verification notes must list the exact commands and outcomes. A run with no completed verification uses Verification status: UNVERIFIED together with Commit verdict: UNVERIFIED; it cannot issue PASS or BLOCK. Health check 10 rejects an UNVERIFIED status or verdict, a PASS or BLOCK verdict without VERIFIED, conflicting markers, and VERIFIED paired with notes that explicitly report no execution. A caller can therefore distinguish an execution-backed block from an unsupported one: PASS check-10 verdict=BLOCK verification=VERIFIED plus concrete command outcomes is admissible; FAIL check-10 verdict=BLOCK verification=MISSING or FAIL check-10 verdict=BLOCK verification=UNVERIFIED is a hard intake failure. Review formats that give no commit verdict remain backward compatible in the health check.
Embedded-diff retry for Codex tool-sandbox failure (sandbox-strict environments only): With the default --sandbox danger-full-access Codex can inspect the repo directly and this retry path should never fire. The retry exists as a defensive fallback for two cases: (1) CODEX_DISPATCH_SANDBOX has been narrowed to workspace-write or read-only in a CI / shared environment, and Codex hits windows sandbox: runner error: CreateProcessAsUserW failed: 1312 or a similar internal sandbox error; (2) some future Codex version regresses the same class of failure under the relaxed sandbox. Symptom: dispatch exits 0 and Review-Codex.md is fresh, but the review body says Codex could not run git diff --cached or inspect files; Phase 2.0 flags this through Check 7, Check 8, or Substance heuristics. Procedure: retry Auto-terminal once with an embedded-diff prompt before downgrading to Terminal-relay. Generate the diff from Claude Code's shell by running the exact diff command chosen in Phase 1b, and include it after the normal save contract, summary, lens, focus, and prior findings. Mark the round line with this content: Round N (RETRY: codex-exec sandbox blocked tool access; diff is embedded inline below.) Then add this sentence: Do NOT run git diff or any shell command -- use the embedded diff as the source of truth. The retry may be larger than the primary prompt; keep it limited to the Phase 1b in-scope paths and do not include unrelated staged or working-tree content. Run the same dispatch, auto-watch, and health-check sequence on the retry. Important quality caveat: the retry sees only the embedded diff hunks, not the surrounding file context. Treat retry findings as diff-scoped — they are reliable for hunk-self-contained issues (test coverage gaps, naming, in-hunk regressions) but prone to false positives for claims that depend on non-diff code (e.g., a "this is missing X" finding when X actually exists elsewhere in the file). Because of this elevated false-positive rate, Medium findings from a retry-channel review are subject to mandatory Phase 2.5 verification before being applied (see Phase 2.5 trigger). If the retry produces a usable review, proceed with that review under the Medium-verify discipline; if it also fails or only records blocked verification, downgrade to Terminal-relay.
Script presence is also required: if any of the dispatch-codex / health-check / stall-watch scripts for the current platform is missing (e.g., Phase B has not landed yet in a given checkout), this path is documented-only — Phase 1c automatically downgrades to Terminal-relay without setting sticky downgrade, because the absence is design state, not a runtime failure. See the "Auto-terminal path (opt-in)" subsection in Phase 1c for the script-presence probe specifics.
Auto-terminal Copilot backend (cross-vendor reviewer, opt-in)
The Auto-terminal channel has a second dispatch backend that runs GitHub Copilot CLI as the reviewer instead of codex exec. It exists for the agent-fungibility case in AGENTS.md § "Agent Fungibility": when Claude Code is unavailable and Codex (or the user) is the primary implementer, Codex cannot review its own work and Claude is absent, so Copilot is the reviewer. It is opt-in only via the triggers in Path selection below; a bare /implement-review auto still selects Codex.
The backend is a drop-in. Apply the entire Auto-terminal path (opt-in) mechanics below — script-presence probe, prompt assembly, dispatch invocation, STATE-DIR capture, Phase 1d auto-watch, the Phase 2.0 Health checks, Substance heuristics, and Phase 1d coordination — with two substitutions and one probe swap:
dispatch-codex.{ps1,sh} → dispatch-copilot.{ps1,sh}
- expected review file
Review-Codex.md → Review-GitHub-Copilot.md
- the
codex PATH probe → a copilot PATH probe (falling back to gh copilot)
Everything else is reviewer-agnostic: the STATE-DIR contract, the flags passed to health-check and to await-review (--state-dir, --round, --review-file Review-GitHub-Copilot.md), the stopped-task resolution rule, the silent-advance gating, and the downgrade / sticky-downgrade rules are identical. The save contract already normalizes GitHub Copilot → Review-GitHub-Copilot.md (Phase 1c), so Phase 2 intake needs no change.
Copilot-specific dispatch details, all handled inside dispatch-copilot (no caller change):
- Deployed-script release: Before argument parsing, preflight, or reviewer work,
dispatch-copilot re-executes from a private temp copy. It uses the shared IMPLEMENT_REVIEW_DISPATCH_REEXEC sentinel and IMPLEMENT_REVIEW_DISPATCH_SOURCE_DIR source-directory handoff, removes the copy after exit, and propagates the child status. Preflight and the main run still resolve stall-watch from the deployed source directory.
- Prompt delivery: the assembled prompt (byte-identical to the Terminal-relay block) is written to a temp file and passed as
-p "@<prompt-file>"; Copilot reads the file as its prompt. A long literal -p argument fails, so the file reference is mandatory -- this replaces Codex's exec - stdin feed.
- Binary resolution: prefer standalone
copilot; fall back to gh copilot when copilot is not on PATH. Override with COPILOT_BIN / GH_BIN.
- Trust posture: a narrow allow-list --
--allow-tool=read, --allow-tool=write, --allow-tool='shell(git:*)', plus --add-dir <repo>, scoped to the repo. This is tighter than the Codex backend's danger-full-access: Copilot may read files, run git, and write its review, nothing more. It also stays offline: the Copilot CLI gates URLs only through an all-or-nothing url() permission (a scoped allow-list cannot anticipate which citation or documentation domains a reviewer needs), so for this auto-launched fallback the URL grant is withheld and --no-ask-user denies any un-granted fetch. The Working-method web-verification line is therefore a no-op on the Copilot backend; the Codex backend (network via danger-full-access) and the Claude backend (built-in WebSearch/WebFetch) carry web verification instead. Copilot writes Review-GitHub-Copilot.md itself per the prompt's save contract, exactly as Codex writes Review-Codex.md.
- Pager:
GIT_PAGER=cat is set so Copilot's own git diff does not stall on a pager.
- Auth preflight: With the official CLI and the default
COPILOT_PREFLIGHT=auto, each dispatch first sends a small live prompt that runs and must return before the full review starts. This checks the stored credential, network path, JSON stream, and git-shell permission. It costs one small Copilot request per dispatch because Copilot CLI 1.0.78 exposes no non-interactive auth-status command. applies the same check to a wrapper; skips it.
With read + git access Copilot inspects the repo directly, so there is no embedded-diff retry unique to Copilot; the same Phase 2.0 checks apply with the review-file name swapped.
Auto-terminal Claude backend (cross-vendor reviewer, opt-in)
A second cross-vendor backend mirrors the Copilot one with the reviewer swapped: Codex (or the user) implements, headless Claude Code (claude -p) reviews. Use when Claude is preferred as the reviewer voice, the human orchestrator runs Codex as the primary implementer, or fungibility scenarios where Codex cannot self-review and Copilot is absent. The Claude backend is opt-in only: a bare auto / cli token still selects Codex.
Self-review guard (mechanical). Path selection treats the invoking runtime as authoritative. When this skill is running inside Claude Code, the orchestrator is claude; /implement-review auto claude is rewritten to Codex (or Copilot if Codex is unavailable on PATH) BEFORE any dispatch-claude script is launched, with one user-visible line: Claude backend skipped: Claude Code cannot review its own implementation; using <backend> instead.
The script-level guard in dispatch-claude.{sh,ps1} enforces the same refusal for direct callers that bypass SKILL.md path selection. The scripts exit 2 with the message dispatch-claude: refusing to dispatch (orchestrator=claude; self-review) when ANY of these holds:
IMPLEMENT_REVIEW_ORCHESTRATOR=claude (case-insensitive), OR
IMPLEMENT_REVIEW_ORCHESTRATOR is unset/empty AND CLAUDECODE=1 (Claude Code's documented subprocess marker, set in Bash / PowerShell / hook / tmux / status-line subprocesses).
IMPLEMENT_REVIEW_ORCHESTRATOR=codex and IMPLEMENT_REVIEW_ORCHESTRATOR=user proceed regardless of CLAUDECODE. The CLAUDECODE=1 fall-through exists so a direct script launch from a Claude Code session without setting IMPLEMENT_REVIEW_ORCHESTRATOR does not bypass the guard. The path-selection rewrite + script-level env exit together make the refusal mechanical at both layers; prose alone is not enforceable.
Dispatch detail mirrors the Copilot backend with a relay-save variant:
- Probe:
claude on PATH (override via CLAUDE_BIN); no fallback binary.
- Deployed-script release: Before it creates dispatch state or starts a preflight,
dispatch-claude re-executes from a private temp copy. IMPLEMENT_REVIEW_DISPATCH_REEXEC prevents a loop, and IMPLEMENT_REVIEW_DISPATCH_SOURCE_DIR retains sibling-script lookup at the deployed source directory. The wrapper removes the copy and propagates the child exit status.
- No-model preflight:
CLAUDE_PREFLIGHT=auto (the default) runs claude auth status --json for the official CLI and skips opaque wrappers. API-key, gateway, Bedrock, Vertex, Foundry, and bare modes use claude --version as an availability probe because first-party login state does not describe those credentials. force applies the probe and strict postflight checks to a wrapper; off skips the probe. CLAUDE_PREFLIGHT_TIMEOUT_SECONDS sets the positive-integer timeout, default 60 seconds. A rejected preflight exits 70, or 124 on timeout, before a model request is sent.
- Invocation:
claude -p --permission-mode bypassPermissions --tools "Read,Bash,WebSearch,WebFetch" --add-dir <staged-snapshot> --setting-sources project,local --strict-mcp-config --mcp-config <state-dir>/empty-mcp-config.json --output-format text. The empty MCP config is required for cross-agent review: a user-level Codex MCP server must not auto-start inside the Claude reviewer backend, or the reviewer can recurse into Codex and hang with empty output. Excluding user settings also keeps user-level hooks out of the headless review path. CLAUDE_DISPATCH_BARE=1 may opt into --bare only in environments that provide ANTHROPIC_API_KEY or an explicit apiKeyHelper; do not enable it by default because Claude Code 2.1.153 disables OAuth and keychain auth in bare mode. No --sandbox flag (Codex-only). The long prompt is fed via stdin (POSIX redirection; PowerShell ProcessStartInfo.RedirectStandardInput, avoiding ARG_MAX), but dispatch-claude first wraps it in a relay prompt. This embedded diff covers every staged path, because the dispatcher has no scope argument; use the Claude backend only when the entire staged set is in scope. The dispatcher exports the Git index to <state-dir>/staged-snapshot with git checkout-index -a and launches Claude from that directory; if export fails or the directory is not a git worktree, it falls back to the original working directory and records the reason in . The relay prompt tells Claude not to use Write/Edit tools, permits Bash verification commands in the current directory, appends a dispatcher-provided , and asks Claude to return the complete review as its final answer. The dispatcher writes Claude stdout to ; stderr remains in for diagnostics. On save, the dispatcher trims any preface before ; if Claude omitted the marker, the dispatcher inserts it so Phase 2 intake has a stable first line. This is intentional: live probes showed current Claude Code can hang under unattended when given path-scoped or exact preapproval patterns on Windows, while with lets Claude run tests and verify external facts without exposing Write/Edit tools. The added / are Claude Code built-in tools, not MCP tools, so plus the empty MCP config still keeps a user-level Codex MCP server out of the reviewer; the relay prompt also forbids network shell commands (curl/wget) so network access stays scoped to the two built-in tools. Do not re-add Write/Edit or Bash patterns unless a live probe and contract test cover the exact CLI version and platform. : decomposes its self-review env-check into a sibling helper alongside it. Some Windows AV products (e.g., Bitdefender) score the combination of env-check + stderr-write + non-zero exit + cmdBody construction in a single as a malicious-orchestration signature and AMSI-block the file at parse time. Splitting the guard into a tiny helper file decouples the two patterns and clears the block on a typical Bitdefender install. keeps the guard inline because POSIX AV scanners do not have the same heuristic.
State-dir, stdout contract (STATE-DIR <abs-path> single line), state files (pre-mtime / timestamp / tail / tail.stderr-tmp), and the stall-watch launch match the shared dispatch contract. For Claude, tail growth supplies liveness; the Codex-only terminal suffix is not a Claude completion record.
Plugin path (IDE sidebar)
Codex runs as an IDE plugin with direct access to the repo. The user tells Codex to review in the plugin sidebar (e.g., "review the staged changes"). Codex can see the repository and run the exact diff command chosen in Phase 1b, so no diff needs to be copy-pasted. Plain git diff shows the working tree against the index rather than the staged patch this skill reviews. The user relays Codex's feedback back to Claude Code.
Path selection
- Default: Terminal-relay (manual copy-paste) on every platform. Users who do not opt into another channel get the current Terminal-relay flow without modification.
- User-scoped default override: when the environment variable
IMPLEMENT_REVIEW_DEFAULT_CHANNEL is set (case-insensitive) to auto, cli, or auto-terminal, which is the same synonym set the slash args accept, Auto-terminal becomes that user's default and no per-invocation opt-in token is needed. Read the variable once at Phase 1c entry. This is a per-user, per-machine setting; set it in the env block of ~/.claude/settings.json. It is deliberately not a change to the shipped default: a consumer that does not set it sees today's behavior unchanged, channel line included. Follows the IMPLEMENT_REVIEW_ORCHESTRATOR precedent of a documented, case-insensitive env var read.
- When the variable is unset, empty, or holds an unrecognized value, the shipped Terminal-relay default applies and the variable is never treated as an opt-in, so a typo degrades to today's behavior rather than silently selecting a channel the user did not ask for. The three cases differ only in what is reported: unset and empty are fully unchanged, including the channel line, while an unrecognized value keeps the same channel selection and the same dispatch side effects but adds one clause to the channel line naming the value that was ignored. That added clause is the single intentional deviation from pre-W3 output, and it exists because a silently ignored typo would otherwise leave the user believing Auto-terminal is their default when it is not.
- The override changes only which channel is the default. Every rule in item 2 still applies on top of it: manual override tokens still win, the
codex PATH probe and the dispatch-script presence check still run, and a failed probe still warns and downgrades to Terminal-relay for the round.
- Auto-terminal opt-in triggers, evaluated in detection order at Phase 1c entry:
- Mid-flow override toward manual: "back to manual" / "next round manual" / "use terminal-relay" in the user's most recent message forces Terminal-relay.
- Mid-flow opt-in toward auto: "next round use cli" / "next round auto codex" forces Auto-terminal.
- Slash-arg opt-in:
/implement-review cli, /implement-review auto, and /implement-review auto-terminal are equivalent synonyms; auto is the most natural keyword and is accepted.
When .claude/commands/implement-review.md forwards slash arguments through , evaluate that forwarded argument string the same way as the original slash invocation.
Manual override tokens still win before Auto-terminal opt-in tokens.
Emit one line at Phase 1c entry stating which channel was picked and why (e.g., Channel: Auto-terminal (triggered by "/implement-review auto"; codex on PATH at C:\...\codex.cmd)), so the user can immediately override if it picked wrong. When the channel came from the user-scoped default rather than a per-invocation token, name the variable as the reason, e.g. Channel: Auto-terminal (IMPLEMENT_REVIEW_DEFAULT_CHANNEL=auto; codex on PATH at C:\...\codex.cmd). When the variable held an unrecognized value, say so and state that the shipped default applied, e.g. Channel: Terminal-relay (IMPLEMENT_REVIEW_DEFAULT_CHANNEL="plugin" not recognized; shipped default applied). Naming the source matters because a user-scoped default is invisible at the call site: without it, a user who set the variable months ago cannot tell why a round dispatched itself.
Prerequisites
Begin each run by showing the cross-agent usage snapshot, so the quota situation is visible at this run (Codex has no statusLine, so an implement-review run is where a Codex-primary session surfaces it). Invoke agent-quota with a real Python interpreter matched to your shell. Do not execute the bare ~/.claude/agent-quota.py path (it hits the Windows Store launcher shim), and do not call the extensionless ~/.claude/hooks/_python wrapper from PowerShell (it is a Bash script and runs there as a silent no-op). In Bash or Git Bash, use "$HOME/.claude/hooks/_python" "$HOME/.claude/agent-quota.py". In PowerShell, run the script with your project Python directly, for example & <project-python> "$HOME/.claude/agent-quota.py". In either shell you may instead run the repo copy with the project's Python (scripts/agent-quota.py, or .agent-config/repo/scripts/agent-quota.py in a consumer). Show its two-row Claude / Codex · 5h / 7d output. Read the percentages as remaining quota (headroom left), not consumed: a high value such as 93% left means plenty of quota is still available and is not a reason to downgrade the channel or stop the review; only a low remaining figure near 0% left signals real quota pressure. It is a local disk read with no API or token cost (about 0.1s), so it is fine to run every time; if neither the script nor a Python runner is available, skip silently and never block the review on it.
At skill start, check for staged changes (git diff --cached). If nothing is staged but unstaged or untracked changes exist, list them and ask the user whether to stage all (git add -A), stage specific files, or abort. Do not auto-stage without confirmation — untracked files may be sensitive or unrelated. If there are no changes at all, there is nothing to review -- inform the user and stop.
Pre-Review Checks (optional)
Before sending staged changes for review, run automated checks that catch mechanical issues locally. This lets reviewers focus on content and judgment calls instead of issues a script could find. Skip this phase if the user says to proceed directly, or if the project has no relevant tooling.
| Content type | Checks |
|---|
| LaTeX paper or proposal | Compile. Scan the log for overfull/underfull box warnings and undefined references. Report counts. |
| Anonymized submission | Grep staged files for author names, GitHub/lab URLs, institutional names, and tool names. Source these from the project's de-anonymization checklist if one exists; otherwise use the git user name, institution domain, and any names in the paper's author metadata or \author{} block. |
| Code | Run the project linter and type checker if configured. |
Prose (.md / .rst / .txt / .tex, or prose-heavy diff) | Run <python> <scripts-dir>/style-audit.py --repo <repo>, resolving <scripts-dir> through the same lookup order as the other scripts. It finds the staged prose itself, skips anything under agent-io, and reports file:line:col RULE detail for every deterministic rule. It then names the rules it covered only in part, and the rules no detector here reaches, so a partial audit does not read as a clean pass. RULE-07 antithesis (not just ... but, it is not ... it is, clause-level X, not Y) is among the ones no detector reaches; audit that one by reading the rule pack. Fix locally before sending to the reviewer. |
Report any findings to the user before proceeding to Phase 1. Findings here do not go to the reviewer; fix them locally first.
The style audit runs on content, and never gates the round. Run style-audit.py whenever the staged diff carries prose, so skipping it is a decision someone made rather than a default. The script always exits 0, including when it finds violations and when agent_style is absent, so no step in the loop can fail on it. Style findings stay out of the reviewer's prompt, out of the Round history Still open list, and out of the verdict.
That placement is deliberate, because three properties would otherwise let mechanical findings hold the loop open. RULE-12 fires on any sentence over thirty words, so splitting one long sentence can produce another, and the rule has no fixed point. A prose fix is a diff change, and a diff change earns another round under the normal rules. Handed a list of style findings, a reviewer will treat them as findings and ask for them to be resolved. Running the audit before Round 1 costs zero rounds. Inside the loop is where each of those three turns into one.
Phase 1: Prepare and Send Review
1a. Detect content type
Inspect the file extensions in the staged diff to classify the change:
| Extensions | Content type |
|---|
.py, .js, .ts, .go, .rs, .java, .c, .cpp, .h, .sh, .yaml, .json, .toml | code |
.tex, .bib (in a paper or manuscript directory) | paper |
.tex, .bib (in a proposal or grant directory) | proposal |
.md, .rst, .txt (in a proposal or grant directory) | proposal |
| Everything else or mixed | general |
If the diff spans multiple types, pick the dominant one. The user can override by saying, e.g., "review this as a proposal." For proposals, also ask which agency lens to apply (NSF or NIH) since they use different evaluation frameworks.
1b. Build the review context
Prepare a review request with:
- Summary -- one to three sentences on what changed and why.
- Diff scope -- choose the exact diff command before assembling the prompt, and list the changed files. If every staged path is in scope, use
git diff --cached. If staging is broader than the review scope, use git diff --cached -- <in-scope paths> and list the staged paths that are explicitly out of scope, so the reviewer is not left inferring the boundary. This command applies to Terminal-relay, Plugin, Codex Auto-terminal, and Copilot Auto-terminal. The Claude Auto-terminal backend cannot honour it: its dispatcher embeds a bare git diff --cached in the relay prompt and has no scope argument, so use that backend only when every staged path is in scope. Path scoping keeps unrelated staged content out of the primary review input before the run; health checks 1 through 3 catch a missing or stale review only after one has been spent. Do not paste the diff inline in the primary prompt; this keeps the prompt compact and avoids bloat across rounds. The only exception is the Auto-terminal embedded-diff retry (a sandbox-strict-environment fallback when Codex's own shell tool cannot read the repo), described in Codex Channels, which must embed the same in-scope diff selected here.
- Splitting the round -- use a single pass by default. Split only when no shared contract crosses the boundary; keep mirrored platform files, a script and its tests, and a source and its generated or vendored copies inside one reviewer's scope. Independence is a judgement made before the split, so verify it afterwards rather than assuming it held: re-read the boundary you drew, and run the mechanical checks that apply, such as
scripts/check-parity.sh. See anywhere-agents#41.
- Review lens -- the content-type-specific criteria from references/review-lenses.md. If a focused sub-lens or agency-specific lens fits better than the full lens, use it (e.g.,
paper/formatting for a layout-only change, proposal/nsf when the agency is known). See the lens tables in that file.
- Additional focus -- specific concerns beyond the generic lens. This is often the highest-value part of the prompt because it catches real bugs that generic criteria miss. Always ask the user explicitly rather than guessing. Recurring project concerns belong here: phased-development coupling, anonymization checks, page-limit compliance, budget-to-narrative consistency, terminology drift, benchmark-claim calibration, overclaim flagging. If there are no project-specific concerns this round, write "none" rather than padding the line. Examples: "check that all appendix URLs are anonymized", "verify Year 3 budget matches the narrative", "flag any overclaim in intro / conclusion", "watch for Phase 1 / Phase 2 coupling issues".
1c. Send to reviewer
All review prompts sent to the reviewer (regardless of channel) must include a save instruction at the very top of the prompt, before the summary or diff, so the reviewer sees it first. This lets Claude Code read the feedback directly from the file, and lets the user read or forward it without copy-pasting from chat. The save instruction is:
IMPORTANT: Save your complete review to Review-<YourAgentName>.md in the repository root. Normalize <YourAgentName> as follows: choose the stable agent or product name visible to the user (not a transient model/version list unless that is the only identity available); convert any run of whitespace to a single dash; delete every character except ASCII letters, digits, and dashes; collapse repeated dashes; trim leading and trailing dashes. Examples: Codex → Review-Codex.md, GitHub Copilot → Review-GitHub-Copilot.md, Gemini 3.1 Pro → Review-Gemini-31-Pro.md, Claude Code → Review-Claude-Code.md. If the normalized result is empty or you cannot identify your own name with reasonable confidence, use Review-Unknown.md and note the uncertainty at the top of the file. Publish each round atomically: write the complete review to a temporary file in the same directory, then rename that file over Review-<YourAgentName>.md. Do not clear the target first, and do not append across rounds. A reader then sees either the previous complete review or this one, and never a hole. A round interrupted before it finishes leaves the previous round's review intact, which is when it matters most. Use plain Markdown. Start the file with a <!-- Round N --> comment (matching the round number below) so the reader can verify freshness. Begin the review with a short "Verification notes" section (paragraph or short bulleted list; "Validation notes" is also an accepted name) stating the exact commands and outcomes (e.g., latexmk built cleanly, pytest pyod/test/... 5 passed, checked citation X against arXiv:YYYY). Then add one standalone Verification status: VERIFIED or Verification status: UNVERIFIED line. Use VERIFIED only when at least one relevant verification command actually completed. If no relevant command completed, write Verification notes: none., Verification status: UNVERIFIED, and Commit verdict: UNVERIFIED; do not issue PASS or BLOCK. Separate findings into New (raised for the first time) and Previously raised (with status: Fixed, Still open, Reopened, or Deferred) sections. On Round 1, the Previously raised section may be omitted or shown as "None." Then include the file/diff scope, review lens, findings in priority order, and concrete recommended changes. Do not skip this step.
Recording the expected reviewer set: Before presenting the prompt, record two pieces of Claude-side state that Phase 2 will use:
- Expected reviewer set: the reviewers the user intends to invoke this round. Infer from, in order of preference: (1) explicit user statement in this or a recent turn (e.g., "I'll run Codex and Copilot", "just Gemini", "only Codex"); (2) prior-round pattern with no change announced; (3) channel default of
{Codex} when only Terminal-relay, Auto-terminal, or Plugin has been engaged and no other reviewer is in scope. If none of these produces a confident set, ask the user which reviewers they plan to invoke before presenting the prompt; do not guess.
- Phase 1c emission time: the timestamp when the prompt is shown to the user. Used as an mtime tiebreaker in Phase 2 for files that cannot be classified by expected set alone.
Phase 2 uses the expected set as a scope partition axis and the emission time as a freshness tiebreaker.
Terminal path: Present a compact, copy-pasteable review prompt as a fenced text block. Keep the prompt under 20 lines. Tell the reviewer to run the exact diff command chosen in Phase 1b rather than pasting the diff inline; this prevents prompt bloat as rounds accumulate. The abbreviated save instruction below inherits the full contract stated above (statuses, Round 1 behavior, required sections).
IMPORTANT: Save your complete review to Review-<YourAgentName>.md in the repo root. Normalize your name: pick the stable product name, whitespace → one dash, keep only ASCII letters/digits/dashes, collapse repeated dashes, trim edge dashes. Examples: Codex → Review-Codex.md, GitHub Copilot → Review-GitHub-Copilot.md, Gemini 3.1 Pro → Review-Gemini-31-Pro.md, Claude Code → Review-Claude-Code.md. Use Review-Unknown.md if the result is empty or you cannot identify yourself, and note the uncertainty at the top of the file. Write the complete review to a temporary file in the same directory, then rename it over that filename rather than clearing the target first. Start with <!-- Round N -->. Begin with Verification notes listing exact commands and outcomes. Add one standalone Verification status: VERIFIED or Verification status: UNVERIFIED line. Use VERIFIED only after at least one relevant verification command completed. With no completed verification, write Verification notes: none., Verification status: UNVERIFIED, and Commit verdict: UNVERIFIED; do not issue PASS or BLOCK. Include file/diff scope and review lens. Separate findings into New and Previously raised (Fixed / Still open / Reopened / Deferred) sections. For High-priority findings, include an exact rewrite with file:line. See skills/implement-review/references/example-reviews/ for expected depth.
Review staged changes in <repo path>. Round <N>.
Run `<diff command chosen in Phase 1b>` to see the diff. Files changed: <in-scope file list>.
<When staging is broader than the review scope, add:> Staged but out of scope: <excluded staged paths>.
Summary: <one to three sentences>
Lens: <content type> — <abbreviated criteria, sub-lens, or agency-specific lens name>
Focus: <additional focus if any, or omit line>
Working method (optional, only if your runtime supports it): for a large or multi-file diff, you may parallelize across scopes that satisfy Phase 1b item 3, keeping every shared-contract pair in one reviewer's context and re-reading that boundary while consolidating; for any finding that rests on a checkable external fact (citation, link, library or API behavior, version), use web search to verify it before asserting, and record what you checked in Verification notes.
Scope-challenge focus (mandatory; reviewer must take an explicit position): (a) Why exactly this scope — what user pain or opportunity does it close, could a smaller scope close most of it, could a marginally larger scope close all of it for low cost? (b) Is each "out of scope / deferred to vNext" worth its process tax (extra plan-review + implement + execution-review + CI + publish cycle) versus inclusion now? (c) Is this plan the simplest path? Be adversarial about purpose and shape; do NOT fish for low-probability edge cases.
<When the staged diff spans two or more variant targets:>
Variant targets:
- TARGET A: <path or pattern>
- TARGET B: <path or pattern>
(Review each target in its own top-level section and add a Cross-variant drift check at the end.)
<For rounds 2+:>
Prior findings:
- <finding> (Resolved | Still open | Deferred | Refuted | Inconclusive)
Then wait for the user to relay the reviewer's feedback or confirm that the reviewer has finished (see Phase 2 for how Claude Code picks up the review).
Auto-terminal path (opt-in): When the user has opted in per the trigger rules in Codex Channels > Path selection, first check whether the required Auto-terminal scripts exist. Look up all three script pairs in this order: repo-local skills/implement-review/scripts/, then pack-deployed .claude/skills/implement-review/scripts/, then bootstrapped .agent-config/repo/skills/implement-review/scripts/. Required scripts are dispatch-codex.{ps1,sh}, health-check.{ps1,sh}, stall-watch.{ps1,sh}, and await-review.py. The last one is required because a stopped task is resolved through it. Without it the round cannot tell a live reviewer from a dead one, which is the failure this channel is most exposed to. await-review.py is Python and has no shell variant, so the probe also has to find an interpreter that runs it. Check <state-dir>/python-interpreter when a previous dispatch recorded one, otherwise resolve one the way dispatch-codex does. A missing interpreter is the same class of absence as a missing script. Say Auto-terminal needs a Python interpreter for await-review.py and none was found; using Terminal-relay for this round. and downgrade without setting sticky downgrade. This matters beyond Python projects: the Copilot and Claude backends never write python-interpreter, and dispatch-codex itself proceeds after failing to resolve one. If any required script for the current platform is missing, say Auto-terminal is documented but unavailable until the Phase B scripts are present; using Terminal-relay for this round. Then downgrade to Terminal-relay without setting sticky downgrade (the absence is design state, not failure; sticky should kick in only for real Auto-terminal runtime failures).
If the scripts are present, Claude Code does NOT present a copy-paste prompt block. Instead, the skill:
- Probes
codex on PATH (Get-Command codex on Windows, command -v codex on POSIX). If absent: warn the user and downgrade to Terminal-relay for this round.
- Probes session sticky-downgrade state. If active: downgrade to Terminal-relay (silent unless the user asks why).
- Assembles the prompt: byte-identical to the fenced Terminal-relay block above (same save contract, lens, focus, scope-challenge focus, prior findings).
- Writes the prompt to
<scratch>/agent-io/round-<N>-prompt.txt under %TEMP% / $TMPDIR. See Where the round's own files go below for why the directory is named.
- Invokes
skills/implement-review/scripts/dispatch-codex.{ps1,sh} (repo-local first, then pack-deployed under .claude/skills/implement-review/scripts/, then bootstrapped under .agent-config/repo/skills/implement-review/scripts/) with --prompt-file <temp-path>, --round <N>, --expected-review-file Review-Codex.md. Run in the background, and size the timeout to the reasoning tier rather than to one number: about 20 minutes (1200000) at xhigh, and about 45 minutes (2700000) at max, because raising the tier roughly doubles wall-clock. On POSIX use the Bash tool. On Windows the script is dispatch-codex.ps1, and the PowerShell tool caps a single call at 600000, which is below both figures; dispatch through the Bash tool there as well, or expect the harness to background the call at its cap. The dispatch script internally launches stall-watch.{ps1,sh} in the background to monitor tail-file growth. Its default 600-second silence threshold records <state-dir>/stall-warning without killing any process. A terminal Codex response-stream suffix records <state-dir>/stream-death and invokes the bounded reap contract below.
- Reads the dispatch script's stdout: it emits exactly one line
STATE-DIR <abs-path> (the only stdout line). Capture this path for Phase 2 to pass to health-check --state-dir <abs-path> --round <N> --review-file Review-Codex.md. All three flags are required by health-check.py's argparse (--round has no default, --review-file defaults to Review-Codex.md but pass it explicitly so the invocation is unambiguous when read fresh from SKILL.md); omitting errors out before any check runs. All other dispatch diagnostics plus the last-80 codex-exec lines go to the script's stderr.
Where the round's own files go: this skill writes two kinds of file around the reviewer. One is the prompt handed over, the other is the output captured back. Both belong under an agent-io directory inside the session scratch area. Step 4 writes <scratch>/agent-io/round-<N>-prompt.txt, and a captured round output goes to <scratch>/agent-io/round-<N>.txt. That directory name is a declaration the writing-style hook reads, and it skips any path carrying the segment. Neither file is this skill's prose to rewrite: a prompt is an instruction to another agent, and a captured review is another agent's words. Files written for a human reader, such as PLAN-<identifier>.md or the review body itself, stay outside agent-io and stay covered.
Bounded retry after confirmed Codex stream death: IMPLEMENT_REVIEW_STREAM_RETRY_LIMIT sets the maximum number of automatic redispatches, default 1; 0 disables them. The dispatcher records the effective limit and current count in the state directory. A retry begins only when both <state-dir>/stream-death and <state-dir>/stream-retry-request exist, the count is below the limit, and <state-dir>/stream-reap-complete confirms the old worker tree has been reaped. The dispatcher archives the failed attempt under <state-dir>/attempt-N, clears the active attempt markers, updates the timestamp and count, and runs the same prompt again. It reuses the original state directory, so the initial STATE-DIR <abs-path> remains the only dispatcher stdout line. Each redispatch writes AUTO-REDISPATCH attempt=N/M reason=codex-response-stream-disconnected state-dir=<abs-path> to dispatcher stderr; auto-watch mirrors that schema in its own output after the count advances. Silence can write stall-warning and wake the coordinator, but it never requests or starts a retry.
On Auto-terminal failure (non-zero exit, timeout, missing fresh review file, or Health check fail): downgrade to Terminal-relay for that round AND set sticky downgrade for the rest of the session. A harness notification that the background task was stopped is not one of these triggers, and neither is a watcher that stopped with it. Resolve that case with await-review first (see Phase 1d); only its DEAD verdict is an Auto-terminal runtime failure. With the default --sandbox danger-full-access Codex can inspect the repo directly and tool-sandbox failures should be vanishingly rare; if one does occur (typically only when CODEX_DISPATCH_SANDBOX has been narrowed in a CI / shared environment) and Phase 2.0 surfaces it via Check 7 / 8 / Substance heuristics with dispatch exit 0, use the embedded-diff retry once before setting sticky downgrade (see "Embedded-diff retry for Codex tool-sandbox failure" in Codex Channels for the procedure and the diff-scoped-findings caveat). Do not add a truncated positional-argument fallback.
Script contract invariants (apply to all dispatch-codex / health-check / stall-watch .sh and .ps1 variants):
- State-dir lifecycle: created once per logical dispatch by
dispatch-codex under %TEMP% / $TMPDIR; preserved on any WARN or FAIL outcome so the user can inspect; deleted only after a clean Phase 2 intake completes silently. State-dir names carry <pid>-<nonce> and are unique across unrelated dispatches. Automatic stream-death attempts reuse the same directory and preserve each failed attempt under attempt-N, which keeps the single STATE-DIR stdout contract stable.
- Deployed-script release: before it creates dispatch state or starts the reviewer,
dispatch-codex re-executes from a private temp copy. IMPLEMENT_REVIEW_DISPATCH_REEXEC prevents a loop, and IMPLEMENT_REVIEW_DISPATCH_SOURCE_DIR keeps sibling-script lookup at the original deployed directory. The wrapper removes the temp copy after the dispatch and propagates its exit status. This releases the deployed dispatch-codex.sh path before Bash can block a composer replacement.
- Timestamp units: all values in
<state-dir>/timestamp and <state-dir>/pre-mtime are integer Unix epoch seconds. Every producer writes integers (date +%s, ToUnixTimeSeconds()), and both readers parse with int() and reject a float spelling as a state-contract failure, so a fractional value is not a permitted alternative spelling. mtime comparisons happen in UTC; cross-platform stat is the implementer's responsibility. POSIX may use stat -c %Y (GNU) or stat -f %m (BSD/macOS). PowerShell must convert LastWriteTimeUtc to Unix epoch seconds, for example $utc = (Get-Item -LiteralPath <path>).LastWriteTimeUtc; ([DateTimeOffset]$utc).ToUnixTimeSeconds() (two-step form, avoids cast-precedence confusion) or an equivalent Unix-epoch conversion. Do NOT write Windows FILETIME values from ToFileTimeUtc() (FILETIME is 100-nanosecond ticks since 1601-01-01, not Unix epoch; mixing units across .ps1 and .sh would silently break Health check 2 freshness comparisons).
- stdin invocation shape: POSIX uses redirection with the prompt file as stdin (
codex exec --sandbox "$CODEX_DISPATCH_SANDBOX" [isolation args] -c "developer_instructions=..." - < <prompt-file>). PowerShell writes a transient helper with the same argument order and handle redirection, then invokes it through . These shell-level redirections preserve the byte-identical prompt invariant and let Codex child processes inherit the logon-session token cleanly. The value comes from (default ); see the Auto-terminal Trust-Model paragraph above for why. By default both variants pass (R from , default ) so a user-level Codex MCP server, plugin, or hook does not auto-start inside the headless reviewer and recurse into a nested codex, the failure recorded as agent-config#1; set to opt out and run with the full user config (do this if the review needs the user's or a custom , which isolation drops and does not re-pass). Independently of isolation, both variants pass the separate argument before the trailing . That argument suppresses only bootstrap and shared configuration refresh in the child session; it leaves and all other project rules active. Because it is CLI configuration and the prompt still arrives only through input redirection, it does not modify the prompt-file bytes. is used because the narrower is deep-merged by Codex 0.139 and leaves the configured servers running. It also resets the reasoning effort, so the re-pass restores the dispatcher's cross-model compatibility floor ( by default) while the model stays Codex's built-in default. Set on GPT-6 Astra or GPT-5.6 for maximum single-agent reasoning. Use on GPT-6 Astra, GPT-5.6 Sol, or GPT-5.6 Terra only when automatic task delegation is intended. Re-passing is deliberately skipped: hardcoding the maintainer's tier would make every round fail for a consumer whose account lacks it, so a temp- sanitizer (config minus the MCP tables) is the documented path to full config-preserving isolation. This shape replaced an earlier and a variant: the pipe form could inject a BOM under PS 5.1, and routes through which strips the token (Codex's git subprocess then failed with Windows error 1312). Neither variant may use command substitution () or positional-arg passing of the full prompt, because both hit ARG_MAX on Windows. Path values interpolated into the cmd helper must escape to so cmd does not env-expand them, and the helper is written as UTF-8 (no BOM) with a prefix so non-ASCII paths survive cmd's codepage layer.
Evidence for latency claims
<state-dir>/tail is a transcript for a human to read. It has no timestamps, and the reviewer's prose can quote the same error strings that appear in real diagnostics. Counting occurrences in a tail therefore does not measure elapsed time, call count, or failure frequency. For any claim about where time goes, use ~/.codex/sessions/**/rollout-*.jsonl. Rollout records carry per-event millisecond timestamps and token counts, and a run can be joined to them by session id. A latency claim without rollout evidence should not be acted on.
Two corollaries matter when reading retained tails. A single tail block can represent one call within a parallel batch; repeated material inside that block does not establish several separate calls. When the diff under review includes this skill, the skill's own diagnostic strings appear in the tail as reviewed content. Any cross-tail scan must exclude that case.
Plugin path: Tell the user the changes are ready for review and provide the same review prompt content used by the Terminal-relay path (save contract first, then round, diff scope, summary, lens, focus, scope-challenge focus when applicable, variant targets when applicable, prior findings for rounds 2+). The user pastes the same content into the plugin sidebar; the surrounding Markdown fence may be omitted if the plugin UI does not need it, but the prompt content itself must match Terminal-relay byte-for-byte (after the optional fence-strip). This preserves the cross-channel prompt invariant: Codex receives the same instructions regardless of channel.
Example instruction to the user:
Paste the same review prompt shown for Terminal-relay into the Codex plugin sidebar. The plugin can inspect the repository directly (so the diff is visible without copying), but the prompt content itself must still include the save contract, round number, files changed, summary, lens, focus, scope-challenge focus when applicable, variant targets when applicable, and prior findings when applicable. Ask the plugin reviewer to save the complete review to Review-<YourAgentName>.md in the repo root using the normal Phase 1c save contract.
Then wait for the user to relay the reviewer's feedback or confirm that the reviewer has finished.
1d. Auto-watch (Terminal-relay and Auto-terminal channels)
After Phase 1c emits the Terminal-relay prompt or dispatches Auto-terminal (and records the expected reviewer set + emission/dispatch time), the skill automatically launches a background watcher that detects when the reviewer writes Review-<expected>.md and resumes Phase 2 — eliminating the manual "done" relay. The watcher runs by default for both channels; the user does not need to confirm. To opt out, the user can say so explicitly (e.g., "stop auto-watch", "manual mode this round") and the skill terminates the background process and falls through to the wait-for-user path. Plugin path skips this subsection entirely (IDE plugins typically have the file open and gain little from auto-watch).