Code Review
Reviews code changes using dynamically selected reviewer personas. Spawns parallel sub-agents that return structured JSON, then merges and deduplicates findings into a single report.
When to Use
- Before creating a PR
- After completing a task during iterative implementation
- When feedback is needed on any code changes
- Can be invoked standalone
- Can run inside larger workflows; use
mode:agentwhen the caller needs JSON instead of markdown tables
Argument Parsing
Parse $ARGUMENTS for optional tokens. Strip each recognized token before interpreting the remainder as a PR number, GitHub URL, or branch name.
| Token | Example | Effect |
|---|---|---|
mode:agent |
mode:agent |
Report-only: return JSON instead of markdown tables and skip the Stage 5c apply (the caller applies). Does not change reviewer selection, merge logic, or scope rules (see Output format) |
mode:headless |
mode:headless |
Deprecated alias for mode:agent |
mode:report-only |
mode:report-only |
Deprecated — ignored. Former no-artifacts mode; default behavior is review-only without checkout |
base:<sha-or-ref> |
base:abc1234 or base:origin/main |
Diff base on the current checkout (explicit; skips auto base detection) |
plan:<path> |
plan:docs/plans/2026-03-25-001-feat-foo-plan.md |
Plan file for requirements verification (explicit) |
grouping:auto |
grouping:auto |
Default — build thematic triage groups when findings span distinct concerns (Stage 5 step 9b) |
grouping:off |
grouping:off |
Suppress triage groups: no Triage Groups section, empty triage_groups in JSON |
grouping:always |
grouping:always |
Always build triage groups, even for small reviews |
Grouping is presentation, not a mode. The grouping: tokens change how the finding set is organized for triage — never reviewer selection, merge logic, scope rules, or the Stage 5c apply decision.
Mode alias: mode:headless normalizes to mode:agent. mode:agent + mode:headless is not a conflict.
Conflicting arguments: Stop without dispatching reviewers when:
- Multiple incompatible scope selectors appear together (e.g.
base:and a PR number/branch target —base:means "review the current checkout against this base") - Multiple distinct
mode:tokens other than themode:agent/mode:headlessalias pair - Multiple distinct
grouping:tokens (e.g.grouping:offandgrouping:always)
Deprecated mode:autofix is not a conflict — ignore the token and proceed with the normal flow (see below).
Emit a one-line failure reason. In mode:agent, return JSON: {"status":"failed","reason":"..."}.
Operating principles
Same pipeline for default and mode:agent:
- Apply locally; never push. Never push, open PRs, or file tickets in any mode — push is the outward step the user owns. In default (interactive) mode the review applies safe, verified fixes and commits them when the pre-review tree was clean (Stage 5c owns the full rule). In
mode:agentit never mutates the tree — it reports and the caller applies. - No blocking prompts. Never use
AskUserQuestion,request_user_input,ask_user, or other blocking question tools. Infer intent, plan, and scope from explicit tokens, git state, PR metadata, and conversation. Note uncertainty in Coverage or the verdict — do not stop to ask. - Explicit mutations only. Never run
gh pr checkout,git checkout,git switch, or similar branch-switch commands. Passing a PR number, URL, or branch name selects review scope, not permission to mutate the working tree. To review local uncommitted work on a feature branch, check out that branch yourself (or stay on it) and passbase:or no target. - Smart defaults. Untracked files: review tracked changes only and list excluded paths in Coverage. Plan: use
plan:when passed; otherwise discover conservatively from PR body or branch keywords. Weak advisory P2/P3 from testing/maintainability alone: demote totesting_gaps/residual_risksper Stage 5.
Output format
| Invocation | Deliverable |
|---|---|
| Default | Markdown report (pipe-delimited finding tables) + Actionable Findings summary |
mode:agent |
One JSON object (see ### JSON output format below) + the same /tmp/.../ce-code-review/<run-id>/ artifacts |
mode:agent is report-only: it skips the Stage 5c apply (the caller applies) and serializes findings as JSON instead of markdown. It does not change reviewer selection, merge logic, or scope rules — the JSON is the deterministic contract for programmatic and cross-harness callers (Codex, Gemini, etc.). The default markdown is the human view; keep it ASCII-safe (pipe tables, -> not middot ·, no box-drawing) so it degrades gracefully across terminals.
Quick Review Short-Circuit
If $ARGUMENTS indicates the user wants a quick, fast, or light code review — and mode:agent is not active — do not dispatch the multi-agent flow.
Announce the chosen path before any other work (Quick review vs Multi-agent review). Skip this announcement when mode:agent is active.
Sequence:
- Run the harness's built-in code review. Forward any review target after stripping tokens. Then stop — do not dispatch the multi-agent pipeline.
- Exemption: If no built-in review exists, continue into the full multi-agent review.
mode:agentbypasses this short-circuit — always run the full multi-agent review and return JSON.
Deprecated: mode:autofix is no longer supported — there is no apply mode. If passed, ignore the token and proceed with the normal flow (default applies safe fixes via Stage 5c; mode:agent reports and the caller applies).
Severity Scale
All reviewers use P0-P3:
| Level | Meaning | Action |
|---|---|---|
| P0 | Critical breakage, exploitable vulnerability, data loss/corruption | Must fix before merge |
| P1 | High-impact defect likely hit in normal usage, breaking contract | Should fix |
| P2 | Moderate issue with meaningful downside (edge case, perf regression, maintainability trap) | Fix if straightforward |
| P3 | Low-impact, narrow scope, minor improvement | User's discretion |
Action Routing
Severity answers urgency. autofix_class and owner are signal describing follow-up shape for callers — not apply permission or an apply gate. The apply decision is judgment (Stage 5c), not a function of autofix_class: default mode applies; in mode:agent this skill does not mutate the checkout — the caller applies. See references/action-class-rubric.md for persona guidance.
autofix_class |
Default owner | Meaning |
|---|---|---|
gated_auto |
downstream-resolver or human |
Concrete suggested_fix proposed; caller applies after judgment |
manual |
downstream-resolver or human |
Actionable work needing design input or handoff |
advisory |
human or release |
Report-only — learnings, rollout notes, residual risk |
Routing rules:
- Synthesis owns the final route. Persona-provided routing metadata is input, not the last word.
- Choose the more conservative route on disagreement. A merged finding may move from
gated_autotomanual, but never widen without stronger evidence. - Reject
safe_autoandreview-fixerif present — drop the finding or remap togated_auto/downstream-resolverduring synthesis. requires_verification: truemeans any caller-applied fix needs targeted tests or follow-up validation.
Reviewers
14 reviewer personas in layered conditionals, plus CE agents. Quick roster with one-line triggers below; the persona catalog included at the bottom has the full per-persona selection criteria and spawn gates.
Always-on (every review): ce-correctness-reviewer, ce-testing-reviewer, ce-maintainability-reviewer, ce-project-standards-reviewer, plus CE agents ce-agent-native-reviewer and ce-learnings-researcher.
Cross-cutting conditional (per diff):
ce-security-reviewer— auth, public endpoints, user input, permissionsce-performance-reviewer— DB queries, data transforms, caching, asyncce-api-contract-reviewer— routes, serializers, type signatures, versioningce-data-migration-reviewer— migration files / schema dumps / backfills (see spawn gate in Stage 3)ce-reliability-reviewer— error handling, retries, timeouts, background jobsce-adversarial-reviewer— >=50 changed code lines, or auth / payments / data mutations / external APIsce-previous-comments-reviewer— PR with existing review comments (PR-only, comment-gated)
Stack-specific conditional (per diff): ce-julik-frontend-races-reviewer (Stimulus/Turbo, DOM events, async UI) and ce-swift-ios-reviewer (Swift/SwiftUI/UIKit, entitlements, Core Data, .pbxproj).
CE conditional (migration-specific): ce-deployment-verification-agent — deployment checklist + rollback when the migration gate applies and the change is risky.
Review Scope
Every review spawns all 4 always-on personas plus the 2 CE always-on agents, then adds whichever cross-cutting and stack-specific conditionals fit the diff. The model naturally right-sizes: a small config change triggers 0 conditionals = 6 reviewers. A Rails auth feature might trigger security + reliability + adversarial = 9 reviewers.
Protected Artifacts
The following paths are compound-engineering pipeline artifacts and must never be flagged for deletion, removal, or gitignore by any reviewer:
docs/brainstorms/*-- requirements documents created by ce-brainstormdocs/plans/*.md-- plan files created by ce-plan (decision artifacts; execution progress is derived from git, not stored in plan bodies)docs/solutions/*.md-- solution documents created during the pipeline
If a reviewer flags any file in these directories for cleanup or removal, discard that finding during synthesis.
How to Run
Stage 1: Determine scope
Compute the diff range, file list, and diff. Minimize permission prompts by combining into as few commands as possible.
If base: argument is provided (fast path):
The caller already knows the diff base. Skip all base-branch detection, remote resolution, and merge-base computation. Use the provided value directly:
BASE_ARG="{base_arg}"
BASE=$(git merge-base HEAD "$BASE_ARG" 2>/dev/null) || BASE="$BASE_ARG"
Then produce the same output as the other paths:
echo "BASE:$BASE" && echo "FILES:" && git diff --name-only $BASE && echo "DIFF:" && git diff -U10 $BASE && echo "UNTRACKED:" && git ls-files --others --exclude-standard
This path works with any ref — a SHA, origin/main, a branch name. Callers reviewing the current checkout should pass explicit base: when auto-detection is unnecessary. Do not combine base: with a PR number or branch target. If both are present, stop with an error: "Cannot use base: with a PR number or branch target — base: implies the current checkout is already the correct branch. Pass base: alone, or pass the target alone and let scope detection resolve the base."
If a PR number or GitHub URL is provided as an argument:
Do not check out the PR branch. Scope comes from GitHub read APIs plus optional local alignment when HEAD already matches the PR head branch.
Skip-condition pre-check. Before scope detection, run a PR-state probe:
gh pr view <number-or-url> --json state,title,body,files
Apply skip rules in order:
stateisCLOSEDorMERGED-> stop with reasonPR is closed/merged; not reviewing.- Trivial-PR judgment: spawn a lightweight sub-agent (use
model: haikuin Claude Code; gpt-5.4-nano or equivalent in Codex) with the PR title, body, and changed file paths. The agent's task: "Is this an automated or trivial PR that does not warrant a code review? Consider: dependency lock-file or manifest-only bumps, automated release commits, chore version increments with no substantive code changes. When in doubt, answer no — false negatives (skipped reviews that should have run) are more costly than false positives (unnecessary reviews)." If the judgment returns yes: stop with reasonPR appears to be a trivial automated PR; not reviewing. Run without a PR argument to review the current branch, or pass base:<ref> if review is intended.
When any skip rule fires, stop without dispatching reviewers. Default mode: emit the reason as plain text. mode:agent: emit JSON only — {"status":"skipped","reason":"<same message>"} — so programmatic callers can parse the outcome. Standalone, base:, and branch-remote paths are unaffected. Draft PRs are reviewed normally.
If no skip rule fires, fetch PR metadata without checkout:
gh pr view <number-or-url> --json title,body,baseRefName,headRefName,headRefOid,isCrossRepository,url,files,reviews,comments --jq '{title, body, baseRefName, headRefName, headRefOid, isCrossRepository, url, files: [.files[].path], hasPriorComments: ((.reviews | map(select(.state != "APPROVED" or .body != "")) | length) > 0 or (.comments | length) > 0)}'
Set BASE: to pr:<number-or-url> (logical marker — not a git SHA). Set UNTRACKED: from git ls-files --others --exclude-standard on the current checkout (usually empty during PR-remote review).
PR scope mode. Classify as local-aligned only when all of these hold; otherwise use pr-remote. A matching branch name alone is not enough — a fork PR or a stale local branch can share a name with the PR head while pointing at unrelated code, and trusting the name would diff and inspect the wrong tree.
git rev-parse --abbrev-ref HEADequalsheadRefName.- The PR is not cross-repository (
isCrossRepositoryis false). - The PR head commit is contained in the local checkout:
git merge-base --is-ancestor <headRefOid> HEADexits 0. This confirms the working tree actually carries the PR head (allowing unpushed local fixes layered on top) rather than an unrelated same-named branch.
local-aligned— all three checks pass. Local Read/Grep/git blame against workspace files are valid for PR changed paths.pr-remote— any check fails. The working tree is not the PR head; workspace file contents for changed paths may be stale or unrelated.
Diff by scope mode (do not mix remote and local diffs — contradictory hunks cause false positives):
local-aligned: Resolve<resolved-base-ref>frombaseRefName(fetch if needed). ComputeBASE=$(git merge-base HEAD <resolved-base-ref>), then setFILES:fromgit diff --name-only $BASEandDIFF:fromgit diff -U10 $BASE(includes committed, staged, and unstaged changes on the PR branch). Do not callgh pr diffor append remote hunks — when unpushed fixes exist, the local tree is canonical. Note in Coverage:scope: local-aligned (PR; local tree diff).pr-remote: SetFILES:from the PRfilesarray. SetDIFF:fromgh pr diff <number-or-url> --color=never. Ifgh pr difffails, stop with an actionable error — do not fall back to checkout.
When pr-remote, before Stage 4:
- Best-effort fetch PR head without checkout:
git fetch --no-tags origin <headRefName>:refs/review/pr-<number>-head(substitute PR number from metadata). - When fetch succeeds, set
PR_HEAD_REF=refs/review/pr-<number>-headfor reviewers and validators. When fetch fails, omitPR_HEAD_REFand note in Coverage — reviewers must rely on diff hunks only. - Best-effort fetch the PR base without checkout:
git fetch --no-tags origin <baseRefName>. When it succeeds, resolve a concrete ref withgit rev-parse FETCH_HEADand setPR_BASE_REFto that SHA — a real git base ref reviewers and validators use for file-level git diffs (e.g.ce-data-migration-reviewerrunsgit diff <PR_BASE_REF> -- db/schema.rb/structure.sql). Thepr:<number-or-url>logical marker inBASE:stays the scope marker;PR_BASE_REFis the diffable base. When the fetch fails, omitPR_BASE_REFand note in Coverage — schema-drift and other git-diff checks fall back to diff hunks only and must not assumemain. - Include
<pr-scope-mode>pr-remote</pr-scope-mode>and, when set,<pr-head-ref>...</pr-head-ref>and<pr-base-ref>...</pr-base-ref>in the Stage 4 review context bundle.
Reviewers and Stage 5b validators in pr-remote mode must not Read/Grep workspace paths for files in FILES:. Inspect via git show <PR_HEAD_REF>:<path> when PR_HEAD_REF is set, otherwise use only the provided diff hunks. local-aligned uses normal workspace inspection.
If a branch name is provided as an argument:
Substitute the provided branch name as <branch>. Do not check out <branch>.
If git rev-parse --abbrev-ref HEAD equals <branch>, use the standalone (current branch) path below — same tree, explicit branch name; do not use remote-only diff.
Otherwise diff the remote/local ref without checkout:
- Try
gh pr view <branch> --json baseRefName,url,headRefName— if a PR exists, prefer the PR number/URL path above (same remote diff rules). - Else resolve
<branch>asorigin/<branch>or<branch>aftergit fetch --no-tags origin <branch>when needed. - Resolve default base branch (same logic as standalone). Compute
BASE=$(git merge-base <base-ref> <branch-ref>)andgit diff -U10 $BASE <branch-ref>. - If
<branch-ref>cannot be resolved locally, stop: "Cannot diff branch<branch>without checkout. Check out that branch, pass its open PR URL/number, or review the current branch withbase:."
On success for remote branch diff, set branch-remote scope. The working tree is not <branch>. Include <pr-scope-mode>branch-remote</pr-scope-mode> and <branch-head-ref><branch-ref></branch-head-ref> in the Stage 4 review context bundle. Reviewers and Stage 5b validators must not Read/Grep workspace paths for files in FILES:. Inspect via git show <branch-ref>:<path> or diff hunks only.
Produce:
echo "BASE:$BASE" && echo "FILES:" && git diff --name-only $BASE <branch-ref> && echo "DIFF:" && git diff -U10 $BASE <branch-ref> && echo "UNTRACKED:" && git ls-files --others --exclude-standard
If no argument (standalone on current branch):
Apply the same base-detection logic as branch mode above, using the current branch (i.e., gh pr view --json baseRefName,url with no argument defaults to the current branch).
If no base can be resolved, stop. Do not fall back to git diff HEAD — a standalone review without the base would only show uncommitted changes and silently miss all committed work on the branch.
On success, produce the diff:
echo "BASE:$BASE" && echo "FILES:" && git diff --name-only $BASE && echo "DIFF:" && git diff -U10 $BASE && echo "UNTRACKED:" && git ls-files --others --exclude-standard
Using git diff $BASE (without ..HEAD) diffs the merge-base against the working tree, which includes committed, staged, and unstaged changes together.
Untracked file handling: Always inspect UNTRACKED:. Untracked paths are out of scope unless staged. When non-empty, list excluded files in Coverage and continue on tracked changes only — never stop or prompt.
Stage 2: Intent discovery
Understand what the change is trying to accomplish. The source of intent depends on which Stage 1 path was taken:
PR/URL mode: Use the PR title, body, and linked issues from gh pr view metadata. Supplement with commit messages from the PR if the body is sparse.
Branch mode: Run git log --oneline ${BASE}..<branch-ref> using the resolved merge-base and resolved branch ref from Stage 1. Use <branch-ref> (the resolved origin/<branch> or fetched ref), not the raw <branch> argument — a remote-only branch has no matching local ref, so the raw name would fail or read a stale same-named local branch.
Standalone (current branch): Run:
echo "BRANCH:" && git rev-parse --abbrev-ref HEAD && echo "COMMITS:" && git log --oneline ${BASE}..HEAD
Combined with conversation context (plan section summary, PR description), write a 2-3 line intent summary:
Intent: Simplify tax calculation by replacing the multi-tier rate lookup
with a flat-rate computation. Must not regress edge cases in tax-exempt handling.
Pass this to every reviewer in their spawn prompt. Intent shapes how hard each reviewer looks, not which reviewers are selected.
When intent is ambiguous: Infer from branch name, commits, PR title/body, diff, plan:, and conversation. Write the best-effort intent summary and note uncertainty in Coverage — never block on a clarifying question.
Stage 2b: Plan discovery (requirements verification)
Locate the plan document so Stage 6 can verify requirements completeness. Check these sources in priority order — stop at the first hit:
plan:argument. If the caller passed a plan path, use it directly. Read the file to confirm it exists.- PR body. If PR metadata was fetched in Stage 1, scan the body for paths matching
docs/plans/*.md. If exactly one match is found and the file exists, use it asplan_source: explicit. If multiple plan paths appear, treat as ambiguous — demote toplan_source: inferredfor the most recent match that exists on disk, or skip if none exist or none clearly relate to the PR title/intent. Always verify the selected file exists before using it — stale or copied plan links in PR descriptions are common. - Auto-discover. Extract 2-3 keywords from the branch name (e.g.,
feat/onboarding-skill->onboarding,skill). Globdocs/plans/*and filter filenames containing those keywords. If exactly one match, use it. If multiple matches or the match looks ambiguous (e.g., generic keywords likereview,fix,updatethat could hit many plans), skip auto-discovery — a wrong plan is worse than no plan. If zero matches, skip.
Confidence tagging: Record how the plan was found:
plan:argument ->plan_source: explicit(high confidence)- Single unambiguous PR body match ->
plan_source: explicit(high confidence) - Multiple/ambiguous PR body matches ->
plan_source: inferred(lower confidence) - Auto-discover with single unambiguous match ->
plan_source: inferred(lower confidence)
If a plan is found, read its Requirements section — ## Requirements in current plans, ## Requirements Trace in legacy ones — and the R-IDs (R1, R2, etc.) listed there, plus Implementation Units (current numeric subsections such as ### U1., ### U2., or ### Unit 1: under ## Implementation Units; legacy bullet or checkbox unit entries under that section also count). Store the extracted requirements list and plan_source for Stage 6. Do not block the review if no plan is found — requirements verification is additive, not required.
Stage 3: Select reviewers
Read the diff and file list from Stage 1. The 4 always-on personas and 2 CE always-on agents are automatic. For each cross-cutting and stack-specific conditional persona in the persona catalog included below, decide whether the diff warrants it. This is agent judgment, not keyword matching.
File-type awareness for conditional selection: Instruction-prose files (Markdown skill definitions, JSON schemas, config files) are product code but do not benefit from runtime-focused reviewers. The adversarial reviewer's techniques (race conditions, cascade failures, abuse cases) target executable code behavior. For diffs that only change instruction-prose files, skip adversarial unless the prose describes auth, payment, or data-mutation behavior. Count only executable code lines toward line-count thresholds.
previous-comments is PR-only AND comment-gated. Only select this persona when both conditions hold:
- Stage 1 gathered PR metadata (PR number or URL was provided as an argument, or
gh pr viewreturned metadata for the current branch). hasPriorCommentsfrom Stage 1 is true (the PR has at least one review submission or issue comment).
Skip it for standalone branch reviews with no associated PR, and skip it for PRs with no prior feedback yet -- there is nothing for the persona to verify, and a spawned subagent that returns empty findings still costs the full subagent startup overhead (persona spec, diff, schema, plus its own gh calls).
Stack-specific personas are additive when runtime behavior warrants them. A Hotwire UI change may warrant julik-frontend-races; a TypeScript API diff may warrant api-contract and reliability.
data-migration spawn gate. Select ce-data-migration-reviewer only when the diff includes at least one migration or schema artifact: db/migrate/*, db/schema.rb, db/structure.sql, Alembic/Flyway/Liquibase migration paths, or explicit backfill/data-transform scripts (rake tasks, one-off data migration classes). Do not spawn for model-only changes, query-only refactors, serializers/controllers that reference columns without a migration or schema dump in the diff, or migration tests alone.
For ce-deployment-verification-agent, use the same migration-artifact gate when the change is risky (destructive DDL, backfills, NOT NULL without default, column renames/drops).
Announce the team before spawning:
Review team:
- correctness (always)
- testing (always)
- maintainability (always)
- project-standards (always)
- ce-agent-native-reviewer (always)
- ce-learnings-researcher (always)
- security -- new endpoint in routes.rb accepts user-provided redirect URL
- julik-frontend-races -- Stimulus controller with async DOM updates
- data-migration -- adds migration 20260303_add_index_to_orders
- ce-deployment-verification-agent -- destructive migration with backfill
This is progress reporting, not a blocking confirmation.
Stage 3b: Discover project standards paths
Before spawning sub-agents, find the file paths (not contents) of all relevant standards files for the project-standards persona. Use the native file-search/glob tool to locate:
- Use the native file-search tool (e.g., Glob in Claude Code) to find all
**/CLAUDE.mdand**/AGENTS.mdin the repo. - Filter to those whose directory is an ancestor of at least one changed file. A standards file governs all files below it (e.g.,
plugins/compound-engineering/AGENTS.mdapplies to everything underplugins/compound-engineering/).
Pass the resulting path list to the project-standards persona inside a <standards-paths> block in its review context (see Stage 4). The persona reads the files itself, targeting only the sections relevant to the changed file types. This keeps the orchestrator's work cheap (path discovery only) and avoids bloating the subagent prompt with content the reviewer may not fully need.
Stage 4: Spawn sub-agents
Model tiering
Three reviewers inherit the session model with no override: ce-correctness-reviewer, ce-security-reviewer, and ce-adversarial-reviewer. These perform the highest-stakes analysis — logic bugs, security vulnerabilities, adversarial failure scenarios — and should run at whatever capability level the user has configured. If the user is on Opus, these get Opus.
All other persona sub-agents and CE agents use the platform's mid-tier model to reduce cost and latency. See the Spawning subsection below for the exact dispatch-time override.
The orchestrator (this skill) also inherits the session model; it handles intent discovery, reviewer selection, finding merge/dedup, and synthesis.
Run ID
Generate a unique run identifier before dispatching any agents. This ID scopes all agent artifact files and the post-review run artifact to the same directory.
RUN_ID=$(date +%Y%m%d-%H%M%S)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' ')
mkdir -p "/tmp/compound-engineering/ce-code-review/$RUN_ID"
Pass {run_id} to every persona sub-agent so they can write their full analysis to /tmp/compound-engineering/ce-code-review/{run_id}/{reviewer_name}.json.
Large shared context — pass paths, not contents. The diff and file list go to every reviewer and validator. When inlining them into each subagent prompt would be wasteful (many files / a big diff), write them once into the run dir (e.g. full.diff, files.txt) and pass those paths in the diff / changed-files slots instead of inline content — the subagent and validator templates instruct the child to Read a staged path. Inline a small diff directly.
Spawning
Omit the mode parameter when dispatching sub-agents so the user's configured permission settings apply. Do not pass mode: "auto".
Model override at dispatch time. Pass the platform's mid-tier model on every dispatch except ce-correctness-reviewer, ce-security-reviewer, and ce-adversarial-reviewer, which inherit the session model (per the Model tiering subsection above). In Claude Code, add model: "sonnet" to the Agent tool call. In Codex, pass the equivalent mid-tier on spawn_agent (e.g., gpt-5.4-mini as of April 2026). In Pi, pass the equivalent on subagent via the pi-subagents extension. On platforms where the dispatch primitive has no model-override parameter or the available model names are unknown, omit the override — a working review on the parent model beats a broken dispatch on an unrecognized name. Check this on every Agent / spawn_agent / subagent call in the parallel dispatch; omitting it on Opus sessions silently 3-4x's the cost of a review.
Bounded parallel dispatch. Respect the current harness's active-subagent limit. Queue selected reviewers, dispatch only as many as the harness accepts, and fill freed slots as reviewers complete. Treat active-agent/thread/concurrency-limit spawn errors as backpressure, not reviewer failure: leave the reviewer queued and retry after a slot frees. Record a reviewer as failed only after a successful dispatch times out/fails, or when dispatch fails for a non-capacity reason.
Spawn each selected persona reviewer using the subagent template included below. Each persona sub-agent receives:
- Their persona file content (identity, failure modes, calibration, suppress conditions)
- Shared diff-scope rules from the diff-scope reference included below
- The JSON output contract from the findings schema included below
- PR metadata: title, body, and URL when reviewing a PR (empty string otherwise). Passed in a
<pr-context>block so reviewers can verify code against stated intent - Review context: intent summary, file list, diff, scope mode (
local-aligned|pr-remote|branch-remote), and remote head ref (PR_HEAD_REFor<branch-head-ref>) when set - Run ID and reviewer name for the artifact file path
- For
project-standardsonly: the standards file path list from Stage 3b, wrapped in a<standards-paths>block appended to the review context - For
data-migrationonly: the resolved review base ref from Stage 1 (BASE:marker), wrapped in<review-base>inside the review context so schema drift checks never assumemain
Persona sub-agents are read-only with respect to the project: they review and return structured JSON. They do not edit project files or propose refactors. The one permitted write is saving their full analysis to the run-artifact path specified in the output contract (under /tmp/compound-engineering/ce-code-review/<run-id>/).
Read-only here means non-mutating, not "no shell access." Reviewer sub-agents may use non-mutating inspection commands when needed to gather evidence or verify scope, including read-oriented git / gh usage such as git diff, git show, git blame, git log, and gh pr view. In pr-remote or branch-remote scope (see Stage 1), inspect changed files via git show <remote-head-ref>:<path> or diff hunks — do not Read/Grep workspace paths for files in scope. They must not edit project files, change branches, commit, push, create PRs, or otherwise mutate the checkout or repository state.
Each persona sub-agent writes full JSON (all schema fields) to /tmp/compound-engineering/ce-code-review/{run_id}/{reviewer_name}.json and returns compact JSON with merge-tier fields only:
{
"reviewer": "security",
"findings": [
{
"title": "User-supplied ID in account lookup without ownership check",
"severity": "P0",
"file": "orders_controller.rb",
"line": 42,
"confidence": 100,
"autofix_class": "gated_auto",
"owner": "downstream-resolver",
"requires_verification": true,
"pre_existing": false,
"suggested_fix": "Add current_user.owns?(account) guard before lookup"
}
],
"residual_risks": [...],
"testing_gaps": [...]
}
The artifact file must carry the detail-tier fields (why_it_matters, evidence); the compact return omits them, but writing the compact shape to the artifact (a common reviewer slip) silently strips the detail Coverage and the keyed detail lines depend on. However review context is delivered — inlined, or staged to disk for a large diff — each reviewer still receives the full subagent-template output contract; staging context never licenses a thinner one. suggested_fix is optional in both tiers -- included in compact returns when present so callers can apply fixes after review. If the file write fails, the compact return still provides everything the merge needs.
CE always-on agents (ce-agent-native-reviewer, ce-learnings-researcher) are dispatched as standard Agent calls through the same bounded parallel scheduler as the persona agents. Give them the same review context bundle the personas receive: entry mode, any PR metadata gathered in Stage 1, intent summary, review base branch name when known, BASE: marker, file list, diff, and UNTRACKED: scope notes. Do not invoke them with a generic "review this" prompt. Their output is unstructured and synthesized separately in Stage 6.
CE conditional agents (ce-deployment-verification-agent only) are dispatched as standard Agent calls through the same bounded parallel scheduler when the migration-artifact gate applies. Pass the same review context bundle plus the applicability reason (for example, which migration files triggered the agent). Their output is unstructured and must be preserved for Stage 6 synthesis just like the CE always-on agents. Schema drift is handled by the data-migration persona as structured findings — not here.
Stage 5: Merge findings
Convert multiple reviewer compact JSON returns into one deduplicated, confidence-gated finding set. The compact returns contain merge-tier fields (title, severity, file, line, confidence, autofix_class, owner, requires_verification, pre_existing) plus the optional suggested_fix. Detail-tier fields (why_it_matters, evidence) are on disk in the per-agent artifact files and are not loaded at this stage.
confidence is one of 5 discrete anchors (0, 25, 50, 75, 100) with behavioral definitions in the findings schema. Synthesis treats anchors as integers; do not coerce to floats.
- Validate. Check each compact return for required top-level and per-finding fields, plus value constraints. Drop malformed returns or findings. Record the drop count.
- Top-level required: reviewer (string), findings (array), residual_risks (array), testing_gaps (array). Drop the entire return if any are missing or wrong type.
- Per-finding required: title, severity, file, line, confidence, autofix_class, owner, requires_verification, pre_existing
- Value constraints:
- severity: P0 | P1 | P2 | P3
- autofix_class: gated_auto | manual | advisory
- owner: downstream-resolver | human | release
- confidence: integer in {0, 25, 50, 75, 100}
- line: positive integer
- pre_existing, requires_verification: boolean
- Do not validate against the full schema here -- the full schema (including why_it_matters and evidence) applies to the artifact files on disk, not the compact returns.
- Deduplicate. Compute fingerprint:
normalize(file) + line_bucket(line, +/-3) + normalize(title). When fingerprints match, merge: keep highest severity, keep highest anchor, note which reviewers flagged it. Dedup runs over the full validated set (including anchor 50) so cross-reviewer promotion in step 3 can lift matching anchor-50 findings into the actionable tier. - Cross-reviewer agreement. When 2+ independent reviewers flag the same issue (same fingerprint), promote the merged finding by one anchor step:
50 -> 75,75 -> 100,100 -> 100. Note the agreement in the Reviewer column of the output (e.g., "security, correctness"). - Separate pre-existing. Pull out findings with
pre_existing: trueinto a separate list. - Resolve disagreements. When reviewers flag the same code region but disagree on severity, autofix_class, or owner, annotate the Reviewer column with the disagreement (e.g., "security (P0), correctness (P1) -- kept P0").
- Normalize routing. For each merged finding, set the final
autofix_class,owner, andrequires_verification. If reviewers disagree, keep the more conservative route. Remap any legacysafe_autoorreview-fixertogated_auto/downstream-resolver. 6b. Mode-aware demotion of weak general-quality findings. Some persona output is real signal but does not warrant primary-findings attention. Reroute it to the existing soft buckets so the primary findings table stays focused on actionable issues.
A finding qualifies for demotion when all of these hold:
- Severity is P2 or P3 (P0 and P1 always stay in primary findings)
autofix_classisadvisory(concrete-fix findings stay in primary)- All contributing reviewers are
testingormaintainability— if any other persona also flagged this finding, cross-reviewer corroboration is present and the finding stays in primary findings regardless of its severity or advisory status (expand the weak-signal list later only with evidence)
When a finding qualifies:
- Move demoted findings out of the primary set. If the contributing reviewer is
testing, append<file:line> -- <title>totesting_gaps. Ifmaintainability, append toresidual_risks. Use title-only lines (compact return omitswhy_it_matters). Record the demotion count for Coverage.
- Confidence gate. After dedup, promotion, and demotion have shaped the primary set, suppress remaining findings below anchor 75. Exception: P0 findings at anchor 50+ survive the gate -- critical-but-uncertain issues must not be silently dropped. Record the suppressed count by anchor (so Coverage can report "N findings suppressed at anchor 50, M at anchor 25"). The gate runs late deliberately: anchor-50 findings need a chance to be promoted by step 3 (cross-reviewer corroboration) or rerouted by step 6b (mode-aware demotion to soft buckets) before any drop decision.
- Partition the work. Build two sets:
- actionable queue:
gated_autoormanualfindings whose owner isdownstream-resolver(hand off to caller) - report-only queue:
advisoryfindings plus anything owned byhumanorrelease
- actionable queue:
- Sort and number. Order by severity (P0 first) -> anchor (descending) -> file path -> line number, then assign monotonically increasing
#values across the full primary finding set in that sorted order. Do not restart numbering inside each severity table, triage group, or autofix/routing bucket. If later sections repeat a finding (for example Actionable Findings), reuse the same stable#so users and downstream workflows can reference findings by#across the report and caller handoff. 9b. Build thematic triage groups. After stable#values exist, group related findings so the reader can triage themes instead of
…(truncated)