Systematic debugging: root cause analysis, defense-in-depth validation, log correlation, and distributed systems troubleshooting

version
1.0.0

Install

/plugin install debug@dot-claude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pproenca/dot-claude-old.

Contents

Discovered from source

Skills 3

Defense-in-Depth Validation

Overview

When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.

Core principle: Validate at EVERY layer data passes through. Make the bug structurally impossible.

Why Multiple Layers

Single validation: "We fixed the bug" Multiple layers: "We made the bug impossible"

Different layers catch different cases:

  • Entry validation catches most bugs
  • Business logic catches edge cases
  • Environment guards prevent context-specific dangers
  • Debug logging helps when other layers fail

The Four Layers

Layer 1: Entry Point Validation

Purpose: Reject obviously invalid input at API boundary

function createProject(name: string, workingDirectory: string) {
  if (!workingDirectory || workingDirectory.trim() === '') {
    throw new Error('workingDirectory cannot be empty');
  }
  if (!existsSync(workingDirectory)) {
    throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
  }
  if (!statSync(workingDirectory).isDirectory()) {
    throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
  }
  // ... proceed
}

Layer 2: Business Logic Validation

Purpose: Ensure data makes sense for this operation

function initializeWorkspace(projectDir: string, sessionId: string) {
  if (!projectDir) {
    throw new Error('projectDir required for workspace initialization');
  }
  // ... proceed
}

Layer 3: Environment Guards

Purpose: Prevent dangerous operations in specific contexts

async function gitInit(directory: string) {
  // In tests, refuse git init outside temp directories
  if (process.env.NODE_ENV === 'test') {
    const normalized = normalize(resolve(directory));
    const tmpDir = normalize(resolve(tmpdir()));

    if (!normalized.startsWith(tmpDir)) {
      throw new Error(
        `Refusing git init outside temp dir during tests: ${directory}`
      );
    }
  }
  // ... proceed
}

Layer 4: Debug Instrumentation

Purpose: Capture context for forensics

async function gitInit(directory: string) {
  const stack = new Error().stack;
  logger.debug('About to git init', {
    directory,
    cwd: process.cwd(),
    stack,
  });
  // ... proceed
}

Applying the Pattern

When you find a bug:

  1. Trace the data flow - Where does bad value originate? Where used?
  2. Map all checkpoints - List every point data passes through
  3. Add validation at each layer - Entry, business, environment, debug
  4. Test each layer - Try to bypass layer 1, verify layer 2 catches it

Example from Session

Bug: Empty projectDir caused git init in source code

Data flow:

  1. Test setup → empty string
  2. Project.create(name, '')
  3. WorkspaceManager.createWorkspace('')
  4. git init runs in process.cwd()

Four layers added:

  • Layer 1: Project.create() validates not empty/exists/writable
  • Layer 2: WorkspaceManager validates projectDir not empty
  • Layer 3: WorktreeManager refuses git init outside tmpdir in tests
  • Layer 4: Stack trace logging before git init

Result: All 1847 tests passed, bug impossible to reproduce

Key Insight

All four layers were necessary. During testing, each layer caught bugs the others missed:

  • Different code paths bypassed entry validation
  • Mocks bypassed business logic checks
  • Edge cases on different platforms needed environment guards
  • Debug logging identified structural misuse

Don't stop at one validation point. Add checks at every layer.

Integration

Used by: debug:systematic (Phase 4 - after fixing root cause) Pairs with: debug:root-cause (find where to add validation)

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

Large Codebase Optimization

Use Explore subagent to trace call chains:

  • Delegates investigation to subagent
  • Returns focused summary without context bloat
  • Essential for codebases with deep call stacks

This prevents main conversation pollution during investigation. The Explore agent can navigate through multiple files and return a clean summary of the call chain.

The Tracing Process

1. Observe the Symptom

Error: git init failed in /Users/jesse/project/packages/core

2. Find Immediate Cause

What code directly causes this?

await execFileAsync('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 process.cwd()
  • That's the source code directory!

5. Find Original Trigger

Where did empty string come from?

const 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
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 });
}

Critical: Use console.error() in tests (not logger - may not show)

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?)

Finding Which Test Causes Pollution

If something appears during tests but you don't know which test:

Use the bisection script: @find-polluter.sh

./find-polluter.sh '.git' 'src/**/*.test.ts'

Runs tests one-by-one, stops at first polluter. See script for usage.

Real Example: Empty projectDir

Symptom: .git created in packages/core/ (source code)

Trace chain:

  1. git init runs in process.cwd() ← empty cwd parameter
  2. WorktreeManager called with empty projectDir
  3. Session.create() passed empty string
  4. Test accessed context.tempDir before beforeEach
  5. 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

Key Principle

NEVER fix just where the error appears. Trace back to find the original trigger.

Stack Trace Tips

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().stack shows complete call chain

Integration

Used by: debug:systematic (Phase 1, Step 5) Pairs with: debug:defense-in-depth (add validation after finding root cause)

Systematic Debugging

Overview

Random fixes waste time and create new bugs. Quick patches mask underlying issues.

Core principle: ALWAYS find root cause before attempting fixes. Symptom fixes are failure.

Violating the letter of this process is violating the spirit of debugging.

The Iron Law

NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST

If you haven't completed Phase 1, you cannot propose fixes.

When to Use

Use for ANY technical issue:

  • Test failures
  • Bugs in production
  • Unexpected behavior
  • Performance problems
  • Build failures
  • Integration issues

Use this ESPECIALLY when:

  • Under time pressure (emergencies make guessing tempting)
  • "Just one quick fix" seems obvious
  • You've already tried multiple fixes
  • Previous fix didn't work
  • You don't fully understand the issue

Don't skip when:

  • Issue seems simple (simple bugs have root causes too)
  • You're in a hurry (rushing guarantees rework)
  • Manager wants it fixed NOW (systematic is faster than thrashing)

The Four Phases

You MUST complete each phase before proceeding to the next.

Phase 1: Root Cause Investigation

BEFORE attempting ANY fix:

  1. Read Error Messages Carefully

    • Don't skip past errors or warnings
    • They often contain the exact solution
    • Read stack traces completely
    • Note line numbers, file paths, error codes
  2. Reproduce Consistently

    • Can you trigger it reliably?
    • What are the exact steps?
    • Does it happen every time?
    • If not reproducible → gather more data, don't guess
  3. Check Recent Changes

    • What changed that could cause this?
    • Git diff, recent commits
    • New dependencies, config changes
    • Environmental differences
  4. Gather Evidence in Multi-Component Systems

    WHEN system has multiple components (CI → build → signing, API → service → database):

    Context Management: Use Explore subagent to map component boundaries before instrumenting:

    • Prevents main conversation pollution during investigation
    • Produces clean summary of architecture for focused debugging
    • Essential for large codebases with many layers

    Parallel Investigation: For independent components, consider workflow:parallel-agents:

    • Investigate multiple components simultaneously
    • Converge findings to identify root cause
    • Reduces total investigation time for complex systems

    BEFORE proposing fixes, add diagnostic instrumentation:

    For EACH component boundary:
      - Log what data enters component
      - Log what data exits component
      - Verify environment/config propagation
      - Check state at each layer
    
    Run once to gather evidence showing WHERE it breaks
    THEN analyze evidence to identify failing component
    THEN investigate that specific component
    
  5. Trace Data Flow

    WHEN error is deep in call stack:

    REQUIRED SUB-SKILL: Use debug:root-cause for backward tracing technique

    Quick version:

    • Where does bad value originate?
    • What called this with bad value?
    • Keep tracing up until you find the source
    • Fix at source, not at symptom

Phase 2: Pattern Analysis

Find the pattern before fixing:

  1. Find Working Examples

    • Locate similar working code in same codebase
    • What works that's similar to what's broken?
  2. Compare Against References

    • If implementing pattern, read reference implementation COMPLETELY
    • Don't skim - read every line
    • Understand the pattern fully before applying
  3. Identify Differences

    • What's different between working and broken?
    • List every difference, however small
    • Don't assume "that can't matter"
  4. Understand Dependencies

    • What other components does this need?
    • What settings, config, environment?
    • What assumptions does it make?

Phase 3: Hypothesis and Testing

Scientific method:

  1. Form Single Hypothesis

    • State clearly: "I think X is the root cause because Y"
    • Write it down
    • Be specific, not vague
  2. Test Minimally

    • Make the SMALLEST possible change to test hypothesis
    • One variable at a time
    • Don't fix multiple things at once
  3. Verify Before Continuing

    • Did it work? Yes → Phase 4
    • Didn't work? Form NEW hypothesis
    • DON'T add more fixes on top
  4. When You Don't Know

    • Say "I don't understand X"
    • Don't pretend to know
    • Ask for help
    • Research more

Phase 4: Implementation

Fix the root cause, not the symptom:

  1. Create Failing Test Case

    • Simplest possible reproduction
    • Automated test if possible
    • One-off test script if no framework
    • MUST have before fixing
    • REQUIRED SUB-SKILL: Use core:tdd for writing proper failing tests
  2. Implement Single Fix

    • Address the root cause identified
    • ONE change at a time
    • No "while I'm here" improvements
    • No bundled refactoring
  3. Verify Fix

    • Test passes now?
    • No other tests broken?
    • Issue actually resolved?
  4. If Fix Doesn't Work

    • STOP
    • Count: How many fixes have you tried?
    • If < 3: Return to Phase 1, re-analyze with new information
    • If ≥ 3: STOP and question the architecture (step 5 below)
    • DON'T attempt Fix #4 without architectural discussion
  5. If 3+ Fixes Failed: Question Architecture

    Pattern indicating architectural problem:

    • Each fix reveals new shared state/coupling/problem in different place
    • Fixes require "massive refactoring" to implement
    • Each fix creates new symptoms elsewhere

    STOP and question fundamentals:

    • Is this pattern fundamentally sound?
    • Are we "sticking with it through sheer inertia"?
    • Should we refactor architecture vs. continue fixing symptoms?

    Discuss with your human partner before attempting more fixes

    This is NOT a failed hypothesis - this is a wrong architecture.

Red Flags - STOP and Follow Process

If you catch yourself thinking:

  • "Quick fix for now, investigate later"
  • "Just try changing X and see if it works"
  • "Add multiple changes, run tests"
  • "Skip the test, I'll manually verify"
  • "It's probably X, let me fix that"
  • "I don't fully understand but this might work"
  • "Pattern says X but I'll adapt it differently"
  • "Here are the main problems: [lists fixes without investigation]"
  • Proposing solutions before tracing data flow
  • "One more fix attempt" (when already tried 2+)
  • Each fix reveals new problem in different place

ALL of these mean: STOP. Return to Phase 1.

If 3+ fixes failed: Question the architecture (see Phase 4.5)

Common Rationalizations

ExcuseReality
"Issue is simple, don't need process"Simple issues have root causes too. Process is fast for simple bugs.
"Emergency, no time for process"Systematic debugging is FASTER than guess-and-check thrashing.
"Just try this first, then investigate"First fix sets the pattern. Do it right from the start.
"I'll write test after confirming fix works"Untested fixes don't stick. Test first proves it.
"Multiple fixes at once saves time"Can't isolate what worked. Causes new bugs.
"Reference too long, I'll adapt the pattern"Partial understanding guarantees bugs. Read it completely.
"I see the problem, let me fix it"Seeing symptoms ≠ understanding root cause.
"One more fix attempt" (after 2+ failures)3+ failures = architectural problem. Question pattern, don't fix again.

Quick Reference

PhaseKey ActivitiesSuccess Criteria
1. Root CauseRead errors, reproduce, check changes, gather evidenceUnderstand WHAT and WHY
2. PatternFind working examples, compareIdentify differences
3. HypothesisForm theory, test minimallyConfirmed or new hypothesis
4. ImplementationCreate test, fix, verifyBug resolved, tests pass

Integration with Other Skills

This skill requires using:

  • debug:root-cause - Use when error is deep in call stack (see Phase 1, Step 5)
  • core:tdd - Use for creating failing test case (see Phase 4, Step 1)

Complementary skills:

  • debug:defense-in-depth - Add validation at multiple layers after finding root cause
  • testing:condition-wait - Replace arbitrary timeouts identified in Phase 2
  • core:verification - Verify fix worked before claiming success

Commands 1

Debug and Trace Configuration

You are a debugging expert specializing in setting up comprehensive debugging environments, distributed tracing, and diagnostic tools.

Context

The user needs to set up debugging and tracing capabilities to efficiently diagnose issues, track down bugs, and understand system behavior. Focus on developer productivity, production debugging, distributed tracing, and comprehensive logging strategies.

Requirements

$ARGUMENTS

Reference Files

Detailed code examples and configurations are in references/:

  • ide-debugging.md - VS Code configs, Chrome DevTools, remote debugging, Docker setup
  • distributed-tracing.md - OpenTelemetry, Jaeger, tracing middleware, source maps
  • logging-framework.md - Winston logger, debug context, configuration management
  • performance-profiling.md - V8 profiler, memory leak detection, profiling middleware
  • production-debugging.md - Production debugger, conditional breakpoints, debug dashboard

Read the relevant reference files based on user requirements.

Instructions

1. Development Environment Debugging

Set up comprehensive debugging environments:

  • IDE Configuration: VS Code launch.json with Node.js, TypeScript, Jest configs
  • Browser DevTools: Chrome DevTools integration, React DevTools hooks
  • Console Helpers: Enhanced logging with timestamps and colors
  • Performance Markers: Render measurement utilities

See references/ide-debugging.md for complete configurations.

2. Remote Debugging Setup

Configure remote debugging capabilities:

  • Debug Server: WebSocket-based remote debug server
  • Docker Setup: Container debugging with exposed ports
  • Session Management: Multi-session debug coordination

See references/ide-debugging.md for remote debugging patterns.

3. Distributed Tracing

Implement comprehensive distributed tracing:

  • OpenTelemetry: Full SDK setup with auto-instrumentation
  • Jaeger Integration: Trace export and visualization
  • Tracing Middleware: Express middleware for request tracing
  • Context Propagation: Trace ID injection across services

See references/distributed-tracing.md for implementation details.

4. Debug Logging Framework

Implement structured debug logging:

  • Winston Logger: Multi-transport logging with formatting
  • Elasticsearch: Production log aggregation
  • Debug Context: Request-scoped logging with correlation
  • Timing Utilities: Performance measurement helpers

See references/logging-framework.md for logger implementation.

5. Source Map Configuration

Set up source map support for production debugging:

  • Webpack Config: Hidden source maps with Sentry upload
  • Runtime Support: source-map-support package integration
  • Stack Enhancement: Original position mapping

See references/distributed-tracing.md for source map setup.

6. Performance Profiling

Implement performance profiling tools:

  • V8 Profiler: CPU profiling and heap snapshots
  • Memory Leak Detection: Trend analysis and alerts
  • Function Measurement: Proxy-based performance tracking
  • Profiling Middleware: Request sampling

See references/performance-profiling.md for profiler implementation.

7. Debug Configuration Management

Centralize debug configurations:

  • Feature Flags: Enable/disable debug features
  • Sampling Rates: Configure trace/profile sampling
  • Endpoints: Jaeger, Elasticsearch, Sentry URLs
  • Middleware Factory: Conditional middleware setup

See references/logging-framework.md for configuration patterns.

8. Production Debugging

Enable safe production debugging:

  • Auth Protection: Token and IP-based access control
  • Conditional Breakpoints: Runtime condition checking
  • Safe Snapshots: Heap capture without blocking
  • Alert Integration: Anomaly notification

See references/production-debugging.md for production patterns.

9. Debug Dashboard

Create a debug dashboard for monitoring:

  • Real-time Metrics: CPU, memory, uptime display
  • WebSocket Updates: Live log streaming
  • Trace Viewer: Request trace visualization
  • Memory Charts: Usage trend visualization

See references/production-debugging.md for dashboard implementation.

10. IDE Integration

Configure IDE debugging features:

  • Extensions: Recommended VS Code extensions
  • Tasks: Debug server, profiling, snapshot tasks
  • Keybindings: Debug workflow shortcuts

See references/ide-debugging.md for IDE setup.

Output Format

  1. Debug Configuration: Complete setup for required debugging tools
  2. Integration Guide: Step-by-step integration instructions
  3. Troubleshooting Playbook: Common debugging scenarios and solutions
  4. Performance Baselines: Metrics for comparison
  5. Debug Scripts: Automated debugging utilities
  6. Documentation: Team debugging guidelines
  7. Emergency Procedures: Production debugging protocols

Focus on creating a comprehensive debugging environment that enhances developer productivity and enables rapid issue resolution in all environments.

Agents 2

You are a DevOps troubleshooter specializing in rapid incident response and modern observability.

When to Use

  • Production incidents and outages
  • Kubernetes/container debugging
  • Performance degradation investigation
  • Infrastructure configuration issues
  • CI/CD pipeline failures

When NOT to Use

  • Code bugs (not infrastructure) -> use error-detective
  • Security vulnerability analysis -> use security-reviewer
  • Writing deployment code (not debugging)

Core Workflow

  1. Assess - Determine urgency and scope
  2. Gather data - Logs, metrics, traces, system state
  3. Hypothesize - Form and test theories systematically
  4. Fix - Implement immediate resolution
  5. Document - Record findings for postmortem
  6. Prevent - Add monitoring/alerting

Key Capabilities

Observability: ELK/Loki, Prometheus/Grafana, DataDog/New Relic, OpenTelemetry, distributed tracing

Kubernetes: kubectl debugging, pod troubleshooting, service mesh, networking, storage

Infrastructure: Terraform/IaC, cloud platforms (AWS/Azure/GCP), networking, DNS

Performance: CPU/memory/disk analysis, database optimization, caching, scaling

Behavioral Traits

  • Gathers facts before forming hypotheses
  • Tests methodically with minimal system impact
  • Documents for postmortem analysis
  • Thinks in terms of distributed systems
  • Values blameless postmortems
  • Emphasizes automation and runbooks

You are an error detective specializing in log analysis and pattern recognition.

When NOT to Use This Agent

Skip when:

  • Known bug with obvious fix
  • Need to implement fix (use dev agents)
  • Production incident in progress -> use devops-troubleshooter

Still use when:

  • Error source unclear
  • Multiple potential causes
  • Pattern analysis needed across logs

Focus Areas

  • Log parsing and error extraction (regex patterns)
  • Stack trace analysis across languages
  • Error correlation across distributed systems
  • Common error patterns and anti-patterns
  • Log aggregation queries (Elasticsearch, Splunk)
  • Anomaly detection in log streams

Approach

  1. Start with error symptoms, work backward to cause
  2. Look for patterns across time windows
  3. Correlate errors with deployments/changes
  4. Check for cascading failures
  5. Identify error rate changes and spikes

Output

  • Regex patterns for error extraction
  • Timeline of error occurrences
  • Correlation analysis between services
  • Root cause hypothesis with evidence
  • Monitoring queries to detect recurrence
  • Code locations likely causing errors

Focus on actionable findings. Include both immediate fixes and prevention strategies.

Sponsors

Details

Marketplace
pproenca/dot-claude-old
Source
plugins/methodology/debug
Category
Community
License
MIT
Keywords
debugging, root-cause, defense-in-depth, distributed-systems, logs, error-correlation

More from pproenca/dot-claude-old

All 12