/prime:fixfrom prime
Formal bug fix pipeline — root cause analysis, scope lock, behavior contract, differential testing, regression proof. Usage: /fix <description|#issue> <--severity critical|high|medium|low> <--hotfix|--lite|--lite-strict|--verified|--full|--swarm> <--decisions off|shadow|enforce>
Ships in prime. Installing the plugin adds it to Claude Code.
A rigorous bug fix workflow grounded in formal methods. Every step is verifiable. Every guardrail is enforceable. No guessing.
The correctness pipeline:
| Step | Formal Method | What It Proves |
|---|---|---|
| 1. Root Cause Swarm | Competing Hypotheses + Adversarial Debate | Multiple strategies converge on the actual cause |
| 2. Scope Lock | Graph Reachability | Fix only touches what it needs to |
| 3. Behavior Contract | Hoare Logic | We know what should and shouldn't change |
| 4. Implement Fix | Scoped Agent | Changes stay within the Fix Zone |
| 4b. Review Swarm | Parallel Adversarial Review | Independent reviewer + QA attacker agree the fix is correct |
| 5. Differential Test | Bisimulation + Mutation | Fix changes ONLY bug behavior, nothing else |
| Input | Action |
|---|---|
/fix POST /auth/refresh returns 500 | Free-text bug description |
/fix #123 | Load bug from GitHub issue |
/fix #123 --severity critical | With explicit severity |
/fix #123 --hotfix | Critical: expedited path (single backward trace) |
/fix #123 --lite | Force Lite investigation depth (1 round, 2 agents) — auto-escalates to Full if confidence is LOW |
/fix #123 --lite-strict | Force Lite AND disable A2 auto-escalation AND bypass fix-reviewer pre-gate FAIL — full explicit override for budget-capped or CI runs |
/fix #123 --verified | Force Verified investigation depth (1 analyst + 1 challenger) — auto-detection's default when no other signal fires |
/fix #123 --full | Force Full investigation depth (3 rounds, 3 agents) |
/fix #123 --swarm | Alias for --full |
/fix --severity high token refresh fails silently | Severity + description |
/fix #123 --decisions shadow | Per-invocation Arth Decisions mode override (off|shadow|enforce, see below) |
Investigation depth flags (--hotfix / --lite / --lite-strict / --verified / --full / --swarm):
--hotfix is the cheapest (1 backward-tracer), used for production fires where you trust the symptom--lite is what auto-detection picks when a smoking-gun traceback is in the description; A2 will auto-escalate to Full if the lite verdict is low confidence--verified forces the middle depth (1 analyst + 1 challenger) — the documented auto-detect default; the flag exists so the default depth can be forced explicitly like every other depth--lite-strict is the full explicit-override flag: runs lite WITHOUT auto-escalation, accepts the lite verdict as-is on low confidence, AND bypasses the fix-reviewer pre-gate FAIL verdict (Step 4b.1) — trust the user across both safety nets. The pre-gate still runs and surfaces its verdict; --lite-strict just converts a FAIL into a warning rather than a BLOCK.--full (alias --swarm) is what auto-detection picks for auth/payments/migrations/security-touching bugsArth Decisions flag (orthogonal to depth):
--decisions off|shadow|enforce (legacy --jev) — per-invocation override of the Arth Decisions mode (ladder: flag → ARTH_DECISIONS_MODE env → project .claude/qa-config.json → .claude/.arth-decisions.env → global ~/.arthai/config.json; see skills/_lib/decisions-guard.md §3). Resolved once in A1-J via decisions.sh mode. off is byte-identical to today. Unknown value → warn and treat as unset.If no severity provided, assess automatically in Step 1.
Empty-arg handling (A1): If /fix was invoked with no description and no
#N reference, prompt for one before proceeding:
🔍 /fix — what bug should I fix?
Describe in 2-3 sentences (or paste a traceback / GitHub issue #N).
[type description, or 'cancel' to exit]
Use AskUserQuestion with a single free-text option ("Describe the bug…") plus
"Cancel / exit". If the user types cancel or hits the cancel option, print
/fix: cancelled. Re-run with a description anytime. and exit cleanly. If the
user types text, treat it as the bug description and continue normally.
In non-interactive mode (CI / autopilot), missing description is a hard
error — don't prompt; print /fix: bug description required (positional arg or #N issue ref) and exit non-zero.
Non-interactive mode (applies to the whole run): active when env
CLAUDE_AUTOPILOT=1 or CI=true, or when the run was Monitor/webhook-triggered
(see Monitor Integration). In non-interactive mode the skill never prompts.
Checkpoints with a documented non-interactive default take it:
[auto] (already its default; the 1.3-J fix_depth recommendation applies to it when Arth Decisions is not off)Safety checkpoints with no safe default — non-convergence pick, DEPTH-INSUFFICIENT confirmation, review-swarm BLOCK, QA-failure fix/skip/abort — hard-stop with a clear error naming the checkpoint. Never improvise an answer to a safety prompt.
If #N provided — load the GitHub issue:
gh issue view N --json title,body,labels,assignees,comments
Extract: description, reproduction steps, affected area, any labels (bug, critical, etc.)
If free-text — use as the bug description directly.
Sync with remote (MANDATORY — run before any investigation):
# Refuse if there are uncommitted changes — they'd be lost or muddy the rebase
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "✗ Uncommitted changes present — commit, stash, or discard before /fix"
exit 1
fi
git fetch origin
DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')
DEFAULT_BRANCH=${DEFAULT_BRANCH:-main}
git pull --rebase origin "$DEFAULT_BRANCH" || {
echo "✗ Rebase conflicts against origin/$DEFAULT_BRANCH — resolve before continuing the fix"
echo " Run: git rebase --abort (then sync manually before re-running /fix)"
exit 1
}
Why: prevents two failure modes — (a) investigating a bug that was already fixed on the default branch, and (b) building the fix on a stale base that conflicts at push time. Fail loudly on conflicts; don't auto-resolve. A conflicting base means the codebase shifted under you and a human should look before the fix is built on top.
Revert check (advisory — run immediately after the sync): Run /revert-check on
the working tree — the same guard /pr and /qa already run — to catch accidental
reverts of recently-merged work. It runs EARLY here, per issue #311: a buffered revert
of a recently-merged fix can masquerade as the bug under investigation and get encoded
into the scope lock as a fake root cause. Non-blocking: if it flags files, surface them
to the user before continuing the investigation.
Compiled Memory Context (arth-memory Tier 0.5 — if configured): the first
rung of the 3-rung ladder (full contract: skills/_lib/arth-memory-tier05.md).
Attempted ONLY when both bash gates below pass — each line is a single
trivial command (a compound block trips the Bash guard — keep each command
trivial, same discipline as the org-memory block further down):
bash skills/_lib/arth-memory.sh status # must print "configured" — anything else → skip to Knowledge Graph Context below (marketplace-plugin path: "${CLAUDE_PLUGIN_ROOT}/skills/_lib/arth-memory.sh" — same fallback idiom as this file's usage-counter.sh call)
grep -m1 '^ARTH_MEMORY_HEALTH=' .claude/.arth-memory.env 2>/dev/null # must be ARTH_MEMORY_HEALTH=ok — anything else (or missing file) → skip to Knowledge Graph Context below
bash skills/_lib/arth-memory.sh scope-key # → owner/repo; becomes the compile_context scope_key arg
If both gates pass, call mcp__arth-memory__compile_context with:
scope_key — the scope-key output abovetask — the same 3-5 keywords extracted from the bug description that the
kg-query call below uses (extract once, reuse for both — do not derive a
second keyword set)budget: 2000If the tool is unavailable, errors, or returns empty: inject nothing and fall through to the kg-query call below, unchanged (the OKF read stays active too).
On success: prepend the result under ## Compiled Memory Context (arth-memory), [mem:…] citation tokens preserved verbatim, AND skip the
"Consult the org memory KB" OKF read below (D3′ — same org memory; the
compiled, cited form supersedes the raw file-read).
Knowledge Graph Context (fallback rung — supplemental; run before Tier 0-1 KB reads; fires when arth-memory is absent, unhealthy, or returned nothing above):
KG_SCRIPT="${CLAUDE_PLUGIN_ROOT}/skills/knowledge-graph/kg-query.sh" # plugin install: Claude Code substitutes the root at load
[ -f "$KG_SCRIPT" ] || KG_SCRIPT=".claude/skills/knowledge-graph/kg-query.sh" # symlink install
if [ -f "$KG_SCRIPT" ]; then
# Extract keywords from the bug description and query the graph
kg_result=$("$KG_SCRIPT" "<extract 3-5 keywords from bug description>" --top 10 --threshold 0.3 2>/dev/null)
kg_exit=$?
# Exit 0 + non-empty → prepend as supplemental context before reading KB files
# Exit 3 (stale) or Exit 1 (error) or empty → skip graph, proceed with manual KB reads
fi
Rules:
kg-query.sh does not exist: skip silently, proceed normally$kg_result is non-empty: prepend graph output as supplemental context BEFORE Tier 1 readsRead project context (Tier 0→2: read small files fully, grep directories before reading). Run all six reads as parallel tool calls in a single message — they are all independent:
CLAUDE.md for tech stack, test commands, architecture (Tier 0).claude/project-profile.md if it exists (Tier 0).claude/knowledge/shared/domain.md if it exists (Tier 1).claude/qa-knowledge/incidents/ for affected keywords (Tier 2 — selective).claude/qa-knowledge/bug-patterns.md for affected keywords (Tier 2 — selective).claude/wikis/*/wiki/index.md for relevant domain context (Tier 1→2)Check for similar past bugs:
# Search incidents by affected area (Tier 2 — grep-then-read)
grep -rl "{affected_keywords}" .claude/qa-knowledge/incidents/ 2>/dev/null
# Search bug patterns
grep -i "{affected_keywords}" .claude/qa-knowledge/bug-patterns.md 2>/dev/null
# Search topic wikis for domain context on affected area
for idx in .claude/wikis/*/wiki/index.md; do
grep -li "{affected_keywords}" "$idx" 2>/dev/null
done
Consult the org memory KB (arth-memory — if memory-setup has run): SKIPPED
when the Compiled Memory Context block above already succeeded (D3′ — same org
memory, already compiled + cited). Runs only on its absence/failure. The org's
Decisions/Constraints/Facts for the affected area often explain why the code is the way it
is — fixing against the grain of a constraint just re-breaks it. Graceful absence (no-op if
absent). Locate it with simple commands (a single complex bash block trips the Bash guard —
keep each command trivial):
[ "${ARTH_MEMORY:-}" = off ] && echo "memory off — skip org KB" # honor the off switch
ls -d "$HOME"/.arthai/memory/*/arth-memory-okf 2>/dev/null # org KB root(s); skip step if none or if off
git remote get-url origin # → owner/repo
The repo slice is <kb-root>/repos/<owner>/<repo>/ (fall back to <kb-root>/org/ if absent).
Then read it with the Read + Grep tools (not a bash heredoc): Read architecture.md,
and Grep constraints/ + decisions/ for {affected_keywords}, then Read the top
matches. Fold any hits into the bug context the investigation swarm receives.
A matched HARD constraint is authoritative — the fix MUST satisfy it. If the bug exists
because the code violates a constraint, that's your root cause.
If similar past bugs found, show them:
⚠ Similar past incidents found:
• 2026-03-15-token-expiry.md (severity: high, status: covered)
Root cause: token expiry check used wrong timezone
• 2026-02-28-auth-500.md (severity: critical, status: covered)
Root cause: missing null check on session object
Composition Loading + model policy (load ONCE here — every spawn in the run uses them):
Read .claude/registry.json and build three maps from source == "project" entries:
AGENT_SUBSTITUTIONS: composition == "replace" entries with replaces_subagent_type
AGENT_AUGMENTS: composition == "augment" and integrates_with == "fix"
SKILL_EXTENSIONS: composition == "extend" and integrates_with == "fix"
If no registry exists or JSON is malformed, all maps are empty — generic agents run unchanged.
Load model policy: read model-policy.yml (resolve ${CLAUDE_PLUGIN_ROOT}/model-policy.yml first, then ~/.claude-agents/model-policy.yml, then .claude/model-policy.yml) and build
POLICY[agent_key] = { "model", "effort", "fallback" }. Every spawn in this run — the
Step 1.2b explore-light scout, the Step 1.3 investigation swarm, the implementation
agent, and the review swarm — references AGENT_SUBSTITUTIONS['<key>'] or "<default>"
and {POLICY['<key>']['model']} — single source of truth for tier choices.
If unreadable, the hardcoded default inside each spawn stands.
Deprecation fallback: if a spawn errors with model sunset/deprecation, retry
with POLICY[agent_key]['fallback'] and emit a one-line warning. If the fallback
also fails, hard-fail the skill pointing to model-policy.yml. Never silently drop
fix-reviewer or qa-attacker — they are the safety net for the fix.
Loading here (not at Step 4.1b) means calibrate-created investigator substitutes apply to the investigation swarm too, not just to review/implementation spawns.
Goal: Find the actual cause, not a symptom. This is NOT optional — no fix without understanding.
1.1: Reproduce the bug
From the description/issue, determine how to reproduce:
# If it's an API bug — try to hit the endpoint
curl -s -X POST http://localhost:8000/auth/refresh -H "Content-Type: application/json" \
-d '{"refresh_token": "test"}' | head -20
# If it's a test failure — run the specific test
pytest tests/test_auth.py::test_refresh -v
# If it's a UI bug — check the relevant component
If reproduction fails, ask the user for reproduction steps.
1.2: Locate the symptom
Find where the error occurs:
# Search for the error message, status code, or exception
grep -rn "500\|Internal Server Error\|{error_message}" --include="*.py" --include="*.ts"
# Find the route/handler for the affected endpoint
grep -rn "{endpoint_pattern}" --include="*.py" --include="*.ts"
1.2b: Use explore-light for fast codebase search (cost: 1x Haiku)
Before manually grepping, spawn explore-light to quickly locate relevant code
(apply AGENT_SUBSTITUTIONS / POLICY from Step 0):
subagent_type: AGENT_SUBSTITUTIONS['explore-light'] or "explore-light"
model: "{POLICY['explore-light']['model'] or 'haiku'}"
prompt: "Find all code related to {symptom description}. I need:
1. The route/handler for {endpoint or feature}
2. All functions that call or are called by the handler
3. Related test files
4. Any error handling or validation in this code path
Return file paths and line numbers."
This is 60x cheaper than doing the search yourself (Haiku vs Opus). Use the results to focus your manual reading in Step 1.3 — don't read every file, read only what explore-light identified.
1.3: Investigation Swarm — depth selection (A1: auto-default load-bearing)
Auto-detect the appropriate investigation depth — this auto-detection now fires by default. Only ask the user when auto-detection is genuinely uncertain (no clear signal in any direction).
| Signal | Level | Rationale |
|---|---|---|
--hotfix flag | Skip (single backward trace) | Production fire |
| Traceback points to single line ("smoking gun") | Lite + depth-check (1 round, 2 agents, mandatory chain length ≥ 2 in output) | Symptom location is obvious; root cause is not |
| Touches auth/payments/data/migrations/security | Full (3 rounds, 3 agents) — auto-fire | High-risk area |
| Multiple possible causes / unclear reproduction | Full (3 rounds, 3 agents) | Need competing hypotheses |
| User says "this is simple" in description | Lite (chain length ≥ 2 still required) | Trust user, still verify depth |
| None of the above | Verified (1 analyst + challenger) — sensible default | Middle ground |
If auto-detection is genuinely ambiguous (e.g., description has both a traceback AND auth keywords — conflicting signals), only then ask:
Bug complexity estimate: ambiguous (traceback present but touches auth)
Investigation mode:
[1] Lite — 2 agents, 1 round, fastest (~30 units)
[2] Verified — analyst + challenger (moderate, ~60 units)
[3] Swarm — 3 agents, 3 rounds + debate (complex, ~112 units)
[auto] — let me decide based on evidence (default)
Your pick? [auto]
When Arth Decisions is not off and the fix_depth gate (1.3-J below — it runs before this table/prompt is evaluated) returned a recommendation, only the [auto] line of the prompt above gains a suffix, e.g. [auto] — let me decide based on evidence (default · Arth Decisions: lite 0.91). The four options, their order and their labels are a CONTRACT and never change — Arth Decisions annotates, it never adds, removes or reorders an option. Any explicit depth flag (--hotfix/--lite/--lite-strict/--verified/--full/--swarm) bypasses both this table and the gate (Case 1).
Resolve the Arth Decisions mode after the mode/arguments above are parsed and before the A1 mode line prints (ladder + semantics: skills/_lib/decisions-guard.md §3). DECISIONS_FLAG is the value of --decisions (empty when absent):
DECISIONS_MODE_RESOLVED=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions.sh" mode --decisions "${DECISIONS_FLAG:-}" 2>/dev/null || echo off)
This is the only Arth Decisions call in Phase 0 (a missing wrapper resolves to off); the gates arrive in later phases and must read DECISIONS_MODE_RESOLVED rather than re-resolving. The A1 mode line prints · Arth Decisions: {DECISIONS_MODE_RESOLVED} on every variant, and the routing trace's Why: line carries Arth Decisions: {DECISIONS_MODE_RESOLVED} whenever it is not off.
fix_depth (runs before the Step 1.3 table/prompt is evaluated)Execution order: A1-J (mode) → this gate → Step 1.3 auto-detect table / depth prompt → A1 mode line. If DECISIONS_MODE_RESOLVED is off, skip this block entirely — today's behaviour (the Step 1.3 table and, when ambiguous, the prompt decide alone; no Arth Decisions command runs, no scratch file is written). Also skip it when any explicit depth flag was passed (Case 1 — explicit flags bypass every selector). Otherwise write the four inputs and ask ONE command (contract: skills/_lib/decisions-guard.md §11; question file skills/_lib/decisions/fix/depth.json — choice depth + noul smoking_gun_traceback_present), parsing its two-line stdout with the shared idiom:
DECISIONS_TMP=${DECISIONS_TMP:-$(mktemp -d)}
printf '%s\n' "$BUG_DESCRIPTION" > "$DECISIONS_TMP/fix-description.txt"
printf '%s\n' "$TRACEBACK" > "$DECISIONS_TMP/fix-traceback.txt"
git log -5 --format='%h %s' -- $TRACE_FILES > "$DECISIONS_TMP/fix-commits.txt"
grep -rli "$SYMPTOM_KEYWORDS" .claude/qa-knowledge/incidents/ > "$DECISIONS_TMP/fix-incidents.txt" 2>/dev/null
DECISIONS_OUT=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" fix_depth --mode "$DECISIONS_MODE_RESOLVED" --skill fix --step 1.3 --description "$DECISIONS_TMP/fix-description.txt" --traceback "$DECISIONS_TMP/fix-traceback.txt" --commits "$DECISIONS_TMP/fix-commits.txt" --incidents "$DECISIONS_TMP/fix-incidents.txt")
DECISION=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^decision=//p')
FIX_DEPTH_IDS=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^ids=//p')
BUG_DESCRIPTION is the Step 0 description (or the #N issue body); TRACEBACK the pasted traceback, ≤200 lines, first-party frames as pasted (an empty file when there is none); TRACE_FILES the files those frames name (git log -5 of recent commits touching them); SYMPTOM_KEYWORDS the Step 0 error keywords (matching qa-knowledge/incidents/ files — the same lookup 3A.5 of /review-pr makes). FIX_DEPTH_IDS is kept for A2-J.
decision=lite <conf> (enforce; emitted only for depth=lite ≥0.85 AND smoking_gun_traceback_present ≥0.8, both thresholds from the question file) → the same auto-fire path the "smoking gun" table row already takes — depth resolves to Lite + depth-check without the prompt, Arth Decisions supplementing the smoking-gun signal rather than inventing a new one. If the prompt fires anyway (conflicting signals), its [auto] line carries · Arth Decisions: lite <conf> and [auto] (pick or non-interactive) resolves to lite. A2 still runs and can escalate exactly as today.decision=hotfix <conf> · decision=verified <conf> · decision=full <conf> (enforce) → recommendation only: when the prompt fires, its [auto] line carries · Arth Decisions: <depth> <conf>; when [auto] fires (pick or non-interactive) today's auto-detect table decides, not the token (the high-risk auto-Full rows keep precedence).decision=auto (confidence below the act band) · decision=shadow · decision=fallback · decision=off → today's table/prompt, no suffix, nothing printed changes. In shadow the row is logged with the table's own pick as old_decision.Increment usage counter and decide rendering tier:
COUNT=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/usage-counter.sh" increment fix)
TIER=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/usage-counter.sh" should-show-ladder fix)
# TIER ∈ {flashy, dim} — escalation/explicit-flag handled by case logic below
Compute the auto-detection signal (the "why" string):
--hotfix passed?Print the mode line per skills/_lib/mode-line.md spec (v4 ladder).
Case 1 — User passed --hotfix / --lite / --lite-strict / --verified / --full / --swarm:
🔍 /fix {DEPTH} · --{flag} from your input · Arth Decisions: {DECISIONS_MODE_RESOLVED}
Single line — explicit choice.
Case 2 — Auto-fire AND TIER=flashy (first 3 uses or after 30 days):
Render the boxed ladder:
╭─ 🔍 /fix · {DEPTH} mode picked ──────────────────────────────────
│ Why picked: {why — e.g. "smoking gun: app/auth.py:142", "auth/payments detected"} · Arth Decisions: {DECISIONS_MODE_RESOLVED}
│
│ Modes: {ladder showing lite / verified / swarm, → on picked}
│
│ Add-ons: --hotfix (skip non-essential steps for prod fires)
│ Switch: Ctrl-C, ↑, append flag(s), Enter
╰──────────────────────────────────────────────────────────────────
Where {ladder} shows all three depths (picked first, others by cost):
→ lite 1 round, 2 agents ~30u (picked)
verified + challenger round ~60u
swarm 3 agents, 3 rounds, debate ~112u
Case 3 — Auto-fire AND TIER=dim (steady-state):
🔍 /fix {DEPTH} · {short why} · Arth Decisions: {DECISIONS_MODE_RESOLVED} · [?] modes
Single dim line. [?] modes is the persistent escape hatch.
Case 4 — Auto-Full fired due to high-risk signals (auth/payments/migrations):
Always render flashy box even if TIER=dim — the user should see a high-risk
auto-decision was made.
Case 5 — User picked explicitly via the depth prompt (non-auto): Same as Case 1 — single line, no ladder.
If the resolved mode is lite (whether auto-fired from a smoking-gun
traceback or explicitly requested), the investigation is the 2-agent
single-round variant. After it completes, evaluate confidence:
ESCALATE = true IF any of the following:
• The 2 agents disagree on root-cause file:line
• Either agent reports confidence: low
• Either agent says "could not converge on a single cause"
• The hypothesis fails the smoking-gun match (e.g. wrong file referenced)
• [NEW — shallow-agreement] Both agents submitted causation chains of length 1
(no walk-back) — even if they agree
• [NEW — shallow-agreement] Both agents' ROOT link == the smoking-gun traceback line
(symptom == claimed root) AND neither produced a defensible `Stop justification`
When the new shallow-agreement triggers fire, the escalation box's Trigger: line
becomes (e.g.): both agents stopped at the throw site (app/auth.py:142) with no walk-back evidence — symptom, not root cause.
If ESCALATE is true AND the user did NOT pass --lite-strict:
╭─ 🔍 /fix · lite → escalating to full ────────────────────────────
│ Trigger: {why — e.g. "agents disagreed: app/auth.py:142 vs app/session.py:87"}
│ Was: lite (1 round, 2 agents — couldn't resolve)
│ Skipped: verified (also wouldn't resolve a tie)
│ Now: swarm (3 agents, 3 rounds, debate)
│
│ Force lite anyway: Ctrl-C, ↑, append --lite-strict, Enter
╰──────────────────────────────────────────────────────────────────
Spawn the 3rd agent (forward-tracer — the candidate not in the lite team, per the Team composition by depth table below) and proceed to Round 2 (CROSS-CHALLENGE) below as if Full mode had been picked all along.
Append verdict_path: "lite-escalated-to-full" to the audit trail in the
final fix-summary so reviewers know the lite default was insufficient
for this bug.
If ESCALATE is true AND --lite-strict was passed:
Trust the user's explicit override. Print a soft warning but proceed with the lite verdict:
⚠ /fix lite — confidence is LOW but --lite-strict prevents escalation.
Proceeding with the best-available hypothesis. Re-run without --lite-strict
if the fix doesn't pan out.
If ESCALATE is false:
Lite verdict stands. Proceed to Step 1.4 with the converged hypothesis.
A2-J — fix_depth outcome back-fill. If DECISIONS_MODE_RESOLVED is off, or FIX_DEPTH_IDS is empty or {} (gate skipped by an explicit flag, fallback, no ask), skip this — no outcome call. Otherwise, once the depth path has resolved — ESCALATE evaluated above (lite), or the investigation converged without A2 (verified / full / hotfix count as not escalated) — back-fill in shadow exactly as in enforce:
bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" outcome fix_depth --ids "$FIX_DEPTH_IDS" --escalated "$ESCALATED"
ESCALATED is true when ESCALATE fired, else false. The optional --reverted word (fix reverted after merge) has no owner inside /fix — nothing here passes it (PRD Open Questions); a future post-merge consumer may.
Note on --lite-strict: This flag exists specifically as the
A2-escape-hatch for users who want lite-and-only-lite behavior (e.g. CI
budget caps, debugging the auto-escalation logic itself). It's listed in
the argument table above.
Team: fix-investigate-{slug}
The 3 candidate agents:
| Agent | subagent_type | model | Strategy |
|---|---|---|---|
| backward-tracer | code-reviewer | sonnet | Traces backward from symptom through call chain |
| forward-tracer | code-reviewer | sonnet | Checks git log for recent changes in affected area, traces forward |
| pattern-matcher | explore-light | haiku | Searches knowledge base (incidents/, bug-patterns.md) for similar patterns |
Apply AGENT_SUBSTITUTIONS from Step 0 to every investigation spawn —
AGENT_SUBSTITUTIONS['code-reviewer'] or "code-reviewer",
AGENT_SUBSTITUTIONS['explore-light'] or "explore-light" — and read the model tier
from {POLICY['<key>']['model']}, with the table's listed model as the hardcoded
fallback if the policy is unreadable.
Team composition by depth (which candidates actually spawn):
| Depth | Team | Spawn order |
|---|---|---|
| Hotfix | backward-tracer only | single spawn |
| Lite (1 round, 2 agents) | pattern-matcher + backward-tracer | KB-aware: pattern-matcher (Haiku) first, then backward-tracer |
| Verified (1 analyst + challenger) | backward-tracer (analyst) + challenger (AGENT_SUBSTITUTIONS['qa-challenger'] or "qa-challenger", sonnet) | analyst first; challenger receives the analyst's causation chain and attempts to disprove it |
| Full / Swarm (3 rounds, 3 agents) | all 3 candidates | KB-aware reordering below |
Shared cacheable context (build ONCE, reuse across all spawns in this /fix run):
Every spawned agent in this /fix run (investigation swarm, implementation agent, review swarm) receives the same project context. Build it once at the start of Step 1.3, hoist it into a cacheable system-prompt prefix, and reuse it verbatim across every spawn.
Construct SHARED_CONTEXT as a string (concatenate, in this order — keep the order
stable across spawns so the cache hits):
SHARED_CONTEXT = concat(
read(".claude/project-profile.md"), # if exists
read("CLAUDE.md"),
read(".claude/knowledge/shared/conventions.md"), # if exists
read(".claude/knowledge/shared/domain.md"), # if exists
read(".claude/knowledge/shared/vocabulary.md"), # if exists
read(".claude/knowledge/shared/patterns.md"), # if exists
grep_matches(".claude/qa-knowledge/incidents/", affected_keywords), # selective
grep_matches(".claude/qa-knowledge/bug-patterns.md", affected_keywords),
)
Pass it via the Task tool's spawn call as the cacheable prefix:
system: [
{
"type": "text",
"text": SHARED_CONTEXT,
"cache_control": {"type": "ephemeral"} # ← prompt-cache marker
}
]
prompt: <per-agent variable content — role, hypothesis, scope lock, etc.>
See https://docs.claude.com/en/docs/build-with-claude/prompt-caching for the
cache_control semantics. First agent in the run primes the cache; subsequent
agents within the 5-minute TTL read from it.
Rules:
SHARED_CONTEXT is identical byte-for-byte across every spawn within a single
/fix run. Do NOT interpolate per-agent values into it. Per-agent content goes in the
prompt field that follows.cache_hit_count, cache_miss_count, and the total token
count saved on each /fix run. Surface in the fix-summary Telemetry section.Spawn order (KB-aware reordering — Haiku-first, conditional tracers):
root_cause_pattern for the affected area): spawn ONLY ONE Sonnet tracer
(backward-tracer by default) to verify the matched hypothesis. Skip the second tracer.Rationale: 20-30% of fixes in calibrated projects hit the KB. On hits this saves one
Sonnet call ($0.015) and ~30s of parallel-tracer latency. On misses it adds ~3s of
serial latency before the tracers fire — Haiku is fast, the tradeoff is favorable.
Each spawned agent receives: bug description, symptom location (file:line), reproduction steps, and access to CLAUDE.md / project-profile.md. They do NOT share conclusions with each other until Round 2.
Early termination conditions (check before proceeding to Round 2):
Round 1 — HYPOTHESIZE
Each agent submits independently to the orchestrator:
**Hypothesis**: {1-sentence description}
**Causation chain** (required, length ≥ 2, ordered symptom → root; each link cites the connecting call/import/assignment):
1. SYMPTOM — {file}:{line} — {what fails} ← (connection from #2: cite file:line of the call/assignment that propagates state here)
2. PROXIMATE — {file}:{line} — {bad value/state produced here} ← (connection from #3: ...)
3. ROOT — {file}:{line} — {assumption violated; "code assumes X but X is not always true"}
**Stop justification**: why the chain stops at ROOT (e.g., "next hop is third-party / validated input / framework boundary"). Length-1 chains REJECTED unless symptom IS the assumption-violation site (rare, must be justified here).
**Confidence**: high / medium / low
Round 2 — CROSS-CHALLENGE (only if no early termination)
Orchestrator broadcasts all 3 hypotheses to all 3 agents. Each agent attempts to disprove the other two:
## Challenge to {agent}'s hypothesis
**Counter-evidence**: [file:line] — {why it contradicts}
**Verdict**: DISPROVED | WEAKENED | CONSISTENT
Round 3 — FINAL POSITION (only if no convergence after Round 2)
Each agent submits a final hypothesis, incorporating any valid challenges received.
Convergence scoring rubric (depth-aware):
| Signal | Score |
|---|---|
| Evidence citation: verified file:line | +2 per citation |
| Evidence citation: refuted by challenge | -1 per refuted |
| Corroborated by another agent on the SAME ROOT (last chain link) | +3 |
| Causation chain length ≥ 3 with cited walk-back evidence per hop | +2 |
| Causation chain length = 1 (no walk-back) | -3 unless Stop justification is accepted by another agent |
| Hypothesis stops at the throw site (symptom == claimed root) | -2 unless explicitly justified AND corroborated |
| Contradicted with counter-evidence | -2 |
| Pattern match from KB (incidents/, bug-patterns.md) AT THE ROOT link | +2 |
| Pattern match from KB at any other link | +1 |
| Survived cross-challenge intact | +3 |
| Hypothesis disproved by challenge | -3 |
| Walk-back evidence missing for any hop | -1 per missing hop |
Convergence conditions:
| Outcome | When | Action |
|---|---|---|
| DEPTH-INSUFFICIENT | Leading hypothesis has chain length = 1 AND no agent submitted a longer chain | Force walk-back verification (Step 1.4b) BEFORE accepting convergence; if walk-back still returns length-1, escalate to user with the Stop justification for explicit confirmation |
| CONVERGE immediately | All 3 agree on same ROOT (last-link file:line), each with chain length ≥ 2 | Proceed to Step 1.4 |
| CONVERGE | 2 agree on ROOT, 3rd disproved (Round 2), winning chain length ≥ 2 | Adopt majority hypothesis |
| MERGE | 2 agree on ROOT, 3rd's chain is compatible at a deeper link | Adopt the DEEPER chain (3rd's view extends the diagnosis) |
| CONVERGE | Highest score leads by 3+ AND chain length ≥ 2 | Adopt leading hypothesis |
| ESCALATE | Scores within 2 points | Present all 3 to user — do not guess |
Escalation prompt (if no convergence):
⚠ Investigation swarm could not converge — 3 competing hypotheses remain after debate:
backward-tracer (score: {N}):
Root cause: {hypothesis}
Location: {file}:{line}
Key evidence: {citations}
forward-tracer (score: {N}):
Root cause: {hypothesis}
Location: {file}:{line}
Key evidence: {citations}
pattern-matcher (score: {N}):
Root cause: {hypothesis}
Location: {file}:{line}
Key evidence: {citations}
Which should we pursue?
[1] backward-tracer's diagnosis
[2] forward-tracer's diagnosis
[3] pattern-matcher's diagnosis
[4] Investigate all — there may be multiple bugs
1.4: Identify root cause
The root cause is the earliest point in the dependency chain where behavior diverges from the specification. It's where "this code assumes X but X is not always true."
Document using the same causation-chain schema as Round 1 (one schema, used twice — no parallel "Root Cause Chain" structure):
**Hypothesis**: {1-sentence description}
**Causation chain** (length ≥ 2, ordered symptom → root):
1. SYMPTOM — {file}:{line} — {what fails} ← (connection from #2: cite file:line)
2. PROXIMATE — {file}:{line} — {bad value/state produced here} ← (connection from #3: ...)
3. ROOT — {file}:{line} — {assumption violated}
**Stop justification**: why the chain stops at ROOT. Length-1 chains REJECTED unless symptom IS the assumption-violation site (rare, must be justified here).
**When it breaks**: {specific conditions that trigger the bug}
**When it works**: {conditions under which the bug doesn't manifest}
**Swarm verdict**: {CONVERGE | MERGE | user-resolved} — {which agents agreed}
1.4b: Walk-back verification (mandatory, post-convergence)
Before locking in the root cause, verify it is the EARLIEST divergence point. Walk back N=3 hops from the symptom and check each:
For each hop H from 1 to N:
Output:
**Walk-back verification:**
Hop 1 upstream of root ({root_file}:{root_line}):
→ Checked {file}:{line} — assumption {X} holds here. Root is not deeper at this hop.
Hop 2 upstream:
→ Checked {file}:{line} — assumption {Y} holds here. Root is not deeper at this hop.
Hop 3 upstream:
→ Reached system boundary ({external input / framework call / validated source}). Stop.
**Verdict: ROOT CONFIRMED at {file}:{line}** (or **ROOT MOVED DEEPER to {new_file}:{new_line}** — restart Step 1.4)
If the walk-back moves the root deeper, restart Step 1.4 with the new root and re-run walk-back from there. Cap: 3 walk-back iterations per fix (prevents infinite chains).
This step runs as a single Sonnet call (~$0.003) using the existing investigation context — no new agent spawn required.
1.5: Assess severity (if not provided)
| Signal | Severity |
|---|---|
| Production users affected NOW | critical |
| Data corruption or security | critical |
| Feature broken but workaround exists | high |
| Edge case, rare trigger | medium |
| Cosmetic, no functional impact | low |
Goal: Determine exactly which files the fix may touch and which are OFF LIMITS.
2.1: Build dependency graph from root cause
Starting from the root cause location, trace outward:
Hop 0 (ROOT CAUSE): The file/function with the bug
→ Read the file, identify the broken function
Hop 1 (DIRECT DEPENDENCIES): Files the root cause imports from or is called by
→ grep for imports in the root cause file
→ grep for who imports/calls the root cause function
Hop 2 (INDIRECT): Files that depend on hop-1 files
→ Same grep pattern, one level out
Hop 3+: Everything else
Execute with actual code analysis:
# Hop 0: root cause file
ROOT_FILE="backend/app/services/auth.py"
# Hop 1: what does root cause import?
grep -E "^from|^import" "$ROOT_FILE" | grep -v "^from typing\|^import os\|^import json"
# Hop 1: who imports root cause?
grep -rl "from.*auth import\|import.*auth" backend/ --include="*.py"
# Hop 2: extend one more level from hop 1 results
# (repeat the above for each hop 1 file)
2.2: Classify zones
Write the scope lock document — this is the guardrail for the entire fix:
## Scope Lock — {bug description}
### Fix Zone (ALLOWED — may modify)
{Files at the ROOT link of the causation chain (Step 1.4), plus any files on the chain
between root and symptom that the fix must traverse}
- {root_link_file}:{lines} — ROOT: {why this needs to change}
- {intermediate_chain_file}:{lines} — if fix spans multiple chain links
- {symptom_file} — ONLY if symptom is the root, OR if the root cannot be fixed at its location and a defensive check at the symptom is added IN ADDITION TO the root fix
- {test_file} — regression test goes here
### Watch Zone (CAUTION — may be affected)
{Files at hop 2 that might be affected by the fix}
- {file} — {how it relates, what to watch for}
### Frozen Zone (BLOCKED — must NOT modify)
{Everything else — especially:}
- All files outside the dependency chain
- Migration files (unless root cause is in schema)
- Config files (unless root cause is in config)
- Unrelated services/modules
- Frontend (if backend bug) or vice versa
2.3: Set up enforcement
Save the scope lock to a file that the implementation step reads:
# Write scope lock for the implementation agents
cat > .claude/.fix-scope-lock.json << 'EOF'
{
"bug": "{description}",
"severity": "{severity}",
"root_cause": "{file}:{line}",
"fix_zone": ["{file1}", "{file2}", "{test_file}"],
"watch_zone": ["{file3}", "{file4}"],
"frozen_zone_patterns": ["migrations/*", "frontend/*", "*.lock"],
"created_at": "{timestamp}"
}
EOF
The implementation agent reads this and is BLOCKED from editing files outside fix_zone.
The pre-edit-guard hook can enforce this if .claude/.fix-scope-lock.json exists.
Goal: Define exactly what the fix should change and what must stay the same.
3.1: Extract existing contracts
For each function in the Fix Zone, extract its behavioral contract:
From type signatures:
# Reading: def refresh_token(token: str) -> TokenPair
# Contract: str → TokenPair (not str → Exception)
From existing passing tests:
# Run tests that touch Fix Zone files BEFORE the fix
# Each passing test = a behavioral contract that must be preserved
pytest tests/test_auth.py -v --tb=no 2>&1
# Output:
# test_login_valid_creds PASSED → contract: valid creds → token
# test_login_invalid_creds PASSED → contract: invalid creds → 401
# test_refresh_valid_token FAILED → THIS IS THE BUG
# test_refresh_expired_token PASSED → contract: expired → 401
From API schemas/validators:
# Check route definitions for response models
grep -A10 "@router.post.*refresh" backend/app/api/auth.py
# Check Pydantic models, Zod schemas, etc.
From database constraints:
# Check model definitions for invariants
grep -A20 "class.*Token\|class.*Session" backend/app/models/*.py
3.2: Build the behavior contract table
## Behavior Contract — {bug description}
### Behaviors That MUST CHANGE (fix verification)
| Input | Current (broken) | Expected (after fix) | Test |
|-------|-----------------|---------------------|------|
| refresh("valid_token") | 500 Internal Server Error | 200 + new TokenPair | WRITE NEW |
| refresh("tampered_token") | 500 Internal Server Error | 401 Unauthorized | WRITE NEW |
### Behaviors That MUST NOT CHANGE (regression protection)
| Input | Current (correct) | After Fix (same) | Test |
|-------|------------------|------------------|------|
| login("user", "pass") | 200 + TokenPair | 200 + TokenPair | EXISTING: test_login_valid |
| login("user", "wrong") | 401 | 401 | EXISTING: test_login_invalid |
| refresh("expired_token") | 401 | 401 | EXISTING: test_refresh_expired |
| GET /me with valid token | 200 + User | 200 + User | EXISTING: test_get_me |
### Invariants (always true, before and after)
- Tokens table: every token has a user_id (FK constraint)
- Sessions table: expired sessions are never returned by get_active_session()
- Auth: no endpoint returns 200 without valid authentication
3.3: Capture baseline test results
# Run ALL tests and save results — this is the "before" snapshot
# for differential testing in Step 5
#
# Use the project's ACTUAL test commands from CLAUDE.md Test Commands table
# or project-profile.md testing conventions. Examples for common stacks:
#
# Python: pytest --tb=line -q
# Node: npm test -- --watchAll=false
# Go: go test ./... -count=1
# Rust: cargo test
# Ruby: bundle exec rspec --format progress
# Java: ./gradlew test
# Swift: swift test
# Flutter: flutter test
#
cd {project_root}
# Backend (use detected test command)
{backend_test_command} 2>&1 | tee /tmp/fix-baseline-backend.txt
# Frontend (if applicable, use detected test command)
{frontend_test_command} 2>&1 | tee /tmp/fix-baseline-frontend.txt
# Save pass/fail counts
echo "Baseline captured at $(date)" > .claude/.fix-baseline-summary.txt
grep -cE "passed|PASSED|ok|OK" /tmp/fix-baseline-backend.txt >> .claude/.fix-baseline-summary.txt || true
grep -cE "failed|FAILED|FAIL|ERROR" /tmp/fix-baseline-backend.txt >> .claude/.fix-baseline-summary.txt || true
Save to .claude/.fix-behavior-contract.md for the implementation and QA steps.
Goal: Apply the minimal fix within the scope lock, write regression tests.
4.1: Determine implementation approach
Based on severity:
| Severity | Approach |
|---|---|
| critical / --hotfix | Fix directly (no /planning, no team). Minimal change. |
| high | Fix directly with code-reviewer validation. |
| medium | Consider if /planning is needed for architectural changes. |
| low | Standard flow — may batch with other work. |
4.1b: Composition + policy application (maps loaded in Step 0)
AGENT_SUBSTITUTIONS, AGENT_AUGMENTS, SKILL_EXTENSIONS, and POLICY were built at
the end of Step 0 (Composition Loading + model policy) — the explore-light scout and the
investigation swarm already consumed the substitutions. Apply them to the implementation
and review phases below; the deprecation-fallback rule from Step 0 applies to every spawn.
After the implementation agent completes, spawn any AGENT_AUGMENTS to review the fix
from a project-specific angle (e.g., auth-specialist reviews auth fixes).
Augmented agents focus on project-specific concerns only — they don't redo the generic
agent's work. Give them: "The generic agent handled the fix. Review it for project-specific
issues only — domain rules, convention violations, past incidents in this area."
Run SKILL_EXTENSIONS at their specified phase:
pre-baseline: before fix attempt (e.g., capture baseline state)post-baseline: after fix, before verification (e.g., domain constraint check)post-main: after verification passes, as final gate4.2: Spawn implementation agent
Select the right agent based on which layer the bug is in.
Apply AGENT_SUBSTITUTIONS from Step 0 (see 4.1b) — check if the subagent_type
has a replacement before spawning.
| Bug is in... | Spawn | subagent_type | Why |
|---|---|---|---|
| Backend (any language) | backend agent | AGENT_SUBSTITUTIONS['python-backend'] or python-backend | Adaptive — detects Python/Node/Go/Rust/Ruby/Java/Elixir at runtime |
| Frontend (any framework) | frontend agent | AGENT_SUBSTITUTIONS['frontend'] or frontend | Adaptive — detects React/Vue/Svelte/Angular/etc. at runtime |
| Both layers | backend + frontend | Both (with substitutions applied) | Scope lock keeps each in their zone |
| Unknown | general-purpose | general-purpose | Fallback — reads project-profile.md for context |
If .claude/project-profile.md exists, read it to determine the platform and pick the right agent.
Check AGENT_SUBSTITUTIONS first — calibrate-created agents take priority over manual detection.
4.2-J: Arth Decisions lane selector (spawn_lane) — right-sizes the model tier and reasoning effort of THIS implementation spawn; model-policy.yml alone gives a one-line null guard and a race-condition fix the same lane. If DECISIONS_MODE_RESOLVED is off, skip this block entirely — today's behaviour (the spawn uses POLICY exactly as written, no Arth Decisions command runs, no scratch file is written). Also skip it for an agent with no POLICY entry (general-purpose). Otherwise ask ONE command per implementation agent before spawning it (contract skills/_lib/decisions-guard.md §11; question file $(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions/shared/spawn-lane.json, shared with /implement):
DECISIONS_TMP=${DECISIONS_TMP:-$(mktemp -d)}
DECISIONS_OUT=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" spawn_lane --mode "$DECISIONS_MODE_RESOLVED" --skill fix --step 4.2 --agent "$LANE_AGENT_KEY" --task "$DECISIONS_TMP/fix-lane-task.md" --files "$(cat "$DECISIONS_TMP/fix-lane-files.json")" --goal "$BUG_TITLE" --policy-model "$LANE_POLICY_MODEL" --policy-effort "$LANE_POLICY_EFFORT")
LANE_DECISION=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^decision=//p')
LANE_IDS=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^ids=//p')
LANE_RUNG=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^rung=//p')
LANE_AGENT=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^agent=//p')
Router rung (three-rung ladder: router → decisions → policy). The gate works WITH the Arth Router, not beside it: Arth Decisions JUDGES the sub-task, the router DECIDES the final model + effort from that judgment plus plan pace, credits, governance and the org's past outcome labels, and the static model-policy.yml lane is the floor and the last fallback. Whenever ARTH_ROUTER_URL is set and the mode is enforce, decisions-state.py itself sends ONE /route request through skills/_lib/arth-router.sh (2 s deadline, zero retries) — on EVERY asked spawn, not only when Arth Decisions moved the lane, because the router sees pace and credits that Arth Decisions cannot: the redacted sub-task text, a type_hint, Arth Decisions' judgments as task.context hints (complexity, blast_radius, risk, tool_use_reliability_needed, latency_sensitivity — each only when its own confidence cleared act — plus protected_path, hint_source=arth-decisions, hint_confidence), options.llms limited to the Claude tiers the floors allow and options.harnesses=["claude-code"]. The router's answer is final and the floors apply to it again (it may raise, never lower past a floor — an answer floored back onto the policy lane prints policy floor with rung=router); router down / slow / error → Arth Decisions' own lane; Arth Decisions down → POLICY. The rung that decided is printed on a third stdout line (rung=router|decisions|policy, plus router=<decision_id> when the router answered) and recorded on the decision row. shadow never calls the router for this gate (the would-be request is logged on the row); off runs nothing.
Inputs — written with the Write tool before the call (never whole files, never SHARED_CONTEXT, never a secret): $DECISIONS_TMP/fix-lane-task.md = the root cause line, the causation chain and the Behavior Contract's MUST CHANGE rows (the same variable content the agent's prompt carries; the builder keeps the first 4,000 characters); $DECISIONS_TMP/fix-lane-files.json = the Fix Zone paths as a JSON list; BUG_TITLE = the bug description's first line or the issue title; LANE_AGENT_KEY = python-backend or frontend; LANE_POLICY_MODEL / LANE_POLICY_EFFORT = POLICY[LANE_AGENT_KEY]['model'] (or sonnet when the policy is unreadable) and ['effort'] (empty when the entry has none) — the old_decision, shadow baseline and fallback.
Branch on LANE_DECISION (enforce only; every other token → POLICY exactly as today):
<model> <effort> <down|up|mixed> (optionally followed by floor) → spawn THIS implementation agent with model=<model>. The effort half is only real when the gate printed a non-empty LANE_AGENT: Claude Code reads a sub-agent's reasoning effort from its DEFINITION's frontmatter effort: and the Task tool has no per-spawn effort input, so a non-empty LANE_AGENT names the generated <agent-key>-effort-<level> definition — spawn THAT subagent_type instead of the plain one (a byte-for-byte copy of the agent apart from name: and effort:). When LANE_AGENT is empty the chosen effort is ADVISORY: append the single line Reasoning effort for this sub-task: <effort>. to the END of the prompt field (never into SHARED_CONTEXT — the cached prefix stays byte-identical) and expect nothing from it; the gate records effort_status (advisory) and the outcome call leaves that dimension unlabelled. The gate will never print one for a haiku lane — Haiku's model has no reasoning-effort setting at all, so a haiku low answer moves the tier only and the row records effort_status: not_applicable. Nor will it when CLAUDE_CODE_EFFORT_LEVEL is set, which outranks every agent definition (effort_status: env_override). Print ⚙️ /fix lane: <policy model> → <model>/<effort> · Arth Decisions: <down|up|mixed> · rung: <LANE_RUNG>. down is the cost win, up the quality win; both are logged.policy · policy floor · pinned · shadow · fallback · off → spawn with POLICY exactly as today.LANE_IDS and the lane the spawn actually carried (LANE_USED_MODEL, LANE_USED_EFFORT; effort default when none was passed) for the outcome call after 4.4 ({} → no outcome call).Floors Arth Decisions can never lower (enforced in decisions-state.py): the investigation and review swarms are NOT asked about — code-reviewer (backward-tracer, forward-tracer, fix-reviewer) prints pinned with no ask, and the review lane stays on its policy pin; a migration / auth / payment path in the Fix Zone, or the requires_migration / touches_auth_or_payment noul at or above its flag threshold (0.3), keeps the lane at or above POLICY's tier and effort (trailing floor); uncertain or a confidence below act (0.8) keeps POLICY. The Step 0 deprecation fallback applies to an Arth Decisions-chosen model too.
4.2b: Escalation protocol for fix agents
Include this in the implementation agent's prompt:
## When Your Fix Doesn't Work (MANDATORY)
1. After first failed attempt: re-read the root cause analysis from Step 1.
Is the root cause correct? If not, go back to Step 1.
2. After second failed attempt: consult knowledge base:
- .claude/qa-knowledge/ (error keywords)
- .claude/knowledge/shared/conventions.md (project gotchas)
- git log --all --grep="<error keyword>" --oneline -10
3. After third failed attempt: STOP. Do not try another fix.
Generate a STUCK REPORT and send to team-lead (in /fix, "team-lead" is the
orchestrator running this skill — there is no separate team-lead agent):
- Error: [exact message]
- Root cause hypothesis: [from Step 1]
- Fix attempts: [1, 2, 3 with results]
- KB consultation results: [what you found]
- Recommendation: [re-investigate root cause / ask user for X / try different approach]
4. If a troubleshooter agent is available, team-lead may spawn one — same procedure
as /implement's escalation handling: spawn `troubleshooter` with the stuck report
+ error context, relay its diagnosis back; if its confidence is LOW, escalate to
the user with structured options.
Agent prompt structure — apply prompt caching (see Step 1.3 "Shared cacheable context"). The Task spawn uses two parts:
system: [{
"type": "text",
"text": SHARED_CONTEXT, # ← identical to swarm spawns; cache-hits
"cache_control": {"type": "ephemeral"}
}]
prompt: <the variable content below>
Items 4–6 below are already in SHARED_CONTEXT — do not duplicate them into the
prompt. Items 1–3 are per-spawn variable content and go in the prompt field.
Agent prompt (variable content — goes in the prompt field) includes:
1. Root cause analysis from Step 1 (includes the causation chain)
2. Scope lock from Step 2 (Fix Zone ONLY)
3. Behavior contract from Step 3
(4–6 supplied via SHARED_CONTEXT — DO NOT duplicate here)
INSTRUCTIONS:
- You may ONLY modify files listed in the Fix Zone: {fix_zone_files}
- If you need to modify a file NOT in the Fix Zone, STOP and explain why
- The root cause is: {root_cause_description} at {file}:{line}
- Your fix must satisfy the Behavior Contract:
- All "MUST CHANGE" rows must work after your fix
- All "MUST NOT CHANGE" rows must still work after your fix
- Write regression tests that:
a) Test the "MUST CHANGE" behaviors (prove the bug is fixed)
b) Would FAIL if the fix were reverted (prove the test catches this bug)
- The fix must modify the code at or near the ROOT link of the causation chain, NOT
at the SYMPTOM link. The causation chain is:
{causation_chain_from_step_1}
Your changes should land at link N (the root), or between link N and link N-1 (the
proximate cause) if and only if the root link is in untouchable code (third-party,
framework, generated). If you find yourself editing the SYMPTOM link's file, STOP
and explain why the upstream root cannot be fixed instead.
- Keep changes MINIMAL relative to the root cause — not minimal relative to the
symptom. A 1-line fix at the symptom that doesn't address the root cause is REJECTED
by the review swarm (Step 4b). A 5-line fix at the root cause that prevents the bad
state from being produced is preferred.
- This is a bug fix, not a refactor: do not restructure code, rename variables, or
reorganize modules unless directly required to fix the root cause.
- Follow the project's coding conventions from project-profile.md / knowledge base
- Use the project's test framework (detected from profile or CLAUDE.md, not assumed)
4.3: Scope guard validation
After the agent finishes, verify scope compliance:
# What files were actually modified?
CHANGED=$(git diff --name-only)
# Check each against scope lock
for file in $CHANGED; do
if echo "{fix_zone_files}" | grep -q "$file"; then
echo "✓ $file (in Fix Zone)"
elif echo "{watch_zone_files}" | grep -q "$file"; then
echo "⚠ $file (in Watch Zone — needs justification)"
else
echo "✗ $file (in FROZEN ZONE — VIOLATION)"
fi
done
If ANY Frozen Zone file was modified → BLOCK and require explanation. If Watch Zone files were modified → WARN and require justification.
4.4: Regression test validation (Mutation Testing)
Verify the regression test actually catches the bug:
# 1. Save the fix
git diff > /tmp/fix.patch
# 2. Revert the fix temporarily
git checkout -- .
# 3. Run ONLY the new regression test — it MUST FAIL
pytest tests/test_auth_refresh_regression.py -v 2>&1
# Expected: FAIL (bug exists, test catches it)
# 4. Re-apply the fix
git apply /tmp/fix.patch
# 5. Run the regression test again — it MUST PASS
pytest tests/test_auth_refresh_regression.py -v 2>&1
# Expected: PASS (bug fixed, test confirms it)
If the test passes both with and without the fix → the test is USELESS. It doesn't actually verify the bug. Reject it and write a better test.
If the test fails both with and without the fix → the fix is BROKEN. The fix doesn't actually resolve the bug. Go back to Step 1.
Only valid result: FAIL without fix, PASS with fix.
4.4-J: spawn_lane outcome back-fill. If DECISIONS_MODE_RESOLVED is off, or LANE_IDS is empty or {} (gate skipped, pinned, fallback, no ask), skip this — no outcome call. Otherwise, once 4.3 and 4.4 have resolved for that agent, back-fill in shadow exactly as in enforce (the label: did the spawned sub-task succeed first time on the lane it ran with):
bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" outcome spawn_lane --ids "$LANE_IDS" --result "$LANE_RESULT" --model "$LANE_USED_MODEL" --effort "$LANE_USED_EFFORT" --gates-passed "$LANE_GATES_PASSED" --rework-cycles "$LANE_REWORK_CYCLES" --failure-cause "$LANE_FAILURE_CAUSE"
LANE_GATES_PASSED is true when 4.4 gave FAIL-without / PASS-with, else false; LANE_REWORK_CYCLES is the number of failed attempts the agent reported (0 unless retried). LANE_FAILURE_CAUSE (empty unless LANE_RESULT is retried / escalated / failed) separates label noise from lane noise, from what this run already saw: plan when the STUCK REPORT named a missing requirement, a wrong root cause or a Behavior Contract the plan got wrong — the lane was not the reason; implementation when the agent had everything it needed and still got it wrong; unknown when neither is clear. A plan cause is EXCLUDED from the lane's label and never reported to the router (the row is annotated and left unlabelled), the same way the router drops an overridden decision — otherwise a plan gap would teach the lane that a perfectly adequate model was too small. One label set: when the router rung decided, the same command also reports the label to the router for the recorded router decision_id — once, idempotency key spawn-lane:<Arth Decisions decision id>: ok_first_try → success (+ gates_passed), retried → success with rework_cycles, escalated / failed → failure, overridden when the spawn did not run the router's pick, evaluation_id from .arthai-eval-attempt when that file exists.
LANE_RESULT comes from what this step already observed — never a fresh judgment: ok_first_try (the agent returned without reporting a failed attempt, 4.3 found no Frozen Zone violation, and 4.4 gave FAIL-without / PASS-with on its first pass); retried (the agent reported one or more failed attempts under 4.2b before succeeding, or 4.3 / 4.4 sent it back once); escalated (STUCK REPORT, troubleshooter, or the user was asked); failed (4.4 ended in "the fix is BROKEN — go back to Step 1", or the orchestrator took the fix over). A deprecation-fallback retry is not a retry.
Goal: Two independent agents review the fix simultaneously from different angles — one checks correctness, one attacks it. Their cross-examination produces a more reliable verdict than a single reviewer could.
Team: fix-review-{slug}
Two code paths, decided once by DECISIONS_MODE_RESOLVED (4b-J below):
off · shadow · fallback — spawn these 2 agents in parallel, exactly as today (shadow additionally asks the fix_review gate for calibration only, after fix-reviewer returns, with --old-decision spawn; its answer gates nothing).enforce — sequential: 4b.1 fix-reviewer runs alone first; the fix_review gate reads its output; 4b.2 qa-attacker spawns only on spawn_attacker.Spawn these 2 agents in parallel (off/shadow/fallback; in enforce 4b.2 is conditional and spawns after 4b.1 returns):
| Agent | subagent_type | model | Role |
|---|---|---|---|
| fix-reviewer | code-reviewer | sonnet | 7-point correctness checklist |
| qa-attacker | qa-challenger | sonnet | Generate 3-5 attack scenarios against this specific fix |
4b.1: Spawn fix-reviewer (apply AGENT_SUBSTITUTIONS from Step 0)
The Task call uses prompt caching (Step 1.3 "Shared cacheable context") — pass
SHARED_CONTEXT as the cacheable system prefix, then the variable prompt below.
system: [{"type": "text", "text": SHARED_CONTEXT, "cache_control": {"type": "ephemeral"}}]
subagent_type: AGENT_SUBSTITUTIONS['code-reviewer'] or "code-reviewer"
model: "{POLICY['code-reviewer']['model'] or 'sonnet'}"
prompt: |
## Fix Review — Correctness Checklist
A bug fix has been implemented. Review it for correctness and completeness.
**Bug description**: {bug_description}
**Root cause**: {root_cause} at {file}:{line}
**Swarm verdict**: {convergence result from Step 1.3}
**Scope lock**:
- Fix Zone: {fix_zone_files}
- Watch Zone: {watch_zone_files}
**Behavior contract**:
{behavior_contract_table_from_step_3}
**The diff**:
Run `git diff` to see exactly what changed.
**PRE-GATE — Root cause verification (MUST PASS before remaining checks)**:
The diff must be demonstrably UPSTREAM of the symptom in the call graph.
**Short-circuit (cheap path) — gated on `is_smoking_gun == true`:**
1. Confirm the bug has a smoking-gun traceback (Step 1.3 auto-detection captured a clear
symptom file:line). If NOT a smoking-gun bug — skip short-circuit, run full procedure
unconditionally. (For symptom-less bugs the "symptom file" is fuzzy and a not-touching-it
diff could still be a refactor-shaped symptom patch.)
2. Read SYMPTOM file:line from the causation chain (Step 1.4).
3. Run `git diff --name-only`.
4. If the symptom file is NOT in the diff at all → AUTO-PASS pre-gate (the diff cannot be a
symptom patch if it doesn't touch the symptom file). Skip the full procedure below.
5. Otherwise → run the full procedure.
**Full procedure (only when symptom file is in the diff):**
1. Read the causation chain from Step 1.4. Identify the ROOT link (last link).
2. Read `git diff`. Identify the file:line of each changed hunk.
3. For each changed hunk, classify: ROOT-LINK / INTERMEDIATE-LINK / SYMPTOM-LINK / OFF-CHAIN
4. Verify: at least one hunk modifies code at or upstream of the ROOT link.
5. Build the call-graph evidence: from any SYMPTOM-LINK hunk, show the call path that
leads to a ROOT-LINK hunk. If no such path exists, the fix patches the symptom only.
Output:
Pre-gate verdict: PASS / FAIL / SYMPTOM-ONLY-JUSTIFIED Hunk classification table:
| File:line(hunk) | Chain link | Justification |
|---|---|---|
| auth.py:142 | SYMPTOM | throw site, defensive null check added |
| session.py:87 | ROOT | fixed bad assignment that produced null |
| Call-graph evidence: session.py:87 → token.py:33 → auth.py:142 (session value flows here) |
Pre-gate outcomes:
- **PASS**: at least one hunk is at ROOT or upstream of ROOT, with call-graph evidence. Proceed to remaining checks.
- **FAIL**: all hunks are at SYMPTOM or off-chain. **BLOCK the fix immediately.** Do not run remaining checks. Verdict = BLOCK. Reason: "Diff does not address root cause; fix patches symptom only." (Unless the user passed `--lite-strict` — see Argument Parsing — which bypasses both A2 escalation AND this FAIL with an explicit override warning.)
- **SYMPTOM-ONLY-JUSTIFIED**: all hunks at symptom, but reviewer writes a defense ("root link is in third-party code / validated input / framework — symptom-side defensive check is appropriate"). Proceed with reduced confidence; verdict = REQUEST CHANGES with reviewer's defense attached. The orchestrator surfaces this to the user for explicit confirmation in interactive mode, or emits a warning-only in CI/autopilot.
**Remaining checks (only run if pre-gate PASS or SYMPTOM-ONLY-JUSTIFIED) — answer each with ✓ or ✗ and explanation**:
2. **Complete fix?** Are there other code paths that have the same bug pattern?
Search for similar patterns in the codebase — the bug may exist in multiple places.
```bash
grep -rn "{pattern_from_root_cause}" --include="*.{ext}" | grep -v "{fixed_file}"
```
3. **Scope respected?** Are all changed files within the Fix Zone? Any Watch Zone
files touched without justification? Any Frozen Zone violations?
4. **Behavior contract honored?** For each "MUST NOT CHANGE" row — does the diff
risk changing that behavior? Trace each changed line's callers to check.
5. **Edge cases?** Does the fix handle:
- Null/undefined/empty inputs at the fix point?
- Concurrent access (if applicable)?
- Error paths (what if the fix itself throws)?
6. **Regression test quality?** Read the new test(s):
- Does the test actually exercise the bug scenario?
- Would the test fail if the fix were reverted? (Don't run it — reason about it)
- Does the test name clearly describe the bug it catches?
7. **Subtle issues?** Any of these:
- Type coercion or implicit conversion near the fix?
- Changed error messages that other code might match on?
- Modified function signatures that callers depend on?
- Performance implications (e.g., added a DB query in a hot path)?
**Output format**:
Pre-gate verdict: PASS / FAIL / SYMPTOM-ONLY-JUSTIFIED {If FAIL: stop here — verdict = BLOCK} {If SYMPTOM-ONLY-JUSTIFIED: include reviewer's defense}
| Check | Result | Notes |
|---|---|---|
| Complete fix | ✓/✗ | {similar patterns found?} |
| Scope respected | ✓/✗ | {any violations?} |
| Behavior contract | ✓/✗ | {any risks?} |
| Edge cases | ✓/✗ | {any missing?} |
| Test quality | ✓/✗ | {assessment} |
| Subtle issues | ✓/✗ | {any found?} |
Verdict: APPROVE / REQUEST CHANGES / BLOCK Summary: {1-2 sentence overall assessment} {If REQUEST CHANGES or BLOCK: specific changes needed}
4b-J: Arth Decisions pre-gate advisory + review-swarm gate (fix_pregate, fix_review)
If DECISIONS_MODE_RESOLVED is off, skip this block entirely — today's behaviour (the binary pre-gate inside 4b.1 decides alone; 4b.1 and 4b.2 spawn in parallel unconditionally; no Arth Decisions command runs, no scratch file is written). Otherwise (contract: skills/_lib/decisions-guard.md §11):
Pre-gate advisory — fix_pregate (question file skills/_lib/decisions/fix/pregate.json, noul diff_modifies_code_upstream_of_symptom). Runs alongside the 4b.1 spawn — it needs only the diff and the Step 1.4 causation chain:
DECISIONS_TMP=${DECISIONS_TMP:-$(mktemp -d)}
git diff > "$DECISIONS_TMP/fix-diff.patch"
printf '%s\n' "$CAUSATION_CHAIN" > "$DECISIONS_TMP/fix-chain.txt"
DECISIONS_OUT=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" fix_pregate --mode "$DECISIONS_MODE_RESOLVED" --skill fix --step 4b.1 --diff "$DECISIONS_TMP/fix-diff.patch" --chain "$DECISIONS_TMP/fix-chain.txt")
PREGATE_DECISION=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^decision=//p')
CAUSATION_CHAIN is the Step 1.4 chain (SYMPTOM → … → ROOT, one link per line as file:line — role). Tokens decision=upstream <conf> · decision=symptom_only <conf> · decision=uncertain print ONE advisory line in 4b.4, directly beside the reviewer's binary pre-gate verdict — PRE-GATE (decisions): upstream_of_symptom <conf> / PRE-GATE (decisions): symptom_only <conf> / PRE-GATE (decisions): uncertain (e.g. PRE-GATE (decisions): upstream_of_symptom 0.86) — and nothing else: in every mode, including enforce, it never substitutes for, skips, auto-passes or fails the 4b.1 PASS / FAIL / SYMPTOM-ONLY-JUSTIFIED check. decision=shadow · decision=fallback · decision=off → no line. Advisory gate: no outcome call.
Review-swarm gate — fix_review (question file skills/_lib/decisions/fix/review.json, noul first_review_found_blocking_issue, act 0.3). After fix-reviewer (4b.1) returns, write its full output and ask — the state is reviewer 1's output only, never qa-attacker's:
printf '%s\n' "$FIX_REVIEWER_OUTPUT" > "$DECISIONS_TMP/fix-review-output.md"
DECISIONS_OUT=$(bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" fix_review --mode "$DECISIONS_MODE_RESOLVED" --skill fix --step 4b --review-output "$DECISIONS_TMP/fix-review-output.md")
DECISION=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^decision=//p')
FIX_REVIEW_IDS=$(printf '%s\n' "$DECISIONS_OUT" | sed -n 's/^ids=//p')
decision=spawn_attacker (enforce, noul ≥0.3) → spawn 4b.2 qa-attacker now, sequentially; 4b.3 / 4b.4 run as written.decision=skip_attacker (enforce) → do NOT spawn 4b.2; print REVIEW SWARM: attacker skipped (decisions); skip 4b.3; in 4b.4 the qa-attacker column reads 0 HIGH (skipped, decisions).decision=shadow · decision=fallback → qa-attacker was already spawned in parallel with fix-reviewer (today's path; shadow logs --old-decision spawn); the answer gates nothing.FIX_REVIEW_IDS is not {} (shadow exactly as enforce; nothing to back-fill when it was skipped):bash "$(echo "${CLAUDE_PLUGIN_ROOT}" | sed 's|^$|.claude|')/skills/_lib/decisions-state.sh" outcome fix_review --ids "$FIX_REVIEW_IDS" --attacker-found-blocking "$ATTACKER_FOUND_BLOCKING"
ATTACKER_FOUND_BLOCKING is true when qa-attacker reported at least one HIGH attack that survived 4b.3 cross-examination, else false.
4b.2: Spawn qa-attacker (in parallel with fix-reviewer — off/shadow/fallback; in enforce only after 4b-J says spawn_attacker) (apply AGENT_SUBSTITUTIONS)
The Task call uses prompt caching (Step 1.3 "Shared cacheable context") — pass
SHARED_CONTEXT as the cacheable system prefix, then the variable prompt below.
system: [{"type": "text", "text": SHARED_CONTEXT, "cache_control": {"type": "ephemeral"}}]
subagent_type: AGENT_SUBSTITUTIONS['qa-challenger'] or "qa-challenger"
model: "{POLICY['qa-challenger']['model'] or 'sonnet'}"
prompt: |
## Fix Attack — Adversarial QA
A bug fix has been implemented. Your job is to find ways it could fail or cause regressions.
Do NOT try to be fair — try to break it.
**Bug description**: {bug_description}
**Root cause**: {root_cause} at {file}:{line}
**The diff**: Run `git diff` to see exactly what changed.
Generate 3-5 attack scenarios targeting this specific fix. For each:
Attack {N}: {scenario name} Input / trigger: {what causes this} Expected (correct): {what should happen} Attack outcome: {what could go wrong with this fix} Severity: HIGH / MEDIUM / LOW Exploits: {which aspect of the fix creates this risk}
Focus attacks on:
- Inputs the fix doesn't handle (null, empty, boundary values)
- Concurrent or race conditions introduced
- Callers of the changed function with different usage patterns
- Side effects on Watch Zone files
- The regression test's blind spots (inputs not covered)
- Conditions where the fix itself could throw
4b.3: Cross-examination (1 round after both complete) — skipped when 4b-J skipped the attacker.
Orchestrator performs cross-examination:
Share fix-reviewer's verdict AND pre-gate evidence with qa-attacker: "The fix-reviewer gave verdict {APPROVE/REQUEST CHANGES/BLOCK} and a pre-gate verdict of {PASS/FAIL/SYMPTOM-ONLY-JUSTIFIED}. The pre-gate call-graph evidence is: {chain}. Verify this upstream evidence — does the cited call path actually exist in the code? Are the cited hunks where the reviewer says they are? Do your attacks change their assessment? Which of your HIGH attacks did they miss?"
Share qa-attacker's attacks with fix-reviewer: "The qa-attacker found these scenarios: {attacks}. Are any of these covered by your findings? Do any change your verdict?"
4b.4: Verdict merge
The pre-gate verdict (Step 4b.1 PRE-GATE) is the first column; the rest of the
checklist is the second. Pre-gate FAIL short-circuits — remaining checks are skipped.
When 4b-J produced a fix_pregate token, print PRE-GATE (decisions): upstream_of_symptom <conf> (or
symptom_only <conf> / uncertain) on the line directly under the reviewer's pre-gate verdict — advisory, it changes no row of this
table. A skipped attacker (4b-J skip_attacker) scores as 0 HIGH in the qa-attacker column.
| fix-reviewer pre-gate | fix-reviewer remaining | qa-attacker | Merged Verdict |
|---|---|---|---|
| FAIL | (skipped) | any | BLOCK (root cause not addressed) — unless --lite-strict is in effect, in which case BLOCK downgrades to APPROVE-with-warning |
| SYMPTOM-ONLY-JUSTIFIED | APPROVE | 0 HIGH | REQUEST CHANGES — user confirmation (surface justification to user in interactive mode; emit warning-only in CI/autopilot) |
| SYMPTOM-ONLY-JUSTIFIED | APPROVE | 1+ HIGH | BLOCK (symptom patch + attacks = unsafe) |
| PASS | APPROVE | 0 HIGH | APPROVE |
| PASS | APPROVE | 1+ HIGH | REQUEST CHANGES |
| PASS | REQUEST CHANGES | any | REQUEST CHANGES (union of feedback) |
| PASS | BLOCK | any | BLOCK |
| PASS | APPROVE (after cross-exam) | attacks downgraded | APPROVE |
4b.5: Handle merged verdict
| Verdict | Action |
|---|---|
| APPROVE | Proceed to Step 5 (Differential Testing). |
| REQUEST CHANGES | Send combined feedback (checklist findings + unaddressed attacks) to the implementing agent. Re-run Step 4b after changes. Max 2 rounds — if not resolved, escalate to user. |
| BLOCK | STOP. Present the blocker to the user. Common blockers: fix addresses symptom not root cause, same bug pattern exists elsewhere unfixed, scope violation. |
4b.6: Check for incomplete fixes (same pattern elsewhere)
If fix-reviewer found similar patterns (check #2), decide:
Reviewer found the same bug pattern in 2 other files:
- backend/app/services/session.py:45 — same missing null check
- backend/app/services/token.py:78 — same missing null check
Options:
[1] Fix all instances now (expand Fix Zone)
[2] Fix only the reported bug, create issues for the others
[3] Ask user
Default to option 2 for medium severity. Default to option 1 for critical/high.
Always inform the user of the other instances regardless.
Cost: Two Sonnet agent calls + 1 cross-examination round (~2-4 min). The attacker
surfaces attack vectors the reviewer's structured checklist would miss. With fix_review
enforced the second call is conditional (see Cost Analysis — modeled, not measured).
Skip conditions: NOT skippable even in --hotfix mode. A bad fix shipped fast is worse
than a good fix shipped 2 minutes later. The fix-reviewer always runs; qa-attacker is dropped only in hotfix mode or when 4b-J (enforce) answers skip_attacker.
Goal: Prove the fix changes ONLY bug behavior, nothing else.
5.1: Run full test suite after fix
# Use the SAME test commands as the baseline capture (Step 3.3)
# Backend (detected test command)
{backend_test_command} 2>&1 | tee /tmp/fix-after-backend.txt
# Frontend (if applicable, detected test command)
{frontend_test_command} 2>&1 | tee /tmp/fix-after-frontend.txt
5.2: Diff against baseline
# Compare before vs after
diff /tmp/fix-baseline-backend.txt /tmp/fix-after-backend.txt
Expected results:
| Change | Meaning | Action |
|---|---|---|
| FAIL → PASS (bug tests) | Bug is fixed | ✓ Expected |
| New tests PASS | Regression tests work | ✓ Expected |
| No change (all other tests) | No side effects | ✓ Expected |
| PASS → FAIL (unrelated test) | FIX HAS SIDE EFFECTS | ✗ Investigate — fix broke something else |
| PASS → FAIL (related test) | Fix may be incomplete or wrong | ✗ Investigate — may need broader fix |
If any PASS → FAIL: The fix is NOT safe. Either:
Do NOT proceed to PR until all PASS→FAIL cases are resolved.
5.3: Behavior contract verification
Check each row of the behavior contract table:
✓ MUST CHANGE: refresh("valid_token") → 200 + TokenPair (was 500)
✓ MUST CHANGE: refresh("tampered_token") → 401 (was 500)
✓ MUST NOT CHANGE: login("user", "pass") → 200 + TokenPair (unchanged)
✓ MUST NOT CHANGE: login("user", "wrong") → 401 (unchanged)
✓ MUST NOT CHANGE: refresh("expired_token") → 401 (unchanged)
✓ MUST NOT CHANGE: GET /me → 200 + User (unchanged)
✓ INVARIANT: All tokens have user_id (FK intact)
After all verification steps pass, this is the coordinated handoff to PR. No redundant QA runs — Step 5 already ran the full test suite for differential testing.
Step 5 ran the full test suite for differential comparison, but that's not the same as a proper QA pass. Ask the user:
Fix verified. What level of QA should I run before PR?
[1] commit — targeted checks on changed files only (~1-3 min)
[2] full — comprehensive checks across full codebase (~10-20 min) — recommended for severity critical/high (Severity Routing)
[3] skip — differential test was enough, go straight to PR
Default: {commit for medium/low severity; full for critical/high — per Severity Routing}
(recommended — catches issues differential testing misses like lint, types, domain rules)
Store choice as QA_LEVEL.
Non-interactive mode: do not prompt. Derive QA_LEVEL from severity per the
Severity Routing table — critical/high → full, medium/low → commit —
and log the choice. Conservative by design: unattended runs get MORE checking,
not less.
If user chose skip, skip to Step 6.3.
Otherwise, invoke /qa {QA_LEVEL} via the Skill tool:
/qa {QA_LEVEL} --invoked-by fix (the flag suppresses /qa's own continuation prompt — this workflow owns the next step)yes → fix issues, re-run QAskip → proceed (user takes responsibility)abort → stopRecord QA results as QA_RESULT for the PR body.
Check if local services exist — read CLAUDE.md ## Local Dev Services table.
If the table exists and has entries:
/restart if the project has that skill configuredAfter restart (or if no local services), ask the user:
Local servers restarted. Please test the fix manually — verify the bug is gone
and nothing else broke.
When you're done:
[ready] — looks good, proceed to PR
[issues] — found problems (describe them)
If issues: Address problems, re-run /qa commit only, ask again.
If ready: Proceed to Step 6.4.
Non-interactive mode: skip the server restart and the manual-test wait entirely.
Log manual verification deferred — unattended run (the same CI/autopilot treatment
as Step 4b's SYMPTOM-ONLY path), record User testing: deferred — unattended run for
the PR template's Test Evidence section, and proceed to Step 6.4.
Invoke /pr --skip-qa with bug-specific PR content. The --skip-qa flag tells /pr
to skip its own /qa commit since QA already ran in Step 6.2.
/pr will only:
Do NOT announce the PR URL to the user yet. The reward line is withheld until the post-fix checklist renders in the closing report (Step 6.5, which runs after Steps 7-8 complete). Issue #311 showed that once the PR URL prints, everything after it gets skipped — 0 of 4 observed runs invoked the verifier or wrote incident files.
PR template for bug fixes (passed to /pr):
## Bug Fix: {title}
**Severity**: {critical|high|medium|low}
**Root Cause**: {precise description from Step 1}
**Location**: {file}:{line}
### What was broken
{Description of the bug behavior}
### Why it was broken
{Root cause explanation — what assumption was violated}
### What this fix does
{Description of the changes — minimal, precise}
### Scope
- Fix Zone: {files modified}
- Watch Zone: {files checked but not modified}
- Frozen Zone: {verified untouched}
### Behavior Contract
| Behavior | Before | After |
|----------|--------|-------|
| {bug behavior} | {broken} | {fixed} |
| {preserved behavior} | {same} | {same} |
### Test Evidence
- Root cause: investigation swarm converged (Step 1.3) — {convergence type}
- Fix review: approved by review swarm (Step 4b) — fix-reviewer + qa-attacker
- Regression test: `{test_file}::{test_name}`
- ✓ Fails without fix (catches the bug)
- ✓ Passes with fix (confirms the fix)
- Differential test: {N} tests unchanged, {M} tests fixed, 0 regressions
- QA: {QA_LEVEL} mode — {QA_RESULT summary}
- User testing: confirmed manually
### Root cause analysis depth
- Causation chain length: {N}
- Walk-back verification: {iterations} iterations, root {confirmed | moved deeper to ...}
- Pre-gate verdict: {PASS | SYMPTOM-ONLY-JUSTIFIED | FAIL→re-implemented}
- Verdict path: {standard | lite-escalated-to-full | shallow-agreement-escalation | walk-back-moved-root-deeper | kb-match-verified}
### Telemetry
- Cache hits / misses: {hit}/{miss}
- Estimated input tokens saved by caching: {N}
- /fix cost (approx): {$X.XX}
### Rollback Plan
{How to revert if this fix causes problems — typically: revert this commit}
Closes #{issue_number}
This step executes LAST — after Step 7 (KB update) and Step 8 (completion verification) complete. Print the post-fix checklist line FIRST — the PR URL appears after it, never before. This makes a skipped incident record, bug-pattern append, kg-write, or completion-verifier visible instead of silently buried under the reward (issue #311):
Post-fix checklist: incident record {✓|✗} · bug-pattern {✓|✗} · kg-write {✓|✗} · verifier: {PASS|GAPS|INCONCLUSIVE}
PR #{number} created: {url}
What's next?
[1] Fix another bug — /fix #N or /fix <description>
[2] Start a feature — /planning <feature>
[3] See project status — /onboard
[4] Done for now
In --hotfix mode the KB checklist items legitimately render as deferred (post-merge)
— the Hotfix compression table ("7. Knowledge Base — Post-merge (don't block the fix)")
governs; the checklist makes the deferral explicit rather than hiding it.
If autopilot is active, print the checklist + PR line, skip the what's-next question, and continue the loop.
Knowledge base update is not optional. Every bug teaches something — capture it (this is a Rules-section invariant, repeated here because this step executes after the PR exists, in issue #311's named skip zone; the Step 6.5 checklist makes a skip visible).
After the PR is created, update the knowledge base:
Create incident record:
For standard fixes, status: covered. For --hotfix mode (where pre-merge depth
checks may have been compressed), use the hotfix-specific schema below — the
deferred swarm reconciles the status post-merge.
# .claude/qa-knowledge/incidents/{date}-{slug}.md
---
status: covered
severity: {severity}
affected_files: [{file1}, {file2}]
root_cause: {description}
fix_pr: #{pr_number}
regression_test: {test_file}::{test_name}
created: {date}
---
## What happened
{Bug description}
## Root cause
{From Step 1}
## How QA missed it
{Why existing tests didn't catch this}
## Prevention
{What kind of test would have prevented this}
Hotfix incident record (Step 7 — hotfix mode only):
---
status: hotfix-symptom-patch # NOT "covered" until reconciled by deferred swarm
severity: {severity}
hotfix_pr: #{pr_number}
hotfix_root_cause_claim: {symptom-site description}
deferred_swarm: pending # set post-swarm to {agreed | disagreed | extended | skipped}
follow_up_issue: #{issue_number} # created BEFORE hotfix PR is merged
follow_up_deadline: {merge_date + 14 days}
follow_up_assignee: @{hotfix_author}
---
Update bug patterns:
# Append to .claude/qa-knowledge/bug-patterns.md
echo "### {date} — {title}" >> .claude/qa-knowledge/bug-patterns.md
echo "- Area: {affected_area}" >> .claude/qa-knowledge/bug-patterns.md
echo "- Pattern: {root_cause_pattern}" >> .claude/qa-knowledge/bug-patterns.md
echo "- Prevention: {test_type}" >> .claude/qa-knowledge/bug-patterns.md
Update knowledge base + knowledge graph (dual write — KB file + KG node):
shared/conventions.md if the bug revealed a coding convention violation
kg-write.sh convention "{convention violation}" "fix"shared/domain.md if the bug revealed a business rule not in code
kg-write.sh domain "{business rule}" "fix"agents/{agent-name}.md if the implementing agent learned somethingkg-write.sh domain "bug pattern: {root_cause_pattern} in {area}" "fix"kg-write.sh domain "incident: {slug} — {root_cause}" "fix"KG_WRITE="${CLAUDE_PLUGIN_ROOT}/skills/knowledge-graph/kg-write.sh" # plugin install: Claude Code substitutes the root at load
[ -f "$KG_WRITE" ] || KG_WRITE=".claude/skills/knowledge-graph/kg-write.sh" # symlink install
[ -f "$KG_WRITE" ] && "$KG_WRITE" "{type}" "{one-line summary}" "fix"
If a KG node from the initial context gathering (the Step 0 KG supplemental query) helped identify the root cause faster (e.g., a past bug pattern matched), reinforce it.
Spawn the completion-verifier agent (subagent_type="completion-verifier", model="sonnet"):
SKILL_NAME: fix
FEATURE_NAME: {bug-slug or issue-number}
PLAN_PATH: .claude/plans/{feature-name}.md (if applicable)
SPEC_PATH: .claude/specs/{feature-name}.md (if applicable)
FAILURE_LOG: .claude/knowledge/shared/completion-failures.jsonl
AUTO_FIX: false
Wait for output. Display verbatim — PASS, GAPS FOUND, or INCONCLUSIVE. Non-blocking for the PR — but NOT optional to run; the checklist line in Step 6.5 makes skips visible. User decides whether to rerun on gaps.
Then run Step 6.5 (closing report: post-fix checklist + PR URL + what's next).
For critical production bugs, the pipeline is compressed:
| Step | Standard | Hotfix |
|---|---|---|
| 1. Root Cause | Investigation Swarm (3 agents, debate) | Single backward-tracer (Sonnet, 5 min max) |
| 2. Scope Lock | Full dependency graph | Direct file only — hop 0-1 |
| 3. Behavior Contract | Full table | Bug behavior + 3 critical paths only |
| 4. Implement | Spawn agent team | Fix directly — single agent |
| 4b. Fix Review | Review Swarm (2 agents, cross-examine) | Single fix-reviewer (no cross-examine) |
| 5. Differential Test | Full suite | Critical path tests only |
| 6. PR | Full template | Abbreviated — merge fast |
| 7. Knowledge Base | Full update | Post-merge (don't block the fix) |
Hotfix STILL requires:
status: hotfix-symptom-patch,
deferred_swarm: pending, follow-up issue created BEFORE the PR is merged with a 14-day
deadline assigned to the hotfix author.Conditional firing — runs within 24h of merge only when ANY of:
git diff --name-only ⊆ {symptom_file})critical OR high (the "looks deep but might be wrong" case — multi-file
diff with chain length ≥ 2 can still have the wrong root; high-severity bugs deserve
the post-merge verification)If none of those fire, the hotfix incident is marked status: hotfix-verified-via-tests
and the deferred swarm is skipped. Saves ~40-50% of the deferred-swarm bill — medium
and low severity hotfixes with multi-file diffs and length-≥2 chains skip verification
(they're the safest hotfix category and the deferred swarm rarely changes their verdict).
When it fires, the deferred swarm is a Full investigation swarm (3 agents, 3 rounds). It outputs one of three verdicts:
| Verdict | Action |
|---|---|
| AGREED — swarm's ROOT matches the hotfix's symptom-site fix | Mark incident status: covered. Update deferred_swarm: agreed. Close the follow-up issue. |
| EXTENDED — swarm's ROOT is upstream of the hotfix fix | Update follow-up issue with the deeper root cause. Hotfix STAYS MERGED (defensive symptom check is still useful). Open a new /fix PR to address the upstream root. Incident stays hotfix-symptom-patch until the deeper PR merges. Update deferred_swarm: extended. |
| DISAGREED — swarm's ROOT is in a different location entirely | Mark follow-up issue HIGH-PRIORITY, deadline 7 days, assigned to hotfix author. Hotfix may need to be reverted if it's masking the real bug. Surface to user: "Hotfix #{N} may have masked the real bug. Investigation swarm thinks root cause is at {file}:{line}. Revert hotfix? [yes / no / investigate first]" Update deferred_swarm: disagreed. |
Cost: one Full /fix --full investigation per qualifying hotfix (~$0.05 each). For typical
hotfix frequency (~1-2/month per project), ~$1/year. Negligible.
The QA Mode column is wired into Step 6.1: it is the recommended default in the interactive prompt and the auto-selected level in non-interactive runs. The Review and Merge columns are guidance for your team's downstream process — NOT behavior this skill implements (/fix never schedules an SRE review or controls merge timing).
| Severity | QA Mode | Review | Merge |
|---|---|---|---|
| critical | Full QA + critical paths + E2E | Bug-specific + SRE review | Expedited |
| high | Full QA | Bug-specific review | Standard |
| medium | Commit mode QA | Standard review | Standard |
| low | Commit mode QA | Standard review | Batched |
| Mode | Agents | Estimated Cost | When |
|---|---|---|---|
| Hotfix (investigation) | 1 Sonnet backward-tracer | ~$0.005 | --hotfix flag |
| Lite | 1 Haiku pattern-matcher + 1 Sonnet backward-tracer (1 round) | ~$0.008 | Smoking-gun / simple bug |
| Verified | 1 Sonnet analyst (backward-tracer) + 1 Sonnet challenger (qa-challenger) | ~$0.014 | Moderate bugs — the default depth |
| Full Swarm (investigation) | 2 Sonnet + 1 Haiku + debate rounds | ~$0.045 | Complex / unclear bugs |
| Review Swarm (hotfix) | 1 Sonnet fix-reviewer | ~$0.006 | --hotfix fix review |
| Review Swarm (standard) | 2 Sonnet + cross-exam | ~$0.018 | Standard fix review |
| Full pipeline (standard) | All of the above | ~$0.08 average | Default |
| Full pipeline (hotfix) | Compressed | ~$0.021 | --hotfix |
| Full pipeline (Arth Decisions Phase 2 gates enforced — modeled, not measured) | fix_depth auto-lite more often · fix_review skips qa-attacker when reviewer 1 found nothing blocking · fix_pregate advisory only | ~35u average (≈$0.05) | once an operator flips a gate (--decisions enforce) |
spawn_lane (Step 4.2-J, modeled): one ask per implementation agent, eight questions in one call (two lane choices, two floor nouls, four router hints), ≈3k input tokens → ≈$0.00013 per spawn; with ARTH_ROUTER_URL set an enforce-act adds one ≤2 s router call and no model spend at the descriptor price ($0.042 per 1M input tokens, output free). Expected direction in enforce: DOWN on smoking-gun one-liners (Sonnet → Haiku / low effort, that spawn at roughly a third of its cost), UP on concurrency or money bugs (Opus / high effort, paid back by one avoided failed attempt). The investigation and review swarms are never asked about (reviewer pin). Off adds nothing; shadow adds the ask only. Measured on three live sub-tasks (2026-09-19): a two-file rename answered haiku low down (0.97 / 0.99 confidence, 262 ms); an atomic-and-idempotent credit deduction across concurrent finalize calls answered opus high up (0.99 / 1.0, auth/payment noul 0.85, 220 ms); an auth refresh endpoint on a protected path was held at policy (auth noul 0.98, 195 ms) — the floor working, not the model guessing. The effort half only changes what runs where install.sh --apply-model-policy --effort-variants has generated the matching agent definitions; without them it is advisory and is left unlabelled, so the numbers above are a MODEL-TIER saving only.
~35u, modeled (decisions-selectors 2.3): lite (~30u) fires on about half of runs instead of the
verified default (~60u) — fix_depth supplements the smoking-gun signal; the review swarm drops
one Sonnet call (~7u) on ~40% of runs via fix_review; fix_pregate adds a line, never a spawn;
the gate calls themselves (4 decision rows per run) are negligible in unit terms. Shadow mode
changes nothing — the $ rows above remain the measured baseline.
Delta from previous single-agent pattern: ~3.8x more per full pipeline run. One prevented misdiagnosis (wrong root cause → wrong fix → debugging cycle → re-fix) saves the entire investigation and implementation time — the swarm pays for itself on the first catch.
file:line is not a root cause —
it's a symptom.SYMPTOM-ONLY-JUSTIFIED path — surfaced to the user in interactive mode, warning-only in
CI/autopilot. Never silent.hotfix-symptom-patch and a follow-up issue is filed with a deadline.npm test/jest/vitest for Node, go test ./... for Go,
cargo test for Rust, dotnet test for C#, swift test for Swift. Read CLAUDE.md
Test Commands table for the project's actual commands.Instead of manually running /fix after a bug report, register a Monitor watcher that
automatically detects runtime errors and launches the formal fix pipeline.
Webhook-triggered runs execute in non-interactive mode (defined in Step 0): the missing-description hard error, Step 4b's warning-only SYMPTOM-ONLY path, Step 6.1's severity-derived QA level, and Step 6.3's deferred manual verification all apply — the loop runs unattended end-to-end, from error event to PR.
[Runtime error event fires (Sentry, Datadog, Rollbar, etc.)]
│
▼
[Monitor checks event filter]
│
───────────┴───────────
│ New error, N occurrences│ │ Known/resolved — no-op
▼
[/fix agent wakes]
│
├─► Load error context (stack trace, frequency, affected users)
├─► Step 0: Load bug context from Monitor event payload
├─► Step 1: Root cause swarm (swarm investigators analyze stack)
├─► Step 2: Scope lock (identify Fix Zone from traceback)
├─► Step 3: Behavior contract
├─► Step 4: Implement fix
├─► Step 4b: Review swarm
├─► Step 5: Differential test
└─► /pr to ship fix
│
└─► Monitor registers PR merge watcher
→ on merge → /sre health verify
Create .claude/monitors/runtime-errors.json:
{
"name": "runtime-error-watcher",
"description": "Wake /fix agent when new runtime errors are detected in production",
"trigger": "webhook",
"endpoint": "/webhooks/errors",
"filter": "$.level == 'error' AND $.occurrences >= 5 AND $.status == 'unresolved'",
"skill": "fix",
"args": "{{$.culprit}} — {{$.title}} ({{$.occurrences}} occurrences) --severity {{$.severity}}"
}
Error monitoring webhook setup:
Severity mapping from event payload to /fix severity:
{
"filter_map": {
"$.level == 'fatal'": "--severity critical",
"$.level == 'error' AND $.occurrences >= 50": "--severity high",
"$.level == 'error' AND $.occurrences < 50": "--severity medium"
}
}
The Monitor filter uses $.occurrences >= 5 to prevent a single error storm from
spawning dozens of /fix agents. Tune the threshold to your error volume.
Add "cooldown_minutes": 60 to the config to enforce a minimum gap between invocations
for the same error fingerprint:
{
"name": "runtime-error-watcher",
"filter": "$.level == 'error' AND $.occurrences >= 5 AND $.status == 'unresolved'",
"cooldown_minutes": 60,
"dedupe_key": "{{$.fingerprint}}"
}
| Approach | Response time | Tokens wasted while idle |
|---|---|---|
| Manual: engineer notices error | Minutes to hours | 0 (human scans dashboard) |
| Cron poll Sentry API | Up to poll interval | ~200 tokens/poll × N polls |
| Monitor: event-driven | <1s after error threshold | 0 tokens while healthy |
After the closing report (Step 6.5 — KB updated, PR created, checklist rendered), print this block verbatim:
─────────────────────────────────────────────
💡 Context tip — /fix accumulates investigation swarm output, scope locks,
behavior contracts, and review rounds. Context is heavy after a full pipeline.
Bug fixed, PR open → next task is unrelated?
Best practice: /clear + one-line brief for the new session.
Next bug is related (same module)?
/compact focus on {bug-slug} fix — done, PR #{pr_number} open
(Keeps root cause context alive if you need it for a follow-up.)
If a fix attempt failed and you're about to retry:
Rewind (Esc Esc) to after root cause was confirmed (Step 1), NOT to before
all the investigation — keep the diagnosis, discard the bad fix.
Then re-prompt: "Don't do X — try Y instead."
If 3 attempts exhausted and starting manual investigation:
Always /clear — context is polluted with failed attempts. Start clean.
─────────────────────────────────────────────
Files this command reads when invoked
What the command file sets; muted values are Claude Code's defaults
7-day visitors to each command page
2 plugins in one repository ship this exact command · first indexed Dec 1, 2026
53 commands in this plugin
/adapters:READMEDiagram AdaptersThis directory contains push adapters for `/kb-diagram --push <adapter>`./arth-helpAnswer questions about installing, using, trusting and removing Arth, from the docs bundled with the plugin only — cites the page, says when the docs do not cover it, and makes no network call. Usage: /arth-help <question>/arth-setupSet up Arth in one command. Open edition: Arth Intelligence (/otel-setup, local Docker) plus Arth Decisions (off by default); memory and model routing are built in. `/arth-setup local` does the whole local setup with defaults and no questions. Pro edition adds memory (/memory-setup), router (/router-setup) and the Central posture. Also handles `switch <local|cloud|off>` (plus `switch <shadow|enforce> decisions`) and `uninstall`. Usage: /arth-setup, /arth-setup local, /arth-setup switch <local|cloud|off> <product|all>, /arth-setup switch <off|shadow|enforce> decisions, /arth-setup uninstall <product|all> --purge-datanpx claudepluginhub arthtech-ai/sarathi --plugin primeOther plugins' commands for the same job