ai-agents Debugging Playbook
<!-- vendor-portability: contributor-facing knowledge pack for the rjmurillo/ai-agents repo itself; intentionally references upstream paths because its audience is repo contributors, not plugin consumers. Declared paths: .agents/governance/FAILURE-MODES.md, .agents/schemas/session-log.schema.json, .claude/lib/hook_utilities/guards.py, .project-toolkit/retrospective, .project-toolkit/sessions/handoffs/2026-09-01-5404-handoff.md, .project-toolkit/sessions/handoffs/2026-09-11-5706-handoff.md, .project-toolkit/sessions/handoffs/2026-09-15-5774-handoff.md, build/generate_agents.py, build/scripts/build_all.py, build/scripts/check_plugin_manifest_parity.py, build/scripts/validate_plugin_version_bump.py, scripts/validate_session_json.py, scripts/validation/check_spec_id_uniqueness.py, scripts/validation/checks_dash.py, scripts/validation/pre_pr.py, scripts/validation/run_install_parity_ci.py, scripts/validation/run_plugin_version_bump_ci.py, scripts/validation/validate_python_syntax.py, templates/agents -->
Symptom-first triage for this repository's known failure modes. Every row below was earned by a real incident; the retro path is cited so you can read the full story. The playbook answers one question: given this symptom, what is the FIRST command to run, what experiment discriminates between causes, and what trap has already cost someone real time here?
Vocabulary used once: a "guard" is a PreToolUse or pre-push hook that can block an action (exit 2 blocks, exit 0 allows). A "drift gate" is a CI check that fails when a generated tree no longer matches its canonical source. A "discriminating experiment" is one cheap action whose outcome splits the hypothesis space in two.
Triggers
triage this failurewhy is my push blockeddebug this CI redwhat does this gate failure meanhook blocked my tool call
When NOT To Use This Skill
| You want | Use instead |
|----------|-------------|
| The full history of an incident (root cause, evidence, what changed) | ai-agents-failure-archaeology |
| To measure something (budgets, telemetry, drift as a number) | ai-agents-diagnostics-toolkit |
| Evidence standards, test layout, how to write the missing test | ai-agents-validation-and-qa |
| The catalog of every env var, marker, and escape hatch | ai-agents-config-catalog |
| How the harness itself behaves (payload shapes, plugin roots) | agent-harness-reference |
| Fix a NON_COMPLIANT session log | Hand-edit against .agents/schemas/session-log.schema.json, re-run scripts/validate_session_json.py |
| Resolve merge conflicts | Agent: merge-resolver |
| Query agent JSONL event logs | observability |
Process
Phase 1: Match the symptom
Find your symptom in the master table. Run the first command exactly as written (from repo root). Do not guess at fixes before the discriminating experiment tells you which cause you have.
Before guessing at a symptom the table does not cover, search this repo's memory corpus and ADRs first (.claude/skills/programming-advisor/references/search-before-building.md, "diagnosing a failure" trigger). It covers CI, git, and PR-gate quirks densely, so the cause is often already written down; re-deriving it is the expensive miss.
Local blocks (a hook stopped you)
| Symptom | First command | Discriminating experiment | Fix path | Trap |
|---------|---------------|---------------------------|----------|------|
| Push rejected by a guard, stderr shows EVENT={...} | Read the EVENT JSON on stderr; the guard field names which of .claude/hooks/PreToolUse/invoke_*_guard.py fired | Is outcome a block or fail_open? A block means the guard did its job; fail_open means guard infra broke | Fix the underlying violation, then re-push. No tier-classifier consumes this telemetry today; the guard-maturity skill that did was retired under ADR-084 | Bypassing instead of fixing. SKIP_PREPUSH was abused 3x within an hour of creation and removed (retro 2026-02-08-session-1187-skip-prepush-abuse.md) |
| ModuleNotFoundError: No module named 'yaml' running a skill script | Re-run with uv run python <script> | Does uv run python -c "import yaml" succeed while python3 -c "import yaml" fails? Then it is interpreter resolution, not a missing dep | Always use uv run python for .claude/skills/*/scripts/; they import github_core which needs PyYAML from the project venv | Bare pip install fails under PEP 668 on this machine. Everything goes through uv |
| markdown-autofix/markdown-check blocks the commit, or lint "fixed" files you never touched | git status to see the blast radius | Did you run markdownlint --fix '**/*.md' (unscoped)? | Revert unrelated files; lint ONLY changed files. The Lefthook job itself is scoped to staged .md files (lefthook.yml markdown-autofix/markdown-check, glob: "**/*.md" against {staged_files}) | An earlier PR: an unscoped markdownlint --fix **/*.md reformatted memory files repo-wide; the PR hit 59 commits / 95 files (retro 2026-01-15-pr-908-comprehensive-retrospective.md). The PreToolUse markdownlint guard that originally enforced this was removed under ADR-084; the same scoping now lives in the two Lefthook jobs named above |
| Bot review thread flags an em-dash or en-dash | Run the dash-scan instrument (instruments.py --repo . run dash-scan). Without uv: grep -rnP '[\x{2013}\x{2014}]' <your changed files> | Is the hit under tests/hooks/fixtures/? That prefix is exempt | Replace with comma, colon, parentheses, or hyphen (.claude/rules/universal.md MUST NOT 4; validator scripts/validation/checks_dash.py) | Each dash costs one or more bot threads per PR. Fix all occurrences, not just the flagged one |
CI reds (a gate failed on the PR)
| Symptom | First command | Discriminating experiment | Fix path | Trap |
|---------|---------------|---------------------------|----------|------|
| Any CI failure you did not expect | Check whether the same job fails on main before touching your branch | Same failure on main = pre-existing, not yours; file or link an issue instead of "fixing" your PR | Memory .serena/memories/ci-infrastructure-observations.md | Hours misattributed to PR code when main was already red |
| Drift gate red (generated tree differs from source) | Identify which of the 4 surfaces failed, then run its local command: uv run python build/generate_agents.py --validate, uv run python build/scripts/build_all.py --check (covers the lib trees too, ADR-109 B5), uv run python ./scripts/validation/run_install_parity_ci.py (build_all imports PyYAML; bare python3 fails in a fresh shell, see ai-agents-generation-and-release) | Ask the DIRECTION question before editing anything: which tree is canonical here? Agents: templates/agents/*.shared.md is source. Rules/skills/hooks/commands: .claude/ is source | Edit the canonical tree, regenerate, commit source and generated together (ai-agents-generation-and-release) | 2025-12-15 disaster: agent edited the SOURCE to match the GENERATED tree; drift output shows a difference, not a direction (retro 2025-12-15-drift-detection-disaster.md) |
| Plugin version-field gate red (VERSION FIELD PRESENT) | Read the failure list from python3 scripts/validation/run_plugin_version_bump_ci.py (workflow validate-plugin-version-bump.yml) | Which file carries the field? The gate names it: one of the two .claude-plugin/plugin.json manifests (src/claude/, src/copilot-cli/), or an entry in .claude-plugin/marketplace.json or .github/plugin/marketplace.json | DELETE the version key from the named file, then re-run python3 build/scripts/validate_plugin_version_bump.py until it prints plugin-version-bump: OK | The gate inverted in ADR-092 (supersedes ADR-079): it now fails on the field's PRESENCE. Adding a version back to clear a red gate makes it permanently red. Parity no longer covers versions; build/scripts/check_plugin_manifest_parity.py checks description component counts only |
| Coverage pin trips at ~63% (or another surprise number) | Re-run the pinned step's EXACT file list locally, e.g. pytest tests/test_ai_review.py tests/test_verdict.py tests/test_quality_gate.py --cov --cov-branch --cov-report= then coverage report --include=scripts/ai_review_common/verdict.py --fail-under=100 | Does the number change when you add/remove test files? The pin is file-set sensitive: running one file alone reports 63% | Run all files that exercise the module; add tests for genuinely uncovered branches (pytest.yml step Pin REQ-009 module coverage collection, ai_review_common.verdict) | The pin runs as two steps: broad collection (--cov --cov-branch --cov-report=), then a separate coverage report --include= isolation gate. Do not collapse them into one module-name --cov= call; that combination is what an earlier audit found broken, for the REQ-009 pin the next Provenance row covers |
| Syntax gate fails on code that runs fine locally | python3 scripts/validation/validate_python_syntax.py | Does the flagged construct exist only in Python 3.14 (e.g. PEP 758 unparenthesized except clauses)? | Rewrite to parse at the support floor. The gate compiles every tracked file at the 3.10 floor grammar, not the 3.14 dev target (scripts/validation/validate_python_syntax.py:2-49) | "It passes on my 3.14" is exactly the failure the gate exists to catch: a 3.13 host would wedge on import |
| Test fails with a test-launched Git command changed the REAL repo HEAD | Read the failing test for real git commit/checkout/reset calls | Does the test pass when its git ops target a tmp_path repo? | Point all git mutation at a temp repo fixture; the root conftest.py:438 (_check_head_change) snapshots HEAD and fails any test that moves it | The corruption shows up in whichever test the checker runs after, not necessarily the guilty one |
Shared checkout (many worktrees, one `.git`)
Worktrees share branches, remote refs, and refs/stash (git-advanced-workflows, "Shared-state caveat").
| Symptom | First command | Discriminating experiment | Fix path | Trap |
|---------|---------------|---------------------------|----------|------|
| Unknown git stash list entry, or stash pop conflicts on a file you never touched | git stash list --format='%gd %gs' | Does WIP on <branch> name your branch? If not, another worktree made it | Leave foreign entries alone. Undo a bad pop with git-advanced-workflows, "Undo a foreign pop". Save work as a WIP commit | pop takes the newest entry repo-wide; git reset --hard HEAD recovery drops your staged edits (.project-toolkit/sessions/handoffs/2026-09-01-5404-handoff.md:47) |
| Validate Spec ID Uniqueness red, or two PRs add the same REQ-/TASK- id | git fetch origin main && git merge origin/main, then python3 scripts/validation/check_spec_id_uniqueness.py | Passes alone, fails after the merge? The checker scans only the working tree | Renumber your side by hand: the id: field, the filename, and every git grep -n REQ-NNN hit. The rename script finds only unslugged REQ-NNN.md names, which no spec here uses | Parallel issues took the same next-free ids twice in one day (.project-toolkit/sessions/handoffs/2026-09-11-5706-handoff.md:44). Allocate ids late, after a fetch |
| After a long run, drift, a red gate, or conflicts on files you never touched | git fetch origin main && git rev-list --left-right --count origin/main...HEAD | Left count non-zero and the red reproduces after git merge origin/main? Your base lags main; your diff is not the cause | git merge origin/main, regenerate, re-run the gate. Fetch again before the final push | A fetch moves origin/main for every worktree, never your branch. main moved three times in one run (.project-toolkit/sessions/handoffs/2026-09-15-5774-handoff.md:52) |
Copilot CLI runtime failures
| Symptom | First command | Discriminating experiment | Fix path | Trap |
|---------|---------------|---------------------------|----------|------|
| Hook "errored" under Copilot CLI, exit code 143 | Get the exit code from the process log; 143 = SIGTERM, Copilot kills hooks at a 2-3s budget | Exit 2 = the hook itself crashed (often payload shape); exit 143 = timeout. Same "hook errored" surface, different root causes (retro 2026-06-02-issue-2290-copilot-hook-payload-format.md:27) | Reduce per-hook work; ADR-068 consolidates to one dispatcher per event. Contract details: agent-harness-reference | Exit 143 was flagged P0 and unresolved in the Copilot hook payload-format retro (as of 2026-07-02); verify current status before assuming it is fixed |
| Hook reads wrong/missing payload fields under Copilot CLI | Check the event key casing in the hook config | camelCase event keys deliver toolName/toolArgs (args as a JSON string); PascalCase delivers tool_name/tool_input | Use PascalCase event keys so payloads match what hook scripts expect (memory .serena/memories/copilot-hooks-observations.md, which says "Use PascalCase registrations for source hooks that expect snake_case input"; session fix/2290) | Vendor docs omit this contract; it was settled by empirical probe, not documentation |
Scripts
Run ( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/ai-agents-debugging-playbook/scripts/instruments.py --repo . list; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 ) to see every linked checker and whether its file exists. Run one by writing run <id> in place of list inside the locator. Rows: plugin version gate, dash scan, spec id uniqueness, Python 3.10 syntax gate, CI drift step, drift self-check.
Two shared-checkout answers are computed, not eyeballed:
# own or foreign per stash entry
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/ai-agents-debugging-playbook/scripts/first_command.py --repo . stash; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )
# left and right counts of origin/main...HEAD
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/ai-agents-debugging-playbook/scripts/first_command.py --repo . lag; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )
stash calls an entry foreign when its WIP branch is checked out in no worktree. It cannot tell who made an entry on a branch that exists elsewhere, and it reads refs/stash as is. lag does not fetch: run git fetch origin main first, or the counts are stale. Exit 1 means a foreign stash or a non-zero left count.
Phase 2: Run the discriminating experiment
Before writing any fix, answer three questions in order:
- Does it reproduce on main? If yes, it is not your PR. Stop debugging your branch.
- Is the gate doing its job, or is the gate broken? A guard block with a clear violation message is the gate working; fix the violation. A
fail_openEVENT, a timeout, or a gate red that reproduces on main is gate infrastructure; file it, do not route around it. - If it is a drift red: which tree is canonical? Never edit until you can answer this from
AGENTS.mdor the generator docstring, not from the diff.
If three read-only commands have not identified the cause, stop and escalate to a real investigation (analyze skill) instead of shotgun-fixing. If you are looping on the same failed fix, stuck-detection names the pattern.
Phase 3: Fix, then prove it locally
- Apply the fix on the canonical surface only.
- Re-run the exact failing check locally, not a proxy for it:
- Tests:
uv run pytest tests/ -x(new skill tests belong intests/skills/<name>/; the default bundle runner reaches legacy colocated suites, while direct legacy-path invocation is only for targeted diagnosis) - Full shift-left sweep:
uv run python scripts/validation/pre_pr.py(exit codes per ADR-035: 0 ok, 1 logic, 2 config). Save the output and its exit code to a file first (> pre_pr.log 2>&1; echo "exit=$?"); a pipe would report the distiller's exit code instead. Then distill the file withdistill_artifact.py(usage: context-optimizer skill, Tool Details: Distill Artifact), and use the digest to locate the failure. A middle detail can be omitted, so search the raw log for the failing gate's name and read that section. - Drift: the specific surface command from the table above
- Prove the check can still fail: re-run it with a deliberate defect injected. A gate that prints OK both ways does not cover your change. Four gates pass in ways that read as success (install parity, plugin bump, agent drift, drift exit capture); see
references/vacuous-gates.md. - Commit with logical, reviewable granularity (author judgment; no hook measures commit or file count, ADR-100 deleted the last advisory).
- Escape hatches (a drift allowlist entry, etc.) require documented justification and are cataloged in
ai-agents-config-catalog. Using one IS the incident report; say so in the PR.
Traps
Each row's Trap column cites its retro. Dated incident stories and the settled-battles list live in ai-agents-failure-archaeology. The failure catalog is .agents/governance/FAILURE-MODES.md (13 numbered sections as of 42e409325; section 13 is State Conflation in a Boolean Guard).
Anti-Patterns
- Editing a generated tree to make a drift gate green. The gate reads difference, not direction; you may be destroying the source of truth.
- Reaching for an escape hatch (a drift allowlist entry, etc.) as a first move. Escapes are for infrastructure failure, not friction.
- Switching
--covbetween module-name and file-path forms to "fix" a coverage red. Only the module-name form resolves correctly here. - Fixing by analogy ("the other CLI sets this env var, so this one probably does"). This repo's rule is empirical probe first; see
ai-agents-empirical-probe-toolkit.
Verification
Before declaring the failure triaged and fixed:
- [ ] The symptom was matched to a table row, and the FIRST command output (not a guess) identified the cause
- [ ] The discriminating experiment was run and its outcome recorded in the session log or PR description
- [ ] The exact failing check passes locally (same command, same file set as CI), not a proxy
- [ ] The check was proven to still fail with a defect injected, so its pass is about your change and not vacuous
- [ ] No escape hatch was used; or if one was, the PR description says which, why, and links the infrastructure issue
- [ ] If the fix touched a canonical surface with mirrors, the drift command for that surface passes and source plus generated are in the same commit
Provenance and Maintenance
reverify.json holds the cited files, anchors and counts (verified 2026-10-31 at 42e409325). Retro-cited short SHAs do not resolve locally; use .project-toolkit/retrospective/ and .serena/memories/ for archaeology, not git log.
Retired: the EVENT= stderr guard schema (push_guard_base.py, deleted under ADR-084). A narrower survivor is _emit_skip_event in .claude/lib/hook_utilities/guards.py.
Re-verify:
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/skill-bootstrap/scripts/bootstrap_drift.py check --repo . --skills-root .claude/skills --name ai-agents-debugging-playbook --require; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )