| name | debug-investigate |
| version | 2.0.0 |
| description | [Fix & Debug] Use when investigating a bug's root cause โ reproduce the symptom, trace it end-to-start through the code, form and test hypotheses, and pinpoint the defect before any fix. |
[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: 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:
- This is investigation-ONLY โ never patch here; classify the bug type FIRST (Phase 0, BLOCKING) to route to the right agent and decide which evidence matters before tracing anything.
- Trace end-to-start: name Frame 0 (observed final state), walk backward reader โ storage/projection โ writer โ consumer/job โ producer, and enumerate ALL feeder paths โ the bug enters where bad state is WRITTEN, not where it crashes.
- Every root-cause claim carries
Confidence: X% + file:line proof; below 60% you report "hypothesis, not confirmed" with named evidence gaps, never a guess.
- The
/why-review gate is non-negotiable: run it in the SAME session/main agent before declaring confirmed; 2 rounds without passing โ STOP and escalate via AskUserQuestion. Run a graph trace when graph.db exists โ it surfaces bus/event consumers grep cannot see.
Workflow:
- Classify โ Detect bug scenario type (Phase 0) โ route to specialized agent
- Reproduce โ Confirm expected vs actual with evidence
- Hypothesize โ Form 2-3 ranked theories
- Trace โ Follow code paths; collect
file:line proof per hypothesis
- Confirm โ Single root cause explains ALL symptoms
- Validate โ Trigger
/why-review on 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:line evidence
- NEVER declare confirmed root cause without passing the
/why-review validation 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 |
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?
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:line evidence
- 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:line evidence 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
/fix for implementation
Dependency Tracing (MANDATORY when graph.db exists)
MUST ATTENTION use structural queries โ graph reveals ALL callers/consumers grep misses.
python .claude/scripts/code_graph query callers_of <function> --json
python .claude/scripts/code_graph query importers_of <file> --json
python .claude/scripts/code_graph query tests_for <function> --json
python .claude/scripts/code_graph trace <suspect-file> --direction both --json
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:line evidence 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-review PASSES โ declare confirmed, proceed to /fix
/why-review finds 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-bugfix workflow (Recommended) โ scout โ investigate โ debug โ plan โ fix โ prove-fix โ review โ test
- Execute
/debug-investigate directly โ 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 /review-changes task as LAST task.
[IMPORTANT] Use TaskCreate to 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:line evidence.
- 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
connections
NEVER: 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].md
Main agent reads Full report file 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 report on 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.
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. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting โ don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
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
TaskList first. If a matching active parent workflow row exists, set nested=true and record parentTaskId; 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_progress before work and completed immediately after evidence is written.
- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until: TaskList done, child phases created, parent linked when nested, first child marked in_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.
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookup docs-index-reference.md; review code-review-rules.md; backend/CQRS/API backend-patterns-reference.md; domain/entity domain-entities-reference.md; frontend/UI frontend-patterns-reference.md; styles/design scss-styling-guide.md + design-system/design-system-canonical.md; integration tests integration-test-reference.md; E2E e2e-test-reference.md; feature docs/specs feature-spec-reference.md + spec-system-reference.md + spec-principles.md; behavior/public-contract/spec-test-code sync workflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guides spec-system-reference.md + source Feature Specs under docs/specs/; architecture/new area project-structure-reference.md.
- Read every required doc. 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 lower-level 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.
- Before target work, state:
Reference docs read: ... | Not applicable: ....
Ready when: scope evaluated, required docs checked/read or setup route completed, lessons.md confirmed, 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_progress before work and completed immediately after evidence; never batch transitions.
- For plan/review work, create
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md before 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/uncertainty
Thought N/M [REVISION of Thought K]: ... โ when prior reasoning invalidated; state Original / Why revised / Impact
Thought N/M [BRANCH A from Thought K]: ... โ explore alternative; converge with decision rationale
Thought N/M [HYPOTHESIS]: ... then [VERIFICATION]: ... โ test before acting
Thought 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-thinking skill (.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) โ cite file:line evidence
- Read existing files in target area โ understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists
- Map dependencies via
connections or callers_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 stated
Forbidden 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, IntegrationEvent |
| Event consumers | Consumer, EventHandler, Subscribe, @EventListener, inbox |
| Sagas/orchestration | Saga, ProcessManager, Choreography, Workflow, Orchestrator |
| Sync 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_hours
likely_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 speedup
story_points DERIVED from likely_days via SP-Days โ NEVER driver. Disagreement >50% โ trust bottom-up
Productivity 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 |
Red Flag Stop Conditions โ STOP and escalate to user via AskUserQuestion when:
- Confidence drops below 60% on any critical decision
- Changes would affect >20 files (blast radius too large)
- Cross-service boundary is being crossed
- Security-sensitive code (auth, crypto, PII handling)
- Breaking change detected (interface, API contract, DB schema)
- Test coverage would decrease after changes
- Approach requires technology/pattern not in the project
NEVER proceed past a red flag without explicit user approval.
Fix-Layer Accountability โ NEVER fix at the crash site. Trace the full flow, fix at the owning layer.
AI default behavior: see error at Place A โ fix Place A. This is WRONG. The crash site is a SYMPTOM, not the cause.
MANDATORY before ANY fix:
- Trace full data flow โ Map the complete path from data origin to crash site across ALL layers (storage โ backend โ API โ frontend โ UI). Identify where the bad state ENTERS, not where it CRASHES.
- Identify the invariant owner โ Which layer's contract guarantees this value is valid? That layer is responsible. Fix at the LOWEST layer that owns the invariant โ not the highest layer that consumes it.
- One fix, maximum protection โ Ask: "If I fix here, does it protect ALL downstream consumers with ONE change?" If fix requires touching 3+ files with defensive checks, you are at the wrong layer โ go lower.
- Verify no bypass paths โ Confirm all data flows through the fix point. Check for: direct construction skipping factories, clone/spread without re-validation, raw data not wrapped in domain models, mutations outside the model layer.
BLOCKED until: - [ ] Full data flow traced (origin โ crash) - [ ] Invariant owner identified with file:line evidence - [ ] All access sites audited (grep count) - [ ] Fix layer justified (lowest layer that protects most consumers)
Anti-patterns (REJECT these):
- "Fix it where it crashes" โ Crash site โ cause site. Trace upstream.
- "Add defensive checks at every consumer" โ Scattered defense = wrong layer. One authoritative fix > many scattered guards.
- "Both fix is safer" โ Pick ONE authoritative layer. Redundant checks across layers send mixed signals about who owns the invariant.
MUST ATTENTION apply critical + sequential thinking โ every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
MUST ATTENTION apply sequential-thinking โ multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see /sequential-thinking skill.
MUST ATTENTION apply AI mistake prevention โ verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
- MANDATORY Bootstrap task tracking before target work; transition one task at a time.
- MANDATORY Persist plan/review findings to
plans/reports/ incrementally and synthesize from disk.
- MANDATORY After task-tracking bootstrap and before target/source work, read required project-reference docs and cite
Reference docs read: ....
- MANDATORY Always include
lessons.md; project conventions override generic defaults.
- MANDATORY If project config, root instruction files, or any required reference doc is missing or stale, auto-run
/project-init or the narrow lower-level route before ordinary project-specific work.
IMPORTANT MUST ATTENTION debugger trace gate: for non-trivial bug/fix/investigation/review work, start at the observed final output and trace backward through reader -> storage/projection -> writer -> consumer/job -> producer/trigger. Enumerate all feeder paths and hypotheses before fixing. BLOCKED until trace, hypothesis matrix, owning fix layer, and forward convergence proof exist.
- MANDATORY Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
- MANDATORY Orchestrators pre-expand child skill phases before invocation; use
[N.M] $skill-name โ phase prefixes and one-in_progress discipline.
Prompt-Enhance Closing Anchors
IMPORTANT MUST ATTENTION follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
IMPORTANT MUST ATTENTION for every step/sub-skill call: set in_progress before execution, set completed after execution
IMPORTANT MUST ATTENTION every skipped step MUST include explicit reason; every completed step MUST include concise evidence
IMPORTANT MUST ATTENTION if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
Closing Reminders
IMPORTANT MUST ATTENTION 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.
Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
- End-to-Start Debugger Trace: MUST ATTENTION trace backward from final state.
- Root Cause Debugging: reproduce, isolate, trace โ NEVER guess-and-check.
- Incremental Persistence: append findings to report per file.
- Sub-Agent Return Contract: return summary only, full report on disk.
- Source/Test Drift Check: changed behavior โ reconcile affected tests from evidence.
- AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
- Nested Task Creation: expand child phases, link parent when nested.
- Project Reference Docs: ALWAYS read required project docs, cite them.
- Task Tracking & External Report: bootstrap tasks, persist findings incrementally.
- Critical Thinking: traced proof per claim, confidence >80%.
- Sequential Thinking: multi-step Thought N/M with confidence closer.
- Understand Code First: read code, grep 3+ patterns before concluding.
- Evidence: cite
file:line, declare confidence โ NEVER speculate.
- Cross-Service Check: scan producers/consumers/sagas/contracts for silent regressions.
- Estimation Framework: bottom-up hours, derived SP, min-max range.
- Red Flag Stop Conditions: escalate on confidence/blast/boundary/security flags.
- Fix-Layer Accountability: fix lowest invariant-owning layer โ NEVER crash site.
IMPORTANT MUST ATTENTION investigation-ONLY โ NEVER patch here; hand confirmed cause to /fix โ why: a fix from un-validated findings patches the symptom and masks the real defect.
IMPORTANT MUST ATTENTION Phase 0 FIRST (BLOCKING) โ classify bug type, route to the specialized agent (debugger / performance-optimizer / security-auditor) before any investigation โ why: classification decides which evidence matters and which agent has the right checklist.
IMPORTANT MUST ATTENTION NEVER fix at the crash site โ trace full data flow origin โ crash, fix at the lowest invariant-owning layer that protects ALL downstream consumers โ why: the crash site is a symptom; scattered guards at consumers signal nobody owns the invariant.
MUST ATTENTION trace END-to-START โ name Frame 0 (observed final state), walk reader โ storage/projection โ writer โ consumer/job โ producer, enumerate ALL feeder paths, build the hypothesis matrix BEFORE proposing any fix โ why: the bug enters where bad state is WRITTEN, not where it crashes.
MUST ATTENTION every root-cause claim carries Confidence: X% + file:line proof; <60% โ report "hypothesis, not confirmed" with named evidence gaps, NEVER a guess โ why: self-confirmed findings rationalize their own gaps.
MUST ATTENTION NEVER declare a confirmed root cause without passing the /why-review gate (SAME session, SAME main agent, NO sub-agent); 2 rounds without passing โ STOP, escalate via AskUserQuestion.
MUST ATTENTION search 3+ existing patterns and READ the actual code before concluding โ cite file:line; inference alone is insufficient โ why: trial-and-error and assumed APIs hallucinate causes.
MUST ATTENTION run a graph trace when graph.db exists โ callers_of / importers_of / tests_for / trace reveal MESSAGE_BUS consumers and event handlers grep cannot see โ why: cross-service chains are invisible to text search.
MUST ATTENTION prove convergence FORWARD after choosing the fix layer โ walk start โ end, map each root cause to a fix part and each fix part to a test/proof; /prove-fix MUST run after /fix applies changes.
MUST ATTENTION OOM/memory โ check row COUNT before row SIZE (unbounded query > large row); 3+ failed fixes โ STOP, question the architecture, escalate to user.
MUST ATTENTION bootstrap TaskCreate task tracking BEFORE first file read; persist findings incrementally to ; standalone (outside workflow) โ add a task as the LAST task โ why: context cutoff loses in-memory findings.
Anti-Rationalization:
| Evasion | Rebuttal |
|---|
| "I see the problem, let me fix it" | Symptom โ root cause. This skill is investigation-ONLY โ trace end-to-start first. |
| "Too simple for Phase 0" | Root-cause assumptions waste more time than classification. Apply Phase 0 anyway. |
| "Already traced, no graph needed" | Show file:line evidence. No proof = no trace. Run graph trace if graph.db exists. |
"Skip /why-review, findings look solid" | Self-confirmed findings rationalize their own gaps. The /why-review gate is non-negotiable. |
| "This is a frontend bug, no graph" | Frontend โ backend โ bus chains exist. Run trace first. |
| "It's OOM, must be a large object" | Check row COUNT before row SIZE. Unbounded query > large single row. |
| "Just try changing X and see" | One hypothesis at a time. Scientific method, not trial and error. |
IMPORTANT MUST ATTENTION investigation-ONLY: trace end-to-start to the invariant-owning layer, NEVER patch here.
IMPORTANT MUST ATTENTION every root-cause claim needs Confidence: X% + file:line proof; <60% = "hypothesis, not confirmed", NEVER a guess.
IMPORTANT MUST ATTENTION NEVER declare confirmed without the /why-review gate; TaskCreate before starting.
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using TaskCreate.