Hard Rules
- High-stakes systems first: Any issue touching irreversible side effects (live order execution, payments, production data writes, anything in a live-money or production financial system) is CRITICAL regardless of apparent severity. Stop and assess before proceeding.
- Never assume cause — always diagnose before fixing. State a hypothesis BEFORE changing any code.
- Fix one thing at a time — never bundle multiple fixes or refactor while fixing.
Debug Session — Systematic Root-Cause Diagnosis
A disciplined diagnose-before-fix workflow. The goal is to find the root cause, not patch the first symptom, and to leave the codebase with a regression test plus a captured insight so the same bug can't recur.
Routing: Debug vs. Browser/UI Testing
Before starting, route to the right approach:
| Situation |
Use |
| App won't start, build fails, crash on load |
This skill (debug-session) |
| Runtime error, logic bug, wrong data |
This skill (debug-session) |
| "UI isn't doing what I expect visually" |
Browser-automation testing (Playwright) |
| "Verify a specific UI interaction works" |
Browser-automation testing (Playwright) |
| "Take a screenshot of the app" |
Browser-automation testing (Playwright) |
| "Why isn't my button/form/component working?" |
Start here → if no code error found, hand off to browser-automation testing |
If a debug session isolates the problem to a UI behavior (not a code crash), stop and switch to browser-level investigation.
Step 0: Step Back (before any diagnosis)
Before investigating the specific bug, categorize it:
- What category of failure is this?
- Data issue (wrong input, corrupt data, missing values, type mismatch)
- Logic error (wrong condition, off-by-one, incorrect algorithm)
- State bug (race condition, stale cache, incorrect initialization)
- Environment mismatch (works locally, fails in CI; dependency version; config difference)
- Integration failure (API changed, schema drift, timeout, auth expired)
- What general debugging principle applies?
- If data: validate inputs first, check the pipeline upstream
- If logic: find the smallest reproducing case, binary-search for the breaking change
- If state: add logging at every state transition, check for concurrent access
- If environment: compare environments systematically (versions, configs, env vars)
- If integration: test the external dependency in isolation first
- What's the most common cause for this category in this codebase?
(Check any local record of past bugs/known failure modes if one exists.)
This narrows the search space BEFORE you read code. The category determines your strategy.
Step 1: Get the Situation
Before asking the user anything, run these immediately:
git diff # what changed in the working tree
git log --oneline -5 # recent commit history
Fallback: If git diff fails (git not found, not a repo, or permission error), skip it and ask: "What changed since it last worked? Any recent file edits, installs, or commands?"
Prior-insight retrieval: Before diagnosing, check whatever local notes exist (project notes, prior-decisions file, persistent insight log) for past learnings in this domain. Grep for keywords from the error (module names, error types, domain tags). If a past insight matches, state it: "Previously learned: [insight]. Checking if it applies here." This prevents re-discovering the same root cause.
Then collect only what you still can't answer from context:
- What broke? (error message, wrong behavior, crash — exact output if possible)
- When did it last work? (last commit, last action, "never worked")
- What changed? — answer from
git diff / git log first; only ask if unclear
- Can you reproduce it? — run the failing command directly first; only ask if intermittent
If the user gives a vague "it's broken" — run git commands first, then ask only the questions you can't self-answer.
Step 2: Triage — How Bad Is It?
| Severity |
Definition |
Action |
| 🔴 Critical |
App won't start / data at risk / irreversible side effects affected |
Stop everything, stabilize first |
| 🟠 High |
Core feature broken, tests failing, build fails |
Fix before new work |
| 🟡 Medium |
Feature degraded, visual bug, non-critical test fail |
Fix in current session |
| 🟢 Low |
Minor cosmetic, edge case, nice-to-have |
Log and schedule |
High-stakes note: Any issue touching live execution / payments / production writes = 🔴 Critical regardless of apparent severity. Stop and assess before proceeding.
Step 3: Reproduce
Don't debug what you can't reproduce. Steps:
- Run the exact failing command / interaction
- Capture the full error output (not just the last line)
- Confirm it's reproducible (not a fluke)
- If intermittent → note the conditions that trigger it
If it can't be reproduced:
- Check if it was a one-time environment issue
- Check for race conditions or async timing issues
- Try a clean restart (clear cache, restart dev server, fresh virtual environment)
Step 4: Isolate
Narrow down where the problem lives before touching code.
Frontend / web UI checklist:
Backend / service checklist:
An agent made changes and broke something:
Step 5: Diagnose
Root cause, not symptoms. Don't fix the first thing that looks wrong. Ask "Why did this happen?" at least twice. The first answer is usually a symptom. Infrastructure bugs especially tend to have a structural cause that recurs if you only patch the symptom. (Classic example: a series of "contamination" fixes that were all symptoms of one structural problem — a shared working directory.)
Step 5a: Gather Diagnostic Evidence
IMPORTANT: Log your hypothesis BEFORE running reproduce attempts. Without a hypothesis first, you're guessing — not debugging.
Before forming a hypothesis, collect raw evidence:
- Add temporary logging:
console.log('DEBUG:', variable) / print(f"DEBUG: {variable}") at the point of failure
- Log raw API response shape: Don't assume the shape — log
JSON.stringify(response) or print(response) and read the actual output
- Check async/await coverage: Scan the call chain — every async function needs an
await; a missing one returns a Promise/coroutine object instead of the value
- Verify immutability: If state looks wrong in a UI framework, check for direct mutation (
state.x = y instead of an immutable update)
- Check if the bug exists in isolation: Comment out surrounding code — does the issue persist with minimal input?
Only after collecting this evidence, proceed to form a hypothesis.
Form a hypothesis before writing any fix. State it explicitly:
"I think the issue is [X] because [evidence Y]. If I'm right, fixing [Z] should resolve it."
Evidence that supports a hypothesis > instinct. Common root causes by type:
Import / dependency errors:
- Missing package → install it
- Version mismatch → check the dependency manifest (
package.json / requirements.txt / lockfile)
- Circular import → restructure the module
Config / env errors:
- Missing
.env var → add it
- Wrong path → verify by printing/logging it
- Wrong port / host → check the config file
Logic errors:
- Off-by-one, wrong condition, inverted boolean
- Async timing (promise not awaited, callback order)
- State mutation (state directly mutated instead of via the framework's setter)
Data errors:
- API response shape changed
- Null/undefined where a value was expected
- Type mismatch (string vs number)
Agent-introduced errors:
- Read the diff — what did it actually change vs what it said it changed?
- Did it touch a file it shouldn't have? (cross-reference project rules / off-limits paths)
- Did it change shared utilities, breaking other things?
- If an agent may have caused the bug, read the project's "Off-Limits" / "Hard Rules" sections first — these contain constraints agents sometimes miss.
Step 6: Fix
Only after Steps 3–5 are complete.
Fix rules:
- Fix one thing at a time — don't bundle multiple fixes
- Make the smallest change that addresses the root cause
- Don't refactor while fixing — add that to a TODO
- Add a comment if the fix is non-obvious:
# Fixes: [what was wrong and why]
For high-stakes (trading/financial/production) fixes:
- Test in paper/sandbox mode first, always
- If fixing execution logic: write a unit test before applying the fix
- Never go live to "test" a fix
Step 7: Verify
After the fix:
- Reproduce the original failure → confirm it no longer occurs
- Run the test suite: does anything new break?
- Spot-check adjacent behavior — did the fix have side effects?
- Commit with a clear message:
fix: [what was broken and what fixed it]
Don't mark as resolved until verified.
Step 8: Capture
After resolving, capture what happened so it doesn't repeat:
- Add a project rule (in your agent-instructions file, e.g.
CLAUDE.md / AGENTS.md) if an agent was the cause or this is a common mistake to avoid
- Log it in your project changelog/journal: what broke, what caused it, how it was fixed
- Add a test if the bug is reproducible and no test would have caught it
- Update
.claude/rules/ (or equivalent rules dir) if there's a pattern to prevent
- Persist the pattern to whatever cross-session memory you keep so future sessions don't repeat the diagnosis. Format:
"[BUG PATTERN]: [cause] → [fix]" — e.g., "[API KeyError]: response shape changed in v2 → access data['result']['price'], not data['price']"
- Extract a compact insight to your persistent notes, tagged with the relevant domain. Before writing, scan existing entries for the same tag — consolidate rather than duplicate. Format:
[DATE] [tag] INSIGHT: [root cause in one sentence]
[DATE] [tag] WHY: [why it wasn't obvious / what made it tricky]
Tag with the domain (e.g., [data], [ml], [api], [auth]) for future retrieval.
Was the agent the cause? Ask explicitly: "Did the agent produce the bug (wrong edit, wrong approach, wrong assumption)?" If yes, record the mistake pattern, check whether it's a repeat, and promote repeats into your hard-rules file so they can't recur.
Platform-Specific Checks (when on Windows)
- Encoding: prefix Python scripts with
PYTHONUTF8=1 (cp1252 vs UTF-8 mismatches)
- Paths: use forward slashes or raw strings; never backslash in Python imports
- Signal handlers: use
try/except, not add_signal_handler (not supported on Windows)
- Shell: verify
which bash works; PowerShell behaves differently for shell scripts
Quick Reference: Common Errors
Frontend / web UI
| Error |
Likely Cause |
Quick Fix |
| White screen / blank render |
UI framework crash — check console |
Capture console output via browser automation |
Cannot read properties of undefined |
Data not loaded before render |
Add loading state / null check |
| Styles missing |
Utility class not in config |
Check class name, check the CSS/build config |
| API 404 |
Wrong endpoint or dev server not running |
Confirm the dev server is running |
| Stale UI after change |
Hot reload failed |
Hard refresh (Ctrl+Shift+R) |
Backend / service
| Error |
Likely Cause |
Quick Fix |
ModuleNotFoundError |
Package not installed |
Install it / activate the correct virtual environment |
KeyError on API response |
API response shape changed |
Print the raw response and inspect |
| Logic not triggering |
Condition / branch not met |
Add debug logging where the condition is evaluated |
| Request rejected by an external service |
Input exceeds a limit |
Check the relevant limit/config value |
AttributeError on config |
Missing key or wrong default |
Check the config module and class defaults |
Bug appears in two repos at once: Likely a shared dependency. Debug each repo independently first; check shared tooling (runtime, package manager, git, virtual environment) last.
Rollback Procedure
If changes broke things and you want to revert:
# See what changed
git diff HEAD
# Unstage (keeps working-tree changes)
git reset HEAD
# Discard all working-tree changes
git reset --hard HEAD
# Revert a specific file only
git checkout HEAD -- path/to/file.py
# Go back to a specific commit
git log --oneline -10 # find the commit hash
git reset --hard <hash> # go back to it
Always confirm with the user before running git reset --hard — it discards changes permanently.
Second Opinion
If the bug is elusive after 2+ hypotheses, suggest a different model's perspective (e.g. codex exec 'Find the bug in this diff'). If the bug involves an external API/library behaving unexpectedly, suggest verifying the documented behavior with a grounded search tool (e.g. gemini -p 'Does [API/function] actually work this way? Check the docs.').
Trigger Conditions
- "It's not working", "tests are failing", "the build is broken", "nothing is running"
- "Something weird is happening", "it worked before", "I don't know what changed"
- "Rollback this" / any request to audit or reverse autonomous agent changes
- Any error, crash, unexpected output, or regression where the cause isn't obvious
Out of Scope
- An agent produced structurally wrong output (missed requirements, ignored instructions, added unwanted scope) → that's a reasoning bug, not a code bug; analyze the prompt/response instead
- "You missed the point", "that's not what I asked" → reasoning analysis, not this skill
- Design reviews → use code-review-session
- Refactoring → use refactor-session
- This skill is for CODE bugs (crashes, test failures, broken builds), not model-reasoning failures.
Common Traps
- Chasing symptoms instead of root cause: A
TypeError on line 50 may be caused by bad data on line 12. Trace the data flow backward from the error site before fixing at the crash point.
- Tests pass but prod fails: Tests often use mocked data or a clean environment. Bugs that only appear with real data, stale cache, or platform-specific behavior (encoding, timezone) won't be caught by unit tests. Reproduce in the closest-to-prod environment available.
- Fixing two things at once: Bundling a "quick cleanup" with a bug fix makes it impossible to tell which change resolved the issue — and if it regresses, you can't bisect cleanly.
- Assuming the error message is the bug: Error messages describe what failed, not why. "Connection refused" might be a missing env var, not a network issue. Read the full stack trace and check preconditions before trusting the message.
- Skipping diagnostic evidence (Step 5a): Jumping to a hypothesis without logging actual values leads to "I thought it was X" debugging loops. Always add temporary logging and read real output before forming a theory.
1---2name: debug-session3description: Use when something is broken and the cause isn't obvious. Trigger on: "it's not working", "tests are failing", "the build is broken", "nothing is running", "something weird is happening", "it worked before", "I don't know what changed", "rollback this", any error, crash, unexpected output, or regression. Also trigger when an agent made autonomous changes that need auditing or reversing. NOT for design reviews or refactoring — use code-review-session or refactor-session instead. Never assume cause — always diagnose before fixing.4license: MIT5---67## Hard Rules89- **High-stakes systems first:** Any issue touching irreversible side effects (live order execution, payments, production data writes, anything in a live-money or production financial system) is CRITICAL regardless of apparent severity. Stop and assess before proceeding.10- **Never assume cause — always diagnose before fixing.** State a hypothesis BEFORE changing any code.11- **Fix one thing at a time** — never bundle multiple fixes or refactor while fixing.1213# Debug Session — Systematic Root-Cause Diagnosis1415A disciplined diagnose-before-fix workflow. The goal is to find the *root* cause, not patch the first symptom, and to leave the codebase with a regression test plus a captured insight so the same bug can't recur.1617## Routing: Debug vs. Browser/UI Testing1819Before starting, route to the right approach:2021| Situation | Use |22|-----------|-----|23| App won't start, build fails, crash on load | **This skill** (debug-session) |24| Runtime error, logic bug, wrong data | **This skill** (debug-session) |25| "UI isn't doing what I expect visually" | Browser-automation testing (Playwright) |26| "Verify a specific UI interaction works" | Browser-automation testing (Playwright) |27| "Take a screenshot of the app" | Browser-automation testing (Playwright) |28| "Why isn't my button/form/component working?" | Start here → if no code error found, hand off to browser-automation testing |2930If a debug session isolates the problem to a UI behavior (not a code crash), stop and switch to browser-level investigation.3132---3334## Step 0: Step Back (before any diagnosis)3536Before investigating the specific bug, categorize it:37381. **What category of failure is this?**39 - Data issue (wrong input, corrupt data, missing values, type mismatch)40 - Logic error (wrong condition, off-by-one, incorrect algorithm)41 - State bug (race condition, stale cache, incorrect initialization)42 - Environment mismatch (works locally, fails in CI; dependency version; config difference)43 - Integration failure (API changed, schema drift, timeout, auth expired)442. **What general debugging principle applies?**45 - If data: validate inputs first, check the pipeline upstream46 - If logic: find the smallest reproducing case, binary-search for the breaking change47 - If state: add logging at every state transition, check for concurrent access48 - If environment: compare environments systematically (versions, configs, env vars)49 - If integration: test the external dependency in isolation first503. **What's the most common cause for this category in this codebase?**51 (Check any local record of past bugs/known failure modes if one exists.)5253This narrows the search space BEFORE you read code. The category determines your strategy.5455---5657## Step 1: Get the Situation5859Before asking the user anything, run these immediately:60```bash61git diff # what changed in the working tree62git log --oneline -5 # recent commit history63```6465> **Fallback:** If `git diff` fails (git not found, not a repo, or permission error), skip it and ask: "What changed since it last worked? Any recent file edits, installs, or commands?"6667> **Prior-insight retrieval:** Before diagnosing, check whatever local notes exist (project notes, prior-decisions file, persistent insight log) for past learnings in this domain. Grep for keywords from the error (module names, error types, domain tags). If a past insight matches, state it: "Previously learned: [insight]. Checking if it applies here." This prevents re-discovering the same root cause.6869Then collect only what you still can't answer from context:70711. **What broke?** (error message, wrong behavior, crash — exact output if possible)722. **When did it last work?** (last commit, last action, "never worked")733. **What changed?** — answer from `git diff` / `git log` first; only ask if unclear744. **Can you reproduce it?** — run the failing command directly first; only ask if intermittent7576If the user gives a vague "it's broken" — run git commands first, then ask only the questions you can't self-answer.7778---7980## Step 2: Triage — How Bad Is It?8182| Severity | Definition | Action |83|----------|-----------|--------|84| 🔴 Critical | App won't start / data at risk / irreversible side effects affected | Stop everything, stabilize first |85| 🟠 High | Core feature broken, tests failing, build fails | Fix before new work |86| 🟡 Medium | Feature degraded, visual bug, non-critical test fail | Fix in current session |87| 🟢 Low | Minor cosmetic, edge case, nice-to-have | Log and schedule |8889**High-stakes note:** Any issue touching live execution / payments / production writes = 🔴 Critical regardless of apparent severity. Stop and assess before proceeding.9091---9293## Step 3: Reproduce9495Don't debug what you can't reproduce. Steps:96971. Run the exact failing command / interaction982. Capture the full error output (not just the last line)993. Confirm it's reproducible (not a fluke)1004. If intermittent → note the conditions that trigger it101102If it can't be reproduced:103- Check if it was a one-time environment issue104- Check for race conditions or async timing issues105- Try a clean restart (clear cache, restart dev server, fresh virtual environment)106107---108109## Step 4: Isolate110111Narrow down *where* the problem lives before touching code.112113**Frontend / web UI checklist:**114- [ ] Capture browser console output via a browser-automation tool (agents can't open browser devtools directly)115- [ ] Network requests failing?116- [ ] Which component throws? (error-boundary message)117- [ ] Does it fail with mock data too, or only with live data?118- [ ] Does a clean dependency install + dev-server restart fix it?119- [ ] Any missing env vars?120121**Backend / service checklist:**122- [ ] Full traceback — read the *bottom* of the stack trace first123- [ ] Which module raises? Is it your code or a library?124- [ ] Does it fail in isolation (unit test) or only in the full pipeline?125- [ ] Environment issue? (runtime version, virtual environment active, deps installed)126- [ ] Any `.env` vars missing or misread?127- [ ] If it's a financial/trading system: does it fail in paper/sandbox mode? (if so, don't test in live mode)128129**An agent made changes and broke something:**130- [ ] Run `git diff` to see exactly what changed131- [ ] Run `git log --oneline -10` to find the last known-good commit132- [ ] Were there session notes describing what was being built?133134---135136## Step 5: Diagnose137138**Root cause, not symptoms.** Don't fix the first thing that looks wrong. Ask "Why did this happen?" at least twice. The first answer is usually a symptom. Infrastructure bugs especially tend to have a structural cause that recurs if you only patch the symptom. (Classic example: a series of "contamination" fixes that were all symptoms of one structural problem — a shared working directory.)139140### Step 5a: Gather Diagnostic Evidence141142IMPORTANT: Log your hypothesis BEFORE running reproduce attempts. Without a hypothesis first, you're guessing — not debugging.143144Before forming a hypothesis, collect raw evidence:145- **Add temporary logging:** `console.log('DEBUG:', variable)` / `print(f"DEBUG: {variable}")` at the point of failure146- **Log raw API response shape:** Don't assume the shape — log `JSON.stringify(response)` or `print(response)` and read the actual output147- **Check async/await coverage:** Scan the call chain — every async function needs an `await`; a missing one returns a Promise/coroutine object instead of the value148- **Verify immutability:** If state looks wrong in a UI framework, check for direct mutation (`state.x = y` instead of an immutable update)149- **Check if the bug exists in isolation:** Comment out surrounding code — does the issue persist with minimal input?150151Only after collecting this evidence, proceed to form a hypothesis.152153Form a hypothesis *before* writing any fix. State it explicitly:154155> "I think the issue is [X] because [evidence Y]. If I'm right, fixing [Z] should resolve it."156157Evidence that supports a hypothesis > instinct. Common root causes by type:158159**Import / dependency errors:**160- Missing package → install it161- Version mismatch → check the dependency manifest (`package.json` / `requirements.txt` / lockfile)162- Circular import → restructure the module163164**Config / env errors:**165- Missing `.env` var → add it166- Wrong path → verify by printing/logging it167- Wrong port / host → check the config file168169**Logic errors:**170- Off-by-one, wrong condition, inverted boolean171- Async timing (promise not awaited, callback order)172- State mutation (state directly mutated instead of via the framework's setter)173174**Data errors:**175- API response shape changed176- Null/undefined where a value was expected177- Type mismatch (string vs number)178179**Agent-introduced errors:**180- Read the diff — what did it actually change vs what it said it changed?181- Did it touch a file it shouldn't have? (cross-reference project rules / off-limits paths)182- Did it change shared utilities, breaking other things?183- If an agent may have caused the bug, read the project's "Off-Limits" / "Hard Rules" sections first — these contain constraints agents sometimes miss.184185---186187## Step 6: Fix188189Only after Steps 3–5 are complete.190191**Fix rules:**192- Fix one thing at a time — don't bundle multiple fixes193- Make the smallest change that addresses the root cause194- Don't refactor while fixing — add that to a TODO195- Add a comment if the fix is non-obvious: `# Fixes: [what was wrong and why]`196197**For high-stakes (trading/financial/production) fixes:**198- Test in paper/sandbox mode first, always199- If fixing execution logic: write a unit test before applying the fix200- Never go live to "test" a fix201202---203204## Step 7: Verify205206After the fix:2072081. Reproduce the original failure → confirm it no longer occurs2092. Run the test suite: does anything new break?2103. Spot-check adjacent behavior — did the fix have side effects?2114. Commit with a clear message: `fix: [what was broken and what fixed it]`212213**Don't mark as resolved until verified.**214215---216217## Step 8: Capture218219After resolving, capture what happened so it doesn't repeat:2202211. **Add a project rule** (in your agent-instructions file, e.g. `CLAUDE.md` / `AGENTS.md`) if an agent was the cause or this is a common mistake to avoid2222. **Log it** in your project changelog/journal: what broke, what caused it, how it was fixed2233. **Add a test** if the bug is reproducible and no test would have caught it2244. **Update `.claude/rules/`** (or equivalent rules dir) if there's a pattern to prevent2255. **Persist the pattern** to whatever cross-session memory you keep so future sessions don't repeat the diagnosis. Format: `"[BUG PATTERN]: [cause] → [fix]"` — e.g., `"[API KeyError]: response shape changed in v2 → access data['result']['price'], not data['price']"`2266. **Extract a compact insight** to your persistent notes, tagged with the relevant domain. Before writing, scan existing entries for the same tag — consolidate rather than duplicate. Format:227 ```228 [DATE] [tag] INSIGHT: [root cause in one sentence]229 [DATE] [tag] WHY: [why it wasn't obvious / what made it tricky]230 ```231 Tag with the domain (e.g., `[data]`, `[ml]`, `[api]`, `[auth]`) for future retrieval.232233**Was the agent the cause?** Ask explicitly: "Did the agent produce the bug (wrong edit, wrong approach, wrong assumption)?" If yes, record the mistake pattern, check whether it's a repeat, and promote repeats into your hard-rules file so they can't recur.234235---236237## Platform-Specific Checks (when on Windows)238239- Encoding: prefix Python scripts with `PYTHONUTF8=1` (cp1252 vs UTF-8 mismatches)240- Paths: use forward slashes or raw strings; never backslash in Python imports241- Signal handlers: use `try/except`, not `add_signal_handler` (not supported on Windows)242- Shell: verify `which bash` works; PowerShell behaves differently for shell scripts243244---245246## Quick Reference: Common Errors247248### Frontend / web UI249| Error | Likely Cause | Quick Fix |250|-------|-------------|-----------|251| White screen / blank render | UI framework crash — check console | Capture console output via browser automation |252| `Cannot read properties of undefined` | Data not loaded before render | Add loading state / null check |253| Styles missing | Utility class not in config | Check class name, check the CSS/build config |254| API 404 | Wrong endpoint or dev server not running | Confirm the dev server is running |255| Stale UI after change | Hot reload failed | Hard refresh (Ctrl+Shift+R) |256257### Backend / service258| Error | Likely Cause | Quick Fix |259|-------|-------------|-----------|260| `ModuleNotFoundError` | Package not installed | Install it / activate the correct virtual environment |261| `KeyError` on API response | API response shape changed | Print the raw response and inspect |262| Logic not triggering | Condition / branch not met | Add debug logging where the condition is evaluated |263| Request rejected by an external service | Input exceeds a limit | Check the relevant limit/config value |264| `AttributeError` on config | Missing key or wrong default | Check the config module and class defaults |265266> **Bug appears in two repos at once:** Likely a shared dependency. Debug each repo independently first; check shared tooling (runtime, package manager, git, virtual environment) last.267268---269270## Rollback Procedure271272If changes broke things and you want to revert:273```bash274# See what changed275git diff HEAD276277# Unstage (keeps working-tree changes)278git reset HEAD279280# Discard all working-tree changes281git reset --hard HEAD282283# Revert a specific file only284git checkout HEAD -- path/to/file.py285286# Go back to a specific commit287git log --oneline -10 # find the commit hash288git reset --hard <hash> # go back to it289```290291Always confirm with the user before running `git reset --hard` — it discards changes permanently.292293---294295## Second Opinion296297If the bug is elusive after 2+ hypotheses, suggest a different model's perspective (e.g. `codex exec 'Find the bug in this diff'`). If the bug involves an external API/library behaving unexpectedly, suggest verifying the documented behavior with a grounded search tool (e.g. `gemini -p 'Does [API/function] actually work this way? Check the docs.'`).298299---300301## Trigger Conditions302303- "It's not working", "tests are failing", "the build is broken", "nothing is running"304- "Something weird is happening", "it worked before", "I don't know what changed"305- "Rollback this" / any request to audit or reverse autonomous agent changes306- Any error, crash, unexpected output, or regression where the cause isn't obvious307308## Out of Scope309310- An agent produced structurally wrong *output* (missed requirements, ignored instructions, added unwanted scope) → that's a reasoning bug, not a code bug; analyze the prompt/response instead311- "You missed the point", "that's not what I asked" → reasoning analysis, not this skill312- Design reviews → use code-review-session313- Refactoring → use refactor-session314- This skill is for CODE bugs (crashes, test failures, broken builds), not model-reasoning failures.315316## Common Traps317318- **Chasing symptoms instead of root cause:** A `TypeError` on line 50 may be caused by bad data on line 12. Trace the data flow backward from the error site before fixing at the crash point.319- **Tests pass but prod fails:** Tests often use mocked data or a clean environment. Bugs that only appear with real data, stale cache, or platform-specific behavior (encoding, timezone) won't be caught by unit tests. Reproduce in the closest-to-prod environment available.320- **Fixing two things at once:** Bundling a "quick cleanup" with a bug fix makes it impossible to tell which change resolved the issue — and if it regresses, you can't bisect cleanly.321- **Assuming the error message is the bug:** Error messages describe *what* failed, not *why*. "Connection refused" might be a missing env var, not a network issue. Read the full stack trace and check preconditions before trusting the message.322- **Skipping diagnostic evidence (Step 5a):** Jumping to a hypothesis without logging actual values leads to "I thought it was X" debugging loops. Always add temporary logging and read real output before forming a theory.