Debugging Strategies
Purpose
"Guess and check" programming wastes hours. This skill replaces randomness with the scientific method: reproduce the bug reliably, isolate the failing component via binary search, formulate testable hypotheses, and apply minimal fixes. The goal is deterministic bug resolution, not random fixes that seem to work.
When to use
- Investigating a defect reported in production
- Facing a failing test with no obvious root cause
- Understanding unfamiliar or undocumented legacy code
- Debugging intermittent failures (flaky tests)
When NOT to use
- Performance optimization (use Caching Strategies or Database Query Optimization)
- Code review (use Code Review Guidelines)
- Architecture decisions (different concern)
Inputs required
- Failing code, test, or end-to-end scenario
- Ability to reproduce the failure
- Source code and execution environment
Workflow
- Reproduce the Bug: Consistently replicate the failure state. If you CANNOT reproduce it, STOP (get more details). Write a failing test.
- Isolate the Subsystem: Use binary search (comment out code halves, use
git bisect, add logging) to locate the exact module causing the issue
- Formulate Hypothesis: Propose WHY the failure is happening based on logs, stack traces, and code inspection
- Test Hypothesis: Add targeted logging or step through debugger to verify assumptions about state/variables at runtime
- Apply Minimal Fix: Change ONLY what's necessary to make the test pass (single line if possible)
- Verify Fix: Confirm the failing test now passes, and no other tests break
- Add Regression Test: Ensure this bug never reoccurs
Rules
- MUST establish a reproducible test BEFORE changing code
- MUST only change one variable or line at a time during hypothesis testing
- MUST NOT apply multiple changes simultaneously (makes diagnosis impossible)
- MUST use binary search for isolation (comment out halves, not random guessing)
- MUST formulate a hypothesis before adding logging or changes
- MUST keep the fix minimal (change only what caused the bug)
Anti-patterns
- Shotgun Debugging: Randomly changing configuration or code until things "seem to work"
- Blaming the Compiler: Assuming the language/framework is broken before checking your code
- Adding Debug Code: Adding excessive logging everywhere instead of targeted logging
- Not Isolating: Staring at code trying to reason about it instead of actually testing
- Fixing Symptoms: "Fixing" the error message instead of fixing the root cause
- Multiple Changes: Changing 5 things at once, then one works, but you don't know which
Failure conditions
- Bug cannot be reproduced
- Test passes but bug still exists in production
- No hypothesis formed before debugging
- Fix applied without verification test
- Multiple changes applied simultaneously
Validation checklist
Output format
- Failing test: Automated test that reproduces the bug
- Minimal fix: Code change addressing root cause only
- Regression test: Test ensuring bug never reoccurs
- Documentation: Comment explaining root cause and why fix works
Security considerations
- Debug logging MUST NOT leak sensitive data (credentials, PII)
- Breakpoint debugging MUST NOT be left in production code
- Temporary logging MUST be removed before commit
- Hypothesis testing MUST NOT modify production data
Agent execution notes
- Agent MAY: Add failing tests, add targeted logging, apply minimal fixes, use git bisect
- Agent MUST NEVER: Make multiple changes simultaneously, apply fixes without tests, leave debug code
- Agent MUST ASK: Before running expensive operations, before modifying production-like data
- Agent MUST VALIDATE: Failing test reproduces bug, fix is minimal, regression test present
Example
❌ Anti-pattern (Shotgun debugging, multiple changes, no hypothesis):
// User reports: "Login sometimes fails"
// Response: randomly change stuff
// Change 1: Remove cache (wild guess)
Cache.clear();
// Change 2: Increase timeout (wild guess)
timeout = 5000;
// Change 3: Retry login (wild guess)
retry();
// Change 4: Restart server
process.restart();
// "It works now!" - but which change fixed it?
✅ Correct pattern (Systematic, hypothesis-driven, minimal fix):
// User reports: "Login sometimes fails with 'Session token invalid'"
// 1. Create failing test
test('login should succeed with valid credentials', async () => {
const user = await login('user@test.com', 'password');
expect(user).toBeDefined();
});
// 2. Run test 10 times - fails randomly - good, reproducible
for (let i = 0; i < 10; i++) {
npm test; // Run failing test
}
// 3. Isolate subsystem with logging
function validateToken(token) {
console.log('Token:', token, 'Expires:', token.expiresAt, 'Now:', Date.now());
if (token.expiresAt < Date.now()) {
throw new Error('Token expired');
}
}
// 4. Hypothesis: Token generation race condition in parallel requests
// 5. Test: Run login twice simultaneously
Promise.all([login(...), login(...)]);
// Confirm: Second request gets token from first request but with different expiresAt
// 6. Minimal fix: Add mutex to token generation
const mutex = new Mutex();
async function generateToken() {
return mutex.runExclusive(async () => {
return createToken();
});
}
// 7. Verify: Failing test now passes 100 times
// 8. Add regression test
test('concurrent logins should not fail', async () => {
const results = await Promise.all([
login('user@test.com', 'password'),
login('user@test.com', 'password')
]);
expect(results.every(r => r)).toBe(true);
});
1---2name: debugging-strategies3description: When isolating and fixing unpredictable or complex software bugs.4license: MIT5---67# Debugging Strategies89## Purpose10"Guess and check" programming wastes hours. This skill replaces randomness with the scientific method: reproduce the bug reliably, isolate the failing component via binary search, formulate testable hypotheses, and apply minimal fixes. The goal is deterministic bug resolution, not random fixes that seem to work.1112## When to use13- Investigating a defect reported in production14- Facing a failing test with no obvious root cause15- Understanding unfamiliar or undocumented legacy code16- Debugging intermittent failures (flaky tests)1718## When NOT to use19- Performance optimization (use Caching Strategies or Database Query Optimization)20- Code review (use Code Review Guidelines)21- Architecture decisions (different concern)2223## Inputs required24- Failing code, test, or end-to-end scenario25- Ability to reproduce the failure26- Source code and execution environment2728## Workflow291. **Reproduce the Bug**: Consistently replicate the failure state. If you CANNOT reproduce it, STOP (get more details). Write a failing test.302. **Isolate the Subsystem**: Use binary search (comment out code halves, use `git bisect`, add logging) to locate the exact module causing the issue313. **Formulate Hypothesis**: Propose WHY the failure is happening based on logs, stack traces, and code inspection324. **Test Hypothesis**: Add targeted logging or step through debugger to verify assumptions about state/variables at runtime335. **Apply Minimal Fix**: Change ONLY what's necessary to make the test pass (single line if possible)346. **Verify Fix**: Confirm the failing test now passes, and no other tests break357. **Add Regression Test**: Ensure this bug never reoccurs3637## Rules38- MUST establish a reproducible test BEFORE changing code39- MUST only change one variable or line at a time during hypothesis testing40- MUST NOT apply multiple changes simultaneously (makes diagnosis impossible)41- MUST use binary search for isolation (comment out halves, not random guessing)42- MUST formulate a hypothesis before adding logging or changes43- MUST keep the fix minimal (change only what caused the bug)4445## Anti-patterns46- **Shotgun Debugging**: Randomly changing configuration or code until things "seem to work"47- **Blaming the Compiler**: Assuming the language/framework is broken before checking your code48- **Adding Debug Code**: Adding excessive logging everywhere instead of targeted logging49- **Not Isolating**: Staring at code trying to reason about it instead of actually testing50- **Fixing Symptoms**: "Fixing" the error message instead of fixing the root cause51- **Multiple Changes**: Changing 5 things at once, then one works, but you don't know which5253## Failure conditions54- Bug cannot be reproduced55- Test passes but bug still exists in production56- No hypothesis formed before debugging57- Fix applied without verification test58- Multiple changes applied simultaneously5960## Validation checklist61- [ ] Failing test or scenario created and reproducible62- [ ] Bug can be consistently reproduced every time63- [ ] Subsystem isolated (know which file/function is failing)64- [ ] Hypothesis is specific (not "something is wrong")65- [ ] Targeted logging/breakpoints confirm hypothesis66- [ ] Fix is minimal (only necessary changes)67- [ ] Failing test now passes68- [ ] No other tests broken69- [ ] Regression test added70- [ ] Root cause documented in code comments or commit7172## Output format73- **Failing test**: Automated test that reproduces the bug74- **Minimal fix**: Code change addressing root cause only75- **Regression test**: Test ensuring bug never reoccurs76- **Documentation**: Comment explaining root cause and why fix works7778## Security considerations79- Debug logging MUST NOT leak sensitive data (credentials, PII)80- Breakpoint debugging MUST NOT be left in production code81- Temporary logging MUST be removed before commit82- Hypothesis testing MUST NOT modify production data8384## Agent execution notes85- Agent MAY: Add failing tests, add targeted logging, apply minimal fixes, use git bisect86- Agent MUST NEVER: Make multiple changes simultaneously, apply fixes without tests, leave debug code87- Agent MUST ASK: Before running expensive operations, before modifying production-like data88- Agent MUST VALIDATE: Failing test reproduces bug, fix is minimal, regression test present8990## Example9192**❌ Anti-pattern (Shotgun debugging, multiple changes, no hypothesis):**93```javascript94// User reports: "Login sometimes fails"95// Response: randomly change stuff9697// Change 1: Remove cache (wild guess)98Cache.clear();99100// Change 2: Increase timeout (wild guess)101timeout = 5000;102103// Change 3: Retry login (wild guess)104retry();105106// Change 4: Restart server107process.restart();108109// "It works now!" - but which change fixed it?110```111112**✅ Correct pattern (Systematic, hypothesis-driven, minimal fix):**113```javascript114// User reports: "Login sometimes fails with 'Session token invalid'"115116// 1. Create failing test117test('login should succeed with valid credentials', async () => {118 const user = await login('user@test.com', 'password');119 expect(user).toBeDefined();120});121122// 2. Run test 10 times - fails randomly - good, reproducible123for (let i = 0; i < 10; i++) {124 npm test; // Run failing test125}126127// 3. Isolate subsystem with logging128function validateToken(token) {129 console.log('Token:', token, 'Expires:', token.expiresAt, 'Now:', Date.now());130 if (token.expiresAt < Date.now()) {131 throw new Error('Token expired');132 }133}134135// 4. Hypothesis: Token generation race condition in parallel requests136// 5. Test: Run login twice simultaneously137Promise.all([login(...), login(...)]);138// Confirm: Second request gets token from first request but with different expiresAt139140// 6. Minimal fix: Add mutex to token generation141const mutex = new Mutex();142async function generateToken() {143 return mutex.runExclusive(async () => {144 return createToken();145 });146}147148// 7. Verify: Failing test now passes 100 times149// 8. Add regression test150test('concurrent logins should not fail', async () => {151 const results = await Promise.all([152 login('user@test.com', 'password'),153 login('user@test.com', 'password')154 ]);155 expect(results.every(r => r)).toBe(true);156});157```