name: debug-detective description: Systematically debug an error by tracing its origin through the codebase, identifying root causes, and suggesting targeted fixes. Produces a structured investigation log.
Debug Detective
Systematically investigate an error or unexpected behavior, trace it to its root cause, and provide actionable fixes.
Inputs
The user provides one or more of:
- An error message or stack trace
- A description of unexpected behavior
- A failing test or command
Steps
1. Capture the Error
If the user provided a stack trace, parse it to extract:
- Error type: e.g.,
TypeError,ReferenceError,ENOENT, HTTP status code - Error message: The human-readable description
- File and line: The origin point from the stack trace
- Call chain: The sequence of function calls leading to the error
If the user only described the behavior, ask them to reproduce it and capture the exact error. Alternatively, search for likely error sources:
grep -r "<error message keywords>" src/
2. Locate the Error Origin
Search the codebase for the exact error message or the throwing code:
grep -rn "<error message>" src/ lib/ app/
grep -rn "throw new" src/ --include="*.ts" --include="*.js"
Read the file and surrounding context at the identified location. If the error comes from a dependency, check node_modules/<package>/ or the package's changelog for known issues.
3. Trace the Call Stack
Starting from the error origin, trace backwards through the code:
- Read the function that throws the error.
- Search for all callers of that function:
grep -rn "<functionName>" src/ - Read each caller to understand what inputs they pass.
- Continue tracing until you reach the entry point (route handler, event listener, CLI command, etc.).
Build a call chain diagram:
Entry: POST /api/orders (src/routes/orders.ts:45)
-> OrderService.create (src/services/order.service.ts:23)
-> validateInventory (src/utils/inventory.ts:78)
-> ERROR: Cannot read property 'quantity' of undefined (line 82)
4. Identify Root Causes
Based on the trace, identify the top 3 most likely root causes. For each, explain:
- What: What specifically is wrong
- Why: Why this condition occurs
- Evidence: Which code/data supports this theory
- Likelihood: High / Medium / Low
Common Patterns to Check
Run through these known bug patterns and check if any apply:
Null/Undefined References
- Optional chaining missing (
obj.propvsobj?.prop) - Array access without bounds check
- Map/Object lookup returning undefined
- Destructuring from null
Async/Await Issues
- Missing
awaiton async function call - Unhandled promise rejection
- Race condition between parallel operations
- Using
.then()without.catch()
Import/Module Errors
- Circular dependencies:
grep -rn "import.*from" <file>and trace the import graph - Default vs named export mismatch
- ESM vs CJS interop issues (
requirein.mjs,importin.cjs) - Missing file extension in ESM imports
Environment/Config Issues
- Missing environment variable:
grep -rn "process.env.<VAR>" src/ - Wrong environment (dev config in prod)
- Missing or malformed
.envfile - Port conflict or connection string error
Type/Data Issues
- String where number expected (or vice versa)
- Date parsing/timezone issues
- JSON parse failure on unexpected input
- Encoding issues (UTF-8, Base64)
Dependency Issues
- Version mismatch: check
package.jsonvspackage-lock.json - Peer dependency conflicts
- Breaking change in minor/patch update
5. Verify the Root Cause
For the highest-likelihood cause, verify it:
- Read the specific code path and confirm the failure condition.
- Check if there are existing tests that should have caught this. If so, understand why they didn't.
- Look for similar patterns elsewhere in the codebase that might have the same bug:
grep -rn "<similar pattern>" src/
6. Suggest Fixes
For each confirmed root cause, provide a specific fix:
## Fix for Root Cause #1: Missing null check on inventory lookup
File: src/utils/inventory.ts, line 82
Before:
const qty = items.find(i => i.sku === sku).quantity;
After:
const item = items.find(i => i.sku === sku);
if (!item) {
throw new Error(`Inventory item not found for SKU: ${sku}`);
}
const qty = item.quantity;
If multiple fixes are needed, present them in order of priority.
7. Check for Related Issues
Search for the same bug pattern elsewhere:
grep -rn "<vulnerable pattern>" src/
Report any additional locations that have the same vulnerability.
8. Create Investigation Log
Create a file debug-notes-<timestamp>.md in the project root (or a docs/ or .debug/ directory if one exists) with the full investigation:
# Debug Investigation: <error summary>
**Date**: <current date>
**Error**: <full error message>
**Status**: RESOLVED | IN_PROGRESS | NEEDS_INPUT
## Stack Trace
<original stack trace>
## Call Chain
<traced call chain>
## Root Causes Investigated
1. <cause> - <likelihood> - <status>
2. <cause> - <likelihood> - <status>
3. <cause> - <likelihood> - <status>
## Fix Applied
<description of the fix>
## Related Issues Found
<list of similar patterns found elsewhere>
## Prevention
<suggestions to prevent this class of bug>
9. Prevention Recommendations
After fixing, suggest preventive measures:
- Add a specific test case that reproduces this bug
- Add TypeScript strict mode if not enabled (
"strict": true) - Add runtime validation at the boundary where bad data entered
- Add a lint rule if the pattern is catchable by static analysis
- Add error monitoring/alerting for this error class
Output Format
Present the investigation as a clear narrative:
## Debug Investigation: <short title>
### Error
<error message>
### Trace
<call chain diagram>
### Root Cause
<explanation of what went wrong and why>
### Fix
<code diff>
### Also Found
<related issues, if any>
### Prevention
<recommendations>
Edge Cases
- No stack trace available: Use search to find where the error message is defined, then work forward to find trigger conditions.
- Error in third-party code: Trace back to find what input from the user's code triggered the library error. The fix is usually at the boundary.
- Intermittent/flaky errors: Look for race conditions, timing dependencies, or external service failures. Suggest adding retries, timeouts, or better error handling.
- Build/compile errors: Check
tsconfig.json,package.jsonscripts, and recent dependency changes.