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: 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-auditor and decides which evidence matters; (0.5) Adjudicate fault — failing/flaky integration test ONLY: READ the $integration-test-review gate 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-review gate; (6) Report the confidence-tagged finding + hand off to $fix → $prove-fix runs 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:line proof; below 60% report "hypothesis, not confirmed" with named gaps, NEVER a guess. Run a graph trace when graph.db exists — it surfaces bus/event consumers grep cannot see.
$why-review gate is non-negotiable: run it in the SAME session/main agent before declaring confirmed; 2 rounds without passing → STOP and escalate by asking the user directly.
Workflow:
- Classify — Detect bug scenario type (Phase 0) → route to specialized agent
1.5. Adjudicate — Failing integration test? Read
$integration-test-review gates (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: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 |
| 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-review from here — READ its protocol instead. Inside integration-test-verify-loop, this skill already runs in the SAME round as an explicit $integration-test-review call (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 by asking the user directly — 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: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.
# 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: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 by asking the user directly
⚠️ 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 ask the user directly:
- 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 ask the user directly 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 task tracking 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.
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-investigate and 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 ask the user directly (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 the current task list 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: the current task list 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.
- Read
docs/project-config.json first — 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-init or the narrow route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) first; if Codex mirrors or AGENTS.md are stale, ask the user to run $sync-codex (never auto-run it).
- 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, then before target work state:
Reference docs read: ... | Not applicable: ....
Ready when: scope evaluated, docs/project-config.json consulted, 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 by asking the user directly · ≥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 |
|
…(truncated)
1---2name: debug-investigate3description: [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.4---5
6> 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.
17
18<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
19
20## Codex Project-Reference Loading (No Hooks)
21
22Codex 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.
24
25**Always read:**
26
27- `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)
30
31**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.
32
33**Situation-based docs:**
34
35- 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 above
40- 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 files
44
45Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
46
47<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
48
49<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
50
51> **[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.
55
56<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
57
58## Quick Summary
59
60**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.
61
62**Summary:**
63
64- **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."
65- **Main steps in order (the digest):** (0) **Classify** bug type — Phase 0, BLOCKING — routes to `debugger` / `performance-optimizer` / `security-auditor` and decides which evidence matters; (0.5) **Adjudicate fault** — failing/flaky integration test ONLY: READ the `$integration-test-review` gate 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-review` gate; (6) **Report** the confidence-tagged finding + hand off to `$fix` → `$prove-fix` runs after the fix.
66- **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.
67- **Evidence law:** every root-cause claim carries `Confidence: X%` + `file:line` proof; below 60% report "hypothesis, not confirmed" with named gaps, NEVER a guess. Run a graph trace when `graph.db` exists — it surfaces bus/event consumers grep cannot see.
68- **`$why-review` gate is non-negotiable:** run it in the SAME session/main agent before declaring confirmed; 2 rounds without passing → STOP and escalate by asking the user directly.
69
70**Workflow:**
71
721. **Classify** — Detect bug scenario type (Phase 0) → route to specialized agent
73 1.5. **Adjudicate** — Failing integration test? Read `$integration-test-review` gates (Phase 0.5) → emit fault verdict before tracing
742. **Reproduce** — Confirm expected vs actual with evidence
753. **Hypothesize** — Form 2-3 ranked theories
764. **Trace** — Follow code paths; collect `file:line` proof per hypothesis
775. **Confirm** — Single root cause explains ALL symptoms
786. **Validate** — Trigger `$why-review` on findings/root cause before declaring confirmed
797. **Report** — Confidence-tagged finding + hand off to `$fix`
80
81**Key Rules:**
82
83- NEVER patch symptoms — trace full call chain, fix at owning layer
84- NEVER report root cause without `file:line` evidence
85- NEVER declare confirmed root cause without passing the `$why-review` validation gate
86- Output: confirmed root cause OR "hypothesis, not confirmed" + evidence gaps
87
88## Phase 0: Classify Bug Scenario (BLOCKING — Do Before ANY Investigation)
89
90**Think:** What type of failure is this? Classification routes to the right agent and determines which evidence matters most.
91
92| Bug Type | Signals | Specialized Agent |
93| ------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
94| Frontend UI / rendering | Console errors, visual regression, component state | `debugger` |
95| Backend logic / data | Wrong API response, data corruption, validation failure | `debugger` |
96| Cross-service / message bus | Events not propagating, consumer failures, sync lag | `debugger` + graph trace MANDATORY |
97| Performance / memory | Slow queries, OOM, N+1, unbounded result sets | `performance-optimizer` |
98| Security / auth | Access denied, token issues, permission bypass | `security-auditor` |
99| **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) |
100
101**Cross-service bugs:** Run graph trace FIRST — grep alone misses implicit bus connections.
102**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?
103
104### Phase 0.5: Fault Adjudication — failing integration tests (BLOCKING for that bug type)
105
106> **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_.
107
108**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.
109
110> **MUST NOT invoke `$integration-test-review` from here — READ its protocol instead.** Inside `integration-test-verify-loop`, this skill already runs in the SAME round as an explicit `$integration-test-review` call (`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.
111
112**Step 2 — emit ONE fault verdict before any trace.**
113
114| Verdict | Meaning | Where to trace next |
115| -------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
116| **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 |
117| **TEST-NOT-OPTIMAL** | Test is right but fragile — timing, shared state, ordering dependence | The fragility's source (missing ARRANGE barrier, shared infra assertion) |
118| **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 |
119| **ENVIRONMENT** | Config, DB, credentials, ports, versions | Mark BLOCKED — do not trace application code |
120| **AMBIGUOUS** | Spec silent or contradictory about which side is correct | **STOP and ask the user** by asking the user directly — never self-resolve |
121
122**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.
123
124## Debug Mindset (NON-NEGOTIABLE)
125
126**Skeptical. Sequential. Every claim needs traced proof, confidence >80%.**
127
128- NEVER assume first hypothesis correct — verify with actual code traces
129- Every root cause claim MUST include `file:line` evidence
130- Cannot prove root cause → state "hypothesis, not confirmed"
131- Challenge assumptions: "Is this really the cause?" → trace actual execution path
132- Challenge completeness: "Other contributing factors?" → check related code paths
133
134## Confidence & Evidence Gate
135
136**MUST ATTENTION** declare `Confidence: X%` + evidence list + `file:line` proof for EVERY claim.
137
138| Confidence | Meaning | Action |
139| ---------- | ---------------------------------------- | ------------------------------------ |
140| 95-100% | Full trace verified | Report as confirmed root cause |
141| 80-94% | Main path verified, edge cases uncertain | Report with caveats |
142| 60-79% | Partial trace | Report as hypothesis |
143| <60% | Insufficient evidence | DO NOT report — gather more evidence |
144
145## Investigation Dimensions
146
147Reason through each dimension — state what fails if weak, then apply with evidence.
148
149### Dim 1: Reproduce
150
151**Think:** What exact conditions trigger this? Data state? User action? Timing? Environment delta?
152
153- Confirm issue exists with evidence (error message, stack trace, screenshot)
154- Identify trigger: user action, data state, timing, env difference
155
156### Dim 2: Hypothesize
157
158**Think:** Given symptoms, what are the most plausible failure modes? What would confirm vs contradict each?
159
160- Form 2-3 theories ranked by likelihood
161- Note evidence needed to confirm/contradict each theory before investigating
162
163### Dim 3: End-to-Start Trace
164
165**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?
166
167- Name Frame 0: observed final state (UI, API response, log, persisted value, assertion, aggregate)
168- Identify the final reader/query/renderer/assertion and the state it consumes
169- Walk backward: reader -> storage/projection/cache -> writer -> consumer/handler/job -> producer/origin
170- Enumerate every feeder path that can write the same final state
171- Check error handling paths
172- Collect `file:line` evidence per hypothesis
173- Use graph trace for implicit connections (event handlers, bus consumers)
174
175### Dim 4: Confirm
176
177**Think:** Does this root cause explain ALL symptoms? Are there bypass paths that skip the fix point?
178
179- Match evidence to single root cause
180- Verify root cause explains ALL observed symptoms
181- Check secondary contributing factors
182- Build hypothesis matrix: primary, contributing, ruled out, latent, unknown
183- Resolve or disclose competing causes before proposing a fix
184- Verify no bypass paths (direct construction, clone/spread without re-validation, mutations outside model layer)
185
186### Dim 5: Report
187
188- Output: confirmed root cause + evidence chain
189- Include: affected files, Debugger Trace: End -> Start, feeder paths, hypothesis matrix, data flow summary, owning fix layer, fix recommendation, forward convergence proof
190- Hand off to `$fix` for implementation
191
192## Dependency Tracing (MANDATORY when graph.db exists)
193
194**MUST ATTENTION** use structural queries — graph reveals ALL callers/consumers grep misses.
195
196```bash
197# Who calls the buggy function
198python .claude/scripts/code_graph query callers_of <function> --json
199
200# Who imports the buggy module
201python .claude/scripts/code_graph query importers_of <file> --json
202
203# What tests exist
204python .claude/scripts/code_graph query tests_for <function> --json
205
206# Full upstream + downstream context
207python .claude/scripts/code_graph trace <suspect-file> --direction both --json
208
209# Callers only (find all trigger points)
210python .claude/scripts/code_graph trace <suspect-file> --direction upstream --json
211```
212
213Graph reveals implicit connections (MESSAGE_BUS, event handlers) that propagate issues across services — invisible to grep.
214
215## Root Cause Validation (`$why-review` Gate)
216
217NEVER 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`.
218
219**Step 1 — Investigate (main agent):** Identify root cause + full evidence chain. Write findings to report file.
220
221**Step 2 — Validate (`$why-review`, same main agent):** Trigger `$why-review` on the findings/root cause. The gate must confirm:
222
223- Root cause is correct and reasonable, with `file:line` evidence that conclusively supports it
224- Evidence has no gaps and explains ALL symptoms
225- The proposed fix direction would NOT introduce other bugs or regressions (check downstream consumers, bypass paths, owning layer)
226
227**Decision:**
228
229- `$why-review` PASSES → declare confirmed, proceed to `$fix`
230- `$why-review` finds GAPS/risks → collect additional evidence, repeat
231- 2 validation rounds without passing → STOP, escalate to user by asking the user directly
232
233## ⚠️ MANDATORY: Post-Fix Verification
234
235After `$fix` applies changes, `$prove-fix` MUST be run — builds code proof traces per change with confidence scores. Non-negotiable in all fix workflows.
236
237## Anti-Rationalization (Red Flags)
238
239| Evasion | Rebuttal |
240| ----------------------------------------- | --------------------------------------------------------------------------------------------- |
241| "I see the problem, let me fix it" | Symptoms ≠ root cause. Investigate first. |
242| "Quick fix for now, investigate later" | Quick fixes mask bugs. Find root cause. |
243| "Just try changing X and see" | One hypothesis at a time. Scientific method, not trial and error. |
244| "Already tried 2+ fixes, one more" | 3+ failed fixes = STOP. Question the architecture, not the fix. |
245| "The error message is misleading" | Read it again carefully. Error messages are usually right. |
246| "It works on my machine" | Reproduce in the failing environment. Your environment hides bugs. |
247| "This can't be the cause" | Verify with evidence, not intuition. Unlikely causes are still causes. |
248| "It's OOM, must be a large object" | Check row COUNT before row SIZE. Unbounded query > large single row. |
249| "Skip `$why-review`, findings look solid" | Self-confirmed findings rationalize their own gaps. The `$why-review` gate is non-negotiable. |
250| "Graph.db not needed for this bug" | Cross-service bugs are invisible to grep. Run trace first. |
251
252---
253
254## Workflow Recommendation
255
256**MUST ATTENTION — NO EXCEPTIONS:** Not in workflow? Use ask the user directly:
257
2581. **Activate `workflow-bugfix` workflow** (Recommended) — scout → investigate → debug → plan → fix → prove-fix → review → test
2592. **Execute `$debug-investigate` directly** — standalone
260
261---
262
263## Next Steps (Standalone only — skip if inside workflow)
264
265**MUST ATTENTION** use ask the user directly after completing. NEVER auto-decide next step:
266
267- **"Proceed with full workflow (Recommended)"** — detect best workflow to continue from here
268- **"$fix"** — apply fix based on debug findings
269- **"$plan"** — if fix requires planning first
270- **"Skip, continue manually"** — user decides
271
272**Standalone Review Gate:** Outside workflow? MUST create `$changes-review` task as LAST task.
273
274---
275
276> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files.
277
278- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
279
280<!-- SYNC:end-to-start-debugger-trace -->
281
282> **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.
283>
284> 1. **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.
285> 2. **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.
286> 3. **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.
287> 4. **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.
288> 5. **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.
289> 6. **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.
290>
291> **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.
292>
293> **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.
294
295<!-- /SYNC:end-to-start-debugger-trace -->
296
297<!-- SYNC:root-cause-debugging -->
298
299> **Root Cause Debugging** — Systematic approach, never guess-and-check.
300>
301> 1. **Reproduce** — Confirm the issue exists with evidence (error message, stack trace, screenshot)
302> 2. **Isolate** — Narrow to specific file/function/line using binary search + graph trace
303> 3. **Trace** — Follow data flow from input to failure point. Read actual code, don't infer.
304> 4. **Hypothesize** — Form theory with confidence %. State what evidence supports/contradicts it
305> 5. **Verify** — Test hypothesis with targeted grep/read. One variable at a time.
306> 6. **Fix** — Address root cause, not symptoms. Verify fix doesn't break callers via graph `connections`
307>
308> **NEVER:** Guess without evidence. Fix symptoms instead of cause. Skip reproduction step.
309
310<!-- /SYNC:root-cause-debugging -->
311
312<!-- SYNC:incremental-persistence -->
313
314> **Incremental Result Persistence** — MANDATORY for all sub-agents or heavy inline steps processing >3 files.
315>
316> 1. **Before starting:** Create report file `plans/reports/{skill}-{date}-{slug}.md`
317> 2. **After each file/section reviewed:** Append findings to report immediately — never hold in memory
318> 3. **Return to main agent:** Summary only (per SYNC:subagent-return-contract) with `Full report:` path
319> 4. **Main agent:** Reads report file only when resolving specific blockers
320>
321> **Why:** Context cutoff mid-execution loses ALL in-memory findings. Each disk write survives compaction. Partial results are better than no results.
322>
323> **Report naming:** `plans/reports/{skill-name}-{YYMMDD}-{HHmm}-{slug}.md`
324
325<!-- /SYNC:incremental-persistence -->
326
327<!-- SYNC:subagent-return-contract -->
328
329> **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.
330>
331> ```markdown
332> ## Sub-Agent Result: [skill-name]
333>
334> Status: ✅ PASS | ⚠️ PARTIAL | ❌ FAIL
335> Confidence: [0-100]%
336>
337> ### Findings (Critical/High only — max 10 bullets)
338>
339> - [severity] [file:line] [finding]
340>
341> ### Actions Taken
342>
343> - [file changed] [what changed]
344>
345> ### Blockers (if any)
346>
347> - [blocker description]
348>
349> Full report: plans/reports/[skill-name]-[date]-[slug].md
350> ```
351>
352> Main agent reads `Full report` file ONLY when: (a) resolving a specific blocker, or (b) building a fix plan.
353> Sub-agent writes full report incrementally (per SYNC:incremental-persistence) — not held in memory.
354>
355> **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.
356
357<!-- /SYNC:subagent-return-contract -->
358
359<!-- SYNC:source-test-drift-check -->
360
361> **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.
362
363<!-- /SYNC:source-test-drift-check -->
364
365<!-- SYNC:test-failure-fault-adjudication -->
366
367> **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.
368>
369> 1. **Provisional verdict before touching either side.** Classify the observed evidence as SOURCE-WRONG, TEST-WRONG, TEST-NOT-OPTIMAL, ENVIRONMENT-BLOCKED, or AMBIGUOUS; then `$debug-investigate` and trace end-to-start before editing. A green-again suite is NOT the goal.
370> 2. **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.
371> 3. **Classify who is at fault, then fix the wrong side at its root:**
372> - **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.
373> - **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.
374> - **TEST-NOT-OPTIMAL** — intended behavior is valid but the test seam, timing, or assertion signal is fragile → improve the test without weakening the invariant.
375> - **ENVIRONMENT-BLOCKED** — infrastructure or external state prevents a source/test verdict → preserve diagnostics and stop mutation until the environment is healthy.
376> - **AMBIGUOUS** — evidence or intended behavior does not safely select an owner → ask the user or canonical owner before editing.
377> - 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.)
378> 4. **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 ask the user directly (or consult the canonical spec owner) before editing either side — never silently pick source or test just to make the suite pass.
379>
380> Reconcile to intended behavior, never to whichever side currently passes — green can encode the very bug.
381
382<!-- /SYNC:test-failure-fault-adjudication -->
383
384<!-- SYNC:ai-mistake-prevention -->
385
386> **AI Mistake Prevention** — Failure modes to avoid on every task:
387>
388> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
389> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
390> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
391> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
392> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
393> **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.
394> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
395> **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.
396> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
397
398<!-- /SYNC:ai-mistake-prevention -->
399
400<!-- SYNC:nested-task-creation -->
401
402> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.
403>
404> 1. Call the current task list first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.
405> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.
406> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.
407> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
408> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.
409> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
410>
411> **Blocked until:** the current task list done, child phases created, parent linked when nested, first child marked `in_progress`.
412
413<!-- /SYNC:nested-task-creation -->
414
415<!-- SYNC:project-reference-docs-guide -->
416
417> **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.
418>
419> 1. Identify scope: file types, domain area, and operation.
420> 2. **Read `docs/project-config.json` first — 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-init` or the narrow route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) first; if Codex mirrors or `AGENTS.md` are stale, ask the user to run `$sync-codex` (never auto-run it).
421> 3. 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`.
422> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.
423>
424> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.
425
426<!-- /SYNC:project-reference-docs-guide -->
427
428<!-- SYNC:task-tracking-external-report -->
429
430> **Task Tracking & External Report Persistence** — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
431>
432> 1. Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
433> 2. Mark one task `in_progress` before work and `completed` immediately after evidence; never batch transitions.
434> 3. For plan/review work, create `plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md` before first finding.
435> 4. Append findings after each file/section/decision and synthesize from the report file at the end.
436> 5. Final output cites `Full report: plans/reports/{filename}`.
437>
438> **Blocked until:** task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
439
440<!-- /SYNC:task-tracking-external-report -->
441
442<!-- SYNC:critical-thinking-mindset -->
443
444> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
445> **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.
446
447<!-- /SYNC:critical-thinking-mindset -->
448
449<!-- SYNC:sequential-thinking-protocol -->
450
451> **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.
452>
453> **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.
454>
455> **Format (explicit mode — visible thought trail):**
456>
457> 1. `Thought N/M: [aspect]` — one aspect per thought, state assumptions/uncertainty
458> 2. `Thought N/M [REVISION of Thought K]: ...` — when prior reasoning invalidated; state Original / Why revised / Impact
459> 3. `Thought N/M [BRANCH A from Thought K]: ...` — explore alternative; converge with decision rationale
460> 4. `Thought N/M [HYPOTHESIS]: ...` then `[VERIFICATION]: ...` — test before acting
461> 5. `Thought N/N [FINAL]` — only when verified, all critical aspects addressed, confidence >80%
462>
463> **Mandatory closers:** Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
464>
465> **Stop conditions:** confidence <80% on any critical decision → escalate by asking the user directly · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
466>
467> **Implicit mode:** apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
468>
469> **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).
470
471<!-- /SYNC:sequential-thinking-protocol -->
472
473<!-- SYNC:understand-code-first -->
474
475> **Understand Code First** — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
476>
477> 1. Search 3+ similar patterns (`grep`/`glob`) — cite `file:line` evidence
478> 2. Read existing files in target area — understand structure, base classes, conventions
479> 3. Run `python .claude/scripts/code_graph trace <file> --direction both --json` when `.code-graph/graph.db` exists
480> 4. Map dependencies via `connections` or `callers_of` — know what depends on your target
481> 5. Write investigation to `.ai/workspace/analysis/` for non-trivial tasks (3+ files)
482> 6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
483> 7. NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
484>
485> **BLOCKED until:** `- [ ]` Read target files `- [ ]` Grep 3+ patterns `- [ ]` Graph trace (if graph.db exists) `- [ ]` Assumptions verified with evidence
486
487<!-- /SYNC:understand-code-first -->
488
489<!-- SYNC:evidence-based-reasoning -->
490
491> **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim needs proof.
492>
493> 1. Cite `file:line`, grep results, or framework docs for EVERY claim
494> 2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
495> 3. Cross-service validation required for architectural changes
496> 4. "I don't have enough evidence" is valid and expected output
497>
498> **BLOCKED until:** `- [ ]` Evidence file path (`file:line`) `- [ ]` Grep search performed `- [ ]` 3+ similar patterns found `- [ ]` Confidence level stated
499>
500> **Forbidden without proof:** "obviously", "I think", "should be", "probably", "this is because"
501> **If incomplete →** output: `"Insufficient evidence. Verified: [...]. Not verified: [...]."`
502
503<!-- /SYNC:evidence-based-reasoning -->
504
505<!-- SYNC:cross-service-check -->
506
507> **Cross-Service Check** — Microservices/event-driven: MANDATORY before concluding investigation, plan, spec, or feature doc. Missing downstream consumer = silent regression.
508>
509> | Boundary | Grep terms |
510> | ------------------- | ------------------------------------------------------------------------------- |
511> | Event producers | `Publish`, `Dispatch`, `Send`, `emit`, `EventBus`, `outbox`, `IntegrationEvent` |
512> | Event consumers
513
514…(truncated)