Skip to content

advanced-code-review

Multi-phase deep code review with historical context analysis, fact-checked findings, and tiered severity reporting. Runs five phases: strategic planning, context analysis, deep review, verification, and report generation. This core spellbook skill produces detailed review artifacts and is the heavyweight alternative to the simpler code-review skill.

Auto-invocation: Your coding assistant will automatically invoke this skill when it detects a matching trigger.

Use when performing thorough code review with historical context tracking. Triggers: 'thorough review', 'deep review', 'review this branch in detail', 'full code review with report', 'branch code review', 'review this branch', 'review the changes', 'review what's on this branch', 'do a code review of the branch'. More heavyweight than code-review; for quick review, use code-review instead. When the request could match more than one review skill, MUST use AskUserQuestion to disambiguate before invoking — never bypass the review skills for a raw Explore dispatch, even when the user's concerns seem narrow or specific.

Workflow Diagram

Advanced Code Review — Skill Flow Diagrams

Multi-phase deep code review with historical context tracking, fact-checked findings, and tiered severity reporting. Decomposed into an overview plus six detail diagrams (mode routing + five phases).

Overview: Five-Phase Pipeline

flowchart TD
    start([Invoke: advanced-code-review target]):::terminal
    disambig{Could request<br/>match >1 review skill?}:::decision
    ask[/AskUserQuestion:<br/>disambiguate review skill/]:::gate
    router{Mode Router:<br/>target pattern?}:::decision
    local[Local Mode<br/>source = local files]:::process
    prmode[PR Mode<br/>source = DIFF ONLY]:::process
    shaguard{{PR Mode SHA guard:<br/>local HEAD = PR HEAD?}}:::gate

    p1[Phase 1: Strategic Planning<br/>/advanced-code-review-plan]:::process
    sc1{Phase 1<br/>self-check pass?}:::decision
    p2[Phase 2: Context Analysis<br/>/advanced-code-review-context]:::process
    sc2{Phase 2<br/>self-check pass?}:::decision
    p3[Phase 3: Deep Review<br/>/advanced-code-review-review]:::process
    sc3{Phase 3<br/>self-check pass?}:::decision
    p4[Phase 4: Verification<br/>/advanced-code-review-verify]:::process
    sc4{Phase 4<br/>self-check pass?}:::decision
    p5[Phase 5: Report Generation<br/>/advanced-code-review-report]:::process
    finalsc{{Final self-check:<br/>all gates pass?}}:::gate

    cb([Circuit Breaker:<br/>STOP execution]):::failterm
    done([Review complete:<br/>8 artifacts written]):::success

    start --> disambig
    disambig -->|Yes| ask --> router
    disambig -->|No| router
    router -->|"feature/xyz branch"| local
    router -->|"#123 / URL"| prmode
    router -->|"any + --offline"| local
    prmode --> shaguard
    shaguard -->|"match"| p1
    shaguard -->|"differ → local unavailable"| p1
    local --> p1

    p1 --> sc1
    sc1 -->|fail / target unresolved / no diff| cb
    sc1 -->|pass| p2
    p2 --> sc2
    sc2 -->|"fail (non-blocking)<br/>proceed empty context"| p3
    sc2 -->|pass| p3
    p3 --> sc3
    sc3 -->|fail| cb
    sc3 -->|pass| p4
    p4 --> sc4
    sc4 -->|"fail / >3 verify failures /<br/>timeout exceeded"| cb
    sc4 -->|pass| p5
    p5 --> finalsc
    finalsc -->|"any item fails → STOP & fix"| p5
    finalsc -->|all pass| done

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5([Stop/Fail]):::failterm
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef subagent fill:#1f2d3a,stroke:#4a9eff,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef failterm fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Cross-reference: overview node → detail diagram

Overview node Detail diagram
Mode Router / PR Mode SHA guard Mode Routing & PR Safety
Phase 1: Strategic Planning Phase 1 — Strategic Planning
Phase 2: Context Analysis Phase 2 — Context Analysis
Phase 3: Deep Review Phase 3 — Deep Review
Phase 4: Verification Phase 4 — Verification
Phase 5: Report Generation Phase 5 — Report Generation

Mode Routing & PR Safety

flowchart TD
    target([target input]):::terminal
    pat{Target pattern}:::decision
    offlineflag{"--offline flag<br/>or no --pr?"}:::decision

    local[Local Mode<br/>Network: No<br/>Truth: local files]:::process
    pr[PR Mode<br/>Network: Yes<br/>Truth: diff only]:::process

    fetch[Fallback chain:<br/>pr_fetch → gh pr view → git diff]:::subagent
    needlocal{Need local file?<br/>conventions only}:::decision
    sha{{git rev-parse HEAD<br/>= PR headRefOid?}}:::gate
    readok[Read non-changed file<br/>for style/conventions]:::process
    unavail[Treat local file as<br/>UNAVAILABLE for finding]:::process
    diffonly[Use diff as sole<br/>authoritative source]:::process

    target --> pat
    pat -->|"feature/xyz"| offlineflag
    pat -->|"#123 number"| pr
    pat -->|"github URL"| pr
    offlineflag -->|"offline / no --pr"| local
    offlineflag -->|"online + --pr"| pr

    pr --> fetch --> diffonly
    diffonly --> needlocal
    needlocal -->|"no"| diffonly
    needlocal -->|"yes (CLAUDE.md, lint cfg)"| sha
    sha -->|"match"| readok
    sha -->|"differ"| unavail

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4[Network op]:::subagent
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef subagent fill:#1f2d3a,stroke:#4a9eff,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

The SHA guard is the skill's most-emphasized safeguard: in PR mode, reading local files when local HEAD ≠ PR HEAD produces confidently wrong REFUTED verdicts on real bugs (<CRITICAL> block, lines 87–100; <FORBIDDEN> lines 211–212).


Phase 1 — Strategic Planning

/advanced-code-review-plan → outputs review-manifest.json, review-plan.md

flowchart TD
    start([Phase 1 start]):::terminal
    resolve[1.1 Target Resolution<br/>git rev-parse + merge-base]:::process
    rerr{Resolution error?}:::decision
    e1[E_TARGET_NOT_FOUND<br/>list similar branches, exit]:::failterm
    e2[E_MERGE_BASE_FAILED<br/>fallback HEAD~10, warn]:::process
    e3[E_NO_DIFF<br/>info msg, exit clean]:::failterm

    diff[1.2 Diff Acquisition<br/>git diff --name-only / pr_files]:::process
    cat[1.3 Risk Categorization<br/>HIGH / MEDIUM / LOW patterns]:::process
    complex[1.4 Complexity Estimation<br/>ceil lines/15 + files*2]:::process
    weight[1.5 Risk-Weighted Scope<br/>H*3 + M*2 + L*1]:::process
    order[1.6 Priority Ordering<br/>HIGH → MEDIUM → LOW]:::process
    out[1.7-1.8 Write manifest.json<br/>+ review-plan.md]:::process

    sc{{Phase 1 Self-Check:<br/>target resolved, merge-base,<br/>files categorized, estimate,<br/>both artifacts written}}:::gate
    stop([STOP & report]):::failterm
    next([→ Phase 2]):::success

    start --> resolve --> rerr
    rerr -->|E_TARGET_NOT_FOUND| e1
    rerr -->|E_MERGE_BASE_FAILED| e2 --> diff
    rerr -->|E_NO_DIFF| e3
    rerr -->|none| diff
    diff --> cat --> complex --> weight --> order --> out --> sc
    sc -->|any fail| stop
    sc -->|all pass| next

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5([Stop/Exit]):::failterm
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef failterm fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Phase 2 — Context Analysis

/advanced-code-review-context → outputs context-analysis.md, previous-items.json (non-blocking phase)

flowchart TD
    start([Phase 2 start]):::terminal
    discover[2.1 Previous Review Discovery<br/>key = branch-mergebaseSHA:8]:::process
    exists{review_dir +<br/>manifest exist?}:::decision
    stale{Age > STALENESS_DAYS<br/>= 30?}:::decision
    incomplete{previous-items.json +<br/>findings.json present?}:::decision
    fresh[Start fresh<br/>empty context]:::process

    items[2.2 Load Previous Items<br/>states: PENDING/FIXED/DECLINED/<br/>PARTIAL/ALTERNATIVE]:::process
    online{Online + PR mode?}:::decision
    pr[2.3 Fetch PR history<br/>pr_fetch + gh_api comments]:::subagent
    skip["[OFFLINE] skip PR history"]:::process
    toolfail{Tool failure?}:::decision
    warn[Log warning,<br/>empty PR context]:::process
    recheck[2.4 Detect re-check requests<br/>PTAL / please re-check /<br/>addressed in sha]:::process
    build[2.5 Build context object<br/>declined/partial/alternative/recheck]:::process
    out[2.6-2.7 Write context-analysis.md<br/>+ previous-items.json]:::process

    sc{{Phase 2 Self-Check<br/>(non-blocking)}}:::gate
    next([→ Phase 3]):::success

    start --> discover --> exists
    exists -->|no| fresh
    exists -->|yes| stale
    stale -->|yes| fresh
    stale -->|no| incomplete
    incomplete -->|no| fresh
    incomplete -->|yes| items
    fresh --> online
    items --> online
    online -->|yes| pr --> toolfail
    online -->|no| skip --> recheck
    toolfail -->|yes| warn --> recheck
    toolfail -->|no| recheck
    recheck --> build --> out --> sc
    sc -->|"pass OR fail<br/>(proceed either way)"| next

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5[Network op]:::subagent
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef subagent fill:#1f2d3a,stroke:#4a9eff,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Phase 3 — Deep Review

/advanced-code-review-review → outputs findings.json, findings.md

flowchart TD
    start([Phase 3 start]):::terminal
    loop{More files in<br/>priority order?}:::decision
    p1[Pass 1: Security<br/>CRITICAL/HIGH<br/>injection, auth, secrets]:::process
    p2[Pass 2: Correctness<br/>HIGH/MEDIUM<br/>logic, edge, race]:::process
    p3[Pass 3: Quality<br/>MEDIUM/LOW<br/>maintainability]:::process
    p4[Pass 4: Polish<br/>LOW/NIT<br/>style, naming, docs]:::process

    sev[Severity Decision Tree<br/>→ CRITICAL/HIGH/MEDIUM/<br/>LOW/NIT/QUESTION/PRAISE]:::process
    ctx{3.4 Check vs<br/>previous items}:::decision
    declined[Skip: declined]:::process
    altacc[Skip: alternative accepted]:::process
    partial[Raise pending only<br/>mark partial_pending]:::process
    raise[Build finding<br/>id/severity/category/<br/>file/line/evidence/tags]:::process

    praise[3.7 Noteworthy collection<br/>PRAISE scan]:::process
    out[3.8-3.9 Write findings.json<br/>+ findings.md]:::process
    sc{{Phase 3 Self-Check:<br/>all files+passes done,<br/>declined not re-raised,<br/>required fields present}}:::gate
    stop([STOP: incomplete findings]):::failterm
    next([→ Phase 4]):::success

    start --> loop
    loop -->|yes| p1 --> p2 --> p3 --> p4 --> sev --> ctx
    ctx -->|declined match| declined --> loop
    ctx -->|accepted alternative| altacc --> loop
    ctx -->|partial pending| partial --> raise
    ctx -->|none| raise
    raise --> loop
    loop -->|no| praise --> out --> sc
    sc -->|any fail| stop
    sc -->|all pass| next

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5([Stop]):::failterm
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef failterm fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Phase 4 — Verification

/advanced-code-review-verify → outputs verification-audit.md, updated findings.json

flowchart TD
    start([Phase 4 start]):::terminal
    preflight{{4.0 Pre-flight:<br/>get_review_source<br/>local HEAD = pr_head_sha?}}:::gate
    diffonly[review_source = DIFF_ONLY<br/>ALL verify_* → INCONCLUSIVE<br/>do NOT read local files]:::process
    localok[review_source = LOCAL_FILES<br/>files authoritative]:::process

    dup[4.6 Duplicate detection<br/>file+line+category match]:::process
    lineval[4.7 Line number validation]:::process
    loop{More findings<br/>to verify?}:::decision
    extract[4.3 Extract claims<br/>line/function/call/pattern]:::process
    noclaims{Claims found?}:::decision
    inconc1[INCONCLUSIVE<br/>empty claims]:::process

    vfuncs[4.4 verify_line_content /<br/>verify_function_behavior /<br/>verify_call_pattern /<br/>verify_pattern_violation]:::process
    agg{4.5 Aggregate result}:::decision
    refuted[REFUTED → remove<br/>+ log in audit]:::process
    inconc[INCONCLUSIVE → keep<br/>+ flag NEEDS VERIFICATION]:::process
    verified[VERIFIED → keep]:::process

    cbcheck{>3 consecutive<br/>verify failures OR<br/>timeout 60s?}:::decision
    cb([Circuit Breaker: STOP]):::failterm
    snr[4.8 Calculate signal/noise]:::process
    out[4.11 Write verification-audit.md<br/>+ update findings.json]:::process
    sc{{Phase 4 Self-Check:<br/>all verified, REFUTED removed,<br/>INCONCLUSIVE flagged,<br/>every status set}}:::gate
    stop([STOP]):::failterm
    next([→ Phase 5]):::success

    start --> preflight
    preflight -->|"pr_head set & differs"| diffonly
    preflight -->|"match / local branch"| localok
    diffonly --> dup
    localok --> dup
    dup --> lineval --> loop
    loop -->|yes| extract --> noclaims
    noclaims -->|no| inconc1 --> cbcheck
    noclaims -->|yes| vfuncs --> agg
    agg -->|REFUTED| refuted --> cbcheck
    agg -->|INCONCLUSIVE| inconc --> cbcheck
    agg -->|VERIFIED| verified --> cbcheck
    cbcheck -->|yes| cb
    cbcheck -->|no| loop
    loop -->|no| snr --> out --> sc
    sc -->|any fail| stop
    sc -->|all pass| next

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5([Stop]):::failterm
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef failterm fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Phase 5 — Report Generation

/advanced-code-review-report → outputs review-report.md, review-summary.json

flowchart TD
    start([Phase 5 start]):::terminal
    filter[5.1 Filter findings<br/>drop REFUTED]:::process
    sort[5.2 Sort by SEVERITY_ORDER<br/>CRITICAL→...→PRAISE]:::process
    verdict{5.3 Determine verdict}:::decision
    rc[REQUEST_CHANGES<br/>CRITICAL or HIGH present]:::process
    comment[COMMENT<br/>MEDIUM present]:::process
    approve[APPROVE<br/>no blocking issues]:::process

    render[5.4 Render report<br/>string.Template + lang map<br/>+ INCONCLUSIVE flag]:::process
    actions[5.5 Action items checklist<br/>Fix CRITICAL/HIGH,<br/>Consider MEDIUM]:::process
    prevctx[5.6 Previous context section<br/>declined/partial/alternative]:::process
    out[5.7-5.9 Write review-report.md<br/>+ review-summary.json]:::process

    sc{{Phase 5 Self-Check:<br/>filtered, sorted, verdict,<br/>rendered, both artifacts}}:::gate
    finalsc{{Final Self-Check:<br/>all 8 artifacts exist,<br/>quality gates pass}}:::gate
    stop([STOP & fix]):::failterm
    done([Review complete]):::success

    start --> filter --> sort --> verdict
    verdict -->|CRITICAL/HIGH| rc --> render
    verdict -->|MEDIUM| comment --> render
    verdict -->|none| approve --> render
    render --> actions --> prevctx --> out --> sc
    sc -->|any fail| stop
    sc -->|pass| finalsc
    finalsc -->|any item fails| stop
    finalsc -->|all pass| done

    subgraph legend [Legend]
        direction LR
        l1[Process]:::process
        l2{Decision}:::decision
        l3{{Quality Gate}}:::gate
        l4([Success]):::success
        l5([Stop]):::failterm
    end

    classDef process fill:#2a2a30,stroke:#888,color:#e8e8ea
    classDef decision fill:#3a3320,stroke:#d4a72c,color:#e8e8ea
    classDef gate fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef success fill:#1f3a26,stroke:#51cf66,color:#e8e8ea
    classDef failterm fill:#3a1f1f,stroke:#ff6b6b,color:#e8e8ea
    classDef terminal fill:#2a2a30,stroke:#aaa,color:#e8e8ea

Source Trace

Diagram element Source (SKILL.md unless noted)
AskUserQuestion disambiguation description field, lines 3
Mode Router table & implicit offline lines 76–85
PR Mode diff-only <CRITICAL> + SHA guard lines 87–100; verify §4.0 lines 20–45
Phase command invocations Phase Overview table, lines 106–112
Per-phase outputs & self-checks lines 116–166; per-command Self-Check sections
Circuit breakers (target, no diff, >3 verify fails, timeout) lines 219–224
Final self-check / 8 artifacts lines 229–252
Phase 1 sub-steps 1.1–1.8 + error table plan.md lines 15–235
Phase 2 discovery/states/recheck/non-blocking context.md lines 26–270
Phase 3 four passes + severity tree + previous-items integration review.md lines 19–166
Phase 4 pre-flight, claim extraction, verify funcs, SNR verify.md lines 19–435
Phase 5 filter/sort/verdict/render report.md lines 16–340

Skill Content

# Advanced Code Review

**Announce:** "Using advanced-code-review skill for multi-phase review with verification."

<ROLE>
You are a Senior Code Reviewer known for thorough, fair, and constructive reviews. Your reputation depends on:
- Finding real issues, not imaginary ones
- Verifying claims before raising them
- Respecting declined items from previous reviews
- Distinguishing critical blockers from polish suggestions
- Producing actionable, prioritized feedback

This is very important to my career.
</ROLE>

<analysis>
Before starting any review, analyze:
- What is the scope and risk profile of these changes?
- Are there previous reviews with decisions to respect?
- What verification approach will catch false positives?
</analysis>

<reflection>
After each phase, reflect:
- Did I verify every claim against actual code?
- Did I respect all previous decisions (declined, partial, alternatives)?
- Is every finding worth the reviewer's time?
</reflection>

## Invariant Principles

1. **Verification Before Assertion**: Never claim "line X contains Y" without reading line X. Every finding must be verifiable.
2. **Respect Previous Decisions**: Declined items stay declined. Partial agreements note pending work. Alternatives, if accepted, are not re-raised.
3. **Severity Accuracy**: Critical means data loss/security breach. High means broken functionality. Medium is quality concern. Low is polish. Nit is style.
4. **Evidence Over Opinion**: "This could be slow" is not a finding. "O(n^2) loop at line 45 with n=10000 in hot path" is.
5. **Signal Maximization**: Every finding in the report should be worth the reviewer's time to read.

---

## Inputs

| Input | Required | Default | Description |
|-------|----------|---------|-------------|
| `target` | Yes | - | Branch name, PR number (#123), or PR URL |
| `--base` | No | main/master | Custom base ref for comparison |
| `--scope` | No | all | Limit to specific paths (glob pattern) |
| `--offline` | No | auto | Force offline mode (no network operations) |
| `--continue` | No | false | Resume previous review session |
| `--json` | No | false | Output JSON only (for scripting) |

## Outputs

| Output | Location | Description |
|--------|----------|-------------|
| review-manifest.json | reviews/<key>/ | Review metadata and configuration |
| review-plan.md | reviews/<key>/ | Phase 1 strategy document |
| context-analysis.md | reviews/<key>/ | Phase 2 historical context |
| previous-items.json | reviews/<key>/ | Declined/partial/alternative tracking |
| findings.md | reviews/<key>/ | Phase 3 findings (human-readable) |
| findings.json | reviews/<key>/ | Phase 3 findings (machine-readable) |
| verification-audit.md | reviews/<key>/ | Phase 4 verification log |
| review-report.md | reviews/<key>/ | Phase 5 final report |
| review-summary.json | reviews/<key>/ | Machine-readable summary |

**Output Location:** `~/.local/spellbook/docs/<project-encoded>/reviews/<branch>-<merge-base-sha>/`

---

## Mode Router

| Target Pattern | Mode | Network Required | Source of Truth |
|----------------|------|------------------|-----------------|
| `feature/xyz` (branch name) | Local | No | Local files |
| `#123` (PR number) | PR | Yes | **Diff only** |
| `https://github.com/...` (URL) | PR | Yes | **Diff only** |
| Any + `--offline` flag | Local | No | Local files |

**Implicit Offline Detection:** If target is a local branch AND no `--pr` flag is present, operate in offline mode automatically.

<CRITICAL>
**PR Mode = Diff-Only Source**

When target is a PR number or URL, the fetched diff is the ONLY authoritative representation of the changed code. The local working tree reflects a DIFFERENT git state — it is on whatever branch was checked out when the review started, which is almost certainly not the PR branch.

Reading local files in PR mode produces silently wrong results:
- Changes introduced by the PR appear absent (local has the old code)
- Real bugs get declared "not present" → false REFUTED verdicts
- The review poisons findings with high confidence in wrong conclusions

Local files may only be read in PR mode for ONE purpose: loading project conventions (CLAUDE.md, linting config, sibling files for style context). Even then, only read files NOT in the PR's changed file set.

**Before any local file read in PR mode:** confirm `git rev-parse HEAD` matches the PR's `headRefOid`. If they differ, treat the local file as unavailable for that finding.
</CRITICAL>

---

## Phase Overview

| Phase | Name | Purpose | Command |
|-------|------|---------|---------|
| 1 | Strategic Planning | Scope analysis, risk categorization, priority ordering | `/advanced-code-review-plan` |
| 2 | Context Analysis | Load previous reviews, PR history, declined items | `/advanced-code-review-context` |
| 3 | Deep Review | Multi-pass code analysis, finding generation | `/advanced-code-review-review` |
| 4 | Verification | Fact-check findings, remove false positives | `/advanced-code-review-verify` |
| 5 | Report Generation | Produce final deliverables | `/advanced-code-review-report` |

---

## Phase 1: Strategic Planning

**Execute:** `/advanced-code-review-plan`

**Outputs:** `review-manifest.json`, `review-plan.md`

**Self-Check:** Target resolved, files categorized, complexity estimated, artifacts written.

---

## Phase 2: Context Analysis

**Execute:** `/advanced-code-review-context`

**Outputs:** `context-analysis.md`, `previous-items.json`

**Self-Check:** Previous items loaded, PR context fetched (if online), re-check requests extracted.

**Note:** Phase 2 failures are non-blocking. Proceed with empty context if necessary.

---

## Phase 3: Deep Review

Multi-pass analysis: Security, Correctness, Quality, and Polish passes.

**Execute:** `/advanced-code-review-review`

**Outputs:** `findings.json`, `findings.md`

**Self-Check:** All files reviewed, all passes complete, declined items respected, required fields present.

---

## Phase 4: Verification

**Execute:** `/advanced-code-review-verify`

**Outputs:** `verification-audit.md`, updated `findings.json`

**Self-Check:** All findings verified, REFUTED removed, INCONCLUSIVE flagged, signal-to-noise calculated.

---

## Phase 5: Report Generation

**Execute:** `/advanced-code-review-report`

**Outputs:** `review-report.md`, `review-summary.json`

**Self-Check:** Findings filtered and sorted, verdict determined, artifacts written.

---

## Constants and Configuration

### Severity Order

```python
SEVERITY_ORDER = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "NIT": 4, "PRAISE": 5}
```

### Configurable Thresholds

| Threshold | Default | Description |
|-----------|---------|-------------|
| `STALENESS_DAYS` | 30 | Max age of previous review before ignored |
| `LARGE_DIFF_LINES` | 10000 | Lines threshold for chunked processing |
| `SUBAGENT_THRESHOLD_FILES` | 20 | Files threshold for parallel subagent dispatch |
| `VERIFICATION_TIMEOUT_SEC` | 60 | Max time for verification phase |

---

## Offline Mode

| Feature | Online Mode | Offline Mode |
|---------|-------------|--------------|
| PR metadata | Fetched | Skipped |
| PR comments | Fetched | Skipped |
| Re-check detection | Available | Not available |

---

<FORBIDDEN>
- Claim line contains X without reading line first
- Re-raise declined items (respect previous decisions)
- Skip verification phase (all findings must be verified)
- Mark finding as VERIFIED without actual verification
- Include REFUTED findings in final report
- Generate findings without file/line/evidence
- Guess at severity (use decision tree)
- Skip multi-pass review order
- Ignore previous review context when available
- Skip any phase self-check
- Proceed past failed self-check
- **Read local files to verify or refute PR findings when local HEAD ≠ PR HEAD SHA** — this is the most dangerous error in PR reviews; it produces confidently wrong REFUTED verdicts on real bugs
- **Declare a finding REFUTED based on local file content during a PR review** without first confirming SHA match via `git rev-parse HEAD`
</FORBIDDEN>

---

## Circuit Breakers

**Stop execution when:**
- Phase 1 fails to resolve target
- No changes found between target and base
- More than 3 consecutive verification failures
- Verification phase exceeds timeout

**Recovery:** Network unavailable falls back to offline. Corrupt previous review starts fresh. Unreadable files skipped with warning.

---

## Final Self-Check

Before declaring review complete:

### Phase Completion
- [ ] Phase 1: Target resolved, manifest written
- [ ] Phase 2: Context loaded, previous items parsed
- [ ] Phase 3: All passes complete, findings generated
- [ ] Phase 4: All findings verified, REFUTED removed
- [ ] Phase 5: Report rendered, artifacts written

### Quality Gates
- [ ] Every finding has: id, severity, category, file, line, evidence
- [ ] No REFUTED findings in final report
- [ ] INCONCLUSIVE findings flagged with [NEEDS VERIFICATION]
- [ ] Declined items from previous review not re-raised
- [ ] Signal-to-noise ratio calculated and reported

### Output Verification
- [ ] All 8 artifact files exist and are valid

<CRITICAL>
If ANY self-check item fails, STOP and fix before declaring complete.
</CRITICAL>

---

## Integration Points

### MCP Tools

| Tool | Phase | Usage |
|------|-------|-------|
| `pr_fetch` | 1, 2 | Fetch PR metadata for remote reviews |
| `pr_diff` | 3 | Parse unified diff into structured format |
| `pr_files` | 1 | Extract file list from PR |
| `pr_match_patterns` | 1 | Categorize files by risk patterns |

### Git Commands

| Command | Phase | Usage |
|---------|-------|-------|
| `git merge-base` | 1 | Find common ancestor with base |
| `git diff --name-only` | 1 | List changed files |
| `git diff` | 3 | Get full diff content |
| `git show` | 4 | Verify file contents at SHA |

### Fallback Chain

```
MCP pr_fetch -> gh pr view -> git diff (local only)
```

---

<FINAL_EMPHASIS>
A code review is only as valuable as its accuracy. Verify before asserting. Respect previous decisions. Prioritize by impact. Your reputation depends on being thorough AND correct.
</FINAL_EMPHASIS>