Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Block any plan from reaching implementation unless it is hallucination-free (every existing-code claim proven at file:line) and implementation-ready (every step concrete, small enough to code from immediately) — by auto-reviewing implementation plans for validity, correctness, and best practices. Recursive: when any findings exist, validate findings with $why-review --validate-findings, fix only validated findings in plan files, and rerun the full plan review until the round's exit bar is clear — zero findings in rounds 1-2, zero CRITICAL/HIGH/MEDIUM from round 3 (a LOW-only round ENDS the loop, deferred not fixed).
Every phase review treats Mode, Wave, write set, and SEQ dependency as one indivisible metadata contract; a mismatch in any field blocks approval.
Summary: AI self-review (automatic, NOT a user interview like $plan-validate) that gates a plan before implementation.
- Purpose: review as a SKEPTIC, not validator — every existing-code claim needs
file:line proof (Anti-Hallucination Gate); every phase must clear the "Detailed & Small Enough" granularity gate (≤5 files, ≤3h, no planning verbs) — too vague → detail it, too big → break it.
- Main steps (run in order): Phase 0 detect plan type → Step 1 read
plan.md + goal.md + all phase-*.md, extract requirements/steps/files/risks → Step 2 evaluate the 4 checklist groups: Validity (summary, requirements, steps, files) · Correctness (Granularity Gate + Anti-Hallucination/Code-Proof Gate + spec/TC coverage + Goal-Contract mapping) · Best Practices (YAGNI/KISS/DRY/architecture) · Completeness (risks, testing, success criteria, security, graph-dependency) → run the 11 Adversarial techniques + Anti-Bias Gate + 8 Plan Dimensions → graph-trace each modified file (when graph.db exists) → Step 3 score PASS/WARN/FAIL → Step 4 output result → Step 5 recursive validate-fix-re-review loop.
- Detect plan type FIRST (Phase 0) so the right focus applies — bugfix MANDATES the Behavioral Delta Matrix; security/performance/refactor/contract/infra/data-schema each add targeted checks.
- Findings are never fixed blindly: run the
$why-review --validate-findings gate BEFORE editing any plan.md/phase-*.md, fix only validated findings at the smallest responsible location, then restart the FULL review with a fresh, zero-memory sub-agent — loop until a clean pass at the round's bar.
- Severity floor — from round 3, LOW stops blocking. Rounds 1-2 require zero findings at any severity. From round 3 the bar is zero validated CRITICAL/HIGH/MEDIUM — a review round whose validated findings are ALL LOW ENDS the loop. Do NOT restart the full review for LOW findings alone: record them under
## Deferred LOW Findings (severity floor, round ≥3) in the report and PASS. NEVER re-tier a real CRITICAL/HIGH/MEDIUM down to LOW to reach the exit, and NEVER apply the floor to a hallucinated-code claim or a missing-evidence finding — those are HIGH by definition, not deferrable LOW. Severity tiers per SYNC:severity-rubric.
- Round cap 3 — a ceiling, NEVER a target; a clean pass ends the loop immediately at ANY round (round 1 included). Escalate by asking the user directly when the same blocker survives 2 consecutive full re-reviews with no progress, when round 3 completes with findings still open, or when a finding needs product/owner judgment — cap exhaustion escalates, it NEVER becomes a PASS.
Workflow:
- Resolve Plan — Use $ARGUMENTS path or active plan from
## Plan Context
- Read Files — plan.md + all phase-*.md files, extract requirements/steps/files/risks
- Evaluate Checklist — Validity (summary, requirements, steps, files), Correctness (specific, paths, no conflicts), Best Practices (YAGNI/KISS/DRY, architecture), Completeness (risks, testing, success, security)
- Score & Classify — PASS (all Required + ≥50% Recommended), WARN (all Required + <50% Recommended), FAIL (any Required fails)
- Output Result — Status, checks passed, issues, recommendations, verdict
- If any findings remain — Run
$why-review --validate-findings on the plan-review report first; fix only validated actionable issues in plan files, then re-review (loop back to step 2 until the round's bar is clear — zero findings in rounds 1-2, zero CRITICAL/HIGH/MEDIUM from round 3 — unless the repeated-blocker rule or the 3-round cap applies)
Core Principle — Detailed & Small Enough:
- Too vague? → Detail it: add specific file paths, concrete actions, exact method names
- Too big to detail? → Break it: split into smaller phases/sub-plans until each is detailed
- A plan that can't be immediately coded from is NOT ready. Every step must be implementation-ready.
Key Rules:
- No hallucination: Every plan claim about existing source code must have
file:line proof — unverified paths, class names, or behaviors = FAIL
- PASS: Proceed to implementation
- WARN: Proceed with caution, note gaps
- FAIL (any findings): Validate findings with
$why-review --validate-findings, fix only validated plan issues, then re-run the FULL review from the start. Repeat this self-loop — no forced minimum, capped at 3 rounds MAX — until a complete pass finds ZERO findings.
- Bounded loop — two escalation triggers, neither a completion criterion: (a) no-progress safety — the SAME blocker surviving 2 consecutive full re-reviews with no progress; (b) round cap — round 3 completing with findings still open. Whichever trips first → STOP and escalate to user by asking the user directly, never a silent "good enough" PASS. A clean pass ends the loop immediately, even on round 1 — the cap is a ceiling, not a quota.
- Constructive: Focus on implementation-blocking issues, not pedantic details
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
First Principle — Easy to Change
The success metric of every coding decision is future change cost.
DRY, SRP, abstraction, design patterns, naming, layering, tests — every
technique exists to serve one goal: making the next change cheaper.
Evaluating code, refactor, test, abstraction, ask: does this make the next change cheaper or more expensive?
- Reject "best practices" raising change cost — premature abstraction, speculative generality, leaky indirection, ceremony without payoff.
- Name the real enemies in findings: coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early.
- A simpler design that is easy to change beats a sophisticated one that is not.
Apply this lens before any rule, pattern, or checklist below — a downstream rule that raises change cost LOSES to this principle.
Adversarial Review Mindset (NON-NEGOTIABLE)
Default stance: SKEPTIC, not validator. Your job is to find what cannot work, not confirm what looks right.
Confirmation bias trap: After reading a well-structured plan, AI naturally finds reasons to agree. This section exists to break that loop before it produces a rubber-stamp approval.
Adversarial Techniques (apply ALL before concluding)
Techniques 1-6 stress whether the plan can be built (reality, effort, scope, dependencies). Techniques 7-10 stress whether the chosen design is the right one — the decision-quality lens shared with $why-review's rationale review. Apply both groups: a buildable plan built on the wrong decision is still a failed plan.
1. Implementation Reality Check
Per phase: "a developer starts implementing this right now — what breaks FIRST?" Walk the critical path concretely. A vague phase ("implement the service layer") untraceable to specific files/classes FAILS.
2. Assumption Stress Test
List the top 3 implicit assumptions; per assumption: "what if it is wrong?" A valid plan survives 2 of 3 being false. Usual hidden ones: existing code is in a known state · no external API changes · team already has this domain knowledge.
3. Effort Reality Check
Per estimated phase: "has similar work in THIS codebase shipped in that timeframe, and what slowed it last time?" Underestimating by 2x or more makes it an optimistic guess, NOT a valid plan.
4. Pre-Mortem
Assume the plan shipped exactly as written and the feature has been in production a month. Write ONE concrete, plausible failure scenario. Finding none means you have not looked hard enough.
5. Scope Creep Detector
Flag any task NOT directly required to deliver the stated feature. "While we're here, let's also refactor X" is scope creep.
6. Dependency Blindspot
List 2-3 external dependencies (services, APIs, data sources) the plan assumes stable; per one: "what breaks here if it changes or goes away?" A dependency failure addressed nowhere is a risk gap.
7. Steel-Man the Rejected Alternative
Per design decision choosing X over an alternative, argue FOR the rejected one as strongly as possible. Would a 10-year domain senior pick it? If yes, dismissal needs proof stronger than "we picked X" — why: a decision that never names what it rejected was assumed, not made.
8. Why NOT?
Per "chose X because Y", ask what X sacrifices. A plan listing only upsides is hiding the trade-off, not avoiding it. Demand the named downside.
9. Unseen Alternatives
Name 1-2 viable approaches the plan never mentions. An alternative absent without exclusion reasoning is weak coverage, NOT a settled decision.
10. Pros/Cons Symmetry
Count stated pros vs cons on the chosen approach. Pros outnumbering cons by more than 2:1 signals confirmation bias — demand the missing downsides before accepting.
11. Contrarian Pass
Before ANY verdict, write ≥2 sentences arguing the OPPOSITE. About to write PASS → argue NEEDS WORK, and vice versa. Then pick the stronger argument on evidence.
Forbidden Patterns
- "Structure looks good" → Structure is NOT quality. Can it be implemented?
- "Phases are well-defined" → Presence of phases is NOT correctness. What's in them?
- "Alternatives were considered" → Were they real alternatives or strawmen set up to fail?
- "Risk is managed" → Mitigation of "monitor closely" is NOT a mitigation. What action, by whom, triggered by what?
- "Looks achievable" without tracing the critical path → Not a valid assessment.
Anti-Bias Gate (MANDATORY before finalizing verdict)
Complete ALL checks before writing the final verdict (MUST ATTENTION):
- run Implementation Reality Check on the highest-risk phase
- identify 3 implicit assumptions and stress-test them
- check effort estimates against codebase complexity
- run pre-mortem (one concrete production failure scenario)
- scan for scope creep (tasks not required for stated feature)
- verify dependency blindspots are addressed
- steel-man at least one rejected design alternative (argue FOR it)
- name at least 1 viable alternative the plan does not mention
- check pros/cons symmetry on the plan's primary design decision
If any check is incomplete → you have NOT completed the adversarial review. Go back.
Why-review relationship: Techniques 7-10 + these gate checks are the rationale lens applied DURING the review pass (does the plan's design hold up?). The separate $why-review --validate-findings gate runs AFTER findings exist (are the findings themselves correct before we fix them?). Both stay — they validate different things and must not be collapsed.
Plan Dimension Thinking Framework
After plan-type detection (Phase 0), evaluate each dimension below using this reasoning pattern:
For each dimension: (1) Understand its role in the plan's domain, (2) Read the plan's claims about it, (3) Derive the actual concerns from first principles — what could go wrong if this dimension is weak? (4) Apply your knowledge of the plan's tech stack to find stack-specific gaps.
Dimension 1: Scope Integrity
Think: Does the plan's scope match the stated goal exactly — not broader, not narrower?
- What's the minimal set of changes needed to deliver the stated goal?
- What does the plan add that's NOT in the goal? → Scope creep.
- What's in the goal that the plan doesn't address? → Scope gap.
- Stress test: "If we skip phase X, does the feature still work?" → If yes, that phase is out of scope.
Dimension 2: Data Flow Correctness
Think: Can I trace how data moves through every phase of this plan?
- Where does data originate? Where does it end up?
- What transforms it in between? Are those transforms described in the plan?
- What happens to data at system boundaries (API, message bus, storage, UI)? Does the plan address each boundary?
- What data states are invalid? Does the plan guard against them?
Dimension 3: Dependency Chain Completeness
Think: Does the plan account for everything its changes affect?
- Every file/module the plan touches: what imports it? what calls it? what depends on its contract?
- If the plan changes an interface/contract, are ALL consumers listed?
- External dependencies (third-party services, shared infra): are they stable? If they break, what's the fallback?
- Run graph trace if graph.db exists — compare plan's file list against downstream impact.
Dimension 4: Failure Mode Coverage
Think: What does the plan say about when things go wrong?
- For each external call, async operation, or state change: what's the error behavior?
- Does the plan include a rollback strategy for irreversible operations?
- What's the partial failure state? (half-migrated, half-deployed, race condition) Is it addressable?
- Is there a monitoring/alerting plan for the new code paths?
Dimension 5: Test Observability
Think: How will a developer know if this plan's implementation is correct?
- Can the stated acceptance criteria be mechanically verified by a test?
- Are there behaviors that are only observable via logs/traces (not unit tests)?
- Which phase introduces the risk? Does a test exist in that phase?
- "Tests pass" is NOT a success criterion — name the specific behaviors being tested.
- Spec-Loop scheduling (test-quality gate). The plan MUST schedule the spec-loop, not just "add tests": (1) every
[HARD] §4 rule / §5 invariant gets a universally-quantified property test spec plus a boundary counter-case — not example tests only; (2) changed core logic is gated by a MUTATION-SCORE quality bar (a surviving mutant = a missing invariant ⇒ a killing test owed), NOT a line-coverage % target; (3) a dual-feedback + re-review step exists so each behavior-changing finding enriches BOTH the spec AND the tests and the package is re-reviewed to zero new gaps. FAIL a plan that targets a line-coverage % instead of a mutation-score bar, or that omits property/invariant test specs for its [HARD]/§5 rules.
Dimension 6: Knowledge Prerequisites
Think: Does implementing this plan require knowledge the plan doesn't surface?
- Domain knowledge: Are business rules spelled out, or does the implementer need to already know them?
- System knowledge: Are integration points documented, or does the implementer need tribal knowledge?
- Tooling knowledge: Does the plan assume setup steps that aren't listed?
- If any prerequisite is unstated → the plan is not implementation-ready.
Dimension 7: Estimation Drift
Think: Does the frontmatter estimation still match the finalized plan, or did scope-locking change the cost?
- Pre-completion estimates anchor on rough scope guesses; finalized phases reveal true cost. Re-derive
bottom_up_hours = Σ phase_hours from each phase file's locked tasks/TCs and compare to current frontmatter man_days_traditional / story_points.
- Recompute
likely_days, risk_margin_pct, min-max range per SYNC:estimation-framework. Did unknowns resolve (margin should drop) or new risks surface (margin should rise)?
- If
|delta| > 20% → frontmatter MUST be updated with reestimate_delta_pct: <signed> + 1-line reestimate_reason. Missing update = FAIL.
- If
|delta| > 50% → flag SHOULD-RESCOPE in review verdict; the plan must surface the rescope decision to the user before implementation begins.
- Watch for hidden inflation: phases added during planning, TCs not counted in original estimate, integration work discovered late.
Dimension 8: Domain Entity Design (CONDITIONAL — fires when the plan touches an entity, VO, or aggregate)
Think: Does the plan actually decide the domain model, or does it defer the hard parts to implementation?
Apply SYNC:domain-entity-change-gate (inlined below) — the SAME protocol $plan authored under and $changes-review will review under, whose A–P checklist $domain-entities-review owns. State No domain-entity surface — Dimension 8 N/A when it does not fire.
- An unanswered, hand-waved, or deferred-to-implementation decision point is a FINDING with
file:line into the plan. The word "entity" appearing in a task is NEVER an answer.
- MUST ATTENTION verify the plan states paradigm and subdomain fit before any entity task — a plan proposing a rich domain model for a CRUD subdomain is a FINDING (ceremony with no invariant to protect), and so is a plan proposing setter/encapsulation tasks against an immutable or event-sourced model.
- Check each triggered row names its owning file, not just an intent: classification · invariant ownership + failure signalling · aggregate boundary + concurrency · construction vs reconstitution · events · property-TC test obligation.
- Highest-yield misses: an aggregate boundary chosen by UI screen or DB table rather than by true invariant · cross-aggregate references planned as object navigation · no concurrency token on a contended root · a set-based invariant ("unique email") with no enforcing mechanism · invariants planned into a validator/handler instead of the entity · events planned with no dispatch timing.
- Steel-man the plan's boundary choice before flagging it — a deliberately larger aggregate protecting a real always-consistent invariant is CORRECT; demand the invariant, not a smaller boundary.
Use these dimensions to generate targeted, evidence-backed questions — not generic "add more detail" suggestions.
Your mission
Self-review the implementation plan — valid, correct, best-practice — and surface everything needing a fix BEFORE implementation proceeds.
Key distinction: AI self-review (automatic), NOT a user interview like $plan-validate.
Plan Resolution
$ARGUMENTS provided → use that path
- Else
## Plan Context section → use the active plan path
- No plan found → error: "No plan to review. Run $plan first."
Workflow
Phase 0: Detect Plan Type
Before ANY checklist, read plan.md and classify the plan — why: the type decides the sub-agent, the emphasis, and whether the Behavioral Delta Matrix is mandatory:
| Signal in plan |
Type |
Additional review focus |
| "fix", "bug", "regression", "defect" in title/description |
Bugfix |
Behavioral Delta Matrix (MANDATORY), preservation inventory, regression tests |
| "migrate", "schema", "database", "index" |
Data/Schema |
Rollback path, zero-downtime strategy, data preservation, migration idempotency |
| "auth", "permission", "security", "encrypt", "token", "RBAC" |
Security |
Threat modeling, attack surface, trust boundary changes, sub-agent: security-auditor |
| "performance", "latency", "cache", "N+1", "throughput" |
Performance |
Baseline metrics, regression risk, measurement strategy, sub-agent: performance-optimizer |
| "refactor", "extract", "rename", "restructure" |
Refactor |
Behavior preservation, blast radius, dangling references |
| "API", "contract", "endpoint", "consumer", "event" |
Contract/Integration |
Backward compatibility, consumer impact, versioning strategy |
| "infra", "CI", "pipeline", "deploy" |
Infrastructure/DevOps |
Rollback plan, environment parity, secrets handling |
| None of the above |
Feature |
Standard checklist, acceptance criteria mapping, YAGNI |
If multiple signals match, list all types and apply ALL their focus areas.
Plan type drives:
- Which sub-agent type to use (see "Subagent Type Selection" above)
- Which sections of the Adversarial Review Mindset to emphasize
- Whether Behavioral Delta Matrix is mandatory (bugfix only)
Step 1: Read Plan Files
Read the plan directory:
plan.md - Overview, phases list, frontmatter
goal.md - Goal Contract (when present): Original Request, Purpose, Success Criteria (required vs optional), Constraints
phase-*.md - All phase files
- Extract: requirements, implementation steps, file listings, risks
If {plan-dir}/goal.md is missing, resolve plans/goals/{YYMMDD-HHmm}-{slug}/goal.md; if no Goal Contract exists at all, record No active goal — plan reviewed against plan.md requirements only.
Step 2: Evaluate Against Checklist
Validity (Required - all must pass)
| # |
Check |
Presence |
Quality Depth |
| 1 |
Has executive summary — clear 1-2 sentence description |
Does a summary section exist? |
Is it accurate? Does it scope the work or conceal complexity? |
| 2 |
Has defined requirements section — explicit requirements listed |
Does a requirements section exist? |
Are requirements concrete user needs or vague technical goals? |
| 3 |
Has implementation steps — actionable tasks |
Are implementation steps present? |
Are steps specific (file names, method names) or vague actions? |
| 4 |
Has files to create/modify listing — file inventory present |
Is a file listing present? |
Are file paths real (verified via glob/grep)? Do they follow project conventions? |
Correctness (Required - all must pass)
Decision tree — apply to EACH phase:
Phase too vague? (no file paths, planning verbs, unclear actions)
→ YES → DETAIL IT: add specific file paths, exact method names, concrete actions
→ NO ↓
Phase too big? (>5 files OR >3h effort OR single step is a mini-project)
→ YES → BREAK IT: split into smaller sibling phases until each meets limits
→ NO → PASS this phase
5-Point Criteria (all must pass per phase):
| # |
Criterion |
PASS example |
FAIL example |
| 1 |
Steps name specific files |
"Modify {source-root}/auth/login" |
"Implement authentication" |
| 2 |
No planning verbs |
"Add validateToken() method" |
"Determine the best auth approach" |
| 3 |
Each step ≤30 min effort |
"Add error handler to endpoint" |
"Build the entire auth module" |
| 4 |
Phase ≤5 files AND ≤3h |
3 files, 2h |
12 files, 8h |
| 5 |
No unresolved decisions |
All approaches decided |
"TBD: which library to use" |
Planning verbs that trigger FAIL: "research", "determine", "figure out", "decide", "evaluate", "explore", "investigate" — these belong in investigation, not implementation plans.
Action on failure (after Findings Validation Gate passes):
Do not apply these refinements until $why-review --validate-findings returns CLEAN for the current plan-review report.
- Too vague → Refine in-place: expand steps with file paths, method names, concrete actions
- Too big (≤9 files) → Split phase into sibling phases (Phase 2A, 2B, 2C)
- Too big (10+ files) → Create sub-plan:
{plan-dir}/sub-plans/phase-{XX}-{name}/plan.md
Worked example:
FAILS: "Phase 2: Data Layer — Set up database models, Create repositories, Implement data access patterns. Effort: 4h, Files: ~8"
PASSES after split: "Phase 2A: Data Schema (1h, 3 files) — Create {source-root}/models/user-entity, Create {source-root}/models/session-entity, Create {migration-root}/create-users-sessions" + "Phase 2B: Repository Layer (1.5h, 3 files) — Create {source-root}/repositories/user-repository, Create {source-root}/repositories/session-repository, Register in {composition-root}"
| Claim type |
Required proof |
| File path |
File exists (glob/read) |
| Class/method name |
Symbol grep → file:line |
| Behavior ("X calls Y") |
Code evidence file:line |
| Base class / interface |
Inheritance verified (grep/graph) |
FAIL triggers: unread file paths, ungrepped method names, "should be"/"probably"/"typically" language about existing code, behaviors assumed from similar projects instead of THIS codebase. Greenfield-only plans (no existing code refs) → PASS.
Best Practices (Required - all must pass)
| # |
Check |
Presence |
Quality Depth |
| 1 |
YAGNI — No unnecessary features or over-engineering |
Is every planned component traceable to a stated requirement? |
Flag anything described as "might be useful" or added for future flexibility without a current requirement. |
| 2 |
KISS — Simplest viable solution chosen |
Is there a stated approach for each major step? |
Could any planned abstraction be simpler with the same effect? Are there unnecessary layers, indirections, or framework choices? |
| 3 |
DRY — No planned duplication of logic |
Are there similar patterns described more than once? |
Does the plan introduce new patterns when existing ones work? Are there repeated steps that suggest duplication at implementation time? |
| 4 |
Architecture — Follows project patterns from .claude/docs/ |
Does the plan reference or align with .claude/docs/ patterns? |
Does it follow established patterns or deviate? Any deviations need explicit justification with rationale. |
Completeness (Recommended - ≥50% should pass)
| # |
Check |
Presence |
Quality Depth |
| 1 |
Risk assessment present with mitigations — risks identified with responses |
Is there a risk section with at least one item? |
Are mitigations specific actions (who, when, triggered by what) or vague intentions ("monitor closely")? |
| 2 |
Testing strategy defined — test approach outlined |
Is there a testing section or test references per phase? |
Does it cover unit, integration, and edge case paths, or just "write tests"? Is the approach traceable to acceptance criteria? |
| 3 |
Success criteria per phase — measurable outcomes defined |
Does each phase have stated success criteria? |
Are criteria measurable? Would failing them trigger a rollback, or are they aspirational targets? |
| 4 |
Security considerations addressed — security concerns noted |
Is there a security section or inline security notes? |
Are security concerns specific to this feature's attack surface, or generic boilerplate (e.g., "use HTTPS", "validate inputs")? |
| 5 |
Graph dependency check — importers of modified files are checked |
If .code-graph/graph.db exists: are importers_of queries run for each modified file? |
Are ALL importers checked, not just direct callers? Is the graph.db prerequisite explicitly stated? Are missed dependents flagged? |
Step 3: Score and Classify
| Status |
Criteria |
Action |
| PASS |
All Required pass, ≥50% Recommended |
Proceed to implementation |
| WARN |
All Required pass, <50% Recommended |
Proceed with caution, note gaps |
| FAIL |
Any Required check fails |
STOP - must fix before proceeding |
Step 4: Output Result
## Plan Review Result
**Status:** PASS | WARN | FAIL
**Reviewed:** {plan-path}
**Date:** {current-date}
### Summary
{1-2 sentence summary of plan quality}
### Checks Passed ({X}/{Y})
#### Required ({X}/{Y})
- ✅ Check 1
- ✅ Check 2
- ❌ Check 3 (if failed)
#### Recommended ({X}/{Y})
- ✅ Check 1
- ⚠️ Check 2 (missing)
### Issues Found
- ❌ FAIL: {critical issue requiring fix}
- ⚠️ WARN: {minor issue, can proceed}
### Recommendations
1. {specific fix 1}
2. {specific fix 2}
### Verdict
{PROCEED | REVISE_FIRST | BLOCKED}
Graph-Trace for Plan Coverage
When graph DB is available, verify the plan covers all affected files:
- For each file in the plan's "files to modify" list, run
python .claude/scripts/code_graph trace <file> --direction downstream --json
- Flag any downstream file NOT listed in the plan as "potentially missed"
- This catches cross-service impact (MESSAGE_BUS consumers, event handlers) that the plan author may have overlooked
Recursive Fix-and-Review Protocol (CRITICAL)
Protocol: SYNC:double-round-trip-review + SYNC:fresh-context-review + SYNC:review-protocol-injection (all inlined above in this file).
When the review results in FAIL, WARN, or any non-zero findings, plan-review MUST run the Findings Validation Gate before editing any plan file. Only findings validated by $why-review --validate-findings may be fixed. After fixing validated actionable findings, rerun the full plan-review protocol from the first review step over the current plan. Do not spawn a fresh sub-agent just to re-review known findings before fixing them. If the restarted full review uses a sub-agent, it uses the canonical Agent template from SYNC:review-protocol-injection below and re-reads ALL plan files from scratch with ZERO memory of prior fixes.
Findings Validation Gate (MANDATORY before fixing plan findings)
Trigger this gate whenever the plan-review output contains any finding: FAIL, WARN, recommendation requiring a plan edit, missing evidence, unresolved risk, or implementation-blocking ambiguity. Skip this gate only when the completed review pass has zero findings — or, from round 3, when its only validated findings are LOW (record them as deferred and PASS).
- Finalize the plan-review report with every finding and enough evidence for another reviewer to validate it.
- Call
$why-review --validate-findings against that report in the main review flow before editing plan files.
- If why-review returns CLEAN, fix only the validated actionable findings at the smallest responsible plan location.
- If why-review challenges, rejects, or narrows findings, reconcile the plan-review report first, then rerun
$why-review --validate-findings before any fix.
- If a finding is valid but needs product/owner judgment, stop and ask the user instead of editing around the uncertainty.
NEVER edit plan.md or phase-*.md to fix review findings before this gate passes. This gate validates findings; the fresh full plan-review happens only after the validated fix cycle.
When constructing the Agent call prompt for Round N (N≥2):
- Copy the Agent call shape from the
SYNC:review-protocol-injection template verbatim
- Use
agent_type: "general-purpose" (this is a plan review, not a code review)
- Embed the full verbatim body of these SYNC blocks (inlined above in this skill file):
SYNC:evidence-based-reasoning, SYNC:rationalization-prevention, SYNC:graph-assisted-investigation, SYNC:understand-code-first (omit code-specific protocols like SYNC:bug-detection, SYNC:test-spec-verification which are not applicable to plan files)
- Set the Task as `"Review plan files under {plan-dir}. Validate structural completeness, code-proof anti-hallucination (every file:line claim abou
…(truncated)
1---2name: plan-review3description: "[Planning] Use when you need to auto-review a plan for validity, correctness, and best practices — recursive: review, validate findings with why-review, fix validated findings, full re-review until no findings."4---56> Codex compatibility note:7>8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.10> - User-question prompts mean to ask the user directly in Codex.11> - Ignore Claude-specific mode-switch instructions when they appear.12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.13> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.1718<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->1920## Codex Project-Reference Loading (No Hooks)2122Codex uses static project-reference loading instead of runtime-injected project docs.23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.2425**Always read:**2627- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)3031**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.3233**Situation-based docs:**3435- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`41- Integration test implementation/review: `integration-test-reference.md`42- E2E test implementation/review: `e2e-test-reference.md`43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files4445Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.4647<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->4849<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->5051> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.52> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.53> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.54> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.5556<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->5758## Quick Summary5960**Goal:** Block any plan from reaching implementation unless it is hallucination-free (every existing-code claim proven at `file:line`) and implementation-ready (every step concrete, small enough to code from immediately) — by auto-reviewing implementation plans for validity, correctness, and best practices. **Recursive:** when any findings exist, validate findings with `$why-review --validate-findings`, fix only validated findings in plan files, and rerun the full plan review until the round's exit bar is clear — **zero findings in rounds 1-2, zero CRITICAL/HIGH/MEDIUM from round 3 (a LOW-only round ENDS the loop, deferred not fixed)**.6162Every phase review treats **Mode, Wave, write set, and SEQ dependency** as one indivisible metadata contract; a mismatch in any field blocks approval.6364**Summary:** AI self-review (automatic, NOT a user interview like `$plan-validate`) that gates a plan before implementation.6566- **Purpose:** review as a SKEPTIC, not validator — every existing-code claim needs `file:line` proof (Anti-Hallucination Gate); every phase must clear the "Detailed & Small Enough" granularity gate (≤5 files, ≤3h, no planning verbs) — too vague → detail it, too big → break it.67- **Main steps (run in order):** Phase 0 detect plan type → Step 1 read `plan.md` + `goal.md` + all `phase-*.md`, extract requirements/steps/files/risks → Step 2 evaluate the 4 checklist groups: **Validity** (summary, requirements, steps, files) · **Correctness** (Granularity Gate + Anti-Hallucination/Code-Proof Gate + spec/TC coverage + Goal-Contract mapping) · **Best Practices** (YAGNI/KISS/DRY/architecture) · **Completeness** (risks, testing, success criteria, security, graph-dependency) → run the 11 Adversarial techniques + Anti-Bias Gate + 8 Plan Dimensions → graph-trace each modified file (when graph.db exists) → Step 3 score PASS/WARN/FAIL → Step 4 output result → Step 5 recursive validate-fix-re-review loop.68- **Detect plan type FIRST (Phase 0)** so the right focus applies — bugfix MANDATES the Behavioral Delta Matrix; security/performance/refactor/contract/infra/data-schema each add targeted checks.69- **Findings are never fixed blindly:** run the `$why-review --validate-findings` gate BEFORE editing any `plan.md`/`phase-*.md`, fix only validated findings at the smallest responsible location, then restart the FULL review with a fresh, zero-memory sub-agent — loop until a clean pass at the round's bar.70- **Severity floor — from round 3, LOW stops blocking.** Rounds 1-2 require zero findings at any severity. **From round 3 the bar is zero validated CRITICAL/HIGH/MEDIUM — a review round whose validated findings are ALL LOW ENDS the loop.** Do NOT restart the full review for LOW findings alone: record them under `## Deferred LOW Findings (severity floor, round ≥3)` in the report and PASS. NEVER re-tier a real CRITICAL/HIGH/MEDIUM down to LOW to reach the exit, and NEVER apply the floor to a hallucinated-code claim or a missing-evidence finding — those are HIGH by definition, not deferrable LOW. Severity tiers per `SYNC:severity-rubric`.71- **Round cap 3 — a ceiling, NEVER a target;** a clean pass ends the loop immediately at ANY round (round 1 included). Escalate by asking the user directly when the same blocker survives 2 consecutive full re-reviews with no progress, when round 3 completes with findings still open, or when a finding needs product/owner judgment — cap exhaustion escalates, it NEVER becomes a PASS.7273**Workflow:**74751. **Resolve Plan** — Use $ARGUMENTS path or active plan from `## Plan Context`762. **Read Files** — plan.md + all phase-\*.md files, extract requirements/steps/files/risks773. **Evaluate Checklist** — Validity (summary, requirements, steps, files), Correctness (specific, paths, no conflicts), Best Practices (YAGNI/KISS/DRY, architecture), Completeness (risks, testing, success, security)784. **Score & Classify** — PASS (all Required + ≥50% Recommended), WARN (all Required + <50% Recommended), FAIL (any Required fails)795. **Output Result** — Status, checks passed, issues, recommendations, verdict806. **If any findings remain** — Run `$why-review --validate-findings` on the plan-review report first; fix only validated actionable issues in plan files, then re-review (loop back to step 2 until the round's bar is clear — zero findings in rounds 1-2, zero CRITICAL/HIGH/MEDIUM from round 3 — unless the repeated-blocker rule or the 3-round cap applies)8182**Core Principle — Detailed & Small Enough:**8384- **Too vague?** → Detail it: add specific file paths, concrete actions, exact method names85- **Too big to detail?** → Break it: split into smaller phases/sub-plans until each is detailed86- A plan that can't be immediately coded from is NOT ready. Every step must be implementation-ready.8788**Key Rules:**8990- **No hallucination**: Every plan claim about existing source code must have `file:line` proof — unverified paths, class names, or behaviors = FAIL91- **PASS**: Proceed to implementation92- **WARN**: Proceed with caution, note gaps93- **FAIL (any findings)**: Validate findings with `$why-review --validate-findings`, fix only validated plan issues, then **re-run the FULL review from the start**. Repeat this self-loop — no forced minimum, capped at 3 rounds MAX — until a complete pass finds ZERO findings.94- **Bounded loop — two escalation triggers, neither a completion criterion**: (a) **no-progress safety** — the SAME blocker surviving 2 consecutive full re-reviews with no progress; (b) **round cap** — round 3 completing with findings still open. Whichever trips first → STOP and escalate to user by asking the user directly, never a silent "good enough" PASS. A clean pass ends the loop immediately, even on round 1 — the cap is a ceiling, not a quota.95- **Constructive**: Focus on implementation-blocking issues, not pedantic details9697**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**9899## First Principle — Easy to Change100101> **The success metric of every coding decision is _future change cost_.**102> DRY, SRP, abstraction, design patterns, naming, layering, tests — every103> technique exists to serve one goal: **making the next change cheaper**.104105Evaluating code, refactor, test, abstraction, ask: **does this make the next change cheaper or more expensive?**106107- Reject "best practices" raising change cost — premature abstraction, speculative generality, leaky indirection, ceremony without payoff.108- Name the real enemies in findings: **coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early**.109- A simpler design that is easy to change beats a sophisticated one that is not.110111Apply this lens **before** any rule, pattern, or checklist below — a downstream rule that raises change cost LOSES to this principle.112113---114115## Adversarial Review Mindset (NON-NEGOTIABLE)116117**Default stance: SKEPTIC, not validator. Your job is to find what cannot work, not confirm what looks right.**118119> **Confirmation bias trap:** After reading a well-structured plan, AI naturally finds reasons to agree. This section exists to break that loop before it produces a rubber-stamp approval.120121### Adversarial Techniques (apply ALL before concluding)122123> Techniques 1-6 stress **whether the plan can be built** (reality, effort, scope, dependencies). Techniques 7-10 stress **whether the chosen design is the right one** — the decision-quality lens shared with `$why-review`'s rationale review. Apply both groups: a buildable plan built on the wrong decision is still a failed plan.124125**1. Implementation Reality Check**126Per phase: _"a developer starts implementing this right now — what breaks FIRST?"_ Walk the critical path concretely. A vague phase ("implement the service layer") untraceable to specific files/classes FAILS.127128**2. Assumption Stress Test**129List the top 3 implicit assumptions; per assumption: _"what if it is wrong?"_ A valid plan survives 2 of 3 being false. Usual hidden ones: existing code is in a known state · no external API changes · team already has this domain knowledge.130131**3. Effort Reality Check**132Per estimated phase: _"has similar work in THIS codebase shipped in that timeframe, and what slowed it last time?"_ Underestimating by 2x or more makes it an optimistic guess, NOT a valid plan.133134**4. Pre-Mortem**135Assume the plan shipped exactly as written and the feature has been in production a month. Write ONE concrete, plausible failure scenario. Finding none means you have not looked hard enough.136137**5. Scope Creep Detector**138Flag any task NOT directly required to deliver the stated feature. "While we're here, let's also refactor X" is scope creep.139140**6. Dependency Blindspot**141List 2-3 external dependencies (services, APIs, data sources) the plan assumes stable; per one: _"what breaks here if it changes or goes away?"_ A dependency failure addressed nowhere is a risk gap.142143**7. Steel-Man the Rejected Alternative**144Per design decision choosing X over an alternative, argue FOR the rejected one as strongly as possible. Would a 10-year domain senior pick it? If yes, dismissal needs proof stronger than "we picked X" — why: a decision that never names what it rejected was assumed, not made.145146**8. Why NOT?**147Per "chose X because Y", ask what X _sacrifices_. A plan listing only upsides is hiding the trade-off, not avoiding it. Demand the named downside.148149**9. Unseen Alternatives**150Name 1-2 viable approaches the plan never mentions. An alternative absent without exclusion reasoning is weak coverage, NOT a settled decision.151152**10. Pros/Cons Symmetry**153Count stated pros vs cons on the chosen approach. Pros outnumbering cons by more than 2:1 signals confirmation bias — demand the missing downsides before accepting.154155**11. Contrarian Pass**156Before ANY verdict, write ≥2 sentences arguing the OPPOSITE. About to write PASS → argue NEEDS WORK, and vice versa. Then pick the stronger argument on evidence.157158### Forbidden Patterns159160- **"Structure looks good"** → Structure is NOT quality. Can it be implemented?161- **"Phases are well-defined"** → Presence of phases is NOT correctness. What's in them?162- **"Alternatives were considered"** → Were they real alternatives or strawmen set up to fail?163- **"Risk is managed"** → Mitigation of "monitor closely" is NOT a mitigation. What action, by whom, triggered by what?164- **"Looks achievable"** without tracing the critical path → Not a valid assessment.165166### Anti-Bias Gate (MANDATORY before finalizing verdict)167168Complete ALL checks before writing the final verdict (MUST ATTENTION):169170- run Implementation Reality Check on the highest-risk phase171- identify 3 implicit assumptions and stress-test them172- check effort estimates against codebase complexity173- run pre-mortem (one concrete production failure scenario)174- scan for scope creep (tasks not required for stated feature)175- verify dependency blindspots are addressed176- steel-man at least one rejected design alternative (argue FOR it)177- name at least 1 viable alternative the plan does not mention178- check pros/cons symmetry on the plan's primary design decision179180If any check is incomplete → you have NOT completed the adversarial review. Go back.181182> **Why-review relationship:** Techniques 7-10 + these gate checks are the _rationale_ lens applied DURING the review pass (does the plan's design hold up?). The separate `$why-review --validate-findings` gate runs AFTER findings exist (are the findings themselves correct before we fix them?). Both stay — they validate different things and must not be collapsed.183184## Plan Dimension Thinking Framework185186After plan-type detection (Phase 0), evaluate each dimension below using this reasoning pattern:187188> **For each dimension:** (1) Understand its role in the plan's domain, (2) Read the plan's claims about it, (3) Derive the actual concerns from first principles — what could go wrong if this dimension is weak? (4) Apply your knowledge of the plan's tech stack to find stack-specific gaps.189190### Dimension 1: Scope Integrity191192**Think:** Does the plan's scope match the stated goal exactly — not broader, not narrower?193194- What's the minimal set of changes needed to deliver the stated goal?195- What does the plan add that's NOT in the goal? → Scope creep.196- What's in the goal that the plan doesn't address? → Scope gap.197- Stress test: "If we skip phase X, does the feature still work?" → If yes, that phase is out of scope.198199### Dimension 2: Data Flow Correctness200201**Think:** Can I trace how data moves through every phase of this plan?202203- Where does data originate? Where does it end up?204- What transforms it in between? Are those transforms described in the plan?205- What happens to data at system boundaries (API, message bus, storage, UI)? Does the plan address each boundary?206- What data states are invalid? Does the plan guard against them?207208### Dimension 3: Dependency Chain Completeness209210**Think:** Does the plan account for everything its changes affect?211212- Every file/module the plan touches: what imports it? what calls it? what depends on its contract?213- If the plan changes an interface/contract, are ALL consumers listed?214- External dependencies (third-party services, shared infra): are they stable? If they break, what's the fallback?215- Run graph trace if graph.db exists — compare plan's file list against downstream impact.216217### Dimension 4: Failure Mode Coverage218219**Think:** What does the plan say about when things go wrong?220221- For each external call, async operation, or state change: what's the error behavior?222- Does the plan include a rollback strategy for irreversible operations?223- What's the partial failure state? (half-migrated, half-deployed, race condition) Is it addressable?224- Is there a monitoring/alerting plan for the new code paths?225226### Dimension 5: Test Observability227228**Think:** How will a developer know if this plan's implementation is correct?229230- Can the stated acceptance criteria be mechanically verified by a test?231- Are there behaviors that are only observable via logs/traces (not unit tests)?232- Which phase introduces the risk? Does a test exist in that phase?233- "Tests pass" is NOT a success criterion — name the specific behaviors being tested.234- **Spec-Loop scheduling (test-quality gate).** The plan MUST schedule the spec-loop, not just "add tests": (1) every `[HARD]` §4 rule / §5 invariant gets a universally-quantified **property test spec** plus a boundary counter-case — not example tests only; (2) changed core logic is gated by a **MUTATION-SCORE** quality bar (a surviving mutant = a missing invariant ⇒ a killing test owed), NOT a line-coverage % target; (3) a **dual-feedback + re-review step** exists so each behavior-changing finding enriches BOTH the spec AND the tests and the package is re-reviewed to zero new gaps. **FAIL** a plan that targets a line-coverage % instead of a mutation-score bar, or that omits property/invariant test specs for its `[HARD]`/§5 rules.235236### Dimension 6: Knowledge Prerequisites237238**Think:** Does implementing this plan require knowledge the plan doesn't surface?239240- Domain knowledge: Are business rules spelled out, or does the implementer need to already know them?241- System knowledge: Are integration points documented, or does the implementer need tribal knowledge?242- Tooling knowledge: Does the plan assume setup steps that aren't listed?243- If any prerequisite is unstated → the plan is not implementation-ready.244245### Dimension 7: Estimation Drift246247**Think:** Does the frontmatter estimation still match the finalized plan, or did scope-locking change the cost?248249- Pre-completion estimates anchor on rough scope guesses; finalized phases reveal true cost. Re-derive `bottom_up_hours = Σ phase_hours` from each phase file's locked tasks/TCs and compare to current frontmatter `man_days_traditional` / `story_points`.250- Recompute `likely_days`, `risk_margin_pct`, `min-max range` per `SYNC:estimation-framework`. Did unknowns resolve (margin should drop) or new risks surface (margin should rise)?251- If `|delta| > 20%` → frontmatter MUST be updated with `reestimate_delta_pct: <signed>` + 1-line `reestimate_reason`. Missing update = FAIL.252- If `|delta| > 50%` → flag `SHOULD-RESCOPE` in review verdict; the plan must surface the rescope decision to the user before implementation begins.253- Watch for hidden inflation: phases added during planning, TCs not counted in original estimate, integration work discovered late.254255### Dimension 8: Domain Entity Design (CONDITIONAL — fires when the plan touches an entity, VO, or aggregate)256257**Think:** Does the plan actually decide the domain model, or does it defer the hard parts to implementation?258259Apply `SYNC:domain-entity-change-gate` (inlined below) — the SAME protocol `$plan` authored under and `$changes-review` will review under, whose A–P checklist `$domain-entities-review` owns. State `No domain-entity surface — Dimension 8 N/A` when it does not fire.260261- An **unanswered, hand-waved, or deferred-to-implementation** decision point is a FINDING with `file:line` into the plan. The word "entity" appearing in a task is NEVER an answer.262- MUST ATTENTION verify the plan states **paradigm** and **subdomain fit** before any entity task — a plan proposing a rich domain model for a CRUD subdomain is a FINDING (ceremony with no invariant to protect), and so is a plan proposing setter/encapsulation tasks against an immutable or event-sourced model.263- Check each triggered row names its **owning file**, not just an intent: classification · invariant ownership + failure signalling · aggregate boundary + concurrency · construction vs reconstitution · events · property-TC test obligation.264- Highest-yield misses: an aggregate boundary chosen by UI screen or DB table rather than by true invariant · cross-aggregate references planned as object navigation · no concurrency token on a contended root · a set-based invariant ("unique email") with no enforcing mechanism · invariants planned into a validator/handler instead of the entity · events planned with no dispatch timing.265- Steel-man the plan's boundary choice before flagging it — a deliberately larger aggregate protecting a real always-consistent invariant is CORRECT; demand the invariant, not a smaller boundary.266267**Use these dimensions to generate targeted, evidence-backed questions — not generic "add more detail" suggestions.**268269---270271## Your mission272273Self-review the implementation plan — valid, correct, best-practice — and surface everything needing a fix BEFORE implementation proceeds.274275**Key distinction:** AI self-review (automatic), NOT a user interview like `$plan-validate`.276277## Plan Resolution2782791. `$ARGUMENTS` provided → use that path2802. Else `## Plan Context` section → use the active plan path2813. No plan found → error: "No plan to review. Run $plan first."282283## Workflow284285### Phase 0: Detect Plan Type286287Before ANY checklist, read `plan.md` and classify the plan — why: the type decides the sub-agent, the emphasis, and whether the Behavioral Delta Matrix is mandatory:288289| Signal in plan | Type | Additional review focus |290| ------------------------------------------------------------ | ------------------------- | ------------------------------------------------------------------------------------------- |291| "fix", "bug", "regression", "defect" in title/description | **Bugfix** | Behavioral Delta Matrix (MANDATORY), preservation inventory, regression tests |292| "migrate", "schema", "database", "index" | **Data/Schema** | Rollback path, zero-downtime strategy, data preservation, migration idempotency |293| "auth", "permission", "security", "encrypt", "token", "RBAC" | **Security** | Threat modeling, attack surface, trust boundary changes, sub-agent: `security-auditor` |294| "performance", "latency", "cache", "N+1", "throughput" | **Performance** | Baseline metrics, regression risk, measurement strategy, sub-agent: `performance-optimizer` |295| "refactor", "extract", "rename", "restructure" | **Refactor** | Behavior preservation, blast radius, dangling references |296| "API", "contract", "endpoint", "consumer", "event" | **Contract/Integration** | Backward compatibility, consumer impact, versioning strategy |297| "infra", "CI", "pipeline", "deploy" | **Infrastructure/DevOps** | Rollback plan, environment parity, secrets handling |298| None of the above | **Feature** | Standard checklist, acceptance criteria mapping, YAGNI |299300**If multiple signals match**, list all types and apply ALL their focus areas.301302**Plan type drives:**303304- Which sub-agent type to use (see "Subagent Type Selection" above)305- Which sections of the Adversarial Review Mindset to emphasize306- Whether Behavioral Delta Matrix is mandatory (bugfix only)307308---309310### Step 1: Read Plan Files311312Read the plan directory:313314- `plan.md` - Overview, phases list, frontmatter315- `goal.md` - Goal Contract (when present): Original Request, Purpose, Success Criteria (required vs optional), Constraints316- `phase-*.md` - All phase files317- Extract: requirements, implementation steps, file listings, risks318319If `{plan-dir}/goal.md` is missing, resolve `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md`; if no Goal Contract exists at all, record `No active goal — plan reviewed against plan.md requirements only.`320321### Step 2: Evaluate Against Checklist322323#### Validity (Required - all must pass)324325| # | Check | Presence | Quality Depth |326| --- | ------------------------------------------------------------------- | ---------------------------------- | --------------------------------------------------------------------------------- |327| 1 | **Has executive summary** — clear 1-2 sentence description | Does a summary section exist? | Is it accurate? Does it scope the work or conceal complexity? |328| 2 | **Has defined requirements section** — explicit requirements listed | Does a requirements section exist? | Are requirements concrete user needs or vague technical goals? |329| 3 | **Has implementation steps** — actionable tasks | Are implementation steps present? | Are steps specific (file names, method names) or vague actions? |330| 4 | **Has files to create/modify listing** — file inventory present | Is a file listing present? | Are file paths real (verified via glob/grep)? Do they follow project conventions? |331332#### Correctness (Required - all must pass)333334- [ ] **Granularity Gate — "Detailed & Small Enough"** — FAIL if ANY phase fails ANY criterion below. A plan you can't immediately code from is NOT ready.335336**Decision tree — apply to EACH phase:**337338```339Phase too vague? (no file paths, planning verbs, unclear actions)340 → YES → DETAIL IT: add specific file paths, exact method names, concrete actions341 → NO ↓342Phase too big? (>5 files OR >3h effort OR single step is a mini-project)343 → YES → BREAK IT: split into smaller sibling phases until each meets limits344 → NO → PASS this phase345```346347**5-Point Criteria (all must pass per phase):**348349| # | Criterion | PASS example | FAIL example |350| --- | ------------------------- | ----------------------------------- | ---------------------------------- |351| 1 | Steps name specific files | "Modify `{source-root}/auth/login`" | "Implement authentication" |352| 2 | No planning verbs | "Add `validateToken()` method" | "Determine the best auth approach" |353| 3 | Each step ≤30 min effort | "Add error handler to endpoint" | "Build the entire auth module" |354| 4 | Phase ≤5 files AND ≤3h | 3 files, 2h | 12 files, 8h |355| 5 | No unresolved decisions | All approaches decided | "TBD: which library to use" |356357**Planning verbs that trigger FAIL:** "research", "determine", "figure out", "decide", "evaluate", "explore", "investigate" — these belong in investigation, not implementation plans.358359**Action on failure (after Findings Validation Gate passes):**360361Do not apply these refinements until `$why-review --validate-findings` returns CLEAN for the current plan-review report.362363- **Too vague** → Refine in-place: expand steps with file paths, method names, concrete actions364- **Too big (≤9 files)** → Split phase into sibling phases (Phase 2A, 2B, 2C)365- **Too big (10+ files)** → Create sub-plan: `{plan-dir}/sub-plans/phase-{XX}-{name}/plan.md`366367**Worked example:**368FAILS: `"Phase 2: Data Layer — Set up database models, Create repositories, Implement data access patterns. Effort: 4h, Files: ~8"`369PASSES after split: `"Phase 2A: Data Schema (1h, 3 files) — Create {source-root}/models/user-entity, Create {source-root}/models/session-entity, Create {migration-root}/create-users-sessions"` + `"Phase 2B: Repository Layer (1.5h, 3 files) — Create {source-root}/repositories/user-repository, Create {source-root}/repositories/session-repository, Register in {composition-root}"`370371- [ ] File paths follow project patterns372- [ ] No conflicting or duplicate steps373- [ ] Dependencies between steps are clear374- [ ] **Anti-Hallucination & Code-Proof Gate** — FAIL if ANY plan claim about existing source code lacks `file:line` proof.375376| Claim type | Required proof |377| ---------------------- | --------------------------------- |378| File path | File exists (glob/read) |379| Class/method name | Symbol grep → `file:line` |380| Behavior ("X calls Y") | Code evidence `file:line` |381| Base class / interface | Inheritance verified (grep/graph) |382383**FAIL triggers:** unread file paths, ungrepped method names, "should be"/"probably"/"typically" language about existing code, behaviors assumed from similar projects instead of THIS codebase. Greenfield-only plans (no existing code refs) → PASS.384385- [ ] **New Tech/Lib Gate:** If plan introduces new packages/libraries/frameworks not in the project, verify alternatives were evaluated (top 3 compared) and user confirmed the choice. FAIL if new tech is added without evaluation.386- [ ] **Test spec coverage** — Every phase has `## Test Specifications` section with TC mappings. "TBD" is valid for TDD-first mode.387- [ ] **TC-requirement mapping** — Every functional requirement maps to ≥1 TC (or explicit "TBD" with rationale)388- [ ] **Behavior preservation** — Behavior-changing phases name expected behavior, unchanged behavior to preserve, and TC/test proof.389- [ ] **Docs/spec/test sync** — Relevant phases include canonical spec/doc/test updates or explicit N/A evidence.390- [ ] **Artifact freshness** — AI-extracted specs/TCs are marked reference-only until accepted; generated mirror sync is included for shared workflow/skill/tooling changes.391- [ ] **Goal Contract mapping** — When an active `goal.md` exists: every saved required success criterion is covered by ≥1 phase, and each phase's success criteria trace to saved criteria (or are marked supporting work with reason). FAIL if a saved required criterion has no covering phase, or the plan delivers work the Goal Contract never asked for without recorded justification. Skip with `No active goal` evidence when no Goal Contract exists.392393#### Best Practices (Required - all must pass)394395| # | Check | Presence | Quality Depth |396| --- | ---------------------------------------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |397| 1 | **YAGNI** — No unnecessary features or over-engineering | Is every planned component traceable to a stated requirement? | Flag anything described as "might be useful" or added for future flexibility without a current requirement. |398| 2 | **KISS** — Simplest viable solution chosen | Is there a stated approach for each major step? | Could any planned abstraction be simpler with the same effect? Are there unnecessary layers, indirections, or framework choices? |399| 3 | **DRY** — No planned duplication of logic | Are there similar patterns described more than once? | Does the plan introduce new patterns when existing ones work? Are there repeated steps that suggest duplication at implementation time? |400| 4 | **Architecture** — Follows project patterns from `.claude/docs/` | Does the plan reference or align with `.claude/docs/` patterns? | Does it follow established patterns or deviate? Any deviations need explicit justification with rationale. |401402#### Completeness (Recommended - ≥50% should pass)403404| # | Check | Presence | Quality Depth |405| --- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |406| 1 | **Risk assessment present with mitigations** — risks identified with responses | Is there a risk section with at least one item? | Are mitigations specific actions (who, when, triggered by what) or vague intentions ("monitor closely")? |407| 2 | **Testing strategy defined** — test approach outlined | Is there a testing section or test references per phase? | Does it cover unit, integration, and edge case paths, or just "write tests"? Is the approach traceable to acceptance criteria? |408| 3 | **Success criteria per phase** — measurable outcomes defined | Does each phase have stated success criteria? | Are criteria measurable? Would failing them trigger a rollback, or are they aspirational targets? |409| 4 | **Security considerations addressed** — security concerns noted | Is there a security section or inline security notes? | Are security concerns specific to this feature's attack surface, or generic boilerplate (e.g., "use HTTPS", "validate inputs")? |410| 5 | **Graph dependency check** — importers of modified files are checked | If `.code-graph/graph.db` exists: are `importers_of` queries run for each modified file? | Are ALL importers checked, not just direct callers? Is the graph.db prerequisite explicitly stated? Are missed dependents flagged? |411412### Step 3: Score and Classify413414| Status | Criteria | Action |415| -------- | ----------------------------------- | --------------------------------- |416| **PASS** | All Required pass, ≥50% Recommended | Proceed to implementation |417| **WARN** | All Required pass, <50% Recommended | Proceed with caution, note gaps |418| **FAIL** | Any Required check fails | STOP - must fix before proceeding |419420### Step 4: Output Result421422```markdown423## Plan Review Result424425**Status:** PASS | WARN | FAIL426**Reviewed:** {plan-path}427**Date:** {current-date}428429### Summary430431{1-2 sentence summary of plan quality}432433### Checks Passed ({X}/{Y})434435#### Required ({X}/{Y})436437- ✅ Check 1438- ✅ Check 2439- ❌ Check 3 (if failed)440441#### Recommended ({X}/{Y})442443- ✅ Check 1444- ⚠️ Check 2 (missing)445446### Issues Found447448- ❌ FAIL: {critical issue requiring fix}449- ⚠️ WARN: {minor issue, can proceed}450451### Recommendations4524531. {specific fix 1}4542. {specific fix 2}455456### Verdict457458{PROCEED | REVISE_FIRST | BLOCKED}459```460461### Graph-Trace for Plan Coverage462463When graph DB is available, verify the plan covers all affected files:464465- For each file in the plan's "files to modify" list, run `python .claude/scripts/code_graph trace <file> --direction downstream --json`466- Flag any downstream file NOT listed in the plan as "potentially missed"467- This catches cross-service impact (MESSAGE_BUS consumers, event handlers) that the plan author may have overlooked468469## Recursive Fix-and-Review Protocol (CRITICAL)470471> **Protocol:** `SYNC:double-round-trip-review` + `SYNC:fresh-context-review` + `SYNC:review-protocol-injection` (all inlined above in this file).472473When the review results in **FAIL, WARN, or any non-zero findings**, plan-review MUST run the Findings Validation Gate before editing any plan file. Only findings validated by `$why-review --validate-findings` may be fixed. After fixing validated actionable findings, rerun the full plan-review protocol from the first review step over the current plan. Do not spawn a fresh sub-agent just to re-review known findings before fixing them. If the restarted full review uses a sub-agent, it uses the canonical Agent template from `SYNC:review-protocol-injection` below and re-reads ALL plan files from scratch with ZERO memory of prior fixes.474475## Findings Validation Gate (MANDATORY before fixing plan findings)476477Trigger this gate whenever the plan-review output contains **any finding**: FAIL, WARN, recommendation requiring a plan edit, missing evidence, unresolved risk, or implementation-blocking ambiguity. Skip this gate only when the completed review pass has zero findings — or, from round 3, when its only validated findings are LOW (record them as deferred and PASS).4784791. Finalize the plan-review report with every finding and enough evidence for another reviewer to validate it.4802. Call `$why-review --validate-findings` against that report in the main review flow before editing plan files.4813. If why-review returns CLEAN, fix only the validated actionable findings at the smallest responsible plan location.4824. If why-review challenges, rejects, or narrows findings, reconcile the plan-review report first, then rerun `$why-review --validate-findings` before any fix.4835. If a finding is valid but needs product/owner judgment, stop and ask the user instead of editing around the uncertainty.484485**NEVER edit `plan.md` or `phase-*.md` to fix review findings before this gate passes.** This gate validates findings; the fresh full plan-review happens only after the validated fix cycle.486487**When constructing the Agent call prompt for Round N (N≥2):**4884891. Copy the Agent call shape from the `SYNC:review-protocol-injection` template verbatim4902. Use `agent_type: "general-purpose"` (this is a plan review, not a code review)4913. Embed the full verbatim body of these SYNC blocks (inlined above in this skill file): `SYNC:evidence-based-reasoning`, `SYNC:rationalization-prevention`, `SYNC:graph-assisted-investigation`, `SYNC:understand-code-first` (omit code-specific protocols like `SYNC:bug-detection`, `SYNC:test-spec-verification` which are not applicable to plan files)4924. Set the Task as `"Review plan files under {plan-dir}. Validate structural completeness, code-proof anti-hallucination (every file:line claim abou493494…(truncated)