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, merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: in_progress on start, completed on end.
[BLOCKING] Every completed/skipped step MUST include evidence or explicit skip reason.
[BLOCKING] If Task tools unavailable, maintain equivalent step-by-step plan tracker with same status transitions.
Quick Summary
Goal: Eliminate the root cause of an issue using parallel subagent investigation — traced end-to-start with file:line evidence and fixed at the lowest invariant-owning layer (never the crash site) — then prove the fix with $prove-fix so the disease is cured, not just the symptom.
Summary:
- Purpose: an intelligent fix router that cures the disease, not the symptom — diagnose root cause with evidence, fix at the lowest invariant-owning layer, prove it with
$prove-fix, then keep spec + tests + code in sync.
- Router first (
--target=): with --target={ci|issue|logs|test|types|ui} clear the Root-Cause Prerequisite Gate, then jump to that self-contained inline branch (each runs its own diagnosis + $prove-fix); no flag = run the full diagnose→fix spine. — why: branches must not re-run §1/§2 of the standalone spine, but no branch is exempt from having a traced root cause.
- Main steps (no-flag spine): Root-Cause Prerequisite Gate → scout (parallel subagents) → diagnose root cause end-to-start (
debug-investigate, file:line evidence, hypothesis matrix, forward convergence proof) → Confidence & Evidence Gate → plan with impact analysis → 🛑 Validate-Before-Fix approval → implement at the owning layer → $prove-fix → conditional $spec correctness check → $changes-review (production code) → $why-review terminal sign-off.
- Root-Cause Prerequisite Gate (BLOCKING, runs FIRST): a direct
$fix call — no-flag spine and every --target= branch — MUST NOT edit code until $debug-investigate produced a root cause for THIS problem in THIS session, proven by a the current task list row or a written investigation report (memory is not evidence; a parent workflow row alone is not proof). Not run → run $debug-investigate first, then resume from the planning step. — why: otherwise the first edit lands with zero traced cause and patches the symptom site.
- Three hard gates that cannot be skipped: the Root-Cause Prerequisite Gate (above), the Confidence & Evidence Gate (declare
Confidence: X% + file:line, STOP if <60%) and the 🛑 Validate-Before-Fix approval (present root cause + plan by asking the user directly before any code change — skip approval only inside a workflow).
- Diagnose before patching: trace the symptom end-to-start to the invariant-owning layer, and NEVER fix at the crash site — the crash site is a symptom, the cause enters at a lower layer.
- Mode + skip rules: default mode HARD (full rigor) unless ALL 5 trivial-bug opt-out conditions hold; standalone (no parent workflow) self-assembles the minimum spine
debug-investigate → fix + prove-fix → $spec correctness check → $changes-review (production code) → $why-review; inside a workflow this whole contract is SKIPPED — except the Root-Cause Prerequisite Gate, which never skips: it still demands proof the sequence actually ran debug-investigate for this problem. — why: standalone has no sequence supplying diagnosis, spec sync, or review; and a workflow row is not proof its diagnosis step ran.
Workflow:
- Scout — Use scout/researcher subagents to explore issue in parallel
- Diagnose — Trace root cause through code paths with evidence
- Plan — Create fix plan with impact analysis
- Fix — Implement and verify the fix
Key Rules:
- Root-Cause Prerequisite Gate (BLOCKING): no code edit until
$debug-investigate traced THIS problem in THIS session — evidence, not recall
- Debug Mindset: every claim needs
file:line evidence
- Use subagents for parallel investigation of multiple hypotheses
- Always create a plan before implementing complex fixes
- Target flag (see Target Routing):
--target={ci|issue|logs|test|types|ui} selects a self-contained inline branch that scopes the fix to that domain. No flag = full diagnose→fix spine below.
Default Mode Policy
Default mode HARD (full rigor). Every section below — parallel scout/researcher subagents, root-cause tracing with file:line evidence, Confidence & Evidence Gate, fix plan with impact analysis, preservation tests for the bug — applies by default.
Opt out to fast mode ONLY when ALL true (bug genuinely trivial):
- Root cause obvious from error message AND already located (no diagnosis needed)
- Single-file fix, ≤10 lines changed
- No cross-service impact, no contract change
- Test for bug already exists OR bug non-functional (typo, log message)
- Confidence in fix ≥95% without further investigation
Any condition fails → use full protocol below. When in doubt, default hard. Skipping diagnosis on non-trivial bug fixes symptom and leaves disease.
Fast mode skips (and only skips): parallel subagent investigation (direct read/grep instead), separate fix plan (inline change), regression-test authoring (only if covering test exists). Does NOT skip Confidence & Evidence Gate, Behavioral Delta Matrix, or running existing test suite.
🛑 Root-Cause Prerequisite Gate (Direct $fix Invocation) — BLOCKING
[BLOCKING] $fix MUST NOT edit code until $debug-investigate has produced a root cause for THIS problem in THIS session. This gate runs BEFORE the Standalone Mode Minimum Contract below, BEFORE any --target= branch body, and BEFORE the 🛑 Validate-Before-Fix approval. — why: $fix invoked directly can otherwise reach its first edit with zero traced root cause, which patches the symptom site and ships the disease.
1. Trigger — ALL direct $fix invocations. User-typed slash command or model-selected skill; every --target={ci|issue|logs|test|types|ui} branch and the no-flag spine alike. The --target= branches do NOT re-run §1/§2 of the contract below, but they DO pass through this gate. — why: a branch's own debugger/tester subagent step is not an end-to-start root-cause trace, so scoping the run does not remove the need for one.
2. Check — evidence, never memory. Before the first code edit, determine whether $debug-investigate already ran in this session, for this same problem. Accept ONLY:
- a the current task list row for
debug-investigate (or its phase tasks) covering this symptom, or
- a written investigation report naming this symptom (e.g.
.ai/workspace/analysis/{issue-name}.analysis.md, plans/reports/debug-investigate-*.md) containing the end-to-start trace.
No such evidence → treat as NOT run. Recalling that the cause "is known" is not evidence. — why: after context compaction the model's belief that it already investigated survives while the actual findings do not.
3. Act. Not run → run $debug-investigate on the problem FIRST, then resume the $fix spine from its planning step using that root-cause report. This subsumes the spine's internal step-1 debugger subagent (identical to the contract's §1 rule below). — why: re-running diagnosis after the skill already traced it double-runs the spine.
4. Same-problem test. A prior $debug-investigate for a different symptom does NOT satisfy this gate. Satisfaction binds to the problem, not to the skill name. When the current <issues> names a symptom the existing report does not cover, the gate FIRES. — why: one investigation per session would otherwise license unlimited untraced fixes.
5. Skip conditions — explicit, narrow, and recorded. Record which one applies with its proof; never skip silently:
| Condition |
Skip? |
Same-problem evidence per §2 exists → cite the file:line / task-row proof and proceed |
YES |
Fast-mode-trivial bug (ALL 5 Default Mode Policy opt-out conditions hold) → MAY inline the end-to-start trace instead of spawning the skill; the trace itself is still REQUIRED |
PARTIAL |
Active parent workflow row whose sequence already executed debug-investigate for this problem → cite the completed step |
YES |
Active parent workflow row alone, with no completed debug-investigate step for this problem |
NO |
The last row is the hole this gate closes. The contract below detects standalone mode by the mere presence of a parent workflow row (Detect mode, §"Standalone Mode Minimum Contract"); a row can exist while the sequence's debug-investigate step never ran, ran for a different symptom, or was skipped. This gate ADDS the stricter requirement — proof of execution for THIS problem — on top of that detection; it never relaxes it. — why: presence of a container task is not evidence that the work inside it happened.
BLOCKED until: the §2 check is stated with its evidence (or its explicit skip row + proof) AND a root-cause trace for this problem exists. NEVER proceed to plan or edit on "the cause is obvious" alone.
Standalone Mode Minimum Contract (Non-Workflow Only)
$fix is normally a step inside workflow-bugfix — there the sequence (scout → investigate → debug-investigate → spec [mode=amend] → plan → … → fix → prove-fix → … → spec [mode=sync] → workflow-review-changes) supplies the diagnosis, spec sync, and review around the fix. Called STANDALONE, no sequence supplies them. $fix alone diagnoses and patches code; it does NOT by itself guarantee the root cause was traced to its owning layer, that the Feature Spec under docs/specs/ still matches behavior, or that the change was reviewed. Standalone, that gap is symptom-patching + spec/doc drift.
Scope: this contract governs the no-flag $fix spine (the full diagnose→fix path). The --target={ci|issue|logs|test|types|ui} branches are self-contained — each runs its own diagnosis + $prove-fix — so they do NOT re-run §1/§2 here; standalone, they inherit only §3 (spec-correctness check) and §4 (why-review) as their trailing gates (and --target=issue already owns its own $changes-review gate — see that branch).
Detect mode: call the current task list first (per the Nested Task Expansion Contract below). Active parent workflow row present → this whole section is SKIPPED (the workflow owns these steps; duplicating them double-runs the spine) — but the Root-Cause Prerequisite Gate above still applies: skipping this section requires the parent sequence's debug-investigate step to be completed for this problem, not merely present. Row present + that step not run → the gate fires and $debug-investigate runs first. No parent row → standalone: before the first code edit, MUST ATTENTION self-assemble this minimum bugfix spine as task tracking todos, in order:
$debug-investigate — root cause, FIRST; mandated by the Root-Cause Prerequisite Gate above, whose §2 evidence check decides whether it already ran for this problem. Trace the symptom end-to-start to the invariant-owning layer with file:line evidence (hypothesis matrix + forward convergence proof). This is the standalone diagnosis — it subsumes the spine's internal step-1 debugger subagent; resume the spine from its planning step using this report. Fast-mode-trivial bugs (ALL Default Mode Policy opt-out conditions met) MAY inline the trace instead of spawning the skill, but the end-to-start trace is still required.
- Fix spine — this skill's
plan → 🛑 approve → implement → $prove-fix`` body below. The Validate-Before-Fix approval gate and $prove-fix are unchanged.
$spec spec-correctness check — CONDITIONAL, ensures spec docs aren't left stale. From the proven root cause, decide which case holds:
- Spec was WRONG / stale — it described behavior that was never true, or intended behavior changed and the spec wasn't updated. The spec is (part of) the defect → run
$spec [mode=amend] to correct the §1-§7 spec, then $spec [mode=sync] to reconcile §8 TC-{FEATURE}-{NNN} ↔ integration tests.
- Spec was CORRECT, the code just failed to meet it — pure code defect; §1-§7 behavior now matches the spec again. No §1-§7 amendment. But still check the §8 test cases: if the bug reproduced a scenario/edge case that no existing
TC-{FEATURE}-{NNN} covered (the spec was correct but lacked the bug case), add a regression test case via $spec [mode=tests] so the spec captures it, then $spec [mode=sync] to reconcile §8 ↔ the new regression test. Only if an existing TC already covered the case do you record Spec verified correct, bug case already in §8 — no spec change (code-only defect) with file:line evidence and move on. Never leave a fixed bug whose case is absent from the spec's §8.
- No governing spec exists — the buggy area has no Feature Spec under
docs/specs/. Record No governing spec — nothing to amend with file:line evidence; if the area now warrants one, run $spec [mode=init] (then [mode=tests] to seed §8 with the bug case as a regression TC) rather than only suggesting it. Decide the case explicitly — skip only the amendment, never the decision; never leave the bug case undocumented when a spec governs the area.
$why-review — rationale review, the FINAL todo (after the fix AND after any $changes-review). Terminal sign-off on the converged change: root cause correctly owned, fix at the lowest invariant-owning layer (not the crash site), no symptom-patching, regression covered, and the §3 spec decision justified. Reporting "done" is blocked until this passes. Non-functional-trivial fixes (typo, log/comment text; fast-mode) MAY satisfy this inline/briefly rather than spawning the full skill — symmetric with §1.
Production-code fixes also get a $changes-review todo before §4 (the broad code review whose validated fixes may change the diff; §4 then signs off on the result). $changes-review placement and the inside-workflow skip are owned by the shared Standalone Review Gate below — reference it; do not restate the mandate. Final standalone todo order: debug-investigate → [fix spine + prove-fix] → spec-check → changes-review (if production code) → why-review.
Debug Mindset (NON-NEGOTIABLE)
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
- Verify each hypothesis against an actual code trace before acting — do NOT assume first hypothesis correct — why: the first guess is usually the nearest-attention trap, not the cause
- Every root cause claim must include
file:line evidence
- If you cannot prove root cause with code trace, state "hypothesis, not confirmed"
- Question assumptions: "Is this really the cause?" → trace actual execution path
- Challenge completeness: "Are there other contributing factors?" → check related code paths
- No "should fix it" without proof — verify fix addresses traced root cause
⚠️ MANDATORY: Confidence & Evidence Gate
MANDATORY IMPORTANT MUST ATTENTION declare Confidence: X% with evidence list + file:line proof for EVERY claim.
95%+ recommend freely | 80-94% with caveats | 60-79% list unknowns | <60% STOP — gather more evidence.
Ultrathink plan and start fixing these issues; follow Orchestration Protocol, Core Responsibilities, Subagents Team, Development Rules:
$ARGUMENTS
Target Routing (--target=)
$fix is an intelligent router. With no flag it runs the full diagnose→fix spine below. Pass --target= to scope the run to a self-contained inline branch:
--target |
Behavior |
types |
Inline branch (below) — TypeScript / type-error resolution. |
ci |
Inline branch (below) — CI / pipeline failure triage. |
issue |
Inline branch (below) — tracked issue / ticket resolution. |
logs |
Inline branch (below) — log / stack-trace-driven debugging. |
test |
Inline branch (below) — failing-test repair. |
ui |
Inline branch (below) — UI / visual-defect fixes. |
No --target (or an unrecognized value) → run the full Workflow spine below; infer the right specialization from <issues>.
Formerly standalone skills. --target=ci|issue|logs|test|ui were previously the separate skills /fix-ci, /fix-issue, /fix-logs, /fix-test, /fix-ui; they are now inline branches of $fix (folded — the standalone names no longer exist).
--target=types — TypeScript / type-error branch
Run tsc --noEmit (or nx build / bun run typecheck / npx tsc) to gather all type errors, then:
- Collect — Capture every type error with
file:line.
- Classify — Group by cause: missing types, wrong signatures, import/export issues.
- Fix at root — Give each value its real, specific type (or
unknown + a narrowing guard). Do NOT use any to silence the checker — any ships the underlying type defect. Fix the root cause (wrong interface, missing export), not the symptom site. — why: any silences the checker and lets the type defect ship.
- Repeat until
tsc --noEmit is clean — zero type errors.
- 🛑 Validate Before Fix: present errors + root cause by asking the user directly, get approval before code changes (skip if inside a workflow).
- After fixing, run
$prove-fix — build code proof traces per change with confidence scores. Never skip.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
--target=ci — CI / pipeline-failure branch
Goal: Analyze CI/CD pipeline logs to identify and fix build/test failures in the configured CI provider/tooling.
Key Rules:
- Infrastructure context: read
docs/project-config.json → infrastructure.cicd.tool to identify the CI provider/tooling (e.g. azure-devops, github-actions, gitlab-ci); target that provider's pipeline config files.
- Focus on CI-specific issues (env vars, Docker, dependencies, build order).
- Verify the fix does not break local development.
Workflow:
- Use the
debugger subagent to read the CI logs via the configured CI tool/API (from docs/project-config.json), analyze the final failing log/error backward to the root cause, and report back. Write findings to .ai/workspace/analysis/{ci-issue}.analysis.md; re-read before implementing.
- 🛑 Present root cause + proposed fix → ask the user directly → wait for approval.
- Implement the fix from the report.
- Use the
tester subagent to verify; report back.
- If tests fail, repeat from step 2.
- Report a summary of changes; suggest next steps. Then run
$prove-fix.
Notes: Use the CLI/API for the configured CI provider. If it is GitHub Actions and gh is unavailable, instruct the user to install and authorize GitHub CLI first.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
--target=issue — tracked-issue / ticket branch
Goal: Investigate and fix bugs reported as tracked issues (e.g. GitHub issues) with full traceability.
Active-goal read (BEFORE root-cause work): resolve the active Goal Contract per SYNC:goal-contract-satisfaction-loop (active plan goal.md → plans/goals/{YYMMDD-HHmm}-{slug}/goal.md → create from the issue). Map the ticket's acceptance criteria to the saved success criteria; after the fix, append proof evidence and remaining gaps to the Iteration Log. Closure is blocked while any required criterion remains FAIL.
Key Rules:
- Link the fix back to the issue for traceability.
- Verify the fix addresses the specific reproduction steps from the issue.
Workflow:
- Activate the
debug-investigate skill and follow its workflow — this step satisfies the Root-Cause Prerequisite Gate for this problem; record its report path as the gate's §2 evidence. See .claude/docs/AI-DEBUGGING-PROTOCOL.md for comprehensive guidelines.
- Use external memory at
.ai/workspace/analysis/issue-[number].analysis.md for structured analysis. Re-read the ENTIRE analysis file before proposing any fix.
- 🛑 Present root cause + proposed fix → ask the user directly → wait for approval before implementing.
- Implement, then run
$prove-fix.
Standalone Review Gate (non-workflow only): any standalone production-code fix — the no-flag spine (Standalone Mode Minimum Contract above) or $fix --target=issue — adds a $changes-review task tracking todo as the final changes-review gate, placed immediately before the contract's §4 $why-review terminal sign-off (spec-check → changes-review → why-review). Inside a workflow, skip — the sequence handles $changes-review.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
--target=logs — log / stack-trace branch
Goal: Analyze application logs to diagnose and fix runtime errors or unexpected behavior.
Key Rules:
- Focus on log patterns: stack traces, error codes, timing anomalies.
- Cross-reference logs with source code to find the actual root cause.
Workflow:
- Check whether
./logs.txt exists. If missing, set up permanent log piping in the project's script config (package.json, Makefile, pyproject.toml, …): Bash/Unix append 2>&1 | tee logs.txt; PowerShell append *>&1 | Tee-Object logs.txt. Run the command to generate logs.
- Use the
debugger subagent to analyze ./logs.txt: read with Grep head_limit: 30 (last 30 lines; increase if needed — avoid loading the whole file). Write analysis to .ai/workspace/analysis/{issue-name}.analysis.md; re-read before fixing.
- Use the
scout subagent to locate the exact source of the issue; report back.
- Use the
planner subagent to create an implementation plan; report back.
- 🛑 Present root cause + fix plan → ask the user directly → wait for approval.
- Implement the fix.
- Use the
tester subagent to verify; report back.
- Use the
code-reviewer subagent to review the changes; report back.
- If tests fail, repeat from step 3.
- Report a summary; suggest next steps. Then run
$prove-fix.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
--target=test — failing-test branch
Goal: Run test suites, analyze failures, and fix the underlying code or test issues.
Active-goal read (BEFORE fixing): resolve the active Goal Contract per SYNC:goal-contract-satisfaction-loop (active plan goal.md → plans/goals/{YYMMDD-HHmm}-{slug}/goal.md → create from the reported test failure). Map failing-test evidence (before) and passing-test evidence (after) to the saved success criteria in the Iteration Log — a passing suite that misses a saved required criterion does NOT close the loop.
Key Rules:
- Distinguish between code bugs and flawed test expectations.
- Re-run tests after the fix to confirm all pass.
- Read
docs/project-reference/integration-test-reference.md before reviewing/writing integration tests; consult docs/specs/ for expected-behavior context when diagnosing failures.
Workflow:
- Use the
tester subagent to compile the code and fix any syntax errors.
- Use the
tester subagent to run the tests; report back. Write failure analysis to .ai/workspace/analysis/{test-issue}.analysis.md; re-read before fixing.
- If tests fail, use the
debugger subagent to find the root cause; report back.
- Use the
planner subagent to create an implementation plan; report back.
- 🛑 Present root cause + fix plan → ask the user directly → wait for approval.
- Implement the plan step by step.
- Use the
tester subagent to verify; report back.
- Use the
code-reviewer subagent to review the changes; report back.
- If tests fail, repeat from step 2.
- Report a summary; suggest next steps. Then run
$prove-fix.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
--target=ui — UI / visual-defect branch
Goal: Diagnose and fix UI/UX issues — layout, styling, responsiveness, and visual bugs.
Key Rules:
- Always use BEM classes on template elements.
- Check responsive breakpoints when fixing layout issues.
- Pre-read (design system): load
designSystem.canonicalDoc + tokenFiles from docs/project-config.json so fixes use real token names (--brand-*, $brand-*) and canonical component classes — not invented values.
Required skills (priority order): ui-ux-pro-max (design-intelligence DB) → web-design-guidelines (principles) → design --lane=marketing (implementation patterns).
Workflow:
FIRST — run ui-ux-pro-max searches to understand context and common issues:
python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "<product-type>" --domain product
python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "<style-keywords>" --domain style
python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "accessibility" --domain ux
python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "z-index animation" --domain ux
If the user provides screenshots/videos, use the visual analysis tooling skill to describe the issue in detail so developers can predict the root causes.
🛑 After identifying the UI root cause, present findings + proposed fix → ask the user directly → wait for approval before any code change.
- Use the
ui-ux-designer subagent to implement the fix step by step (against the design guideline — designSystem.canonicalDoc).
- Capture screenshots (at the exact parent container, not the whole page) and analyze with the appropriate Gemini skill (
visual analysis tooling, video-analysis, or document-extraction) so the result matches the design guideline and addresses all issues. Repeat until addressed.
- Use the browser automation tooling to verify the fix matches the design guideline.
- Use the
tester subagent to compile and test; report back. Repeat until all tests pass.
- If the user approves: run the
project-manager and docs-manager subagents in parallel to update plan progress and ./docs; have project-manager also create/update a project roadmap at ./docs/project-roadmap.md.
- Report a summary; suggest next steps. Then run
$prove-fix.
The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
Workflow:
If user provides screenshots or videos, use visual analysis tooling skill to describe issue in detail; ensure developers can predict root causes from description.
Fulfill the request
Question Everything: Use ask the user directly tool to ask probing questions to fully understand user's request, constraints, true objectives. Don't assume — clarify until 100% certain.
- Use ask the user directly to clarify any open questions.
- Ask 1 question at a time; wait for answer before next question.
- No questions → start next step.
⚠️ Validate Before Fix (NON-NEGOTIABLE): After root cause + plan creation, MUST ATTENTION present findings + proposed fix plan to user by asking the user directly and get explicit approval BEFORE any code changes. No silent fixes.
End-to-Start Trace Gate: For non-trivial bugs, failed verification, stale/incorrect final outputs, or behavior-changing fixes, the root-cause plan MUST ATTENTION include Debugger Trace: End -> Start, feeder paths, hypothesis matrix, owning fix layer, and forward convergence proof. If missing, STOP and run $debug-investigate or $investigate before planning code changes. (The Root-Cause Prerequisite Gate already forces this at invocation time; this gate re-checks the content of the resulting trace.)
Fix the issue
Active-goal read (BEFORE root-cause work): resolve the active Goal Contract per SYNC:goal-contract-satisfaction-loop — active plan goal.md → plans/goals/{YYMMDD-HHmm}-{slug}/goal.md → create from the reported issue via .claude/templates/goal-contract-template.md. The saved success criteria define what "fixed" means — a proven local fix that misses a saved required criterion is NOT complete. After proof, append root cause, proof evidence, and remaining goal gaps to the Iteration Log. Tiny fixes may skip deeper gates ONLY with user-accepted reason recorded in the goal file.
Use sequential-thinking skill to break complex problems into sequential thought steps.
Use problem-solving skills to tackle issues.
Analyze skills catalog and activate other needed skills during the process.
- Use
debugger subagent to find root cause and report back to main agent. Skip this step when the Root-Cause Prerequisite Gate already ran $debug-investigate for this problem — that report subsumes this step; resume at step 3 (planning) instead of re-tracing. — why: re-running diagnosis double-runs the spine.
1.5. Write investigation results to .ai/workspace/analysis/{issue-name}.analysis.md. Re-read ENTIRE file before planning fix.
1.6. Confirm the report contains final symptom -> reader -> storage/projection -> writer -> consumer/job -> producer/origin, all feeder paths, hypothesis matrix, owning fix layer, and forward convergence proof.
- Use
researcher subagent to research root causes on internet (if needed) and report back.
- Use
planner subagent to create implementation plan based on reports; report back.
- 🛑 Present root cause + fix plan → ask the user directly → wait for user approval.
- Use
$plan-execute SlashCommand to implement plan step by step.
- Final Report:
- Report back to user with summary of changes; explain briefly; guide user to get started; suggest next steps.
- Ask user whether to commit and push to git; if yes, use
git-manager subagent.
- IMPORTANT: Sacrifice grammar for concision when writing reports.
- IMPORTANT: List unresolved questions at end of reports, if any.
REMEMBER:
Generate images with visual analysis tooling skills on the fly for visual assets.
Read and analyze generated assets with visual analysis tooling skills to verify they meet requirements.
For image editing (removing background, adjusting, cropping), use media processing tooling as needed.
After fixing, MUST ATTENTION run $prove-fix — build code proof traces per change with confidence scores. Never skip.
Spec-Loop completion gate (canonical: SYNC:spec-loop-discipline). The fix is NOT done until the touched invariants close the loop: (1) every §4 [HARD] rule / §5 invariant the bug violated has a universally-quantified property TC ("for ALL inputs in {domain}, {invariant} holds") + boundary counter-case — not just the single reproduction example (this is the property bar the §3 regression-TC must meet, not merely an example case); (2) the fixed core-logic line is mutation-killed — if a mutant survives on the changed line the killing test is missing, so the bug can silently return (MUTATION-SCORE bar, not line-coverage %); (3) the finding fed BOTH the spec and the tests per the §3 spec-correctness decision AND a guarding test (Dual-Feedback) — a code-only patch with neither leaves the disease undocumented. Re-verify spec + tests + code together before declaring the fix complete.
Next Steps (Standalone: after the Minimum Contract completes. Skip if inside workflow.)
The Root-Cause Prerequisite Gate and the Standalone Mode Minimum Contract above are NOT optional and NOT a question — standalone $fix has already auto-run debug-investigate (gate-enforced) → fix spine → $prove-fix → conditional $spec check → ($changes-review for production code) → $why-review as the terminal sign-off. Do not re-ask the user whether to do those; they are the guaranteed floor.
AFTER that floor is met, MUST ATTENTION use ask the user directly to offer what lies BEYOND the minimum (user decides):
- "Proceed with full workflow (Recommended)" — Hand off to the best-fit workflow (e.g.
workflow-bugfix) from here to add the remaining gates the minimum spine omits — plan-validate, integration-test authoring/review/verify, production-readiness-review, security-review, changelog, docs-update.
- "$test" — Run the full test suite to verify the fix in context.
- "Commit & push" — Hand the proven, reviewed change to the
git-manager subagent.
- "Stop here" — Minimum contract satisfied; user takes it from here.
If already inside a workflow, skip both the contract and this menu — the workflow sequence handles diagnosis, spec sync, review, and next steps.
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. Prevents context loss from long files. For simple tasks, MUST ATTENTION ask user whether to skip.
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. Rea
…(truncated)
1---2name: fix3description: [Implementation] Use when you need to analyze and fix issues [INTELLIGENT ROUTING]. Flag: --target={ci|issue|logs|test|types|ui} scopes the fix; --target=types resolves TypeScript errors inline.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, merge steps without explicit user approval.
52> **[BLOCKING]** Before each step or sub-skill call, update task tracking: `in_progress` on start, `completed` on end.
53> **[BLOCKING]** Every completed/skipped step MUST include evidence or explicit skip reason.
54> **[BLOCKING]** If Task tools unavailable, maintain equivalent step-by-step plan tracker with same status transitions.
55
56<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
57
58## Quick Summary
59
60**Goal:** Eliminate the root cause of an issue using parallel subagent investigation — traced end-to-start with `file:line` evidence and fixed at the lowest invariant-owning layer (never the crash site) — then prove the fix with `$prove-fix` so the disease is cured, not just the symptom.
61
62**Summary:**
63
64- **Purpose:** an intelligent fix router that cures the disease, not the symptom — diagnose root cause with evidence, fix at the lowest invariant-owning layer, prove it with `$prove-fix`, then keep spec + tests + code in sync.
65- **Router first (`--target=`):** with `--target={ci|issue|logs|test|types|ui}` clear the Root-Cause Prerequisite Gate, then jump to that self-contained inline branch (each runs its own diagnosis + `$prove-fix`); no flag = run the full diagnose→fix spine. — why: branches must not re-run §1/§2 of the standalone spine, but no branch is exempt from having a traced root cause.
66- **Main steps (no-flag spine):** Root-Cause Prerequisite Gate → scout (parallel subagents) → diagnose root cause end-to-start (`debug-investigate`, `file:line` evidence, hypothesis matrix, forward convergence proof) → Confidence & Evidence Gate → plan with impact analysis → 🛑 Validate-Before-Fix approval → implement at the owning layer → `$prove-fix` → conditional `$spec` correctness check → `$changes-review` (production code) → `$why-review` terminal sign-off.
67- **Root-Cause Prerequisite Gate (BLOCKING, runs FIRST):** a direct `$fix` call — no-flag spine **and** every `--target=` branch — MUST NOT edit code until `$debug-investigate` produced a root cause for THIS problem in THIS session, proven by a the current task list row or a written investigation report (memory is not evidence; a parent workflow row alone is not proof). Not run → run `$debug-investigate` first, then resume from the planning step. — why: otherwise the first edit lands with zero traced cause and patches the symptom site.
68- **Three hard gates that cannot be skipped:** the Root-Cause Prerequisite Gate (above), the Confidence & Evidence Gate (declare `Confidence: X%` + `file:line`, STOP if <60%) and the 🛑 Validate-Before-Fix approval (present root cause + plan by asking the user directly before any code change — skip approval only inside a workflow).
69- **Diagnose before patching:** trace the symptom end-to-start to the invariant-owning layer, and NEVER fix at the crash site — the crash site is a symptom, the cause enters at a lower layer.
70- **Mode + skip rules:** default mode HARD (full rigor) unless ALL 5 trivial-bug opt-out conditions hold; standalone (no parent workflow) self-assembles the minimum spine `debug-investigate → fix + prove-fix → $spec correctness check → $changes-review (production code) → $why-review`; inside a workflow this whole contract is SKIPPED — **except the Root-Cause Prerequisite Gate, which never skips**: it still demands proof the sequence actually ran `debug-investigate` for this problem. — why: standalone has no sequence supplying diagnosis, spec sync, or review; and a workflow row is not proof its diagnosis step ran.
71
72**Workflow:**
73
741. **Scout** — Use scout/researcher subagents to explore issue in parallel
752. **Diagnose** — Trace root cause through code paths with evidence
763. **Plan** — Create fix plan with impact analysis
774. **Fix** — Implement and verify the fix
78
79**Key Rules:**
80
81- **Root-Cause Prerequisite Gate (BLOCKING):** no code edit until `$debug-investigate` traced THIS problem in THIS session — evidence, not recall
82- Debug Mindset: every claim needs `file:line` evidence
83- Use subagents for parallel investigation of multiple hypotheses
84- Always create a plan before implementing complex fixes
85- **Target flag** (see [Target Routing](#target-routing---target)): `--target={ci|issue|logs|test|types|ui}` selects a self-contained inline branch that scopes the fix to that domain. No flag = full diagnose→fix spine below.
86
87## Default Mode Policy
88
89> **Default mode HARD (full rigor).** Every section below — parallel scout/researcher subagents, root-cause tracing with `file:line` evidence, Confidence & Evidence Gate, fix plan with impact analysis, preservation tests for the bug — applies by default.
90>
91> **Opt out to fast mode ONLY when ALL true** (bug genuinely trivial):
92>
93> - Root cause obvious from error message AND already located (no diagnosis needed)
94> - Single-file fix, ≤10 lines changed
95> - No cross-service impact, no contract change
96> - Test for bug already exists OR bug non-functional (typo, log message)
97> - Confidence in fix ≥95% without further investigation
98>
99> **Any condition fails → use full protocol below.** When in doubt, default hard. Skipping diagnosis on non-trivial bug fixes symptom and leaves disease.
100>
101> **Fast mode skips (and only skips):** parallel subagent investigation (direct read/grep instead), separate fix plan (inline change), regression-test authoring (only if covering test exists). Does NOT skip Confidence & Evidence Gate, Behavioral Delta Matrix, or running existing test suite.
102
103## 🛑 Root-Cause Prerequisite Gate (Direct `$fix` Invocation) — BLOCKING
104
105> **[BLOCKING] `$fix` MUST NOT edit code until `$debug-investigate` has produced a root cause for THIS problem in THIS session.** This gate runs BEFORE the Standalone Mode Minimum Contract below, BEFORE any `--target=` branch body, and BEFORE the 🛑 Validate-Before-Fix approval. — why: `$fix` invoked directly can otherwise reach its first edit with zero traced root cause, which patches the symptom site and ships the disease.
106>
107> **1. Trigger — ALL direct `$fix` invocations.** User-typed slash command or model-selected skill; every `--target={ci|issue|logs|test|types|ui}` branch **and** the no-flag spine alike. The `--target=` branches do NOT re-run §1/§2 of the contract below, but they DO pass through this gate. — why: a branch's own `debugger`/`tester` subagent step is not an end-to-start root-cause trace, so scoping the run does not remove the need for one.
108>
109> **2. Check — evidence, never memory.** Before the first code edit, determine whether `$debug-investigate` already ran **in this session, for this same problem**. Accept ONLY:
110>
111> - a the current task list row for `debug-investigate` (or its phase tasks) covering this symptom, **or**
112> - a written investigation report naming this symptom (e.g. `.ai/workspace/analysis/{issue-name}.analysis.md`, `plans/reports/debug-investigate-*.md`) containing the end-to-start trace.
113>
114> **No such evidence → treat as NOT run.** Recalling that the cause "is known" is not evidence. — why: after context compaction the model's belief that it already investigated survives while the actual findings do not.
115>
116> **3. Act.** Not run → run `$debug-investigate` on the problem FIRST, then resume the `$fix` spine **from its planning step** using that root-cause report. This subsumes the spine's internal step-1 `debugger` subagent (identical to the contract's §1 rule below). — why: re-running diagnosis after the skill already traced it double-runs the spine.
117>
118> **4. Same-problem test.** A prior `$debug-investigate` for a **different** symptom does NOT satisfy this gate. Satisfaction binds to the problem, not to the skill name. When the current `<issues>` names a symptom the existing report does not cover, the gate FIRES. — why: one investigation per session would otherwise license unlimited untraced fixes.
119>
120> **5. Skip conditions — explicit, narrow, and recorded.** Record which one applies with its proof; never skip silently:
121>
122> | Condition | Skip? |
123> | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
124> | Same-problem evidence per §2 exists → cite the `file:line` / task-row proof and proceed | YES |
125> | Fast-mode-trivial bug (**ALL 5** `Default Mode Policy` opt-out conditions hold) → MAY inline the end-to-start trace instead of spawning the skill; the trace itself is still REQUIRED | PARTIAL |
126> | Active parent workflow row whose sequence **already executed** `debug-investigate` for this problem → cite the completed step | YES |
127> | Active parent workflow row **alone**, with no completed `debug-investigate` step for this problem | **NO** |
128>
129> **The last row is the hole this gate closes.** The contract below detects standalone mode by the mere _presence_ of a parent workflow row (`Detect mode`, §"Standalone Mode Minimum Contract"); a row can exist while the sequence's `debug-investigate` step never ran, ran for a different symptom, or was skipped. This gate ADDS the stricter requirement — proof of execution for THIS problem — on top of that detection; it never relaxes it. — why: presence of a container task is not evidence that the work inside it happened.
130>
131> **BLOCKED until:** the §2 check is stated with its evidence (or its explicit skip row + proof) AND a root-cause trace for this problem exists. **NEVER** proceed to plan or edit on "the cause is obvious" alone.
132
133## Standalone Mode Minimum Contract (Non-Workflow Only)
134
135> **`$fix` is normally a step inside `workflow-bugfix`** — there the sequence (`scout → investigate → debug-investigate → spec [mode=amend] → plan → … → fix → prove-fix → … → spec [mode=sync] → workflow-review-changes`) supplies the diagnosis, spec sync, and review around the fix. **Called STANDALONE, no sequence supplies them.** `$fix` alone diagnoses and patches code; it does NOT by itself guarantee the root cause was traced to its owning layer, that the Feature Spec under `docs/specs/` still matches behavior, or that the change was reviewed. Standalone, that gap is symptom-patching + spec/doc drift.
136>
137> **Scope:** this contract governs the **no-flag `$fix` spine** (the full diagnose→fix path). The `--target={ci|issue|logs|test|types|ui}` branches are self-contained — each runs its own diagnosis + `$prove-fix` — so they do NOT re-run §1/§2 here; standalone, they inherit only **§3 (spec-correctness check)** and **§4 (why-review)** as their trailing gates (and `--target=issue` already owns its own `$changes-review` gate — see that branch).
138>
139> **Detect mode:** call the current task list first (per the Nested Task Expansion Contract below). **Active parent workflow row present → this whole section is SKIPPED** (the workflow owns these steps; duplicating them double-runs the spine) — **but the Root-Cause Prerequisite Gate above still applies**: skipping this section requires the parent sequence's `debug-investigate` step to be _completed for this problem_, not merely present. Row present + that step not run → the gate fires and `$debug-investigate` runs first. **No parent row → standalone:** before the first code edit, MUST ATTENTION self-assemble this minimum bugfix spine as task tracking todos, in order:
140>
141> 1. **`$debug-investigate`** — _root cause, FIRST; mandated by the Root-Cause Prerequisite Gate above, whose §2 evidence check decides whether it already ran for this problem._ Trace the symptom end-to-start to the invariant-owning layer with `file:line` evidence (hypothesis matrix + forward convergence proof). This **is** the standalone diagnosis — it subsumes the spine's internal step-1 `debugger` subagent; resume the spine from its planning step using this report. _Fast-mode-trivial bugs (ALL Default Mode Policy opt-out conditions met) MAY inline the trace instead of spawning the skill, but the end-to-start trace is still required._
142> 2. **Fix spine** — _this skill's_ `plan → 🛑 approve → implement → `$prove-fix`` body below. The Validate-Before-Fix approval gate and `$prove-fix` are unchanged.
143> 3. **`$spec` spec-correctness check** — _CONDITIONAL, ensures spec docs aren't left stale._ From the proven root cause, decide which case holds:
144> - **Spec was WRONG / stale** — it described behavior that was never true, or intended behavior changed and the spec wasn't updated. The spec is (part of) the defect → run `$spec [mode=amend]` to correct the §1-§7 spec, then `$spec [mode=sync]` to reconcile §8 `TC-{FEATURE}-{NNN}` ↔ integration tests.
145> - **Spec was CORRECT, the code just failed to meet it** — pure code defect; §1-§7 behavior now matches the spec again. **No §1-§7 amendment.** But still check the §8 test cases: if the bug reproduced a scenario/edge case that **no existing `TC-{FEATURE}-{NNN}` covered** (the spec was _correct but lacked the bug case_), add a regression test case via `$spec [mode=tests]` so the spec captures it, then `$spec [mode=sync]` to reconcile §8 ↔ the new regression test. Only if an existing TC already covered the case do you record `Spec verified correct, bug case already in §8 — no spec change (code-only defect)` with `file:line` evidence and move on. Never leave a fixed bug whose case is absent from the spec's §8.
146> - **No governing spec exists** — the buggy area has no Feature Spec under `docs/specs/`. Record `No governing spec — nothing to amend` with `file:line` evidence; if the area now warrants one, run `$spec [mode=init]` (then `[mode=tests]` to seed §8 with the bug case as a regression TC) rather than only suggesting it. _Decide the case explicitly — skip only the amendment, never the decision; never leave the bug case undocumented when a spec governs the area._
147> 4. **`$why-review`** — _rationale review, the FINAL todo (after the fix AND after any `$changes-review`)._ Terminal sign-off on the converged change: root cause correctly owned, fix at the lowest invariant-owning layer (not the crash site), no symptom-patching, regression covered, and the §3 spec decision justified. Reporting "done" is blocked until this passes. _Non-functional-trivial fixes (typo, log/comment text; fast-mode) MAY satisfy this inline/briefly rather than spawning the full skill — symmetric with §1._
148>
149> **Production-code fixes** also get a `$changes-review` todo **before** §4 (the broad code review whose validated fixes may change the diff; §4 then signs off on the result). `$changes-review` placement and the inside-workflow skip are owned by the shared Standalone Review Gate below — reference it; do not restate the mandate. **Final standalone todo order:** `debug-investigate → [fix spine + prove-fix] → spec-check → changes-review (if production code) → why-review`.
150
151## Debug Mindset (NON-NEGOTIABLE)
152
153**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.**
154
155- Verify each hypothesis against an actual code trace before acting — do NOT assume first hypothesis correct — why: the first guess is usually the nearest-attention trap, not the cause
156- Every root cause claim must include `file:line` evidence
157- If you cannot prove root cause with code trace, state "hypothesis, not confirmed"
158- Question assumptions: "Is this really the cause?" → trace actual execution path
159- Challenge completeness: "Are there other contributing factors?" → check related code paths
160- No "should fix it" without proof — verify fix addresses traced root cause
161
162## ⚠️ MANDATORY: Confidence & Evidence Gate
163
164**MANDATORY IMPORTANT MUST ATTENTION** declare `Confidence: X%` with evidence list + `file:line` proof for EVERY claim.
165**95%+** recommend freely | **80-94%** with caveats | **60-79%** list unknowns | **<60% STOP — gather more evidence.**
166
167**Ultrathink** plan and start fixing these issues; follow Orchestration Protocol, Core Responsibilities, Subagents Team, Development Rules:
168<issues>$ARGUMENTS</issues>
169
170## Target Routing (`--target=`)
171
172`$fix` is an intelligent router. With no flag it runs the full diagnose→fix spine below. Pass `--target=` to scope the run to a self-contained inline branch:
173
174| `--target` | Behavior |
175| ---------- | --------------------------------------------------------------- |
176| `types` | **Inline branch (below)** — TypeScript / type-error resolution. |
177| `ci` | **Inline branch (below)** — CI / pipeline failure triage. |
178| `issue` | **Inline branch (below)** — tracked issue / ticket resolution. |
179| `logs` | **Inline branch (below)** — log / stack-trace-driven debugging. |
180| `test` | **Inline branch (below)** — failing-test repair. |
181| `ui` | **Inline branch (below)** — UI / visual-defect fixes. |
182
183No `--target` (or an unrecognized value) → run the full Workflow spine below; infer the right specialization from `<issues>`.
184
185> **Formerly standalone skills.** `--target=ci|issue|logs|test|ui` were previously the separate skills `/fix-ci`, `/fix-issue`, `/fix-logs`, `/fix-test`, `/fix-ui`; they are now inline branches of `$fix` (folded — the standalone names no longer exist).
186
187### `--target=types` — TypeScript / type-error branch
188
189Run `tsc --noEmit` (or `nx build` / `bun run typecheck` / `npx tsc`) to gather all type errors, then:
190
1911. **Collect** — Capture every type error with `file:line`.
1922. **Classify** — Group by cause: missing types, wrong signatures, import/export issues.
1933. **Fix at root** — Give each value its real, specific type (or `unknown` + a narrowing guard). Do NOT use `any` to silence the checker — `any` ships the underlying type defect. Fix the root cause (wrong interface, missing export), not the symptom site. — why: `any` silences the checker and lets the type defect ship.
1944. **Repeat** until `tsc --noEmit` is clean — zero type errors.
1955. **🛑 Validate Before Fix:** present errors + root cause by asking the user directly, get approval before code changes (skip if inside a workflow).
1966. **After fixing, run `$prove-fix`** — build code proof traces per change with confidence scores. Never skip.
197
198The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
199
200### `--target=ci` — CI / pipeline-failure branch
201
202**Goal:** Analyze CI/CD pipeline logs to identify and fix build/test failures in the configured CI provider/tooling.
203
204**Key Rules:**
205
206- **Infrastructure context:** read `docs/project-config.json` → `infrastructure.cicd.tool` to identify the CI provider/tooling (e.g. `azure-devops`, `github-actions`, `gitlab-ci`); target that provider's pipeline config files.
207- Focus on CI-specific issues (env vars, Docker, dependencies, build order).
208- Verify the fix does not break local development.
209
210**Workflow:**
211
2121. Use the `debugger` subagent to read the CI logs via the configured CI tool/API (from `docs/project-config.json`), analyze the final failing log/error **backward** to the root cause, and report back. Write findings to `.ai/workspace/analysis/{ci-issue}.analysis.md`; re-read before implementing.
2132. **🛑 Present root cause + proposed fix → ask the user directly → wait for approval.**
2143. Implement the fix from the report.
2154. Use the `tester` subagent to verify; report back.
2165. If tests fail, repeat from step 2.
2176. Report a summary of changes; suggest next steps. Then run `$prove-fix`.
218
219**Notes:** Use the CLI/API for the configured CI provider. If it is GitHub Actions and `gh` is unavailable, instruct the user to install and authorize GitHub CLI first.
220
221The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
222
223### `--target=issue` — tracked-issue / ticket branch
224
225**Goal:** Investigate and fix bugs reported as tracked issues (e.g. GitHub issues) with full traceability.
226
227**Active-goal read (BEFORE root-cause work):** resolve the active Goal Contract per `SYNC:goal-contract-satisfaction-loop` (active plan `goal.md` → `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md` → create from the issue). Map the ticket's acceptance criteria to the saved success criteria; after the fix, append proof evidence and remaining gaps to the Iteration Log. Closure is blocked while any required criterion remains FAIL.
228
229**Key Rules:**
230
231- Link the fix back to the issue for traceability.
232- Verify the fix addresses the specific reproduction steps from the issue.
233
234**Workflow:**
235
2361. Activate the `debug-investigate` skill and follow its workflow — this step **satisfies** the Root-Cause Prerequisite Gate for this problem; record its report path as the gate's §2 evidence. See `.claude/docs/AI-DEBUGGING-PROTOCOL.md` for comprehensive guidelines.
2372. Use external memory at `.ai/workspace/analysis/issue-[number].analysis.md` for structured analysis. **Re-read the ENTIRE analysis file before proposing any fix.**
2383. **🛑 Present root cause + proposed fix → ask the user directly → wait for approval before implementing.**
2394. Implement, then run `$prove-fix`.
240
241> **Standalone Review Gate (non-workflow only):** any standalone production-code fix — the no-flag spine (Standalone Mode Minimum Contract above) **or** `$fix --target=issue` — adds a `$changes-review` task tracking todo as the **final changes-review gate**, placed immediately before the contract's §4 `$why-review` terminal sign-off (spec-check → changes-review → why-review). Inside a workflow, skip — the sequence handles `$changes-review`.
242
243The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
244
245### `--target=logs` — log / stack-trace branch
246
247**Goal:** Analyze application logs to diagnose and fix runtime errors or unexpected behavior.
248
249**Key Rules:**
250
251- Focus on log patterns: stack traces, error codes, timing anomalies.
252- Cross-reference logs with source code to find the actual root cause.
253
254**Workflow:**
255
2561. Check whether `./logs.txt` exists. If missing, set up permanent log piping in the project's script config (`package.json`, `Makefile`, `pyproject.toml`, …): **Bash/Unix** append `2>&1 | tee logs.txt`; **PowerShell** append `*>&1 | Tee-Object logs.txt`. Run the command to generate logs.
2572. Use the `debugger` subagent to analyze `./logs.txt`: read with `Grep` `head_limit: 30` (last 30 lines; increase if needed — avoid loading the whole file). Write analysis to `.ai/workspace/analysis/{issue-name}.analysis.md`; re-read before fixing.
2583. Use the `scout` subagent to locate the exact source of the issue; report back.
2594. Use the `planner` subagent to create an implementation plan; report back.
2605. **🛑 Present root cause + fix plan → ask the user directly → wait for approval.**
2616. Implement the fix.
2627. Use the `tester` subagent to verify; report back.
2638. Use the `code-reviewer` subagent to review the changes; report back.
2649. If tests fail, repeat from step 3.
26510. Report a summary; suggest next steps. Then run `$prove-fix`.
266
267The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
268
269### `--target=test` — failing-test branch
270
271**Goal:** Run test suites, analyze failures, and fix the underlying code or test issues.
272
273**Active-goal read (BEFORE fixing):** resolve the active Goal Contract per `SYNC:goal-contract-satisfaction-loop` (active plan `goal.md` → `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md` → create from the reported test failure). Map failing-test evidence (before) and passing-test evidence (after) to the saved success criteria in the Iteration Log — a passing suite that misses a saved required criterion does NOT close the loop.
274
275**Key Rules:**
276
277- Distinguish between code bugs and flawed test expectations.
278- Re-run tests after the fix to confirm all pass.
279- Read `docs/project-reference/integration-test-reference.md` before reviewing/writing integration tests; consult `docs/specs/` for expected-behavior context when diagnosing failures.
280
281**Workflow:**
282
2831. Use the `tester` subagent to compile the code and fix any syntax errors.
2842. Use the `tester` subagent to run the tests; report back. Write failure analysis to `.ai/workspace/analysis/{test-issue}.analysis.md`; re-read before fixing.
2853. If tests fail, use the `debugger` subagent to find the root cause; report back.
2864. Use the `planner` subagent to create an implementation plan; report back.
2875. **🛑 Present root cause + fix plan → ask the user directly → wait for approval.**
2886. Implement the plan step by step.
2897. Use the `tester` subagent to verify; report back.
2908. Use the `code-reviewer` subagent to review the changes; report back.
2919. If tests fail, repeat from step 2.
29210. Report a summary; suggest next steps. Then run `$prove-fix`.
293
294The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
295
296### `--target=ui` — UI / visual-defect branch
297
298**Goal:** Diagnose and fix UI/UX issues — layout, styling, responsiveness, and visual bugs.
299
300**Key Rules:**
301
302- Always use BEM classes on template elements.
303- Check responsive breakpoints when fixing layout issues.
304- **Pre-read (design system):** load `designSystem.canonicalDoc` + `tokenFiles` from `docs/project-config.json` so fixes use real token names (`--brand-*`, `$brand-*`) and canonical component classes — not invented values.
305
306**Required skills (priority order):** `ui-ux-pro-max` (design-intelligence DB) → `web-design-guidelines` (principles) → `design --lane=marketing` (implementation patterns).
307
308**Workflow:**
309
310**FIRST** — run `ui-ux-pro-max` searches to understand context and common issues:
311
312```bash
313python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "<product-type>" --domain product
314python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "<style-keywords>" --domain style
315python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "accessibility" --domain ux
316python $HOME/.claude/skills/ui-ux-pro-max/scripts/search.py "z-index animation" --domain ux
317```
318
319If the user provides screenshots/videos, use the `visual analysis tooling` skill to describe the issue in detail so developers can predict the root causes.
320
321> **🛑 After identifying the UI root cause, present findings + proposed fix → ask the user directly → wait for approval before any code change.**
322
3231. Use the `ui-ux-designer` subagent to implement the fix step by step (against the design guideline — `designSystem.canonicalDoc`).
3242. Capture screenshots (at the exact parent container, not the whole page) and analyze with the appropriate Gemini skill (`visual analysis tooling`, `video-analysis`, or `document-extraction`) so the result matches the design guideline and addresses all issues. Repeat until addressed.
3253. Use the browser automation tooling to verify the fix matches the design guideline.
3264. Use the `tester` subagent to compile and test; report back. Repeat until all tests pass.
3275. **If the user approves:** run the `project-manager` and `docs-manager` subagents in parallel to update plan progress and `./docs`; have `project-manager` also create/update a project roadmap at `./docs/project-roadmap.md`.
3286. Report a summary; suggest next steps. Then run `$prove-fix`.
329
330The Debug Mindset, Confidence & Evidence Gate, and all SYNC gates below apply to this branch unchanged.
331
332## Workflow:
333
334If user provides screenshots or videos, use `visual analysis tooling` skill to describe issue in detail; ensure developers can predict root causes from description.
335
336### Fulfill the request
337
338**Question Everything:** Use ask the user directly tool to ask probing questions to fully understand user's request, constraints, true objectives. Don't assume — clarify until 100% certain.
339
340- Use ask the user directly to clarify any open questions.
341- Ask 1 question at a time; wait for answer before next question.
342- No questions → start next step.
343
344> **⚠️ Validate Before Fix (NON-NEGOTIABLE):** After root cause + plan creation, MUST ATTENTION present findings + proposed fix plan to user by asking the user directly and get explicit approval BEFORE any code changes. No silent fixes.
345> **End-to-Start Trace Gate:** For non-trivial bugs, failed verification, stale/incorrect final outputs, or behavior-changing fixes, the root-cause plan MUST ATTENTION include `Debugger Trace: End -> Start`, feeder paths, hypothesis matrix, owning fix layer, and forward convergence proof. If missing, STOP and run `$debug-investigate` or `$investigate` before planning code changes. (The Root-Cause Prerequisite Gate already forces this at invocation time; this gate re-checks the _content_ of the resulting trace.)
346
347### Fix the issue
348
349**Active-goal read (BEFORE root-cause work):** resolve the active Goal Contract per `SYNC:goal-contract-satisfaction-loop` — active plan `goal.md` → `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md` → create from the reported issue via `.claude/templates/goal-contract-template.md`. The saved success criteria define what "fixed" means — a proven local fix that misses a saved required criterion is NOT complete. After proof, append root cause, proof evidence, and remaining goal gaps to the Iteration Log. Tiny fixes may skip deeper gates ONLY with user-accepted reason recorded in the goal file.
350
351Use `sequential-thinking` skill to break complex problems into sequential thought steps.
352Use `problem-solving` skills to tackle issues.
353Analyze skills catalog and activate other needed skills during the process.
354
3551. Use `debugger` subagent to find root cause and report back to main agent. **Skip this step when the Root-Cause Prerequisite Gate already ran `$debug-investigate` for this problem** — that report subsumes this step; resume at step 3 (planning) instead of re-tracing. — why: re-running diagnosis double-runs the spine.
356 1.5. Write investigation results to `.ai/workspace/analysis/{issue-name}.analysis.md`. Re-read ENTIRE file before planning fix.
357 1.6. Confirm the report contains final symptom -> reader -> storage/projection -> writer -> consumer/job -> producer/origin, all feeder paths, hypothesis matrix, owning fix layer, and forward convergence proof.
3582. Use `researcher` subagent to research root causes on internet (if needed) and report back.
3593. Use `planner` subagent to create implementation plan based on reports; report back.
3604. **🛑 Present root cause + fix plan → ask the user directly → wait for user approval.**
3615. Use `$plan-execute` SlashCommand to implement plan step by step.
3626. Final Report:
363
364- Report back to user with summary of changes; explain briefly; guide user to get started; suggest next steps.
365- Ask user whether to commit and push to git; if yes, use `git-manager` subagent.
366
367* **IMPORTANT:** Sacrifice grammar for concision when writing reports.
368* **IMPORTANT:** List unresolved questions at end of reports, if any.
369
370**REMEMBER:**
371
372- Generate images with `visual analysis tooling` skills on the fly for visual assets.
373- Read and analyze generated assets with `visual analysis tooling` skills to verify they meet requirements.
374- For image editing (removing background, adjusting, cropping), use media processing tooling as needed.
375
376- **After fixing, MUST ATTENTION run `$prove-fix`** — build code proof traces per change with confidence scores. Never skip.
377
378> **Spec-Loop completion gate (canonical: `SYNC:spec-loop-discipline`).** The fix is NOT done until the touched invariants close the loop: (1) every §4 [HARD] rule / §5 invariant the bug violated has a **universally-quantified property TC** ("for ALL inputs in {domain}, {invariant} holds") + boundary counter-case — not just the single reproduction example (this is the property bar the §3 regression-TC must meet, not merely an example case); (2) the fixed core-logic line is **mutation-killed** — if a mutant survives on the changed line the killing test is missing, so the bug can silently return (MUTATION-SCORE bar, not line-coverage %); (3) the finding fed BOTH the spec and the tests per the §3 spec-correctness decision AND a guarding test (Dual-Feedback) — a code-only patch with neither leaves the disease undocumented. Re-verify spec + tests + code together before declaring the fix complete.
379
380---
381
382## Next Steps (Standalone: after the Minimum Contract completes. Skip if inside workflow.)
383
384> **The Root-Cause Prerequisite Gate and the Standalone Mode Minimum Contract above are NOT optional and NOT a question** — standalone `$fix` has already auto-run `debug-investigate` (gate-enforced) → fix spine → `$prove-fix` → conditional `$spec` check → (`$changes-review` for production code) → `$why-review` as the terminal sign-off. Do not re-ask the user whether to do those; they are the guaranteed floor.
385>
386> **AFTER that floor is met,** MUST ATTENTION use ask the user directly to offer what lies BEYOND the minimum (user decides):
387
388- **"Proceed with full workflow (Recommended)"** — Hand off to the best-fit workflow (e.g. `workflow-bugfix`) from here to add the remaining gates the minimum spine omits — `plan-validate`, `integration-test` authoring/review/verify, `production-readiness-review`, `security-review`, `changelog`, `docs-update`.
389- **"$test"** — Run the full test suite to verify the fix in context.
390- **"Commit & push"** — Hand the proven, reviewed change to the `git-manager` subagent.
391- **"Stop here"** — Minimum contract satisfied; user takes it from here.
392
393> If already inside a workflow, skip both the contract and this menu — the workflow sequence handles diagnosis, spec sync, review, and next steps.
394
395> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. Prevents context loss from long files. For simple tasks, MUST ATTENTION ask user whether to skip.
396
397- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
398
399<!-- SYNC:end-to-start-debugger-trace -->
400
401> **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.
402>
403> 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.
404> 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.
405> 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.
406> 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.
407> 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.
408> 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.
409>
410> **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.
411>
412> **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.
413
414<!-- /SYNC:end-to-start-debugger-trace -->
415
416<!-- SYNC:root-cause-debugging -->
417
418> **Root Cause Debugging** — Systematic approach, never guess-and-check.
419>
420> 1. **Reproduce** — Confirm the issue exists with evidence (error message, stack trace, screenshot)
421> 2. **Isolate** — Narrow to specific file/function/line using binary search + graph trace
422> 3. **Trace** — Follow data flow from input to failure point. Rea
423
424…(truncated)