Skip to content
Back to skills

Review

ASecurity

Multi-agent code review of local Python files, directories, or the current git diff covering architecture, tests, performance, docs, lint, security, and API design. Scope: Python source files in local working tree. Python-file-free targets (pure JS/TS/Go/Rust projects) are out of scope. TRIGGER when: user asks to review local Python files, a directory, or the current git diff/working-tree changes, with no GitHub PR number involved; phrases: "review this", "review my changes", "code review thi...

  • 31 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added September 2, 2026
ai-agentspythonrustgoshellbashrefactoringcode-reviewgitapisecurity

Works with

  • terminal
  • api

Security analysis

A100/100

Pro scans all 3 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add Borda/AI-Rig --skill review --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Review?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Review
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/borda-review-9df4c1f7/badge)](https://www.skillsdirectory.com/skills/borda-review-9df4c1f7)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: review
description: 'Multi-agent code review of local Python files, directories, or the current git diff covering architecture, tests, performance, docs, lint, security, and API design. Scope: Python source files in local working tree. Python-file-free targets (pure JS/TS/Go/Rust projects) are out of scope. TRIGGER when: user asks to review local Python files, a directory, or the current git diff/working-tree changes, with no GitHub PR number involved; phrases: "review this", "review my changes", "code review this diff", "review src/foo.py". SKIP when: input is a bare GitHub PR/issue number (use `/oss:review <PR#>`, requires oss plugin); user wants the Codex-native tiered `$code-review` workflow (codex-rig plugin, JSON artifact + specialist fan-out) — different toolchain; implementation work (use `/develop:fix` or `/develop:feature`); non-Python-only projects.'
argument-hint: '[python-file|dir] [--no-challenge] [--challenge] [--codemap] [--no-codemap] [--worktree] [--full] [--keep "<items>"]'
allowed-tools: Read, Write, Bash, Grep, Glob, Agent, Skill, TaskList, TaskCreate, TaskUpdate, AskUserQuestion, EnterWorktree, ExitWorktree
disable-model-invocation: true
effort: high
---

<objective>

Comprehensive code review of local files or working-tree diff. Spawns specialized sub-agents in parallel, consolidates findings into structured feedback with severity levels.

NOT for:

- GitHub PR review (use `/oss:review <PR#>` (requires oss plugin))
- GitHub thread analysis or PR reply drafting (use `/oss:analyse <PR#>` (requires oss plugin))
- implementation (use `/develop:feature` or `/develop:fix`)
- `.claude/` config changes (use `/foundry:manage` (requires foundry plugin) or `/foundry:audit` (requires foundry plugin))
- non-Python-only projects (zero Python source files — pure JS/TS/Go/Rust) — review toolchain assumes Python/pytest
- Python test-only targets where diff contains only test files (no `src/` or top-level `.py` source outside `tests/`) — review is uninformative

Polyglot projects with Python source review Python files only.

</objective>

## Improvement claim evidence

Assess every material improvement claimed in the request, PR title/body or reviewed documentation, including claims without supplied benchmarks.

- Record each claim, its scope and evidence in the existing review report.
- Include the relevant claims, supplied evidence and this measurement protocol in reviewer context; the parent reconciles claim dispositions in the final report even when a specialist is omitted.
- Route performance claims to the performance dimension when admitted by the existing selection rules; the parent retains claim coverage when that dimension is not selected.
- Preserve existing scope, fan-out limits and execution permissions; inspection-only reviewers hand feasible reproduction checks to the parent.
- Behavioral claims need targeted tests; correctness tests alone do not prove performance or model-quality gains.

Bind numerical comparisons to exact baseline/candidate revisions, commands, representative workload/data, software, relevant hardware and settings. Attribute supplied results separately from independent reproduction. Use a predefined practical tolerance, appropriate warmup and accelerator timing, repeated measurements, raw samples, sample counts, summary statistic and variability. Check correctness and material tradeoffs. Explain hardware relevance and limit conclusions to measured workloads/devices.

Shared local CPU/GPU, memory pressure or swapping, I/O contention and thermal/power changes can confound measurements.

- Record relevant observable contention and unavailable observations; never assume isolation.
- Run comparable baseline/candidate samples sequentially in paired, alternating or randomized order; avoid concurrent competing benchmarks or agent-owned heavy checks.
- Bound reruns and retain noisy attempts and exclusion criteria.
- More samples do not remove systematic bias.
- Never stop unrelated processes or change system resource controls without existing authorization.
- If noise or unequal contention could explain the effect, label measurements inconclusive and name the quieter or representative-hardware check needed; do not confirm or refute the claim from that run.

Conclude supported, contradicted or unverified per claim, with provenance, tested scope and whether independent reproduction succeeded. Missing hardware or unresolved noise leaves the claim unverified with prerequisite, owner and next check; feasible unperformed checks remain incomplete. Reliable counterevidence is required for contradiction. Missing verification alone is a coverage limit, not a source defect or grounds for rejection. Preserve each workflow's existing readiness and confidence contract.

<inputs>

- **$ARGUMENTS**: optional file path or directory to review.
  - Path given: review those files
  - Omitted: review current git diff (`git diff HEAD` — staged + unstaged vs HEAD; with `--worktree`, the last commit `HEAD~1..HEAD`)
  - **Scope**: Python source only. Non-Python file (YAML, JSON, shell script, etc.) → state out of scope, suggest appropriate tool. No findings.
  - `--no-challenge`: skip adversarial review (challenger runs by default)
  - `--challenge`: accepted for compatibility, no effect — challenger runs on every diff size unless `--no-challenge`
  - `--full`: run **every** dimension classification preselected, instead of only the `FANOUT_MAX` most relevant. Never widens preselection — a dimension the FIX/CHORE/impact-tier rules ruled out stays out. **Not free**: each extra agent costs ~120,851 tok fixed overhead however little work it does. Default stays capped; pass this when depth matters more than cost.
  - `--codemap`: strict mode — stop and report if codemap not installed (on by default when installed; use `--no-codemap` to opt out)

**PR#/filename disambiguation gate** (its block runs in §Flag parsing, right after the flag block — BEFORE Worktree isolation and Step 1): valid PR# is positive integer (optional leading `#`) with no extension and no existing file at that path.

- Filenames that look like numbers (e.g. `42.py`) must NOT trigger PR mode.
- `dev_parse_args.py` classifies the flag-stripped target, so `42 --full` still counts, and writes the bare number or empty to the `dev-review-pr-number` sentinel; the gate block reads it, checks oss through the install record and prints `OSS_AVAILABLE=` and `PR_NUMBER=`.
- "Proceed to Step 1" below = continue the workflow: Worktree isolation, then Step 1.

`$OSS_AVAILABLE` is `skip` → proceed to Step 1 normally (path / diff / dir mode).

`$OSS_AVAILABLE` is `true` → call `AskUserQuestion` ONCE with BOTH questions in the same call (a second sequential window costs another human-idle round trip):

- Q1: "Looks like you passed a PR/issue number. Did you mean to run `/oss:review $ARGUMENTS` (requires oss plugin) to review that PR?" Options: (a) "Yes — launch `/oss:review $ARGUMENTS`" · (b) "No — review local code".
- Q2: "If reviewing local code: provide the file path or directory (free text; skip if Q1 = Yes)".

Answer handling:

- On (a): call `Skill(skill="oss:review", args="<PR_NUMBER>")` with the bare number the gate block printed (never the flags passed beside it), ignore Q2, then stop — do not enter Step 1.
- On (b): persist the Q2 response as the review target (block below), proceed to Step 1 (Q2 empty → ask once more for the path).

Persist block for Q2 (shared by both branches) — substitute `<Q2 path>` with the user's answer; it replaces the PR number in the clean-args sentinel Step 1 re-reads:

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
Q2_PATH='<Q2 path>'
case "$Q2_PATH" in *'<'*'>'*|"") echo "! BLOCKED — Q2 path unsubstituted"; exit 1;; esac
echo "$Q2_PATH" > "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}"
```

`$OSS_AVAILABLE` is `false` → call `AskUserQuestion` ONCE with BOTH questions — Q1: "Looks like you passed a PR/issue number, but oss plugin not installed — `/oss:review` unavailable. Review local code instead?" Options: (a) "Yes — review local code" · (b) "I need oss plugin". Q2: "If reviewing local code: provide the file path or directory (free text; skip if Q1 = b)". On (a): persist the Q2 response with the block above, proceed to Step 1 (Q2 empty → ask once more). On (b): inform user: install with `claude plugin install oss@borda-ai-rig`, then stop — do not enter Step 1.

</inputs>

<constants>

```text
FANOUT_MAX=FANOUT_CAP   # use the runtime cap printed by §Flag parsing; that block owns the numeric default
                        # cap counts dimension spawn units only; real default lineup = up to 3
                        # dimension units + challenger + bridge co-review + consolidator
                        # (+ up to 3 cross-validation verifiers when criticals exist)
                        # --full runs ALL preselected units instead — no numeric cap
AGENT_CALL_BUDGET=55    # target tool-calls per agent; past ~60 they stall without returning an envelope
CHALLENGE_ENABLED=true  # set to false via --no-challenge
CHALLENGE_FORCED=false  # set to true via --challenge — no-op kept for saved invocations; challenger runs at any diff size
CODEMAP_ENABLED=auto    # on by default if codemap installed + index found; --no-codemap = off; --codemap = strict (stop if not installed)
```

</constants>

<compaction>

- Key boundary: end of Step 3 — parallel review-agent fan-out outputs collected, before Step 5 consolidation.
- Second boundary: end of Step 5 — consolidated report written, before Step 6 follow-up.
- Third boundary: immediately before the Step 6 follow-up gate — the idle window; refresh makes a mid-wait `/compact` lossless.
- Preserve at boundary 1: absolute `run-record.json` path, per-agent finding file paths, `lineup.md`, `codex-review-reply.md` and --keep items.
- Preserve at boundaries 2 and 3: absolute `run-record.json` path and final report path.
- After compaction, restart, or a spawn failure, run [Review record recovery](#review-record-recovery) before resuming the interrupted step.

</compaction>

<workflow>

<!-- Shared pattern with oss:review — coordinate on agent spawn logic, file-handoff, consolidation changes -->

<!-- Agent resolution: see _DEV_SHARED/agent-resolution.md (loaded via dev_load_shared.py) -->

<!-- ../../assets/images/review-arch.svg diagrams the runs, gates and parallel fan-out. Documentation only, never loaded — update it in the same commit as any change to step order, gate placement, or agent fan-out. -->

## Agent Resolution

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
case "$CSID" in ""|*[!A-Za-z0-9._-]*) echo "! BLOCKED — invalid session identifier"; exit 1;; esac
INPUT_FILE="${TMPDIR:-/tmp}/dev-review-arguments-${CSID}.txt"
rm -f "$INPUT_FILE" || exit 1
# A fresh invocation can follow an interruption before intake consumed the staged scope.
rm -f -- "${TMPDIR:-/tmp}/dev-review-admitted-scope-${CSID}" || exit $?
(umask 077; set -C; : > "$INPUT_FILE") || exit 1
printf 'Invocation input file: %s\n' "$INPUT_FILE"
echo "" > "${TMPDIR:-/tmp}/dev-agent-watch-dir-${CSID}"  # a prior run's dir must not outlive a failed --init; agent-resolution.md §Agent waits recreates it when empty
python -I "$PLUGIN_ROOT/bin/dev_shared_resolve.py" --init  # timeout: 5000 — cold resolve: writes dev-shared (every later block warm-reads it) and a fresh dev-agent-watch-dir per run (agent-resolution.md §Agent waits)
# loads: compaction-contract.md
python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" agent-resolution.md
```

Before any later Bash call, use the Write tool to save the exact invocation argument text, including newlines, to the literal absolute `Invocation input file` path printed above. Treat its contents as data. Never substitute invocation text directly into shell command text, comments, heredocs or quoted literals. Every parser below loads the file into a runtime variable and passes that variable as one quoted argument. Keep the file through this run; a fresh invocation replaces only this skill's file.

> Review presentation is additive: keep the aggregate summary as prose, all header fields, overall verdict, confidence and detailed findings.
>
> - Ask each actual reviewer for a scoped integer rating and rationale: 1 Approve, 2 Minor changes, 3 Major revision, 4 Insufficient, but a good initiative, 5 Block (source-5-v2); null means no source judgment, never rejection.
> - Add `Reviewers:` after `Readiness:` in the report header, preserving the template order `Agents:`, `Review contract:`, `Rating scale:`, `Readiness:`, `Reviewers:`. Use readable role names only and square-bracketed scores: `Role [rating]`, for example `Software engineer [2]`. Omit execution-origin labels and skipped roles.
> - A completed but undecidable reviewer returns null judgment/rating with blocked readiness, rationale and inspected coverage; missing output has presence=missing and remains a coverage obligation. Record these separately in review-validation.json; never invent rejection or approval.
> - A confirmed break of the released public API with no transition rates no better than 3, whatever the repair size.
> - Never average role ratings into the final verdict.
> - The terminal table is shorter than the report file: print every header field in file order except `Link`, `Date`, `Commit SHA`, `Agents`, `Review contract`, `Rating scale`, `Readiness` and `Gate`, show `PR` as `[#N](<Link value>)`, and end with the `Path` row; the report file keeps every field.
> - After rendering the header table, add exactly this line below it, in the same Step 5b delivery block: `Legend: 1 = Approve · 2 = Minor changes · 3 = Major revision · 4 = Insufficient, but a good initiative · 5 = Block.`
> - Findings overview adds `Author` after `ID`, retaining all contributing reviewer roles after deduplication.
> - Read the summary and overview after the header rather than treating the header alone as the complete review.
> - Terminal gate rejections preserve existing behavior and use `Reviewers: Not assessed` when no source reviewer ran.

Contains: foundry check + fallback table. If foundry not installed: substitute each `foundry:X` with `general-purpose` per table. Agents this skill uses: `foundry:sw-engineer`, `foundry:qa-specialist`, `foundry:perf-optimizer`, `foundry:doc-scribe`, `foundry:linting-expert`, `foundry:solution-architect`, `foundry:challenger`.

**Task hygiene** — task tools may be deferred; load before first use: `ToolSearch(query="select:TaskList,TaskCreate,TaskUpdate,TaskGet", max_results=4)`. Call `TaskList` first and triage each task it returns: `completed` if work clearly done, `deleted` if orphaned, keep `in_progress` only if genuinely continuing. Never spend a turn on bookkeeping alone — every `TaskCreate`/`TaskUpdate` ships in the same response as the next substantive tool call; one exception, `TaskUpdate(completed)` immediately before a long output block (`rules/task-lifecycle.md`).

After Step 1 completes (scope and `TARGET` known), create these tasks **before any agent spawns** (in order, all at once):

- **"Step 1: Identify scope"** — mark `in_progress` at Step 1 start; mark `completed` when `TARGET` and `SCOPE` set and Python file check passes
- **"Step 2: Codex co-review"** — create before Step 2 (skip task if Codex unavailable); mark `in_progress` before Codex spawn; mark `completed` when codex seed extracted (or timed out)
- **"Step 3: Spawn review agents"** — mark `in_progress` before agents launch; mark `completed` when all agent output files collected (or health-monitoring cutoff reached)
- **"Step 4: Cross-validate critical findings"** — mark `in_progress` before verifier spawns; `completed` when all verdicts received; **skip task creation when no critical/blocking findings exist after Step 3**
- **"Step 5: Consolidate findings"** — mark `in_progress` before spawning consolidator; `completed` when consolidator returns its JSON envelope (Write to `review-report.md` done) — **do NOT mark completed for the terminal print, that's a separate task below**
- **"Step 5b: Print report header"** — created **blockedBy** "Step 5: Consolidate findings"; mark `in_progress` immediately after the consolidator returns. Read the report and build the header table and question summary now; keep it `in_progress` through the question. Mark `completed` only in the response that delivers the table in the final reply after the answer (or on a no-question path), beside the last tool calls immediately before that output, never merely when queued/intended.
  - Consolidator's JSON envelope is a routing signal for the orchestrator, never a substitute for reading `$REPORT_DIR/review-report.md` and rendering its header.
  - **The follow-up `AskUserQuestion` must not fire until the current report has been read and its header table and plain summary are built** — the dedicated task tracks final delivery separately; issuing the question does not complete it.

## Flag parsing

Strip flags from `$ARGUMENTS` before using as path:

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
INPUT_FILE="${TMPDIR:-/tmp}/dev-review-arguments-${CSID}.txt"
[ -f "$INPUT_FILE" ] && [ ! -L "$INPUT_FILE" ] && [ -O "$INPUT_FILE" ] || { echo "! BLOCKED — invocation input missing or untrusted; Write the arguments to the printed Invocation input file first"; exit 1; }
ARGUMENT_BLOB=$(cat "$INPUT_FILE" && printf x) || exit 1
ARGUMENT_BLOB=${ARGUMENT_BLOB%x}  # preserve trailing newlines without evaluating the text
python -I "$PLUGIN_ROOT/bin/extract-keep-flag.py" dev-review "$ARGUMENT_BLOB"  # timeout: 5000 — parses --keep, clears stale contract
python -I "$PLUGIN_ROOT/bin/dev_parse_args.py" --skill review --write-files "$ARGUMENT_BLOB"
# writes ${TMPDIR:-/tmp}/dev-review-{no-challenge,codemap,clean-args,pr-number}-${CSID} + legacy paths
IFS= read -r REVIEW_ARGS < "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}" 2>/dev/null || REVIEW_ARGS=""
# strip --keep so it doesn't leak into find/git diff target path
REVIEW_ARGS=$(echo "$REVIEW_ARGS" | sed -E 's/ *--keep +"[^"]+"//' | xargs 2>/dev/null || echo "$REVIEW_ARGS")
IFS= read -r CHALLENGE_ENABLED < "${TMPDIR:-/tmp}/dev-review-challenge-enabled-${CSID}" 2>/dev/null || CHALLENGE_ENABLED="true"
IFS= read -r CHALLENGE_FORCED < "${TMPDIR:-/tmp}/dev-review-challenge-forced-${CSID}" 2>/dev/null || CHALLENGE_FORCED="false"  # --challenge: no-op, challenger always runs
# fail-safe impact default — codemap block overrides with review_impact_tier.py verdict; codemap off keeps FULL
echo "FULL · impact unknown: codemap unavailable" > "${TMPDIR:-/tmp}/dev-review-impact-${CSID}"
IFS= read -r CODEMAP_RAW < "${TMPDIR:-/tmp}/dev-review-codemap-${CSID}" 2>/dev/null || CODEMAP_RAW="auto"
IFS= read -r FANOUT_FULL < "${TMPDIR:-/tmp}/dev-review-fanout-full-${CSID}" 2>/dev/null || FANOUT_FULL="false"
FANOUT_CAP=3  # single numeric default for FANOUT_MAX
[ "$FANOUT_FULL" = "true" ] && FANOUT_CAP=0  # 0 = no cap: all preselected dimensions
echo "REVIEW_ARGS=$REVIEW_ARGS CHALLENGE_ENABLED=$CHALLENGE_ENABLED FANOUT_CAP=$FANOUT_CAP"  # prose below branches on these — shell state dies with the call
```

PR#/filename disambiguation gate — reads the classified sentinel, never the raw arguments; branch on the printed values per `<inputs>`:

```bash
# timeout: 5000
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
IFS= read -r PR_NUMBER < "${TMPDIR:-/tmp}/dev-review-pr-number-${CSID}" 2>/dev/null || PR_NUMBER=""
if [ -n "$PR_NUMBER" ]; then
    echo "PR number detected — checking oss plugin availability"
    OSS_ROOT=$(python -I "$PLUGIN_ROOT/bin/get_plugin_install_path.py" borda-ai-rig oss 2>/dev/null) || OSS_ROOT=""  # install record, never cache glob — orphaned version dir ≠ installed
    [ -n "$OSS_ROOT" ] && [ -f "$OSS_ROOT/skills/review/SKILL.md" ] && OSS_AVAILABLE=true || OSS_AVAILABLE=false
else
    OSS_AVAILABLE=skip
fi
echo "OSS_AVAILABLE=$OSS_AVAILABLE PR_NUMBER=$PR_NUMBER"  # <inputs> prose branches on these — shell state dies with the call
```

**Unsupported flag check** — after all supported flags extracted, scan `$ARGUMENTS` for remaining `--<token>` tokens not in the supported list below. Found → invoke `AskUserQuestion` with question text `` ! Unknown flag(s): `--<token>`. Supported: `--no-challenge`, `--challenge`, `--codemap`, `--no-codemap`, `--worktree`, `--full`, `--keep`. `` — (a) **Abort** (stop, re-invoke with correct flags) · (b) **Continue ignoring** (skip unknown flags, proceed). On Abort: stop.

## Worktree isolation

> loads: worktree-isolation.md

`--worktree` set → run review in an isolated git worktree so no dimension agent can accidentally mutate main sources — **before** Step 1.

```bash
# timeout: 5000
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
IFS= read -r WORKTREE_ENABLED < "${TMPDIR:-/tmp}/dev-review-worktree-${CSID}" 2>/dev/null; [ "$WORKTREE_ENABLED" = "true" ] || WORKTREE_ENABLED=false
printf '%s\n' review > "${TMPDIR:-/tmp}/dev-worktree-skill-${CSID}"
IFS= read -r REVIEW_ARGS < "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}" 2>/dev/null || REVIEW_ARGS=""
if [ "$WORKTREE_ENABLED" = "true" ]; then
    GIT_DIR=$(git rev-parse --path-format=absolute --git-dir) || exit $?
    COMMON_DIR=$(git rev-parse --path-format=absolute --git-common-dir) || exit $?
    if [ "$GIT_DIR" != "$COMMON_DIR" ]; then
        WORKTREE_ENABLED=false
        printf '%s\n' false > "${TMPDIR:-/tmp}/dev-review-worktree-${CSID}" || exit $?
        echo '⚠ already in worktree — --worktree no-op'
    fi
fi
if [ "$WORKTREE_ENABLED" = "true" ] && [ -z "$REVIEW_ARGS" ]; then
    WORKTREE_STATUS=$(git status --porcelain --untracked-files=normal) || exit 1
    [ -z "$WORKTREE_STATUS" ] || { echo "! BLOCKED — --worktree without a path would omit uncommitted changes; rerun without --worktree to review them, or pass an explicit committed path."; exit 1; }
fi
if [ "$WORKTREE_ENABLED" = "true" ]; then python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" worktree-isolation.md; fi
```

`WORKTREE_ENABLED=true` → follow §Enter (base off HEAD, `EnterWorktree(path=…)`). **Read-only skill** — obey §Deliverable:

- `$RUN_DIR` handoffs stay under the active development run directory, or the worktree's `.developments/` for standalone reviews, but `$REPORT_DIR` (the review report) is written to the **main tree** (`$_ORIG_ROOT`, wired at Step 2) so its printed path + follow-up gate stay valid.
- Reviews committed HEAD state — uncommitted working-tree changes aren't visible, so the default target (no path given) is the last commit (`HEAD~1..HEAD`), matching Agent 0's pre-change ref; pass a path to review other committed files.

Else skip — run in main tree (doc not loaded).

```bash
# CODEMAP_RAW → true/false; strict exits on unavailability  # timeout: 5000
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
CODEMAP_ENABLED=$(python -I "$PLUGIN_ROOT/bin/dev_codemap_gate.py" review) || exit 1
# codemap: integrated-via-shared
python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" codemap-gates.md
```

> loads: codemap-gates.md

Follow Gate A and Gate B.

Use `$REVIEW_ARGS` (not `$ARGUMENTS`) as path for rest of workflow.

## Step 1: Identify scope

Capture the target repository's full Git HEAD once, before source inspection. A file target uses its containing directory; a directory target uses itself; diff mode uses the current directory. This identifies the working-tree base for path/diff reviews; it never claims dirty files equal a clean commit. Keep this frozen value through consolidation and compaction, even if HEAD later moves. Non-Git directories and unborn repositories retain an explicit unavailable reason.

```bash
# timeout: 5000
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
IFS= read -r REVIEW_ARGS < "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}" 2>/dev/null || REVIEW_ARGS=""
REVIEW_SOURCE_DIR="."
if [ -d "$REVIEW_ARGS" ]; then REVIEW_SOURCE_DIR="$REVIEW_ARGS"; elif [ -f "$REVIEW_ARGS" ]; then REVIEW_SOURCE_DIR=$(dirname -- "$REVIEW_ARGS"); fi
REVIEW_SOURCE_DIR=$(cd -- "$REVIEW_SOURCE_DIR" && pwd -P) || exit $?
if command -v cygpath >/dev/null 2>&1; then REVIEW_SOURCE_DIR=$(cygpath -m -- "$REVIEW_SOURCE_DIR") || exit $?; fi
REVIEWED_COMMIT_SHA=$(git -C "$REVIEW_SOURCE_DIR" rev-parse --verify HEAD 2>/dev/null) || REVIEWED_COMMIT_SHA="unavailable (non-Git directory or unborn HEAD)"
REVIEWED_COMMIT_KIND="working-tree base; reviewed files may include uncommitted changes"
IFS= read -r WORKTREE_ENABLED < "${TMPDIR:-/tmp}/dev-review-worktree-${CSID}" 2>/dev/null || WORKTREE_ENABLED=false
if [ "$WORKTREE_ENABLED" = "true" ] && [ -z "$REVIEW_ARGS" ]; then REVIEWED_COMMIT_KIND="committed worktree source; reviewed range HEAD~1..HEAD"; fi
printf '%s\n' "$REVIEWED_COMMIT_SHA" > "${TMPDIR:-/tmp}/dev-review-commit-sha-${CSID}"
printf '%s\n' "$REVIEWED_COMMIT_KIND" > "${TMPDIR:-/tmp}/dev-review-commit-kind-${CSID}"
printf '%s\n' "$REVIEW_SOURCE_DIR" > "${TMPDIR:-/tmp}/dev-review-source-dir-${CSID}"
printf 'Commit SHA: %s (%s)\n' "$REVIEWED_COMMIT_SHA" "$REVIEWED_COMMIT_KIND"
```

Scope + non-Python impact check + Python filter in ONE pass — a single `git diff` capture feeds TARGET, the report-header warnings, and the early exit (previously eight diff invocations across three blocks):

```bash
# timeout: 5000
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
IFS= read -r REVIEW_ARGS < "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}" 2>/dev/null || REVIEW_ARGS=""   # re-derive — bash resets between calls
IFS= read -r WORKTREE_ENABLED < "${TMPDIR:-/tmp}/dev-review-worktree-${CSID}" 2>/dev/null || WORKTREE_ENABLED=false
IFS= read -r REVIEWED_COMMIT_SHA 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-commit-sha-${CSID}" || exit $?
REVIEWED_COMMIT_SHA=${REVIEWED_COMMIT_SHA%$'\r'}
case "$REVIEWED_COMMIT_SHA" in 'unavailable (non-Git directory or unborn HEAD)') printf -v REVIEWED_COMMIT_SHA '%040d' 0;; esac
COMMITTED=""; [ "$WORKTREE_ENABLED" = "true" ] && COMMITTED="--committed"  # fresh worktree: working-tree diff is empty, the change is the last commit
if [ -n "$COMMITTED" ]; then set -- "$COMMITTED"; else set --; fi
python -I "$PLUGIN_ROOT/bin/resolve_review_target.py" "$@" --head "$REVIEWED_COMMIT_SHA" --scope-output "${TMPDIR:-/tmp}/dev-review-admitted-scope-${CSID}" -- "$REVIEW_ARGS" || exit 1
```

Any `⚠` line printed above: include in report header regardless of whether Python files exist. No Python files → `resolve_review_target.py` prints `! Diff contains non-Python files only.`; a nonexistent path prints `! Review target not found: <path>`; either exits 1 and the `|| exit 1` stops Step 1 there — do not continue.

A directory selector is a display label. Intake saves the individual admitted Python files in `scope.paths`, relative to `scope.review_cwd` when inside it and absolute otherwise. Diff mode keeps Git's repository-root-relative paths, including paths outside the invocation directory. Read the saved list on resume. A file added under the selector later requires a fresh review to enter scope.

### Scope pre-check

Before spawning agents, classify diff:

- Count files changed, lines added/removed, new classes/modules introduced
- Classify: **FIX** (corrects wrong behavior), **REFACTOR** (same behavior restructured), **FEATURE** (new public API or capability), **CHORE** (config/deps, no logic), **MIXED** — classify by intent, not file count
- **Complexity smell**: 8+ files changed → note in report header

Persist the classification decision for compaction-safe reuse in later steps and the boundary-1 contract. Closed set, no shell variable — run the ONE block below matching the classification just made:

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
echo "FIX" > "${TMPDIR:-/tmp}/dev-review-classification-${CSID}"
```

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
echo "REFACTOR" > "${TMPDIR:-/tmp}/dev-review-classification-${CSID}"
```

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
echo "FEATURE" > "${TMPDIR:-/tmp}/dev-review-classification-${CSID}"
```

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
echo "CHORE" > "${TMPDIR:-/tmp}/dev-review-classification-${CSID}"
```

```bash
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
echo "MIXED" > "${TMPDIR:-/tmp}/dev-review-classification-${CSID}"
```

Skip optional agents by classification:

- FIX → **only when `IMPACT_TIER=LIGHT`** (see Impact tier below; `FULL` keeps both): skip Agent 3 (perf-optimizer) and Agent 6 (solution-architect), unless diff changes an already-exported public function's signature (added/removed/renamed params, new flags) or removes, renames or moves an exported module, class or function — then Agent 6 still runs per its own trigger (Agent 1's "API-consistency audit" subsection already checks the surface; Agent 6 adds design-quality/backward-compat judgment)
- REFACTOR → skip Agent 6 (solution-architect), same exception — an already-exported public function's signature change still fires Agent 6
- CHORE (config/deps, no logic) → skip Agent 2 (qa-specialist), Agent 3 (perf-optimizer), Agent 6 (solution-architect); keep Agent 1 (sw-engineer), Agent 4 (doc-scribe), Agent 5 (linting-expert). No logic = no test-gap, perf, or architecture surface — same saving pattern as `oss:review`'s DOCS_TYPING/TESTS_CI pre-classification (requires oss plugin).
- FEATURE/MIXED → spawn all agents, plus Agent 0 (blind-solve) when a matching `.plans/active/*.md` exists — see §Agent 0 below
- **Challenger at any diff size** — Agent 7 runs on every classification and every diff size; only `--no-challenge` (`CHALLENGE_ENABLED=false`) disables it. Small diff ≠ low risk: few lines in a private helper on the main path can break the main user story.

**Impact tier** — review depth follows the code path a change sits on, never line or file count. `review_impact_tier.py` (codemap `diff-impact` + `fn-blast`, run in the codemap block below) prints `FULL` or `LIGHT` plus reason:

- `FULL` — any changed symbol, public or private, reaches a public function outside tests/leaf modules (main path), or a changed main-path module has ≥5 importers, or a module-level main-path change. **Unknown impact (codemap off, query failed, unmapped file) = `FULL`.**
- `LIGHT` — every change and every transitive caller stays in tests, leaf modules (`viz`, `plot`, `examples`, `docs`, `notebooks`), or uncalled private code. `conftest.py`, `docs/conf.py`, setup/release/build entrypoints and `scripts/` are always `FULL`.

The Step 2 codemap-copy block prints `IMPACT_TIER=` and `IMPACT=` — apply the FIX skip above from that value (codemap runs after classification). Report the `IMPACT=` line in the review header as `Impact:`.

Create the review run directory and record after target admission and classification, before pre-flight, including when Codemap is disabled. Reuse an active feature/fix/refactor run root when present; standalone reviews use `.developments/`. Inputs above are intake staging. Once initialized, `run-record.json` owns the frozen identity and decisions. Its zero hash represents an unavailable HEAD; the reason remains explicit in the scope and report.

Run the record commands through the normal Bash permission flow.

```bash
# Review record intake
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
IFS= read -r REVIEWED_COMMIT_SHA 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-commit-sha-${CSID}" &&
IFS= read -r REVIEWED_COMMIT_KIND 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-commit-kind-${CSID}" &&
IFS= read -r SOURCE_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-source-dir-${CSID}" || { echo '! BLOCKED — run-record-intake-missing: capture the source identity first' >&2; exit 1; }
IFS= read -r REVIEW_ARGS 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-clean-args-${CSID}" || REVIEW_ARGS=""
IFS= read -r WORKTREE_ENABLED 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-worktree-${CSID}" || WORKTREE_ENABLED=false
IFS= read -r CLASSIFICATION 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-classification-${CSID}" || CLASSIFICATION=""
IFS= read -r CHALLENGE_ENABLED 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-challenge-enabled-${CSID}" || CHALLENGE_ENABLED=true
IFS= read -r FANOUT_FULL 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-fanout-full-${CSID}" || FANOUT_FULL=false
IFS= read -r CODEMAP_ENABLED 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-codemap-enabled-${CSID}" || CODEMAP_ENABLED=false
IFS= read -r CODEMAP_CURRENCY 2>/dev/null < "${TMPDIR:-/tmp}/dev-codemap-currency-${CSID}" || CODEMAP_CURRENCY=no_index
IFS= read -r WATCH_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-agent-watch-dir-${CSID}" || WATCH_DIR=""
case "$CLASSIFICATION" in FIX|REFACTOR|FEATURE|CHORE|MIXED) ;; *) echo '! BLOCKED — run-record-classification-missing' >&2; exit 1;; esac
ADMITTED_SCOPE_PATH="${TMPDIR:-/tmp}/dev-review-admitted-scope-${CSID}"
jq -be '
    select((.paths | type == "array" and length > 0) and (.target_modules | type == "array"))
    | select(all(.paths[], .target_modules[]; type == "string" and length > 0))
' "$ADMITTED_SCOPE_PATH" >/dev/null || { echo '! BLOCKED — run-record-admitted-scope-missing' >&2; exit 1; }
FROZEN_HEAD="$REVIEWED_COMMIT_SHA"
if [ "$REVIEWED_COMMIT_SHA" = 'unavailable (non-Git directory or unborn HEAD)' ]; then FROZEN_HEAD=$(printf '%040d' 0); fi
TARGET_KIND=working-tree-diff
if [ -n "$REVIEW_ARGS" ]; then TARGET_KIND=path; elif [ "$WORKTREE_ENABLED" = true ]; then TARGET_KIND=committed-diff; fi
REVIEW_CWD="$PWD"
REPORT_BASE="$PWD"
if [ "$WORKTREE_ENABLED" = true ]; then
    IFS= read -r REPORT_BASE 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-orig-root-${CSID}" || REPORT_BASE="$PWD"
fi
REPORT_BASE=${REPORT_BASE%$'\r'}
[ -n "$REPORT_BASE" ] || REPORT_BASE="$PWD"
TIMESTAMP=$(date -u +%Y-%m-%dT%H-%M-%SZ)
RUN_BASE=""
for _RUN_SKILL in feature fix refactor; do
    IFS= read -r RUN_BASE 2>/dev/null < "${TMPDIR:-/tmp}/dev-${_RUN_SKILL}-dev-dir-${CSID}" || :
    [ -z "$RUN_BASE" ] || break
done
RUN_DIR="${RUN_BASE:-.developments}/review/$TIMESTAMP"
case "$RUN_DIR" in /*|[A-Za-z]:/*) ;; *) RUN_DIR="$PWD/$RUN_DIR";; esac
if command -v cygpath >/dev/null 2>&1; then RUN_DIR=$(cygpath -m -- "$RUN_DIR") || exit $?; fi
mkdir -p "$RUN_DIR" || exit 1  # timeout: 5000
python -I "$PLUGIN_ROOT/bin/run_record.py" init --run-dir "$RUN_DIR" --skill review --head "$FROZEN_HEAD" || exit $?
jq -bc --arg target "$REVIEW_ARGS" --arg kind "$TARGET_KIND" --arg source "$SOURCE_DIR" --arg cwd "$REVIEW_CWD" --arg sha "$REVIEWED_COMMIT_SHA" --arg commit_kind "$REVIEWED_COMMIT_KIND" --arg worktree "$WORKTREE_ENABLED" --arg challenge "$CHALLENGE_ENABLED" --arg full "$FANOUT_FULL" --arg codemap "$CODEMAP_ENABLED" --arg currency "$CODEMAP_CURRENCY" --arg watch "$WATCH_DIR" --arg report_base "$REPORT_BASE" '{paths, target_modules, target: $target, target_kind: $kind, source_dir: $source, review_cwd: $cwd, reviewed_commit_sha: $sha, reviewed_commit_kind: $commit_kind, worktree: ($worktree == "true"), challenge: ($challenge == "true"), fanout_cap: (if $full == "true" then 0 else 3 end), codemap_enabled: ($codemap == "true"), codemap_currency: $currency, watch_dir: $watch, report_base: $report_base, impact: "FULL · impact unknown: codemap unavailable", codemap_stage: ""}' "$ADMITTED_SCOPE_PATH" |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section scope --value-stdin || exit $?
jq -bcn --arg classification "$CLASSIFICATION" '$classification' |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --decision classification --step intake --value-stdin || exit $?
printf '%s\n' "$RUN_DIR" > "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || exit $?
rm -f -- "$ADMITTED_SCOPE_PATH" || exit $?
printf 'Review record: %s/run-record.json\n' "$RUN_DIR"
```

### Review record recovery

Run the fence at each resume and before entering a later phase. If the locator disappeared, use the Write tool to restore its single line from the preserved absolute record path, using its containing directory. If no exact path is available, stop with `run-record-missing`; a fresh review creates a new run. On any refusal, report its named reason and stop the affected run. Never choose a timestamp by recency or rebuild progress from sentinels, filenames, or conversation.

```bash
# Review record recovery
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
IFS= read -r LOCATED_RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || LOCATED_RUN_DIR=""
LOCATED_RUN_DIR=${LOCATED_RUN_DIR%$'\r'}
if [ -n "${RUN_DIR:-}" ] && [ -n "$LOCATED_RUN_DIR" ] && [ "$RUN_DIR" != "$LOCATED_RUN_DIR" ]; then
    echo '! BLOCKED — run-record-locator-mismatch' >&2
    exit 1
fi
RUN_DIR=${RUN_DIR:-$LOCATED_RUN_DIR}
[ -n "$RUN_DIR" ] || { echo '! BLOCKED — run-record-missing: no exact run directory' >&2; exit 1; }
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
SOURCE_DIR=$(jq -ber '.scope.source_dir | strings | select(length > 0)' <<< "$RECORD") &&
jq -be '.scope | has("target") and has("reviewed_commit_sha")' <<< "$RECORD" >/dev/null &&
jq -be '.decisions.classification.value | IN("FIX", "REFACTOR", "FEATURE", "CHORE", "MIXED")' <<< "$RECORD" >/dev/null || { echo '! BLOCKED — run-record-scope-incomplete' >&2; exit 1; }
[ -d "$SOURCE_DIR" ] || { echo '! BLOCKED — run-record-source-missing' >&2; exit 1; }
if ! LIVE_HEAD=$(git -C "$SOURCE_DIR" rev-parse --verify HEAD 2>/dev/null); then
    case $(jq -br '.scope.reviewed_commit_sha' <<< "$RECORD") in
        'unavailable (non-Git directory or unborn HEAD)') printf -v LIVE_HEAD '%040d' 0 ;;
        *) echo '! BLOCKED — run-record-stale-head: captured source HEAD is unavailable' >&2; exit 1 ;;
    esac
fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review --head "$LIVE_HEAD" || exit $?
if REPORT_DIR=$(jq -ber '.scope.report_dir | strings | select(length > 0)' <<< "$RECORD"); then
    printf '%s\n' "$REPORT_DIR" > "${TMPDIR:-/tmp}/dev-review-report-dir-${CSID}" || exit $?
fi
printf '%s\n' "$RECORD"
```

Route from the record: pending recorded roles await their own notification or deadline; returned roles use their recorded outcomes. `decisions.validation`, `decisions.worktree-exit`, `decisions.follow-up` and `publication` identify completed boundaries. For a published worktree review with exit still pending, resume at [Worktree exit and follow-up](#worktree-exit-and-follow-up) before any question or final delivery. Otherwise resume a published review at its pending follow-up or final delivery. Run only the first uncompleted gate. Reports and watch files are evidence referenced by the record.

### Structural context + review pre-flight (codemap-py — only if `CODEMAP_ENABLED=true`)

**Skip entire section if `CODEMAP_ENABLED=false`** — sets `codemap_available=false` for downstream agent prompts; agents fall back to file reads.

Extended scan for changed modules — runs v5 pre-flight queries per module, persists structured output to `$RUN_DIR/codemap-context.md`, and sets `codemap_available` flag for Step 3 agent spawns:

Use the dotted modules saved in `scope.target_modules` at admission. An unmappable target gets an empty list and file-read fallback. Path/directory and committed worktree reviews keep `FULL` because working-tree `diff-impact` measures a different target.

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
SCOPE=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section scope) || exit $?
CODEMAP_CURRENCY=$(jq -ber '.codemap_currency' <<< "$SCOPE") || exit $?
if [ "$CODEMAP_CURRENCY" = "stale" ]; then export SCAN_NO_AUTOBUILD=1; fi
codemap_available=false
CODEMAP_ENABLED=$(jq -ber '.codemap_enabled | tostring' <<< "$SCOPE") || exit $?
REVIEW_ARGS=$(jq -ber '.target' <<< "$SCOPE") || exit $?
WORKTREE_ENABLED=$(jq -ber '.worktree | tostring' <<< "$SCOPE") || exit $?
IMPACT_LINE=$(jq -ber '.impact' <<< "$SCOPE") || exit $?
TARGET_MODULES=$(jq -ber '.target_modules | join(" ")' <<< "$SCOPE") || exit $?
if [ -n "$REVIEW_ARGS" ] || [ "$WORKTREE_ENABLED" = "true" ]; then
    IMPACT_LINE="FULL · impact unknown: review target is not the working-tree diff"
fi
if [ -z "$TARGET_MODULES" ]; then CODEMAP_ENABLED=false; echo "⚠ target modules unavailable — use file reads and FULL impact"; fi
CODEMAP_CONTEXT_STAGE=""
if [ "$CODEMAP_ENABLED" = "true" ]; then
    codemap_available=true
    CODEMAP_CONTEXT_STAGE="$RUN_DIR/codemap-context.stage.md"
    BATCH_REQ="$RUN_DIR/dev-review-codemap-batch.json-${CSID}"
    # explicit target modules prevent unrelated dirty files from selecting structural context
    python -I "$PLUGIN_ROOT/bin/build_codemap_batch.py" "$BATCH_REQ" --modules "$TARGET_MODULES" || exit 1  # timeout: 5000
    {
        echo "## Structural Context (codemap-py)"
        echo
        echo "### Batched query results (one shared coverage block)"
        codemap-py query --timeout 20 batch "$BATCH_REQ" 2>/dev/null
        if [ -z "$REVIEW_ARGS" ] && [ "$WORKTREE_ENABLED" != "true" ]; then
            echo
            echo "### Change-set blast radius (diff-impact)"
            # fn-level context batch can't give: fn-rdeps per symbol (line-range, methods), unioned test-impact, risk tiers
            _DIFF_IMPACT_JSON=$(codemap-py query --timeout 15 diff-impact 2>/dev/null)
            printf '%s\n' "$_DIFF_IMPACT_JSON"
            IMPACT_LINE=$(printf '%s\n' "$_DIFF_IMPACT_JSON" | python -I "$PLUGIN_ROOT/bin/review_impact_tier.py" 2>/dev/null) || IMPACT_LINE="FULL · impact unknown: codemap unavailable"  # timeout: 300000 — batch + diff-impact + ≤12 tier fn-blast queries
        fi
    } > "$CODEMAP_CONTEXT_STAGE"
fi
jq -bcn --arg available "$codemap_available" --arg stage "$CODEMAP_CONTEXT_STAGE" --arg impact "$IMPACT_LINE" '{codemap_available: ($available == "true"), codemap_stage: $stage, impact: $impact}' |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section scope --value-stdin || exit $?
```

Codemap context propagation in Step 3:

- `codemap_available=true` → copy `$CODEMAP_CONTEXT_STAGE` to `$RUN_DIR/codemap-context.md` once in Step 2, reusing the directory created before pre-flight. Each dimension spawn prompt gets a literal block holding only ITS slice of the batch results (the whole block in every prompt re-bills every query result to consumers that never read it; results for skipped agents injected nowhere):

  - qa unit → `uncovered` + `mock-rdeps` entries
  - doc unit → `undocumented` + `xrefs --broken` entries
  - sw-engineer → `rdeps` + `central` + `diff-impact`

  Entries whose only consumer was skipped by classification aren't injected anywhere:

  ```text
  ## Structural Context (codemap-py, codemap_available=true)
  <this agent's slice of $RUN_DIR/codemap-context.md>

  Read this section first. The payload contains a `batch` array: each entry has `cmd`, `ok`, an ordinal `index`, and `result`. Each child's `result.index` describes its own scope and completeness; the outer `index` is only a conservative summary. Retain child metadata when slicing results for agents. For successful entries passing the reuse gate, skip only equivalent structural retrieval. A valid empty list is not a failed query; failed or unjoinable children remain explicit gaps. Source and test reads for specific findings remain required.

  > Reuse gate: reuse a supplied answer only for the same project, current index, target, query and flags; skip its duplicate pre-flight call. Require success and direction-complete metadata. For batch children require `ok: true` and inspect `result.index`; `ok: false` is a failure, never an empty answer. Missing metadata, `stale`, root mismatch, degraded or incomplete results need targeted fallback. Use legacy `exhaustive: true` only when `query_complete` is absent. A valid empty list settles that scoped query; truncation does not enumerate all matches. Necessary source-body reads, test-quality checks, dynamic behavior and required independent verification remain allowed.

  **Query choice inheritance**: the orchestrator supplies the invocation’s exact enabled/currency sentinel paths in this prompt. Before every fresh shell that queries Codemap or runs a querying helper, reload those files; disabled means no queries, stale means `export SCAN_NO_AUTOBUILD=1` before the command. Retain an inherited freeze. This also applies to fallback and impact/test-selection helpers. **Bounded call budget**: symbol not covered by the batch above → up to 3 additional `codemap-py query` calls this review pass. **Hard stop on `query_complete: true`** (legacy `exhaustive: true` only when `query_complete` is absent): a result passing the reuse gate is final for its direction — no follow-up Grep/Read/query to re-confirm it.

  Per-agent priority (skip redundant reads for symbols the listed query already covers):
  - qa-specialist (Agent 2): `uncovered` + `mock-rdeps` first
  - doc-scribe (Agent 4): `undocumented` + `xrefs --broken` first
  - sw-engineer (Agent 1): `rdeps` first (importers per changed module)
  - challenger (Agent 7): unchanged — always reads source directly
  ```

- `codemap_available=false` → omit block; agents proceed with current file-read behaviour.

> Per-agent consumption guidance kept in sync with `$_DEV_SHARED/codemap-context.md` §Review-pipeline injection — update both on change.

Tier annotation for Agent 1 (sw-engineer) only: label each module's `imported_by` count — **high risk** (>20), **moderate** (5–20), **low** (\<5). Agent 1 uses this to prioritize: high `imported_by` modules warrant deeper scrutiny on API compatibility, error handling, behavioural correctness — downstream callers outside diff otherwise invisible.

## Step 2: Codex co-review

Recover the record, check Codex availability, and materialize codemap context into the run directory:

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
TIMESTAMP=$(basename -- "$RUN_DIR")
_REPORT_BASE=$(jq -ber '.scope.report_base | strings | select(length > 0)' <<< "$RECORD") || exit $?
REPORT_DIR="$_REPORT_BASE/.reports/develop-review/$TIMESTAMP"
if command -v cygpath >/dev/null 2>&1; then REPORT_DIR=$(cygpath -m -- "$REPORT_DIR") || exit $?; fi
mkdir -p "$REPORT_DIR" || exit $?  # timeout: 5000
jq -bcn --arg dir "$REPORT_DIR" '{report_dir: $dir, report_path: ($dir + "/review-report.md")}' |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section scope --value-stdin || exit $?
if jq -be '.publication == null' <<< "$RECORD" >/dev/null; then
    jq -bc '{state: "pending", report: null, head: .frozen_head}' <<< "$RECORD" |
        python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section publication --value-stdin || exit $?
fi
echo "$REPORT_DIR" > "${TMPDIR:-/tmp}/dev-review-report-dir-${CSID}"  # persist for contract-write
REPORT_DIR_LITERAL="$REPORT_DIR"
CODEX_STATUS=$(python -I "$PLUGIN_ROOT/bin/check_bridge.py" --status 2>/dev/null || echo "absent")  # timeout: 5000
[ "$CODEX_STATUS" = "available" ] && echo "bridge@borda-ai-rig available" || echo "⚠ bridge@borda-ai-rig is ${CODEX_STATUS} — skipping co-review"
CODEMAP_CONTEXT_STAGE=$(jq -ber '.scope.codemap_stage' <<< "$RECORD") || exit $?
if [ -n "$CODEMAP_CONTEXT_STAGE" ]; then
    cp -- "$CODEMAP_CONTEXT_STAGE" "$RUN_DIR/codemap-context.md" || exit $?
fi
IMPACT_LINE=$(jq -ber '.scope.impact' <<< "$RECORD") || exit $?
echo "IMPACT_TIER=${IMPACT_LINE%% *}"
echo "IMPACT=$IMPACT_LINE"
```

**Optional Codex dispatch.** If Codex is unavailable, skip to [Record the Codex outcome](#record-the-codex-outcome).

```bash
# Review Codex scope
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
SOURCE_DIR=$(jq -ber '.scope.source_dir' <<< "$RECORD") || exit $?
if ! LIVE_HEAD=$(git -C "$SOURCE_DIR" rev-parse --verify HEAD 2>/dev/null); then LIVE_HEAD=$(printf '%040d' 0); fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review --head "$LIVE_HEAD" || exit $?
FROZEN_HEAD=$(jq -ber '.frozen_head' <<< "$RECORD") || exit $?
CODEX_WORKSPACE=$(jq -ber '.scope.review_cwd' <<< "$RECORD") || exit $?
if jq -be '.scope.target_kind | IN("working-tree-diff", "committed-diff")' <<< "$RECORD" >/dev/null; then
    CODEX_WORKSPACE=$(git -C "$SOURCE_DIR" rev-parse --show-toplevel) || exit $?
    CODEX_WORKSPACE=${CODEX_WORKSPACE%$'\r'}
    if command -v cygpath >/dev/null 2>&1; then CODEX_WORKSPACE=$(cygpath -m -- "$CODEX_WORKSPACE") || exit $?; fi
fi
CODEX_SCOPE=$(jq -bce --arg workspace "$CODEX_WORKSPACE" --arg range "${FROZEN_HEAD}~1..${FROZEN_HEAD}" '
    .scope | select(.paths | type == "array" and length > 0)
    | {target_kind, target, paths, workspace: $workspace, source_dir, base: .reviewed_commit_sha}
    + (if .target_kind == "committed-diff" then {range: $range} else {} end)
' <<< "$RECORD") || { echo '! BLOCKED — run-record-admitted-scope-missing' >&2; exit 1; }
CODEX_OUT="$RUN_DIR/codex.md"
jq -bcn --arg path "$CODEX_OUT" '{codex_out: $path}' |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section scope --value-stdin || exit $?
printf 'CODEX_OUT=%s\n' "$CODEX_OUT"
printf 'CODEX_SCOPE=%s\n' "$CODEX_SCOPE"
```

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" codex-prepass.md  # timeout: 5000
```

Use the loaded `codex-prepass.md` for the **skip/run criteria only** (formatting-only skip, availability check) when deciding whether to dispatch. Use the dispatch and scope rules here so the parent records the reply and Step 6 can find `$RUN_DIR/codex.md`.

When the criteria say to skip, continue at [Record the Codex outcome](#record-the-codex-outcome).

Dispatch — substitute `<TARGET>` with the admitted scope printed as `CODEX_SCOPE` above, including the frozen base for a working-tree diff. Pass `<WORKSPACE>` as one quoted argument using the rules below: `Skill(skill="bridge:review", args="--workspace <WORKSPACE> --timeout-seconds 230 Read-only adversarial review of <TARGET>. Look for bugs, missed edge cases, incorrect logic, and inconsistencies with existing code patterns. Report findings with file:line locations; do not apply fixes.")` (requires `bridge@borda-ai-rig`).

For a diff review, bind the bridge workspace to `CODEX_SCOPE.workspace`, the repository root, and use the exact `CODEX_SCOPE.paths` as literal Git pathspecs from there. For an explicit path review, put only the literal `CODEX_SCOPE.paths` file list in `<TARGET>` and bind the bridge workspace to `CODEX_SCOPE.workspace` when the paths are workspace-relative. For a list outside that workspace, bind to `CODEX_SCOPE.source_dir` and use the exact recorded files. Treat missing entries and any directory selector in a legacy record as unreviewed without expanding them.

Oversized `<TARGET>` (optional): use the `codex-prepass.md` §Oversized diff partition wave instructions with this brief as `task`. Pass the same explicit `--workspace <WORKSPACE>` on every wave. Select the scope by target:

- **Working-tree diff** uses the exact `"paths"` in `CODEX_SCOPE`, including non-Python files admitted in Step 1. Exclude untracked paths. Tell each group to review its listed files' changes against `CODEX_SCOPE.base` using literal Git pathspecs. If the bridge cannot represent admitted paths such as deletions, report them as unreviewed by the partition or use the single call on the same admitted diff. Record the lane as unreviewed if the scope cannot be verified.
- **Committed diff** uses `CODEX_SCOPE.range`, the full `${FROZEN_HEAD}~1..${FROZEN_HEAD}` range, from the repository root. Before dispatch, compare the recorded paths with `git -C <WORKSPACE> diff --name-only -z --no-renames --ignore-submodules=none --no-relative <range> --` for that same literal range. If the lists differ, use the single call limited to the recorded range and paths, or record the lane as unreviewed. Reconcile any paths the bridge reports as skipped before crediting coverage.
- **Explicit file or directory** uses `{"task": "<the brief above>", "paths": <CODEX_SCOPE.paths>}` for an oversized workspace-relative file list. If the bridge cannot represent those paths, use a single call on the same recorded files or mark them unreviewed. Never rediscover files from the directory selector.

Write the merged findings and the paths or groups the partition could not review to `$RUN_DIR/codex.md`. If the bridge rejects partition mode, use the single call on the same target. In a multi-wave partition no wave carries a `confidence`. The lane score is the one `codex-prepass.md` derives from every wave's group rows, never one wave's envelope. A single-wave partition keeps its own envelope score.

Note: with `--timeout-seconds 230`, `bridge:review` uses its synchronous foreground route and blocks until it returns. Its Write tool is limited to its own scratch task file; it returns findings inline in its response envelope and does not write `$RUN_DIR/codex.md`. No background health-monitoring/liveness-probe protocol applies. After `Skill(skill="bridge:review", ...)` returns, the orchestrator itself writes `$RUN_DIR/codex.md` from the returned envelope's `.findings`/`.verdict`/`.transcript_path` fields.

Quota-blocked co-review (a `blocked` or `timeout` result):

- First Read the incident file its `incident` field names.
- Its `fault` is `quota-exhausted` (peer out of credits, never retried by the bridge) → write `codex-blocked:quota` as the first line of `codex.md`.
- A null `incident`, an unreadable file or any other `fault` (`rate-limited`, `capacity`, …) keeps today's record.
- Never decide from verdict or blockers text, which a model-authored `blocked` result can copy.

### Record the Codex outcome

Retain the bridge envelope's `status`, `confidence`, `confidence_null_reason` and `confidence_gaps` fields as returned for the Step 4 evidence handoff. In every route, use the Write tool to record the evidence in `$RUN_DIR/codex-review-reply.md` before Step 3 (bridge absent → `peer-unavailable`). Store original envelopes in fenced JSON blocks.

- **Single call or single-wave partition** records the original envelope.
- **Multi-wave partition** records every wave's original envelope, including its `splits` rows, along with the expected groups, the derived lane score and qualified gap lines, or a null score with the observed cause and any unscored group names.
- **Failure, skip or absence** records the observed failure, skip or absence reason with the original envelope if one returned. If no envelope exists, record the reason explicitly and leave the lane unscored.

After saving that evidence, record `codex-outcome` using [Record a decision](#record-a-decision): save the observed status, reason, reply path, output path when written, and quota status based on the incident. Load this decision for challenger routing and Step 6. If accepted bridge execution was interrupted, recover its actual outcome or record the lane as interrupted with the observed evidence and confidence gap.

After `$RUN_DIR/codex.md` is written (or skipped/blocked), extract compact seed list (≤10 items, `[{"loc":"file:line","note":"..."}]`) to inject into agent prompts in Step 3 as pre-flagged issues to verify or dismiss. Codex skipped, timed out, or found nothing → proceed with empty seed.

**Cap-disclosure**: count total Codex findings before truncating. If ≥10, surface in consolidated report header:

```text
Codex: first 10 items seeded to review agents; full list in $RUN_DIR/codex.md (N total) — review codex.md directly for complete coverage.
```

Pass notice through to consolidator (Step 5) so it appears in final report header, not just terminal scratch.

### Matched plan claim and Agent 0 — blind-solve (FEATURE/MIXED diff with a matching plan only, general-purpose)

Anti-anchoring pre-step: before any agent reads the diff, spawn a standalone agent that derives its own **blueprint-level** solution to the problem the change solves — approach + key data structures + edge cases, not full implementation. Bounded: ~10 tool calls, output ≤1 page. Isolation-motivated spawn, not work displacement — the blind agent must not share the orchestrator's context, so the "under ~73 calls → inline" rule does not apply; it still pays the fixed per-spawn overhead, hence the double gate below.

For every classification, inspect `.plans/active/*.md` with the Read tool. In diff mode, locate that directory from the Git root.

- Match only exact repository-relative paths listed in the plan's **Affected files** section against the review target's files; normalize `./` and path separators, never match stems or free-text mentions. A path/directory review uses its own files, not unrelated dirty files.
- Exactly one matching plan → record its resolved path under `matched-plan` using [Record a decision](#record-a-decision), as `{path, reason}` with reason `matched`.
- None or multiple matches → record an empty path and reason `missing` or `ambiguous` under the same decision.
- Agent 1 receives `PLAN_CLAIM=<resolved matched-plan path>` when present, for every classification; omit the binding otherwise.
- A matched plan remains an author's claim, never contract evidence.

Problem statement for Agent 0 = that matching plan file, nothing else. A local diff has no PR body; the last commit message describes the *previous* change when the target is the working tree, so it is never used. Only FEATURE/MIXED diff reviews run the block below — path/directory targets have no change baseline and skip blind-solve. No diff content is read:

```bash
# timeout: 10000
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
WORKTREE_ENABLED=$(jq -ber '.scope.worktree | tostring' <<< "$RECORD") || exit $?
# pre-change ref: working-tree diff → HEAD is untouched; --worktree reviews committed HEAD → parent is the pre-change state
FROZEN_HEAD=$(jq -ber '.frozen_head' <<< "$RECORD") || exit $?
if [ "$WORKTREE_ENABLED" = "true" ]; then PRE_REF="${FROZEN_HEAD}~1"; else PRE_REF="$FROZEN_HEAD"; fi
PLAN=$(jq -ber '.decisions["matched-plan"].value.path | strings' <<< "$RECORD") || { echo '! BLOCKED — run-record-matched-plan-missing' >&2; exit 1; }
if [ -n "$PLAN" ]; then
  CHANGED=$(jq -bce '.scope.paths | arrays | select(length > 0)' <<< "$RECORD") || exit $?
  { echo "## Plan: $PLAN"; sed -n '1,120p' "$PLAN"; echo; echo "## Changed files (names only)"; printf '%s\n' "$CHANGED"; echo; echo "PRE_REF=$PRE_REF"; } > "$RUN_DIR/blind-solve-input.md"
  echo "blind-solve input: $RUN_DIR/blind-solve-input.md plan=$PLAN pre-ref=$PRE_REF"
else
  echo "blind-solve: skipped — no unambiguous .plans/active/*.md Affected files match"
fi
```

`blind-solve: skipped` → no spawn; note the skip in the report header. Otherwise spawn with the contents of `$RUN_DIR/blind-solve-input.md` verbatim, then:

- "Your only source for pre-change code is `git show <PRE_REF>:<path>` for files listed above. Never use Read, `cat`, `git diff`, or any working-tree path — the working tree contains the change under review. Sketch your own solution to the stated problem — approach, key data structures/functions, edge cases — in ≤1 page. Do not write full code."
- Write to `$RUN_DIR/blind-solve.md`, return `{"status":"done","file":"$RUN_DIR/blind-solve.md","confidence":0.N}`.

Skip Agent 0 when classification is FIX/REFACTOR/CHORE (no fresh problem to solve blind) or target is a path/directory — checked before the block above runs; plan matching and the Agent 1 claim binding still apply. Launch in the same batch as the Step 3 spawn units — it needs no diff, nothing blocks it. Not a `FANOUT_MAX` unit — never counted against the cap, never ranked out, not part of any merged spawn unit.

## Step 3: Spawn sub-agents in parallel

Run [Review record recovery](#review-record-recovery). Use the saved target, classification, fan-out cap, impact, challenger flag, matched-plan and Codex outcome for the gates below. Require the Codex outcome and matched-plan decisions before selecting the lineup. On resumed dispatch, reuse the saved lineup and attempts.

**Spawn-count gate — apply before spawning anything.** Each agent costs ~120,851 tok fixed overhead regardless of how little work it does (~73 tool-calls' worth), plus ~12.0 s/call. Rules, all mandatory:

Three stages, in order — never collapse them:

1. **Classification preselection** (always): the FIX (at `IMPACT_TIER=LIGHT`) / CHORE skips above decide which dimensions are *relevant at all*. Agent 1 always survives because intended behavior applies to every review target. Any other dimension with no target file in its territory is out here and never comes back, at any flag.
2. **Unit grouping** (always): fold the survivors into spawn units per §Merged spawn units below — Agents 3+6 share one spawn, Agents 4+5 share one spawn, Agents 1 and 2 stay standalone. A unit exists when at least one of its dimensions survived stage 1; its prompt lists only the surviving dimensions' brief files.
3. **Relevance ranking** (default only): Agent 1 is never ranked out; reserve its unit within the cap, then rank the other units by evidence — target files and lines in their dimensions' territory, what the classification implies, what the structural context flagged (a merged unit ranks by its strongest surviving dimension) — and fill the remaining `FANOUT_MAX - 1` slots. With `--full` (`FANOUT_CAP=0`) skip this stage and spawn every unit of stage 2.
   - **Promotion within the cap.** Promote any surviving unit covering a changelog or migration guide, a CI workflow, or a stated performance claim in the target. Route CI test jobs to QA when that unit survives preselection and other CI workflow behavior to Agent 1, which also covers test jobs when QA is out. Include the trigger in the unit's delta task line. Rank promoted units ahead of lower-evidence units, using the existing evidence ranking within each group. Fill the remaining slots with unpromoted units. Agent 1 keeps its reserved slot and promotion adds no slots.
   - A promoted unit left unslotted gets an `Unreviewed dimension: <unit> — <trigger>` line and the 0.85 ceiling applies. Its required reviewer coverage is missing, so Readiness is `incomplete` and the lower 0.70 ceiling binds.

- More work → give each agent more, never add agents.
- **Spawn the fewest that keep each near `AGENT_CALL_BUDGET`** — not the most the cap allows. Small diff → merge surviving units into fewer spawns, **never zero**.
- **Diff size never licenses inline review.** ~73-call inline rule covers work-displacement spawns only; review specialists are role-isolated (own system prompt, independent eyes), so it does not apply here. Small diff ≠ low risk: few-line change on hot path often riskiest. Orchestrator never substitutes itself for a unit that survived stages 1–3.
- **Merge before you split**: two dimensions whose files overlap go to one agent, not two — the fixed pairs below are the floor, not the ceiling.
- Every spawn prompt states the budget, requires an envelope even on exhaustion — `partial: true` plus what was finished.

Dimensions dropped by the cap are listed in the report. Before spawning the batch, use the Write tool to save the cap decisions to `$RUN_DIR/lineup.md` for Step 4:

- **Cap-dropped** records the exact unit name, affected roles and cap reason for every drop.
- **Promoted but unslotted** records the exact unit name, promotion trigger and required roles for every unit left without a slot.
- **No omissions** records `No cap omissions` when every preselected unit ran or has a slot.

Save `lineup` with [Record a decision](#record-a-decision), including `selected_roles` (an array of durable role keys, one per selected dimension including merged spawns), the exact selected units, promoted but unslotted units, cap omissions and evidence path. Use it for Step 4 and resumed dispatches.

Use `review/challenger` as the challenger's durable role key in the lineup and dispatch records. When challenge is enabled and the challenger cannot be selected, record the reason against its initial attempt in `dispatch-refusal` before publication.

### Merged spawn units (shared pattern with oss:review — each spawn costs ~120,851 tok fixed overhead, so paired dimensions share one spawn)

- **Agents 3+6 = ONE `foundry:perf-optimizer` spawn** covering Performance + Architecture/API design — spawn when either dimension survives classification preselection; prompt lists only the surviving dimensions' brief files (e.g. FIX with a public-signature change spawns this unit with only the Agent-6 dimension active). (this merged spawn is explicitly authorized to also cover architecture/SOLID review; its own NOT-for line does not apply to this dispatch)
- **Agents 4+5 = ONE `foundry:doc-scribe` spawn** covering Documentation + Linting — same rule. (this merged spawn is explicitly authorized to also cover linting; its own NOT-for line does not apply to this dispatch)
- Agents 1 (sw-engineer, incl. security augmentation), 2 (qa-specialist), 7 (challenger) stay standalone spawns.
- A merged spawn writes **one file per covered dimension**, each with its OWN full sections + Confidence block — never blended: `perf-optimizer.md` + `solution-architect.md`, or `doc-scribe.md` + `linting-expert.md`. Downstream contracts (consolidator filename list, Step-4 cross-validation "same type as origin", report sections) key on those files, stay unchanged.
- Merged-spawn envelope = JSON array, one element per dimension file, same per-element schema as the standard envelope. Element absent from the array ⇒ that dimension gets the ⏱ marker — never silently omitted.

**File-based handoff** — load the protocol, then resolve the develop:review checklist path (version-agnostic) and the dimension-briefs directory (`$REVIEW_CHECKLIST` rules follow the preamble and pre-expansion rule below):

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" file-handoff-protocol.md  # timeout: 5000
# loads: the brief-*.md files in the loop — each child cats only its own; parent passes the directory path only
_DIMENSION_BRIEFS="$PLUGIN_ROOT/skills/review/templates"
for _B in brief-sw-engineer.md brief-qa-specialist.md brief-perf-optimizer.md brief-doc-scribe.md brief-linting-expert.md brief-security-augmentation.md brief-solution-architect.md brief-challenger.md; do
    [ -f "$_DIMENSION_BRIEFS/$_B" ] || { echo "! BLOCKED — dimension brief $_B missing; restore/reinstall this develop version before spawning review agents"; exit 1; }
done
echo "Dimension briefs: $_DIMENSION_BRIEFS"
REVIEW_CHECKLIST="$_DIMENSION_BRIEFS/review-checklist.md"  # develop's own copy — never read from the oss plugin
if [ -f "$REVIEW_CHECKLIST" ]; then
    echo "Checklist: $REVIEW_CHECKLIST"
else
    echo "⚠ review checklist unavailable — review will proceed without severity anchors; restore/reinstall this develop version for full coverage"
    REVIEW_CHECKLIST=""
fi
```

Run directory created before pre-flight and reloaded in Step 2 (`$RUN_DIR`).

<!-- $REPORT_DIR pre-expanded into $REPORT_DIR_LITERAL — substitute literal vars in Agent spawn prompt strings. Run-dir is the exception: agents self-resolve it (see run-dir preamble below), never hand-substituted. -->

### Run-dir preamble (canonical)

Place this in every agent spawn prompt (Agents 0–7, Step 4 verifiers and the Step 5 consolidator) as the paragraph **after** prompt line 1 — line 1 is the delta task line (dimension + target, ≤12 words, delta first; `agent-spawn.md`), never this shared boilerplate:

> "Pass the supplied absolute record path as `REVIEW_RECORD_PATH` and the parent's session ID as `REVIEW_SESSION_ID` when running the read-only run-directory fence. Keep both values for resume. Use its `$RUN_DIR` verbatim for every handoff file you read or write. Report a record refusal to the parent."
>
> "Read-only review: no source edits, no fixers, no dependency installation, no writes outside `$RUN_DIR`; direct all tool caches and temporary output there. Only the consolidator may additionally write the prescribed report and sidecars under `REPORT_DIR_LITERAL`. Do not execute reviewed code, examples or tests. Existing static analyzers and dependency audits may run without fixes, with caches under `$RUN_DIR`, within existing authorization; unavailable or incompatible checks remain explicit coverage gaps. Task tracking: do NOT call TaskCreate or TaskUpdate."

Supply the literal `REVIEW_RECORD_PATH` (`$RUN_DIR/run-record.json`) and `REVIEW_SESSION_ID` (`$CSID`) as data bindings in the prompt. Leave references to `$RUN_DIR` literal so the participant uses the directory verified by the fence.

Supply this fence verbatim with the preamble. `CLAUDE_PLUGIN_ROOT` is rendered by the owning develop skill before dispatch.

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${REVIEW_SESSION_ID:-${CLAUDE_CODE_SESSION_ID:-$PPID}}"
IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""
RUN_DIR=${RUN_DIR%$'\r'}
case "${REVIEW_RECORD_PATH:-}" in
    /*/run-record.json|[A-Za-z]:/*/run-record.json) ;;
    *) echo '! BLOCKED — run-record-locator-mismatch: absolute record path required' >&2; exit 1 ;;
esac
[ -n "$RUN_DIR" ] && [ "$RUN_DIR/run-record.json" = "$REVIEW_RECORD_PATH" ] || { echo '! BLOCKED — run-record-locator-mismatch' >&2; exit 1; }
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section scope || exit $?
printf 'RUN_DIR=%s\n' "$RUN_DIR"
```

### $VAR_LITERAL pre-expansion rule (canonical)

Any OTHER shell variable inserted into an Agent spawn prompt string — `$REPORT_DIR_LITERAL`, `$REVIEW_CHECKLIST`, `$DATE`, `$_REVIEW_TEMPLATE` — must be substituted with its literal resolved value **before** building the Agent call. Bare variable name inside a quoted Agent prompt will NOT expand — spawned agent receives literal dollar-sign text, causing path mismatches. Resolve each to its value first; never pass a bare `$VAR` name. (`$RUN_DIR` is the deliberate exception above — agents self-resolve it.)

Pass the resolved `$REVIEW_CHECKLIST` path (printed by the File-based handoff block above) as a `REVIEW_CHECKLIST=<resolved path>` binding line in Agent 1's spawn prompt and in the consolidator's. **Empty → omit that binding line from Agent 1's prompt entirely** — don't pass empty path.

For Agent 1, pass the recorded `matched-plan` decision's nonempty resolved path as `PLAN_CLAIM=<resolved matched-plan path>` alongside `REVIEW_CHECKLIST`; omit that binding if no unambiguous match exists. Agent 1 loads the claim itself.

**Visible-degradation rule** — `$REVIEW_CHECKLIST` empty → print `⚠ REVIEW_CHECKLIST is empty — review scope undefined` at TOP of review output (before Findings), and consolidator prompt (Step 5) **must** insert into report header (YAML `---` block or first line before Findings): "Review checklist not applied (review-checklist.md missing from this develop install) — severity anchors may be inconsistent." Silent degradation hides the gap from reviewers, makes severity drift invisible.

**Finding evidence standard — applies to every agent, every finding** (tiers, source independence and citation tracing per `quality-gates.md` §Evidence Grounding):

- Every finding must cite specific `file:line` from the target source (changed lines in diff mode) as primary evidence — "I know this typically causes issues" without a target citation isn't a valid finding
- Claims referencing external standards (OWASP, PEP, language spec, CVE) must cite the specific authoritative document — official spec, CVE entry, PEP text; a blog post or Stack Overflow answer referencing the standard is Tier 2 only
- Only Tier 2 available, distinct-origin count < 3, no experiment run → downgrade finding to LOW or drop it; never raise MEDIUM/HIGH/CRITICAL on Tier 2 alone

Launch spawn units simultaneously with Agent tool (security augmentation folded into Agent 1 — not separate spawn; Agent 6 optional; Agents 3+6 and 4+5 launch as merged units per §Merged spawn units; Agent 0 blind-solve joins this batch on FEATURE/MIXED, outside the cap). Every agent prompt opens with its delta task line, carries the [run-dir preamble (canonical)](#run-dir-preamble-canonical) next, and ends with:

> "Write your FULL findings (all sections, Confidence block) to `$RUN_DIR/<agent-name>.md` using the Write tool — where `<agent-name>` is e.g. `sw-engineer`, `qa-specialist`, `perf-optimizer`, `doc-scribe`, `linting-expert`, `solution-architect`. Include your scoped source_outcome, source_rating (source-5-v2 integer 1–5 or null when undecidable), rationale, readiness (complete/blocked/incomplete), readiness_reason and inspected coverage (paths and checks, including unavailable checks). Then return to the caller ONLY a compact JSON envelope on your final line — nothing else after it (a merged unit returns the JSON array of §Merged spawn units instead, one such object per dimension file): `{\"status\":\"done\",\"findings\":N,\"severity\":{\"critical\":0,\"high\":1,\"medium\":2,\"low\":0},\"file\":\"$RUN_DIR/<agent-name>.md\",\"confidence\":0.88,\"source_outcome\":\"MINOR_EDITS\",\"source_rating\":2,\"rationale\":\"<scoped judgment basis>\",\"readiness\":\"complete\",\"readiness_reason\":\"<completed checks or verification limits>\",\"coverage\":[\"<inspected path/check>\"]}`. Replace example judgments with your actual scoped assessment."

**Codemap-py context preamble (substituted by orchestrator)**: use `scope.codemap_available` from the checked record, defaulting to false if pre-flight was disabled.

- When `codemap_available=true`, each dimension spawn prompt is prefixed with its `## Structural Context (codemap-py, codemap_available=true)` slice from `$RUN_DIR/codemap-context.md` per the per-agent slicing rules in Step 1.
- Agents must read that block first and skip redundant Grep/Read on symbols already covered by codemap output.
- Block absent → fall back to current file-read behaviour.
- Challenger (Agent 7) unchanged.

**Dimension briefs** — each dimension's full instructions live in its own file under `templates/` (directory printed above as `Dimension briefs: …`):

- Agent 1 → `brief-sw-engineer.md` (with its API-consistency audit and error-path table)
- Agent 2 → `brief-qa-specialist.md`
- Agent 3 → `brief-perf-optimizer.md`
- Agent 4 → `brief-doc-scribe.md`
- Agent 5 → `brief-linting-expert.md`
- Security augmentation → `brief-security-augmentation.md`
- Agent 6 → `brief-solution-architect.md`
- Agent 7 → `brief-challenger.md`

Do NOT cat, Read or inline them into orchestrator context or the Agent prompt; the child loads them. After the run-dir preamble each spawn prompt carries:

1. One load instruction — a single Bash `cat` of `<DIMENSION_BRIEFS_LITERAL>/<brief file>` for each surviving dimension of that spawn unit (Agents 3+6 and 4+5 list only their survivors; Agent 1 adds the security brief when augmentation is dispatched), followed by "follow ONLY these briefs".
2. Then the literal bindings (`REVIEW_CHECKLIST=<resolved path>` for Agent 1, line omitted when empty; bindings are values, never text to execute).
3. Then the findings-write instruction above.

A `§Merged spawn units` mention inside a brief only describes how this orchestrator grouped dimensions; the prompt names the briefs to follow. `DIMENSION_BRIEFS_LITERAL` is the resolved path, never a bare `$_DIMENSION_BRIEFS`.

Dispatch triggers stay here — the orchestrator decides before any child reads the file:

- **Security augmentation** (folds into Agent 1, never a separate spawn): target touches authentication, user input handling, dependency updates, or serialization → add the security brief to Agent 1's brief list. Skip for purely internal refactoring.
- **Agent 6** (optional, folds into the Agents 3+6 unit): target touches `__init__.py` exports, adds/modifies Protocols or ABCs, changes module structure, introduces new public classes, or changes the signature of any already-exported public function (added/removed/renamed params, new flags), or removes, renames or moves an exported module, class or function → include the Agent 6 brief. Skip for purely internal (non-exported) implementation changes.
- **Agent 7** (challenger): skip only if `CHALLENGE_ENABLED=false`; runs at any diff size. Include `--no-codex` in its prompt when Step 2 completed `bridge:review` on the same target; omit it when that co-review was skipped or unavailable. Apply this rule to any challenger redispatch on the same material.
  - Exception to the omit rule: when `$RUN_DIR/codex.md` opens with `codex-blocked:quota` (the peer is out of credits for the rest of the run), include `--no-codex`.
  - Agent 7's envelope carries `"codex_blocked": "quota"` (its own Codex cross-check met the quota fault) → make `codex-blocked:quota` the first line of `$RUN_DIR/codex.md` (Write it when absent, insert it above any existing content otherwise). Update `codex-outcome` with the quota status so a Step 4 challenger verifier and any later challenger on this material carry `--no-codex`.

**Challenger severity propagation**: consolidator (Step 5) reads `challenger.md` → map its findings by section before merging:

- Blockers (`[CRITICAL]`) → `critical` or `high` (promote to `critical` only when independently corroborated, e.g. a Step 4 CONFIRMED verdict or matching evidence from another agent; otherwise keep the required independent verification open, never downgrade uncertainty into actionable high severity)
- Concerns (`[HIGH]`) → `medium`
- Nitpicks (`[LOW]`) → `low`

Never drop challenger candidates from validation; only parent-CONFIRMED claims become findings, and uncertainty stays separately durable.

**Health monitoring**: arm batch `review` in the spawn response — deliverable `$RUN_DIR/<agent-name>.md` per dimension file (a merged unit gets one row per file); Step 4 verifiers arm `verify`, the Step 5 consolidator arms `consolidate` (deliverable `-`); run the check block once per wake-up (`agent-resolution.md` §Agent waits — no polling, per-agent deadlines).

- Agent calls run in background. Spawn the batch, record accepted attempts, end the turn, resume on each completion notification — no filler tool calls, no "waiting" turns, no sleep, and never `ScheduleWakeup`, `ListAgents`, or a `Monitor` loop: the notification is the only resume signal (`agent-resolution.md` §Agent waits — no polling).
- An agent whose completion or idle notification arrives while `$RUN_DIR/<agent-name>.md` is still missing is ⏱ `timed_out` at once — never wait on it further.
- Agent returns partial results or errors → use Read tool on `$RUN_DIR/<agent-name>.md` for details.
- Mark agents that returned empty or error with ⏱ in final report.
- Never silently omit agents that **failed** (returned error/partial) — must appear with ⏱ marker.
- Agents **not spawned** (skipped due to mode flags, docs-only, CHORE mode) may be absent from RUN_DIR; consolidator "skip missing" applies only to legitimately-not-spawned agents.

### Record dispatch and return attempts

Use the same recorder for the `review`, `verify` and `consolidate` batches. Before issuing a batch, save `dispatch-intent` in [Record a decision](#record-a-decision) with a `roles` array of `{role, attempt, watch}` rows and the coverage decisions. Carry forward each earlier role's latest intent across batches and update its row only on an authorized retry. On dispatch response, stage actual accepted roles with the Write tool at `$RUN_DIR/review-roles.json`, as a JSON array of `{role, status: "spawned", attempt}`. Use `review/<dimension>`, `verify/<batch-slot>` and `consolidate/report` as durable role keys. A merged spawn has one row per covered dimension. Use attempt 1 for a new role and increase it only for an explicitly authorized redispatch; take prior attempts from the record. Run the following fence before yielding for notifications. Never mark a refused or deferred tool call as accepted. Before applying the fallback, add the affected role to the `roles` array of `dispatch-refusal` as `{role, attempt, status, reason}`, with status `refused` or `incomplete` and the coverage reason. Preserve earlier rows across batches and disclose these coverage limits in the report. If an interruption left intent with neither acceptance nor a recorded disposition, recover the matching tool receipt before dispatching again; if the outcome cannot be established, stop with `run-record-dispatch-unconfirmed`.

```bash
# Review accepted dispatch
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
jq -bce 'select(type == "array" and length > 0 and all(.[]; .status == "spawned"))' "$RUN_DIR/review-roles.json" |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section roles_spawned --value-stdin || exit $?
rm -f -- "$RUN_DIR/review-roles.json" || exit $?
```

For an authorized retry, use the next attempt after the latest accepted spawn for that role, or attempt 1 if none was accepted. Before issuing a retry for an already refused attempt number, remove that attempt's stale refusal from the active `dispatch-refusal` decision and retain the prior refusal as coverage evidence. The active refusal must describe the current dispatch outcome.

On each wake-up, recover the record first, then run this watch fence once before consuming results. Apply the existing notification and deadline rules to that batch and attempt. Stage terminal rows in the same `review-roles.json` file using `{role, status, attempt}` with `done`, `partial`, `error` or `timed_out`; recording a partial return preserves the existing coverage warning. Before recording a successful consolidator return, save its exact claim envelope as the pending `consolidation` decision in Step 5. Record only the attempt identified by its notification or deadline. Ignore superseded notifications. An accepted role with no return cannot be redispatched based on a missing handoff file. When the consolidator is unavailable before acceptance, save the refusal and the parent fallback decision without adding a fabricated role row.

```bash
# Review dispatch watch
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
WATCH_DIR=$(jq -ber '.scope.watch_dir | strings | select(length > 0)' <<< "$RECORD") || { echo '! BLOCKED — run-record-watch-missing' >&2; exit 1; }
[ -d "$WATCH_DIR" ] || { echo '! BLOCKED — run-record-watch-missing' >&2; exit 1; }
python -I "$PLUGIN_ROOT/bin/agent_watch.py" --state-dir "$WATCH_DIR" || exit $?  # timeout: 5000
```

```bash
# Review terminal role return
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
jq -bce 'select(type == "array" and length > 0 and all(.[]; .status | IN("done", "partial", "error", "timed_out")))' "$RUN_DIR/review-roles.json" |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section roles_returned --value-stdin || exit $?
rm -f -- "$RUN_DIR/review-roles.json" || exit $?
```

### Record a decision

Use the Write tool to stage one JSON object `{name, value}` at `$RUN_DIR/review-decision.json`, then run this fence immediately at the named transition. `value` contains the observed outcome and any evidence paths. For per-batch decisions, carry forward earlier batch entries from the checked record, including their attempts; each update replaces the named decision. After a successful write, resume from the record even if the staging file is gone.

```bash
# Review decision transition
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
DECISION=$(jq -ber '.name' "$RUN_DIR/review-decision.json") || exit $?
case "$DECISION" in
    codex-outcome|matched-plan) STEP=co-review ;;
    lineup|dispatch-intent|dispatch-refusal) STEP=dispatch ;;
    validation) STEP=validation ;;
    consolidation) STEP=consolidation ;;
    worktree-exit|follow-up) STEP=follow-up ;;
    *) echo '! BLOCKED — run-record-unknown-review-decision' >&2; exit 1 ;;
esac
if [ "$DECISION" = consolidation ]; then
    DECISIONS=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section decisions) || exit $?
    jq -bc --slurpfile staged "$RUN_DIR/review-decision.json" '
        def claim_ids: type == "array" and all(.[]; type == "string" and length > 0);
        (if has("consolidation") then .consolidation.value.new_claims else [] end) as $previous
        | $staged[0].value
        | if ($previous | claim_ids) and (.new_claims | claim_ids) and (($previous - .new_claims) | length == 0)
          then . else error("run-record-consolidation-claims-dropped") end
    ' <<< "$DECISIONS"
else
    jq -bc 'if has("value") then .value else error("review decision value missing") end' "$RUN_DIR/review-decision.json"
fi |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --decision "$DECISION" --step "$STEP" --value-stdin || exit $?
rm -f -- "$RUN_DIR/review-decision.json" || exit $?
```

## Step 4: Validate all candidates and independently verify critical/blocking concerns

Run [Review record recovery](#review-record-recovery). Write the agent phase reports, `lineup.md` and `codex-review-reply.md` to the run-dir before this refresh. The boundary inventories all three under `finding-files`. Use the recorded review attempts to distinguish outstanding, failed and legitimately omitted roles before validating their candidates.

```bash
# compaction boundary 1 (compaction-contract.md §Lifecycle) — written before entering Step 4
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
_RUN_DIR="$RUN_DIR"
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$_RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$_RUN_DIR") || exit $?
_REPORT_DIR=$(jq -ber '.scope.report_dir | strings | select(length > 0)' <<< "$RECORD") || exit $?
_TARGET=$(jq -ber '.scope.target | if . == "" then "working-tree diff" else (.) end' <<< "$RECORD") || exit $?
_CLASS=$(jq -ber '.decisions.classification.value' <<< "$RECORD") || exit $?
_FINDING_FILES=$(ls "$_RUN_DIR/"*.md 2>/dev/null | tr '\n' ' ' | sed 's/ *$//')
_PRESERVE="run-record=$_RUN_DIR/run-record.json, report-dir=$_REPORT_DIR, target=$_TARGET, classification=$_CLASS, finding-files=$_FINDING_FILES"
python -I "$PLUGIN_ROOT/bin/write_skill_contract.py" --keep-sentinel dev-review-keep-items "develop:review" "consolidation (after parallel review-agent fan-out)" "$_RUN_DIR" "$_PRESERVE" "resume: check the review record; re-cat own agent-resolution.md, file-handoff-protocol.md and foundry--cross-validation-protocol.md; cross-validate critical findings (Step 4) → consolidate → final report" -- calls_ahead=20 "drop=expanded review findings" || exit $?  # timeout: 5000
IFS= read -r _DEV_SHARED < "${TMPDIR:-/tmp}/dev-shared-${CSID}" 2>/dev/null || _DEV_SHARED=""
[ -z "$_DEV_SHARED" ] && _DEV_SHARED="plugins/cc_develop/skills/_shared"
python -I "$PLUGIN_ROOT/bin/compaction_boundary.py" "$_DEV_SHARED" || exit $?
RUN_DIR="$_RUN_DIR"
[ -n "$RUN_DIR" ] || { echo "! BLOCKED — run-dir sentinel empty; refusing to write cross-validation notes to a root-relative path"; exit 1; }
if [ ! -f "$_DEV_SHARED/foundry--cross-validation-protocol.md" ]; then
    echo "⚠ foundry--cross-validation-protocol.md not found at $_DEV_SHARED — Step 4 skipped; required validation is incomplete. It ships in this plugin — reinstall develop@borda-ai-rig."
    echo "## Cross-Validation: SKIPPED" >> "$RUN_DIR/cross-validation.md"
    echo "**Reason**: _DEV_SHARED unavailable — cross-validation protocol not executed." >> "$RUN_DIR/cross-validation.md"
else
    cat "$_DEV_SHARED/foundry--cross-validation-protocol.md"
fi
```

Follow the Boundary step printed above before candidate validation and consolidation; reports are the preserved finding-files in the run-dir.

Read `$RUN_DIR/lineup.md` and `$RUN_DIR/codex-review-reply.md` with the Read tool after the boundary, including on resume. Use the `lineup` and `codex-outcome` decisions as the source for selected roles and the lane outcome. If an evidence file is missing or unreadable, recover it from available run evidence. If recovery fails, record that coverage evidence is incomplete, name the missing evidence and the recovery check, and leave any unsupported Codex score unscored.

File present → parent validates all candidates using the printed protocol before consolidation. File absent → record incomplete process coverage, owner and reinstall recovery; no unconditional approval or unvalidated actionable findings. Exhaust allowed static checks. A child read-only limit does not establish that authorized parent runtime checks are infeasible; record the actual authorization/capability boundary and next check when blocked, and feasible undone work as incomplete.

**Skill-specific**: use **same agent type** that raised finding as verifier (e.g. foundry:sw-engineer verifies foundry:sw-engineer's critical finding). **Spawn cap: max 3 verifier agents** — critical/blocking findings > 3 → group into batches of ≤2 findings per verifier (same origin type per batch); note grouped IDs in rationale; each finding still gets its own verdict. Same cap as the shared protocol and oss:review — unbounded verifier fanout costs ~120,851 tok per critical finding.

Before consolidation, persist the parent's all-severity candidate validation and reviewer assessment evidence in `$RUN_DIR/cross-validation.md` with the Write tool.

- Include structured envelope fields defined by the loaded protocol and retain all dispositions.
- Copy the bridge evidence and cap decisions from those records into `$RUN_DIR/cross-validation.md`, including any unresolved coverage evidence gap. Include returned reviewer confidence scores and whether an authorized runtime check ran against the reviewed source.
- Pass that literal evidence path to the consolidator.
- Parent rechecks new/materially strengthened claims and the final envelope before delivery; a model's confirmation label alone is not proof.
- Non-empty `new_claims` in the consolidator envelope → validate each listed candidate ID against the source before delivery; any still unvalidated stays out of Findings and is listed under the report's open concerns.

If the protocol was unavailable, the parent's final Write must retain `## Cross-Validation: SKIPPED` and its reason in `cross-validation.md`; do not overwrite the earlier marker with validation notes that omit it.

Save `validation` with [Record a decision](#record-a-decision) when this gate finishes. Include `status` (`complete` or `incomplete`), `evidence` (the path to `cross-validation.md`, absolute or relative to `$RUN_DIR`), and unresolved checks. A `complete` decision requires a regular, non-empty evidence file under `$RUN_DIR` at consolidation and publication. Apply the same dispatch and return recorder to every verifier attempt before using its outcome.

## Step 5: Consolidate findings

Run [Review record recovery](#review-record-recovery) and the evidence fence below on every Step 5 entry, including resume. The fence also prints the report date and the frozen report and source bindings for a new dispatch.

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
jq -be '.decisions.validation.value.status | IN("complete", "incomplete")' <<< "$RECORD" >/dev/null || { echo '! BLOCKED — run-record-validation-missing' >&2; exit 1; }
if jq -be '.decisions.validation.value.status == "complete"' <<< "$RECORD" >/dev/null; then
    EVIDENCE=$(jq -bce '.decisions.validation.value.evidence | strings | select(length > 0)' <<< "$RECORD") &&
        python -I - "$RUN_DIR" "$EVIDENCE" <<'PY' || { echo '! BLOCKED — run-record-validation-evidence-missing' >&2; exit 1; }
import json
import stat
import sys
from pathlib import Path

try:
    root = Path(sys.argv[1]).resolve(strict=True)
    path = (root / json.loads(sys.argv[2])).resolve(strict=True)
    if not path.is_relative_to(root):
        sys.exit(1)
    info = path.stat()
except (OSError, RuntimeError, ValueError):
    sys.exit(1)
sys.exit(not (stat.S_ISREG(info.st_mode) and info.st_size > 0))
PY
fi
jq -ber '.scope | "REPORT_DIR_LITERAL=\(.report_dir)\nREVIEWED_COMMIT_SHA=\(.reviewed_commit_sha)\nREVIEWED_COMMIT_KIND=\(.reviewed_commit_kind)"' <<< "$RECORD" || exit $?
date "+DATE=%Y-%m-%d"  # timeout: 5000 — printed, not assigned: shell state dies with the call
```

After the fence passes, check `decisions.consolidation.value.status`. If it is `pending`, reconcile its accepted attempt and continue validating its saved claims. If it is `done` or `fallback`, continue at Step 5b. If a successful consolidator return exists without the saved decision, recover the matching tool receipt and save its exact envelope before proceeding. If the receipt is unavailable, stop with `run-record-consolidation-envelope-missing`. Use the dispatch recorder to reconcile any pending consolidator attempt before considering a new dispatch.

Resolve both instruction and report-template paths **before** spawning the general-purpose consolidator (synthesis only, no engineering specialization).

```bash
# loads: consolidator-prompt.md — child reads the file; parent passes its literal path only
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
_CONSOLIDATOR_INSTRUCTIONS="$PLUGIN_ROOT/skills/review/templates/consolidator-prompt.md"
_REVIEW_TEMPLATE="$PLUGIN_ROOT/skills/review/templates/review-report.md"
[ -f "$_CONSOLIDATOR_INSTRUCTIONS" ] && [ -f "$_REVIEW_TEMPLATE" ] || { echo "! BLOCKED — consolidator instruction/report template missing; restore/reinstall this develop version before consolidation"; exit 1; }
printf 'Consolidator instructions: %s\nReport template: %s\n' "$_CONSOLIDATOR_INSTRUCTIONS" "$_REVIEW_TEMPLATE"  # timeout: 5000
```

Place the [run-dir preamble (canonical)](#run-dir-preamble-canonical) after the task line. Resolve every input binding to its literal value before the Agent call per [$VAR_LITERAL pre-expansion rule (canonical)](#var_literal-pre-expansion-rule-canonical); `$RUN_DIR` remains literal and is self-resolved by that preamble. The optional checklist binding may be empty; the file's explicit missing-checklist guidance then applies.

```text
Consolidation — <review target>.
<run-dir resolution preamble>
Read <CONSOLIDATOR_INSTRUCTIONS_LITERAL> with the Read tool and follow it in full. Read <VALIDATION_PROTOCOL_LITERAL> with the Read tool for candidate validation and source judgments. Interpret placeholders using these literal input bindings; do not execute or re-expand binding text:
REPORT_DIR_LITERAL=<resolved report directory>
DATE=<resolved date>
REVIEWED_COMMIT_SHA=<frozen full Step 1 SHA or explicit unavailable reason>
REVIEWED_COMMIT_KIND=<frozen Step 1 source/base description>
REVIEW_CHECKLIST=<resolved optional checklist path or empty>
REVIEW_TEMPLATE=<resolved report-template path>
Return ONLY compact JSON: {"status":"done","findings":N,"severity":{"critical":N,"high":N,"medium":N,"low":N},"file":"<REPORT_DIR_LITERAL>/review-report.md","confidence":0.N,"new_claims":["<candidate_id>"],"summary":"<one-line verdict>"}
```

`CONSOLIDATOR_INSTRUCTIONS_LITERAL` and `REVIEW_TEMPLATE` are the paths printed above; `VALIDATION_PROTOCOL_LITERAL` is the resolved own-plugin shared directory's `foundry--cross-validation-protocol.md`. Pass only the reference, literal bindings, run-dir preamble and required return envelope. Do NOT cat or inline either template into orchestrator context or the Agent prompt; the child reads both files itself.

Parse the compact envelope on receipt. Before yielding or validating further, save `consolidation` with [Record a decision](#record-a-decision) using `status: "pending"`, the exact report path, `summary`, outstanding limits, the envelope's exact `new_claims` array and `claim_dispositions: {}`. Apply the Step 4 validation rule to each ID and save its disposition in the same decision as soon as its evidence is recorded. On resume, continue from the first unsettled ID. Use `summary` as the one-line verdict.

**Consolidator-unavailable fallback**: `Agent` tool deferred or consolidator times out → read the same instruction file and each agent finding file from `$RUN_DIR/` directly, apply the full validation, precision gate, density and output rules, synthesize the report, and write `$REPORT_DIR/review-report.md` with the Write tool. Missing instruction/report-template files block with restore/reinstall recovery; never synthesize from absent rules.

After parsing confidence scores: any agent scored < 0.7 → prepend **⚠ LOW CONFIDENCE** to that agent's findings section, state gap explicitly. Never silently drop uncertain findings.

Update `consolidation` with [Record a decision](#record-a-decision) after checking the envelope or parent fallback. Record `status` (`done` or `fallback`), the exact `report` path, summary and outstanding limits. Preserve `new_claims` (use an empty array when there are none) and save `claim_dispositions` keyed by candidate ID. The decision fence refuses updates that drop a recorded claim ID. Use `confirmed` for validated findings, `rejected` for refuted claims and `open-concern` for obligations that remain open and are excluded from Findings. Keep the report and sidecars in agreement with those dispositions. Record the consolidator's accepted attempt and terminal status where applicable.

TaskUpdate "Step 5b: Print report header" → `in_progress`.

**MANDATORY, not optional narration** — the consolidator's returned JSON envelope is a routing signal only; it is never printed to the user and never satisfies this step. Prepare items 1–3 in this exact order, in this same turn, before any other Step 5/6 output; deliver items 4–5 in the final response:

1. read the top of `$REPORT_DIR/review-report.md` via the Read tool with `limit=60` — the `---` header through its closing delimiter, plus the legend, aggregate summary and findings overview below it; never a bound that stops inside the header, and never the whole file (the detailed finding sections are 5–20K tok and are read per item, later, on demand). A report whose overview runs past that bound: re-read with `offset` from the last line delivered, never the whole file.
2. render its fields as a two-column Markdown table (`Field | Value`, one row per key, file order) without the file-only rows `Link`, `Date`, `Commit SHA`, `Agents`, `Review contract`, `Rating scale`, `Readiness` and `Gate`, and with `PR` shown as `[#N](<Link value>)` per quality-gates.md §Report File Format — never the raw `---`-delimited block.
3. complete the delivery block: the reviewer legend immediately below the table, then the aggregate summary as prose and limits, kept short: 2–3 sentences, each critical/high finding on one line, limits as at most 3 bullets. The table is the required core — its `Path` row points at the full report, where the findings overview with its Author column and the detailed review content stay; end with `→ saved to $REPORT_DIR/review-report.md`.
4. Deliver the block once in the final reply after the answer, after its last tool call, never as Bash/tool stdout. Do not print the header table before the follow-up question or put it in option previews. The question carries only the plain summary defined below; the full table stays in the report file until final delivery. On a no-question path, the block still opens the final reply after all Step 6/7/8 tool calls that apply. The `Stop` hook requires the matching review header table there (the file-only rows may be left out); the question summary does not satisfy final delivery.
5. TaskUpdate "Step 5b: Print report header" → `completed` in the response that delivers the final block, beside the last tool calls immediately before the table text, never at the follow-up question.

Report file already contains the fields — no separate prepend needed.

> **Output-Routing exemption**: the follow-up question carries only a plain summary; quality-gates.md §Report File Format's table-first-in-reply rule and Output Routing step 2a apply to the final reply after the answer, and to no-question paths. The table IS the final reply's header — omit the `╔═╗` Re:Anchor box (communication.md exempts quality-gates `---` report headers). Never emit both a box header and this table.

After preparing the report header from the checked report, run [Review record recovery](#review-record-recovery) and then this publication fence before boundary 2. A refusal leaves publication pending and blocks follow-up and delivery. A replay of the same publication is safe.

```bash
# Review report publication
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
set -o pipefail
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
SOURCE_DIR=$(jq -ber '.scope.source_dir | strings | select(length > 0)' <<< "$RECORD") || exit $?
[ -d "$SOURCE_DIR" ] || { echo '! BLOCKED — run-record-source-missing' >&2; exit 1; }
if ! LIVE_HEAD=$(git -C "$SOURCE_DIR" rev-parse --verify HEAD 2>/dev/null); then
    case $(jq -br '.scope.reviewed_commit_sha' <<< "$RECORD") in
        'unavailable (non-Git directory or unborn HEAD)') LIVE_HEAD=$(printf '%040d' 0) ;;
        *) echo '! BLOCKED — run-record-stale-head: captured source HEAD is unavailable' >&2; exit 1 ;;
    esac
fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review --head "$LIVE_HEAD" || exit $?
REPORT=$(jq -ber '.scope.report_path | strings | select(length > 0)' <<< "$RECORD") || { echo '! BLOCKED — run-record-report-path-missing' >&2; exit 1; }
[ -f "$REPORT" ] && [ -s "$REPORT" ] || { echo '! BLOCKED — run-record-report-missing' >&2; exit 1; }
jq -be --arg report "$REPORT" '
    def disposition($roles; $expected):
        any($roles[]; .role == $expected.role and .attempt == $expected.attempt
            and (.status | IN("refused", "incomplete")) and (.reason | strings | length > 0));
    def returned($roles; $expected):
        any($roles[]; .role == $expected.role and .attempt == $expected.attempt);
    def claims_settled:
        . as $consolidation | (.new_claims | type == "array") and (.claim_dispositions | type == "object")
        and all(.new_claims[]; . as $id | (type == "string" and length > 0)
            and ($consolidation.claim_dispositions[$id] | IN("confirmed", "rejected", "open-concern")));
    def coverage_settled:
        (.decisions.lineup.value.selected_roles) as $selected
        | (.decisions["dispatch-intent"].value.roles) as $intent
        | (.decisions["dispatch-refusal"].value.roles // []) as $refused
        | .roles_returned as $returns
        | ($selected | type == "array") and ($intent | type == "array") and ($refused | type == "array")
        and (.scope.challenge != true or any($selected[]; . == "review/challenger")
            or disposition($refused; {role: "review/challenger", attempt: 1}))
        and all($selected[]; {role: ., attempt: 1} as $initial | (type == "string" and length > 0)
            and (any($intent[]; .role == $initial.role) or disposition($refused; $initial)))
        and all(.roles_spawned[]; . as $spawn
            | any($intent[]; .role == $spawn.role and .attempt >= $spawn.attempt)
            and returned($returns; $spawn))
        and all($intent[]; . as $expected | (.role | type == "string" and length > 0)
            and (.attempt | type == "number" and . >= 1 and floor == .)
            and (returned($returns; $expected) or disposition($refused; $expected)));
    (.publication.state | IN("pending", "published"))
    and (.decisions.validation.value.status | IN("complete", "incomplete"))
    and (.decisions.consolidation.value.status | IN("done", "fallback"))
    and (.decisions.consolidation.value.report == $report)
    and (.decisions.consolidation.value | claims_settled)
    and coverage_settled' <<< "$RECORD" >/dev/null || { echo '! BLOCKED — run-record-publication-incomplete' >&2; exit 1; }
if jq -be '.decisions.validation.value.status == "complete"' <<< "$RECORD" >/dev/null; then
    EVIDENCE=$(jq -bce '.decisions.validation.value.evidence | strings | select(length > 0)' <<< "$RECORD") &&
        python -I - "$RUN_DIR" "$EVIDENCE" <<'PY' || { echo '! BLOCKED — run-record-validation-evidence-missing' >&2; exit 1; }
import json
import stat
import sys
from pathlib import Path

try:
    root = Path(sys.argv[1]).resolve(strict=True)
    path = (root / json.loads(sys.argv[2])).resolve(strict=True)
    if not path.is_relative_to(root):
        sys.exit(1)
    info = path.stat()
except (OSError, RuntimeError, ValueError):
    sys.exit(1)
sys.exit(not (stat.S_ISREG(info.st_mode) and info.st_size > 0))
PY
fi
if jq -be --arg report "$REPORT" '.publication.state == "published" and .publication.report == $report' <<< "$RECORD" >/dev/null; then exit 0; fi
jq -bc --arg report "$REPORT" '{state: "published", report: $report, head: .frozen_head}' <<< "$RECORD" |
    python -I "$PLUGIN_ROOT/bin/run_record.py" set --run-dir "$RUN_DIR" --section publication --value-stdin || exit $?
```

```bash
# compaction boundary 2 (compaction-contract.md §Lifecycle)
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
PUBLICATION=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section publication) || exit $?
REPORT=$(jq -ber 'select(.state == "published") | .report | strings' <<< "$PUBLICATION") || { echo '! BLOCKED — run-record-report-not-published' >&2; exit 1; }
python -I "$PLUGIN_ROOT/bin/write_skill_contract.py" "develop:review" "follow-up (after consolidation)" "$RUN_DIR" "run-record=$RUN_DIR/run-record.json, final-report=$REPORT" "Check the review record; Step 6 only with Codex output; finish any pending worktree exit before follow-up or delivery" || exit $?  # timeout: 5000
```

## Step 6: Delegate implementation follow-up (optional)

Run [Review record recovery](#review-record-recovery). Read the persisted Codex outcome for the optional implementation follow-up:

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
DECISIONS=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section decisions) || exit $?
CODEX_OUT=$(jq -ber '."codex-outcome".value | objects | (.output // "")' <<< "$DECISIONS") || { echo '! BLOCKED — run-record-codex-outcome-missing' >&2; exit 1; }  # timeout: 5000
if [ -n "$CODEX_OUT" ] && [ -f "$CODEX_OUT" ]; then echo "CODEX_OUT=$CODEX_OUT"; else echo "→ no Codex output — Step 6 skipped"; fi
```

Block printed the skip line (`$CODEX_OUT` empty or file at that path doesn't exist) → continue at [Worktree exit and follow-up](#worktree-exit-and-follow-up).

After consolidating, identify findings Codex could implement — not style violations (pre-commit handles those), but bounded code or documentation work grounded in the actual implementation. The review only names them; it never edits code. A fix applied inside review would land outside the fix skills' reproduce-test-verify loop and could collide with their later edits to the same file.

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
python -I "$PLUGIN_ROOT/bin/dev_load_shared.py" codex-delegation.md  # timeout: 5000
```

Apply the "good fit" and "don't delegate" criteria defined there (when found) — criteria only; never invoke `bridge:implement` from this step. Qualifying findings → print a `### Codex-eligible findings` section listing each finding's location and a one-line brief, and add them to the report's **Recommended Next Steps** as candidates for a `bridge:implement` call by the fix workflow or the user. None qualify → omit the section.

## Worktree exit and follow-up

**Hard gate**: before the follow-up question, the Step 5b header table and plain summary must already be built from the current report file. Not built → go back and do it now (see Step 5b). The question carries the summary; the full delivery block opens the final reply after the answer (or on a no-question path). Keep "Step 5b: Print report header" `in_progress` until that final delivery.

**Hook-enforced**: on `Stop`, `hooks/enforce-review-header.js` keeps a turn going once per report when its final reply lacks the matching review header table — skipping the follow-up question does not skip delivery.

- At question time it blocks only this workflow's follow-up until the current report exists and the first question's text names the report path and its `Title`, `Outcome` values as a short plain summary, no table.
- Option descriptions and previews do not supply the summary.
- Missing evidence blocks this transition; apply the placement the deny reason names, then retry.
- Diagnostic/recovery questions remain available; use their own question header, not `dev-review`.
- The existing sentinel lifetime still scopes this workflow guard; it does not prove UI rendering or report correctness.

**Worktree exit** — if the record has `scope.worktree=true` and no successful `worktree-exit` decision: the report already lives in the main tree (§Deliverable). Follow `worktree-isolation.md` §Exit — capture branch, call `ExitWorktree(action="keep")`, append the `Worktree` block to the report/output. Save the verified branch and `status: "complete"` under `worktree-exit` using [Record a decision](#record-a-decision). Exit **before** the follow-up gate so the `/develop:fix`/`/develop:refactor` next-step suggestions below point at the main tree. Never auto-merge.

On resume, if the native exit already succeeded, recover its matching tool receipt, verify the recorded worktree and branch, and finish the annotation and decision from that evidence. Call `ExitWorktree` only when still in the recorded worktree. If the exit outcome cannot be established, stop before follow-up with `run-record-worktree-exit-unconfirmed`.

**Suggested next steps** (plain text, not selectable — `/develop:fix` and `/develop:refactor` both carry `disable-model-invocation: true`, so `Skill()` dispatch is impossible for either): for each blocking finding, print `Run: /develop:fix "<finding title> (<file:line>)"` with the actual title and location to reproduce with a test and apply a targeted fix; structural/quality issues found → `Run: /develop:refactor` for test-first improvements.

Refresh the contract right before the gate — boundary 2 was written before Step 6 pulled more into context when Codex output was available — and print the hint so a long wait can be spent compacted. Run the block after a worktree exit to place the contract in the main tree, including when Step 6 was skipped. If Step 6 was skipped and no worktree was entered, boundary 2 already carries the gate resume line.

```bash
# compaction boundary 3 — immediately before the follow-up idle gate (compaction-contract.md §Lifecycle)
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
PUBLICATION=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR" --section publication) || exit $?
REPORT=$(jq -ber 'select(.state == "published") | .report | strings' <<< "$PUBLICATION") || { echo '! BLOCKED — run-record-report-not-published' >&2; exit 1; }
python -I "$PLUGIN_ROOT/bin/write_skill_contract.py" "develop:review" "follow-up gate" "$RUN_DIR" "run-record=$RUN_DIR/run-record.json, final-report=$REPORT" "Check the review record; re-read report header and ask only if follow-up is still pending" || exit $?  # timeout: 5000
```

**Follow-up gate (NEVER SKIP)** — Call `AskUserQuestion` tool — do NOT write options as plain text first. Map options directly into tool call arguments. The `/compact` hint rides in the question text, never as reply prose or Bash stdout before the call (text before a tool call can vanish on 5.5-family models):

- header: `dev-review`
- question: at most 6 plain lines (target 600 characters, hard cap 1,500), no table, pipe layout or code fence: `Title: <report Title>`; `Outcome: <report Outcome>`; finding counts and blockers; `→ <REPORT_DIR>/review-report.md`; `What next?`; "Long wait? `/compact` now — report saved, resume lossless." Keep the `/compact` hint in the question text.
- (a) label: `walk through findings` — description: go through each finding interactively (procedure: ≤4 findings per `AskUserQuestion` call, per finding options `note` / `skip` / `stop`; after the walk run the contract-clear block below)
- (b) label: `skip` — description: no action
- every option: label and one-line description only, no `preview`; never put the header table in the question or its options.

Use [Record a decision](#record-a-decision) to save `follow-up` with `status: "pending"` just before the question. Save the actual choice immediately as `status: "answered"` with the selected label and later persist `status: "complete"` after the walk or skip. On resume, an answered walk resumes at its saved position; persist its position with each answer. An answered skip proceeds to contract clear. Re-ask only if the question is pending and no answer arrived. Where an existing gate routes directly to final delivery without a question, record `status: "not-required"` and the reason.

**Confidence block** — emitted by consolidator agent in `$REPORT_DIR/review-report.md` because the consolidator owns the report and its evidence synthesis.

```bash
PLUGIN_ROOT=$(python -I "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name develop) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
if [ -z "${RUN_DIR:-}" ]; then IFS= read -r RUN_DIR 2>/dev/null < "${TMPDIR:-/tmp}/dev-review-run-dir-${CSID}" || RUN_DIR=""; fi
python -I "$PLUGIN_ROOT/bin/run_record.py" check --run-dir "$RUN_DIR" --skill review || exit $?
RECORD=$(python -I "$PLUGIN_ROOT/bin/run_record.py" read --run-dir "$RUN_DIR") || exit $?
jq -be '.publication.state == "published" and (.decisions["follow-up"].value.status | IN("complete", "not-required"))' <<< "$RECORD" >/dev/null || { echo '! BLOCKED — run-record-follow-up-incomplete' >&2; exit 1; }
jq -be '.scope.worktree != true or .decisions["worktree-exit"].value.status == "complete"' <<< "$RECORD" >/dev/null || { echo '! BLOCKED — run-record-worktree-exit-incomplete' >&2; exit 1; }
if jq -be '.scope.worktree == true' <<< "$RECORD" >/dev/null; then
    REVIEW_CWD=$(jq -ber '.scope.review_cwd | strings | select(length > 0)' <<< "$RECORD") || exit $?
    WORKTREE_CONTRACT="$REVIEW_CWD/.temp/state/skill-contract.md"
    if grep -Fq -- "run-record=$RUN_DIR/run-record.json," "$WORKTREE_CONTRACT" 2>/dev/null; then
        rm -f -- "$WORKTREE_CONTRACT" || exit $?
    fi
fi
rm -f .temp/state/skill-contract.md  # clear contract — skill complete (compaction-contract.md §Lifecycle)  # timeout: 5000
```

</workflow>

<notes>

- Critical issues always surfaced regardless of scope
- Skip sections with no issues — no padding with "looks good". Reviewing isolated code without git context → skip Performance Concerns unless code itself shows performance issues or the request/documentation makes a material performance claim.
- **Signal-to-noise gate**: function or class ≤50 lines with only 1–2 ground-level issues (critical/high) → no more than 2 medium/low findings beyond them. Remainder as `[nit]` in dedicated "Minor Observations" section — not elevated to same tier as high-severity findings.
- **Follow-up chains**:
  - `[blocking]` bugs or regressions → `/develop:fix "<finding title> (<file:line>)"` per finding to reproduce with test, apply targeted fix
  - Structural or quality issues → `/develop:refactor` for test-first improvements
  - Security findings in auth/input/deps → run `pip-audit` for dependency CVEs; address OWASP issues inline via `/develop:fix`
  - Mechanical issues beyond Step 5 findings → `bridge@borda-ai-rig` available → call its `implement` skill with a brief stating the exact finding, target paths, current evidence, permitted edits, required result, stop condition, verification command.
  - Contributor-facing review of GitHub PR → use `/oss:review <PR#>` (requires oss plugin) instead

</notes>

Files in this skill

  • SKILL.md58.1 KB
  • templates/consolidator-prompt.md4.3 KB
  • templates/review-report.md2.3 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.