# Root Cause Tracing ## Overview 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. ## When to Use **Use when:** - 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 ## The Tracing Process ### 1. Observe the Symptom ``` Error: git init failed in /Users/user/project/packages/core ``` ### 2. Find Immediate Cause **What code directly causes this?** ``` await execFile("git", ["init"], { cwd: projectDir }) ``` ### 3. Ask: What Called This? ``` WorktreeManager.createSessionWorktree(projectDir, sessionId) → called by Session.initializeWorkspace() → called by Session.create() → called by test at Project.create() ``` ### 4. Keep Tracing Up **What value was passed?** - `projectDir = ''` (empty string!) - Empty string as `cwd` resolves to current working directory - That's the source code directory! ### 5. Find Original Trigger **Where did empty string come from?** ``` context = setupCoreTest() # Returns { tempDir: '' } Project.create("name", context.tempDir) # Accessed before beforeEach! ``` ## Adding Stack Traces When you can't trace manually, add instrumentation: ``` # Before the problematic operation function gitInit(directory): stack = getStackTrace() logError("DEBUG git init:", { directory: directory, cwd: getCwd(), nodeEnv: getEnv("NODE_ENV"), stack: stack, }) await execFile("git", ["init"], { cwd: directory }) ``` **Critical:** Use stderr in tests (not logger - may not show) **Run and capture:** ``` runTests() 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?) ## Key Principle **NEVER fix just where the error appears.** Trace back to find the original trigger. **Pattern:** 1. Found immediate cause - can you trace one level up? 2. If yes, keep tracing backward 3. If no (dead end), you found the source 4. Fix at source, then add validation at each layer 5. Bug becomes impossible to reproduce ## Stack Trace Tips **In tests:** Use stderr 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:** `getStackTrace()` shows complete call chain