Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
Core principle: Trace backward through the call chain until you find the original trigger, then fix at the source.
- Error happens deep in execution (not at entry point)
- Stack trace shows long call chain
- Unclear where invalid data originated
- Need to find which test/code triggers the problem
If you can trace backwards, trace to the original trigger. If you hit a dead end, fix at the symptom point as a last resort. Once you find the root cause, also add defense-in-depth validation (see defense-in-depth.md).
Error: git init failed in /Users/jesse/project/packages/core
What code directly causes this?
await execFileAsync('git', ['init'], { cwd: projectDir });WorktreeManager.createSessionWorktree(projectDir, sessionId)
→ called by Session.initializeWorkspace()
→ called by Session.create()
→ called by test at Project.create()What value was passed?
projectDir = ''(empty string!)- Empty string as
cwdresolves toprocess.cwd() - That's the source code directory!
Where did empty string come from?
const context = setupCoreTest(); // Returns { tempDir: '' }
Project.create('name', context.tempDir); // Accessed before beforeEach!When you can't trace manually, add instrumentation:
// Before the problematic operation
async function gitInit(directory: string) {
const stack = new Error().stack;
console.error('DEBUG git init:', {
directory,
cwd: process.cwd(),
nodeEnv: process.env.NODE_ENV,
stack,
});
await execFileAsync('git', ['init'], { cwd: directory });
}Run and capture:
npm test 2>&1 | grep 'DEBUG git init'Analyze stack traces:
- Look for test file names
- Find the line number triggering the call
- Identify the pattern (same test? same parameter?)
If something appears during tests but you don't know which test, use bisection: run tests one-by-one and stop at the first polluter.
# Run each test file in isolation to find which one pollutes
for f in src/**/*.test.ts; do
npx jest "$f" --silent 2>/dev/null
if [ -d ".git" ]; then # or whatever artifact you're looking for
echo "POLLUTER: $f"
break
fi
doneSymptom: .git created in packages/core/ (source code)
Trace chain:
git initruns inprocess.cwd()-- empty cwd parameter- WorktreeManager called with empty projectDir
- Session.create() passed empty string
- Test accessed
context.tempDirbefore beforeEach - setupCoreTest() returns
{ tempDir: '' }initially
Root cause: Top-level variable initialization accessing empty value
Fix: Made tempDir a getter that throws if accessed before beforeEach
Also added defense-in-depth:
- Layer 1: Project.create() validates directory
- Layer 2: WorkspaceManager validates not empty
- Layer 3: NODE_ENV guard refuses git init outside tmpdir
- Layer 4: Stack trace logging before git init
Never fix just where the error appears. The process is:
- Find the immediate cause
- Trace one level up -- keep going until you find the source
- Fix at the source
- Add validation at each layer the data passes through
- The bug becomes structurally impossible
- In tests: Use
console.error()not logger -- logger may be suppressed - Before operation: Log before the dangerous operation, not after it fails
- Include context: Directory, cwd, environment variables, timestamps
- Capture stack:
new Error().stackshows complete call chain
From debugging session (2025-10-03):
- Found root cause through 5-level trace
- Fixed at source (getter validation)
- Added 4 layers of defense
- 1847 tests passed, zero pollution