[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_progresswhen step starts, setcompletedwhen 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: Deliver a /why-review-validated root cause pinned to file:line at the invariant-owning layer — investigation-only, so /fix corrects the cause, not the symptom — or an honest "hypothesis, not confirmed" naming the evidence gaps.
Summary:
- Purpose — investigation-ONLY: pin the root cause, NEVER patch here; the deliverable is a
/why-review-validated cause handed to/fix, or an honest "hypothesis, not confirmed." - Main steps in order (the digest): (0) Classify bug type — Phase 0, BLOCKING — routes to
debugger/performance-optimizer/security-auditorand decides which evidence matters; (0.5) Adjudicate fault — failing/flaky integration test ONLY: READ the/integration-test-reviewgate protocol (never invoke it) and emit one verdict — TEST-WRONG · TEST-NOT-OPTIMAL · SOURCE-WRONG · ENVIRONMENT · AMBIGUOUS — BEFORE any trace, because tracing the source first silently assumes the test is right; (1) Reproduce with evidence (error/stack/screenshot); (2) Hypothesize 2-3 ranked theories + the evidence that confirms/contradicts each; (3) Trace END-to-START — name Frame 0 (observed final state), walk reader → storage/projection → writer → consumer/job → producer, enumerate ALL feeder paths; (4) Confirm one cause explains ALL symptoms via the hypothesis matrix, no bypass paths; (5) Validate through the/why-reviewgate; (6) Report the confidence-tagged finding + hand off to/fix→/prove-fixruns after the fix. - Core discipline: the bug enters where bad state is WRITTEN, not where it crashes — fix at the LOWEST invariant-owning layer, NEVER the crash site.
- Evidence law: every root-cause claim carries
Confidence: X%+file:lineproof; below 60% report "hypothesis, not confirmed" with named gaps, NEVER a guess. Run a graph trace whengraph.dbexists — it surfaces bus/event consumers grep cannot see. /why-reviewgate is non-negotiable: run it in the SAME session/main agent before declaring confirmed; 2 rounds without passing → STOP and escalate viaAskUserQuestion.
Workflow:
- Classify — Detect bug scenario type (Phase 0) → route to specialized agent
1.5. Adjudicate — Failing integration test? Read
/integration-test-reviewgates (Phase 0.5) → emit fault verdict before tracing - Reproduce — Confirm expected vs actual with evidence
- Hypothesize — Form 2-3 ranked theories
- Trace — Follow code paths; collect
file:lineproof per hypothesis - Confirm — Single root cause explains ALL symptoms
- Validate — Trigger
/why-reviewon findings/root cause before declaring confirmed - Report — Confidence-tagged finding + hand off to
/fix
Key Rules:
- NEVER patch symptoms — trace full call chain, fix at owning layer
- NEVER report root cause without
file:lineevidence - NEVER declare confirmed root cause without passing the
/why-reviewvalidation gate - Output: confirmed root cause OR "hypothesis, not confirmed" + evidence gaps
Phase 0: Classify Bug Scenario (BLOCKING — Do Before ANY Investigation)
Think: What type of failure is this? Classification routes to the right agent and determines which evidence matters most.
| Bug Type | Signals | Specialized Agent |
|---|---|---|
| Frontend UI / rendering | Console errors, visual regression, component state | debugger |
| Backend logic / data | Wrong API response, data corruption, validation failure | debugger |
| Cross-service / message bus | Events not propagating, consumer failures, sync lag | debugger + graph trace MANDATORY |
| Performance / memory | Slow queries, OOM, N+1, unbounded result sets | performance-optimizer |
| Security / auth | Access denied, token issues, permission bypass | security-auditor |
| Failing / flaky integration test | A test that was green now fails, fails intermittently, or fails only in a full-suite run | debugger + READ the /integration-test-review protocol FIRST (see Fault Adjudication below) |
Cross-service bugs: Run graph trace FIRST — grep alone misses implicit bus connections. OOM / memory exhaustion: Check row COUNT before row SIZE. Unbounded query loading thousands of records is more common cause. Triage: (1) missing DB-level filter? (2) excessive row size?
Phase 0.5: Fault Adjudication — failing integration tests (BLOCKING for that bug type)
Think: a failing test has TWO candidate defendants — source and test. Tracing source first ASSUMES the test is right; that assumption produces the "fix" rationalizing a broken invariant into green. Decide whose fault before deciding where to trace.
Step 1 — READ the protocol; NEVER invoke the skill. Read .claude/skills/integration-test-review/SKILL.md §"The 8 Quality Gates" into context. Gates 1 (assertion value), 3 (repeatability), 4 (domain logic), 8 (scenario fidelity) reveal whether the TEST is the faulty party — dead/always-true assertion, non-unique ID, assertion on fields the handler never writes, unreachable setup.
MUST NOT invoke
/integration-test-reviewfrom here — READ its protocol instead. Insideintegration-test-verify-loop, this skill already runs in the SAME round as an explicit/integration-test-reviewcall (integration-test-verify-loop/SKILL.md:110,:495); invoking it again runs a 9-phase audit twice per round — the duplicate-ownership defect that loop removes (:31). The loop OWNS the invocation. — why: standalone, reading also suffices — investigation is this skill's only deliverable.
Step 2 — emit ONE fault verdict before any trace.
| Verdict | Meaning | Where to trace next |
|---|---|---|
| TEST-WRONG | Stale assertion, wrong setup, non-unique data, unreachable scenario | The test's own root cause — fix the assertion/setup at its root, NEVER weaken it |
| TEST-NOT-OPTIMAL | Test is right but fragile — timing, shared state, ordering dependence | The fragility's source (missing ARRANGE barrier, shared infra assertion) |
| SOURCE-WRONG | Production code violates the spec or a clear invariant | Normal end-to-start trace to the invariant-owning layer; KEEP or strengthen the test |
| ENVIRONMENT | Config, DB, credentials, ports, versions | Mark BLOCKED — do not trace application code |
| AMBIGUOUS | Spec silent or contradictory about which side is correct | STOP and ask the user via AskUserQuestion — never self-resolve |
Step 3 — governing law (CLAUDE.md:160, mirrored AGENTS.md:446): "A green-again suite is not the goal; the correct verdict on what was actually wrong is." NEVER weaken an assertion, add a skip, or relax a timeout to force green; NEVER change source to satisfy a broken test — instead fix the faulty party the verdict named, at its owning layer. Spec silent or ambiguous → STOP and ask.
Debug Mindset (NON-NEGOTIABLE)
Skeptical. Sequential. Every claim needs traced proof, confidence >80%.
- NEVER assume first hypothesis correct — verify with actual code traces
- Every root cause claim MUST include
file:lineevidence - Cannot prove root cause → state "hypothesis, not confirmed"
- Challenge assumptions: "Is this really the cause?" → trace actual execution path
- Challenge completeness: "Other contributing factors?" → check related code paths
Confidence & Evidence Gate
MUST ATTENTION declare Confidence: X% + evidence list + file:line proof for EVERY claim.
| Confidence | Meaning | Action |
|---|---|---|
| 95-100% | Full trace verified | Report as confirmed root cause |
| 80-94% | Main path verified, edge cases uncertain | Report with caveats |
| 60-79% | Partial trace | Report as hypothesis |
| <60% | Insufficient evidence | DO NOT report — gather more evidence |
Investigation Dimensions
Reason through each dimension — state what fails if weak, then apply with evidence.
Dim 1: Reproduce
Think: What exact conditions trigger this? Data state? User action? Timing? Environment delta?
- Confirm issue exists with evidence (error message, stack trace, screenshot)
- Identify trigger: user action, data state, timing, env difference
Dim 2: Hypothesize
Think: Given symptoms, what are the most plausible failure modes? What would confirm vs contradict each?
- Form 2-3 theories ranked by likelihood
- Note evidence needed to confirm/contradict each theory before investigating
Dim 3: End-to-Start Trace
Think: What exact final output proves the bug? Which reader produced it? Which storage/projection/write path fed that reader? Where does bad state ENTER the system — not where it CRASHES? Which layer owns this invariant?
- Name Frame 0: observed final state (UI, API response, log, persisted value, assertion, aggregate)
- Identify the final reader/query/renderer/assertion and the state it consumes
- Walk backward: reader -> storage/projection/cache -> writer -> consumer/handler/job -> producer/origin
- Enumerate every feeder path that can write the same final state
- Check error handling paths
- Collect
file:lineevidence per hypothesis - Use graph trace for implicit connections (event handlers, bus consumers)
Dim 4: Confirm
Think: Does this root cause explain ALL symptoms? Are there bypass paths that skip the fix point?
- Match evidence to single root cause
- Verify root cause explains ALL observed symptoms
- Check secondary contributing factors
- Build hypothesis matrix: primary, contributing, ruled out, latent, unknown
- Resolve or disclose competing causes before proposing a fix
- Verify no bypass paths (direct construction, clone/spread without re-validation, mutations outside model layer)
Dim 5: Report
- Output: confirmed root cause + evidence chain
- Include: affected files, Debugger Trace: End -> Start, feeder paths, hypothesis matrix, data flow summary, owning fix layer, fix recommendation, forward convergence proof
- Hand off to
/fixfor implementation
Dependency Tracing (MANDATORY when graph.db exists)
MUST ATTENTION use structural queries — graph reveals ALL callers/consumers grep misses.
# Who calls the buggy function
python .claude/scripts/code_graph query callers_of <function> --json
# Who imports the buggy module
python .claude/scripts/code_graph query importers_of <file> --json
# What tests exist
python .claude/scripts/code_graph query tests_for <function> --json
# Full upstream + downstream context
python .claude/scripts/code_graph trace <suspect-file> --direction both --json
# Callers only (find all trigger points)
python .claude/scripts/code_graph trace <suspect-file> --direction upstream --json
Graph reveals implicit connections (MESSAGE_BUS, event handlers) that propagate issues across services — invisible to grep.
Root Cause Validation (/why-review Gate)
NEVER declare a confirmed root cause straight from investigation. Run /why-review as a quality validation gate on the findings and root cause — in the SAME session, SAME main agent (do NOT spawn a sub-agent) — before handing off to /fix.
Step 1 — Investigate (main agent): Identify root cause + full evidence chain. Write findings to report file.
Step 2 — Validate (/why-review, same main agent): Trigger /why-review on the findings/root cause. The gate must confirm:
- Root cause is correct and reasonable, with
file:lineevidence that conclusively supports it - Evidence has no gaps and explains ALL symptoms
- The proposed fix direction would NOT introduce other bugs or regressions (check downstream consumers, bypass paths, owning layer)
Decision:
/why-reviewPASSES → declare confirmed, proceed to/fix/why-reviewfinds GAPS/risks → collect additional evidence, repeat- 2 validation rounds without passing → STOP, escalate to user via
AskUserQuestion
⚠️ MANDATORY: Post-Fix Verification
After /fix applies changes, /prove-fix MUST be run — builds code proof traces per change with confidence scores. Non-negotiable in all fix workflows.
Anti-Rationalization (Red Flags)
| Evasion | Rebuttal |
|---|---|
| "I see the problem, let me fix it" | Symptoms ≠ root cause. Investigate first. |
| "Quick fix for now, investigate later" | Quick fixes mask bugs. Find root cause. |
| "Just try changing X and see" | One hypothesis at a time. Scientific method, not trial and error. |
| "Already tried 2+ fixes, one more" | 3+ failed fixes = STOP. Question the architecture, not the fix. |
| "The error message is misleading" | Read it again carefully. Error messages are usually right. |
| "It works on my machine" | Reproduce in the failing environment. Your environment hides bugs. |
| "This can't be the cause" | Verify with evidence, not intuition. Unlikely causes are still causes. |
| "It's OOM, must be a large object" | Check row COUNT before row SIZE. Unbounded query > large single row. |
"Skip /why-review, findings look solid" |
Self-confirmed findings rationalize their own gaps. The /why-review gate is non-negotiable. |
| "Graph.db not needed for this bug" | Cross-service bugs are invisible to grep. Run trace first. |
Workflow Recommendation
MUST ATTENTION — NO EXCEPTIONS: Not in workflow? Use AskUserQuestion:
- Activate
workflow-bugfixworkflow (Recommended) — scout → investigate → debug → plan → fix → prove-fix → review → test - Execute
/debug-investigatedirectly — standalone
Next Steps (Standalone only — skip if inside workflow)
MUST ATTENTION use AskUserQuestion after completing. NEVER auto-decide next step:
- "Proceed with full workflow (Recommended)" — detect best workflow to continue from here
- "/fix" — apply fix based on debug findings
- "/plan" — if fix requires planning first
- "Skip, continue manually" — user decides
Standalone Review Gate: Outside workflow? MUST create /changes-review task as LAST task.
[IMPORTANT] Use
TaskCreateto break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files.
docs/project-reference/domain-entities-reference.md— Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
End-to-Start Debugger Trace — For non-trivial bugs, failed verification, regression fixes, behavior-changing code, or unclear code flow, start from the observed final state and walk backward before proposing a fix.
- Frame 0: observed end state — Name the exact user-visible output, failing assertion, log line, persisted value, API response, rendered UI, or aggregate bucket. Record the reader/query/renderer that produced it with
file:lineevidence.- Walk backward one hop at a time — Trace final reader -> projection/cache/storage -> writer -> consumer/handler/job -> producer/caller -> original trigger. At every hop record: input, transformation, output, owner, and evidence.
- Enumerate all feeder paths — Find every upstream producer/caller/event/job that can write into the final path, including retry, async, cache, background, and alternate UI/API paths. Mark each path verified, ruled out, or still unknown.
- Build the hypothesis matrix — For each plausible cause, list evidence for, evidence against, how to reproduce/verify, blast radius, and status (
primary,contributing,ruled out,latent). Do not fix until competing causes are explicitly resolved or bounded.- Choose the owning fix layer — Identify the invariant owner and the lowest shared point that protects all downstream consumers. A fix at the symptom site is rejected unless the symptom site owns the invariant.
- Prove convergence forward — After choosing the fix, walk start -> end again and show how the corrected state reaches the observed final output. Map each root cause to a fix part and each fix part to a test/proof.
BLOCKED until: final state named · backward trace written · all feeder paths enumerated · hypothesis matrix completed · owning fix layer justified · forward convergence proof mapped to tests.
NEVER: Start at the first suspicious code path. Collapse multiple producers into one "flow". Treat duplicate symptoms as duplicate records without proving the read model. Skip ruled-out hypotheses.
Root Cause Debugging — Systematic approach, never guess-and-check.
- Reproduce — Confirm the issue exists with evidence (error message, stack trace, screenshot)
- Isolate — Narrow to specific file/function/line using binary search + graph trace
- Trace — Follow data flow from input to failure point. Read actual code, don't infer.
- Hypothesize — Form theory with confidence %. State what evidence supports/contradicts it
- Verify — Test hypothesis with targeted grep/read. One variable at a time.
- Fix — Address root cause, not symptoms. Verify fix doesn't break callers via graph
connectionsNEVER: Guess without evidence. Fix symptoms instead of cause. Skip reproduction step.
Incremental Result Persistence — MANDATORY for all sub-agents or heavy inline steps processing >3 files.
- Before starting: Create report file
plans/reports/{skill}-{date}-{slug}.md- After each file/section reviewed: Append findings to report immediately — never hold in memory
- Return to main agent: Summary only (per SYNC:subagent-return-contract) with
Full report:path- Main agent: Reads report file only when resolving specific blockers
Why: Context cutoff mid-execution loses ALL in-memory findings. Each disk write survives compaction. Partial results are better than no results.
Report naming:
plans/reports/{skill-name}-{YYMMDD}-{HHmm}-{slug}.md
Sub-Agent Return Contract — When this skill spawns a sub-agent, the sub-agent MUST return ONLY this structure. Main agent reads only this summary — NEVER requests full sub-agent output inline.
## Sub-Agent Result: [skill-name] Status: ✅ PASS | ⚠️ PARTIAL | ❌ FAIL Confidence: [0-100]% ### Findings (Critical/High only — max 10 bullets) - [severity] [file:line] [finding] ### Actions Taken - [file changed] [what changed] ### Blockers (if any) - [blocker description] Full report: plans/reports/[skill-name]-[date]-[slug].mdMain agent reads
Full reportfile ONLY when: (a) resolving a specific blocker, or (b) building a fix plan. Sub-agent writes full report incrementally (per SYNC:incremental-persistence) — not held in memory.Context budget — the return payload is a SUMMARY, not a transcript: ≤10 finding bullets, no raw file contents / full diffs / verbatim logs inline, no re-pasted source. Everything beyond the summary lives in the
Full reporton disk. A sub-agent that would exceed the summary shape MUST write the detail to its report and return only the pointer — the orchestrator's context is the scarce resource the whole map-reduce protects.
Source/test drift check. For coding, fix, debug, investigation, test, or review work: when source behavior changes, inspect affected unit/integration/E2E tests and decide from evidence whether tests should change to match intended behavior or the source change is an unintended bug to fix. Do not write tests for migration code; schema/data migrations are one-time execution paths, not core application logic.
Test-Failure Fault Adjudication — When a test fails (or you are debugging or fixing a failure), the job is to determine who is at fault — the source code or the test code. Getting that verdict right matters more than turning the suite green. Binds every debug / fix / test skill identically.
- Provisional verdict before touching either side. Classify the observed evidence as SOURCE-WRONG, TEST-WRONG, TEST-NOT-OPTIMAL, ENVIRONMENT-BLOCKED, or AMBIGUOUS; then
/debug-investigateand trace end-to-start before editing. A green-again suite is NOT the goal.- Triangulate against the spec AND the source. If a governing Feature Spec covers the behavior (e.g.
docs/specs/**— §3 ACs / §4 BRs / §5 invariants / §8 TCs), it is the tiebreaker for intended behavior — compare BOTH the production source and the failing test against it. With no spec, the documented intent / acceptance criteria / caller contract is the reference. Decide from this evidence whether the SOURCE is wrong or the TEST is wrong.- Classify who is at fault, then fix the wrong side at its root:
- SOURCE-WRONG — production code violates the spec's intended behavior or a clear invariant → fix the source at the owning layer; keep or strengthen the test that caught it.
- TEST-WRONG — the test encodes a stale or incorrect assertion, setup, or expectation that contradicts intended behavior → fix the test at its root. NEVER weaken an assertion, add a skip, or relax a timeout to force green.
- TEST-NOT-OPTIMAL — intended behavior is valid but the test seam, timing, or assertion signal is fragile → improve the test without weakening the invariant.
- ENVIRONMENT-BLOCKED — infrastructure or external state prevents a source/test verdict → preserve diagnostics and stop mutation until the environment is healthy.
- AMBIGUOUS — evidence or intended behavior does not safely select an owner → ask the user or canonical owner before editing.
- NEVER change a test to match broken source, and NEVER change source to satisfy a broken test. (Migration code excluded — schema/data migrations are one-time execution paths, not core application logic.)
- Ask the user when intended behavior is unclear. If no spec covers the behavior, the spec is silent, or the spec is ambiguous about which side is correct, STOP and
AskUserQuestion(or consult the canonical spec owner) before editing either side — never silently pick source or test just to make the suite pass.Reconcile to intended behavior, never to whichever side currently passes — green can encode the very bug.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting. Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing. Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first. Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done. Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect. Assume existing values are intentional — ask WHY before changing OR flagging one as a defect. Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard. Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk. Assert the outcome your system owns, not the intermediate state your infrastructure owns. When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure. Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Nested Task Expansion Contract — For workflow-step invocation, the
[Workflow] ...row is only a parent container; the child skill still creates visible phase tasks.
- Call
TaskListfirst. If a matching active parent workflow row exists, setnested=trueand recordparentTaskId; otherwise run standalone.- Create one task per declared phase before phase work. When nested, prefix subjects
[N.M] $skill-name — phase.- When nested, link the parent with
TaskUpdate(parentTaskId, addBlockedBy: [childIds]).- Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
- Mark exactly one child
in_progressbefore work andcompletedimmediately after evidence is written.- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until:
TaskListdone, child phases created, parent linked when nested, first child markedin_progress.
Project Reference Docs Gate — Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
- Identify scope: file types, domain area, and operation.
- Read
docs/project-config.jsonfirst — the project's machine-readable map. It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it before investigating, planning, or coding — never assume framework defaults (CLAUDE.md+ reference docs are derived from it). If it — or the docs index,lessons.md,CLAUDE.md,AGENTS.md, or any required reference doc — is missing or stale, auto-run/project-initor the narrow route (/project-config,/docs-init,/scan-all,/scan --target=<key>,/claude-md-init) first; if Codex mirrors orAGENTS.mdare stale, ask the user to run/sync-codex(never auto-run it).- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookupdocs-index-reference.md; reviewcode-review-rules.md; backend/CQRS/APIbackend-patterns-reference.md; domain/entitydomain-entities-reference.md; frontend/UIfrontend-patterns-reference.md; styles/designscss-styling-guide.md+design-system/design-system-canonical.md; integration testsintegration-test-reference.md; E2Ee2e-test-reference.md; feature docs/specsfeature-spec-reference.md+spec-system-reference.md+spec-principles.md; behavior/public-contract/spec-test-code syncworkflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guidesspec-system-reference.md+ source Feature Specs underdocs/specs/; architecture/new areaproject-structure-reference.md.- Read every required doc, then before target work state:
Reference docs read: ... | Not applicable: ....Ready when: scope evaluated,
docs/project-config.jsonconsulted, required docs checked/read or setup route completed,lessons.mdconfirmed, citation emitted.
Task Tracking & External Report Persistence — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
- Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
- Mark one task
in_progressbefore work andcompletedimmediately after evidence; never batch transitions.- For plan/review work, create
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.mdbefore first finding.- Append findings after each file/section/decision and synthesize from the report file at the end.
- Final output cites
Full report: plans/reports/{filename}.Blocked until: task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
Sequential Thinking Protocol — Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
Trigger when: complex problem decomposition · adaptive plans needing revision · analysis with course correction · unclear/emerging scope · multi-step solutions · hypothesis-driven debugging · cross-cutting trade-off evaluation.
Format (explicit mode — visible thought trail):
Thought N/M: [aspect]— one aspect per thought, state assumptions/uncertaintyThought N/M [REVISION of Thought K]: ...— when prior reasoning invalidated; state Original / Why revised / ImpactThought N/M [BRANCH A from Thought K]: ...— explore alternative; converge with decision rationaleThought N/M [HYPOTHESIS]: ...then[VERIFICATION]: ...— test before actingThought N/N [FINAL]— only when verified, all critical aspects addressed, confidence >80%Mandatory closers: Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
Stop conditions: confidence <80% on any critical decision → escalate via AskUserQuestion · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
Implicit mode: apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
Deep-dive: see
/sequential-thinkingskill (.claude/skills/sequential-thinking/SKILL.md) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
Understand Code First — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
- Search 3+ similar patterns (
grep/glob) — citefile:lineevidence- Read existing files in target area — understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --jsonwhen.code-graph/graph.dbexists- Map dependencies via
connectionsorcallers_of— know what depends on your target- Write investigation to
.ai/workspace/analysis/for non-trivial tasks (3+ files)- Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
- NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
BLOCKED until:
- [ ]Read target files- [ ]Grep 3+ patterns- [ ]Graph trace (if graph.db exists)- [ ]Assumptions verified with evidence
Evidence-Based Reasoning — Speculation is FORBIDDEN. Every claim needs proof.
- Cite
file:line, grep results, or framework docs for EVERY claim- Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
- Cross-service validation required for architectural changes
- "I don't have enough evidence" is valid and expected output
BLOCKED until:
- [ ]Evidence file path (file:line)- [ ]Grep search performed- [ ]3+ similar patterns found- [ ]Confidence level statedForbidden without proof: "obviously", "I think", "should be", "probably", "this is because" If incomplete → output:
"Insufficient evidence. Verified: [...]. Not verified: [...]."
Cross-Service Check — Microservices/event-driven: MANDATORY before concluding investigation, plan, spec, or feature doc. Missing downstream consumer = silent regression.
Boundary Grep terms Event producers Publish,Dispatch,Send,emit,EventBus,outbox,IntegrationEventEvent consumers Consumer,EventHandler,Subscribe,@EventListener,inboxSagas/orchestration Saga,ProcessManager,Choreography,Workflow,OrchestratorSync service calls HTTP/gRPC calls to/from other services Shared contracts OpenAPI spec, proto, shared DTO — flag breaking changes Data ownership Other service reads/writes same table/collection → Shared-DB anti-pattern Per touchpoint: owner service · message name · consumers · risk (NONE / ADDITIVE / BREAKING).
BLOCKED until: Producers scanned · Consumers scanned · Sagas checked · Contracts reviewed · Breaking-change risk flagged
Estimation Framework — Bottom-up first; SP DERIVED; output min-max range when likely ≥3d. Stack-agnostic. Baseline: 3-5yr dev, 6 productive hrs/day. AI estimate assumes Claude Code + project context.
Method:
- Blast Radius pass (below) — drives code AND test cost
- Decompose phases → hours/phase →
bottom_up_hours = Σ phase_hourslikely_days = ceil(bottom_up_hours / 6) × productivity_factor- Sum Risk Margin (base + add-ons) →
max_days = likely_days × (1 + margin)min_days = likely_days × 0.9- Output as range when
likely_days ≥3; single point allowed<3(still record margin)man_days_ai= same range × AI speedupstory_pointsDERIVED fromlikely_daysvia SP-Days — NEVER driver. Disagreement >50% → trust bottom-upProductivity factor: 0.8 strong scaffolding+codegen+AI hooks · 1.0 mature default · 1.2 weak patterns · 1.5 greenfield
Cost Driver Heuristic (apply BEFORE work-type row):
- UI dominates in CRUD/business apps — 1.5-3x backend (states, validation, responsive, a11y, polish)
- Backend dominates ONLY: multi-aggregate invariants, cross-service contracts, schema migrations, heavy query/perf, new event flows
Reuse-vs-Create axis (PRIMARY lever, per layer):
UI tier Cost Reuse component on existing screen 0.1-0.3d Add control/column to existing screen 0.3-0.8d Compose components into NEW screen 1-2d NEW screen, custom layout/states/validation 2-4d NEW shared/common component (themed, tested) 3-6d+
Backend tier Cost Reuse query/handler from new place 0.1-0.3d Small update existing handler/entity 0.3-0.8d NEW query on existing repo/model 0.5-1d NEW command/handler on existing aggregate (additive) 1-2d NEW aggregate/entity (repo, validation, events) 2-4d NEW cross-service contract OR schema migration 2-4d each Multi-aggregate invariant / heavy domain rule 3-5d Rule: Sum tiers across UI+backend+tests, apply productivity factor. Reuse short-circuits tiers — call out.
**Test-Scope drivers (compute test_count EXPLICITLY
…(truncated)