Skip to main content

debug-with-file

Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and analysis-assisted correction.

Source facts

Repository
catlog22/Claude-Code-Workflow
Last source activity
April 16, 2026 at 07:20
Detected SKILL.md language
English
Stars
2,125
Forks
166

Install options

The review-first prompt is selected by default. You can switch to a direct command or download a local copy.

Review the source files

Read SKILL.md and any companion files shown by SkillsMP before deciding whether to install.

Showing SKILL.md

SKILL.md
Source instructions ยท Read-only preview
name
debug-with-file
description
Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and analysis-assisted correction.
argument-hint
BUG="<bug description or error message>"
# Codex Debug-With-File Prompt ## Overview Enhanced evidence-based debugging with **documented exploration process**. Records understanding evolution, consolidates insights, and uses analysis to correct misunderstandings. **Core workflow**: Explore โ†’ Document โ†’ Log โ†’ Analyze โ†’ Correct Understanding โ†’ Fix โ†’ Verify **Key enhancements over /prompts:debug**: - **understanding.md**: Timeline of exploration and learning - **Analysis-assisted correction**: Validates and corrects hypotheses - **Consolidation**: Simplifies proven-wrong understanding to avoid clutter - **Learning retention**: Preserves what was learned, even from failed attempts ## Target Bug **$BUG** ## Project Context Run `ccw spec load --category debug` for known issues, workarounds, and root-cause notes. ## Execution Process ``` Session Detection: โ”œโ”€ Check if debug session exists for this bug โ”œโ”€ EXISTS + understanding.md exists โ†’ Continue mode โ””โ”€ NOT_FOUND โ†’ Explore mode Explore Mode: โ”œโ”€ Locate error source in codebase โ”œโ”€ Document initial understanding in understanding.md โ”œโ”€ Generate testable hypotheses with analysis validation โ”œโ”€ Add NDJSON logging instrumentation โ””โ”€ Output: Hypothesis list + await user reproduction Analyze Mode: โ”œโ”€ Parse debug.log, validate each hypothesis โ”œโ”€ Use analysis to evaluate hypotheses and correct understanding โ”œโ”€ Update understanding.md with: โ”‚ โ”œโ”€ New evidence โ”‚ โ”œโ”€ Corrected misunderstandings (strikethrough + correction) โ”‚ โ””โ”€ Consolidated current understanding โ””โ”€ Decision: โ”œโ”€ Confirmed โ†’ Fix root cause โ”œโ”€ Inconclusive โ†’ Add more logging, iterate โ””โ”€ All rejected โ†’ Assisted new hypotheses Fix & Cleanup: โ”œโ”€ Apply fix based on confirmed hypothesis โ”œโ”€ User verifies โ”œโ”€ Document final understanding + lessons learned โ”œโ”€ Remove debug instrumentation โ””โ”€ If not fixed โ†’ Return to Analyze mode ``` ## Implementation Details ### Session Setup & Mode Detection ##### Step 0: Determine Project Root ๆฃ€ๆต‹้กน็›ฎๆ น็›ฎๅฝ•๏ผŒ็กฎไฟ `.workflow/` ไบง็‰ฉไฝ็ฝฎๆญฃ็กฎ๏ผš ```bash PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd) ``` ไผ˜ๅ…ˆ้€š่ฟ‡ git ่Žทๅ–ไป“ๅบ“ๆ น็›ฎๅฝ•๏ผ›้ž git ้กน็›ฎๅ›ž้€€ๅˆฐ `pwd` ๅ–ๅฝ“ๅ‰็ปๅฏน่ทฏๅพ„ใ€‚ ๅญ˜ๅ‚จไธบ `{projectRoot}`๏ผŒๅŽ็ปญๆ‰€ๆœ‰ `.workflow/` ่ทฏๅพ„ๅฟ…้กปไปฅๆญคไธบๅ‰็ผ€ใ€‚ ```javascript const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() const projectRoot = bash('git rev-parse --show-toplevel 2>/dev/null || pwd').trim() const bugSlug = "$BUG".toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30) const dateStr = getUtc8ISOString().substring(0, 10) const sessionId = `DBG-${dateStr}-${bugSlug}` const sessionFolder = `${projectRoot}/.workflow/.debug/${sessionId}` const debugLogPath = `${sessionFolder}/debug.log` const understandingPath = `${sessionFolder}/understanding.md` const hypothesesPath = `${sessionFolder}/hypotheses.json` // Auto-detect mode const sessionExists = fs.existsSync(sessionFolder) const hasUnderstanding = sessionExists && fs.existsSync(understandingPath) const logHasContent = sessionExists && fs.existsSync(debugLogPath) && fs.statSync(debugLogPath).size > 0 const mode = logHasContent ? 'analyze' : (hasUnderstanding ? 'continue' : 'explore') if (!sessionExists) { bash(`mkdir -p ${sessionFolder}`) } ``` ### Explore Mode #### Step 1.1: Locate Error Source ```javascript // Extract keywords from bug description const keywords = extractErrorKeywords("$BUG") // Search codebase for error locations const searchResults = [] for (const keyword of keywords) { const results = Grep({ pattern: keyword, path: ".", output_mode: "content", "-C": 3 }) searchResults.push({ keyword, results }) } // Identify affected files and functions const affectedLocations = analyzeSearchResults(searchResults) ``` #### Step 1.2: Document Initial Understanding Create `understanding.md`: ```markdown # Understanding Document **Session ID**: ${sessionId} **Bug Description**: $BUG **Started**: ${getUtc8ISOString()} --- ## Exploration Timeline ### Iteration 1 - Initial Exploration (${timestamp}) #### Current Understanding Based on bug description and initial code search: - Error pattern: ${errorPattern} - Affected areas: ${affectedLocations.map(l => l.file).join(', ')} - Initial hypothesis: ${initialThoughts} #### Evidence from Code Search ${searchResults.map(r => ` **Keyword: "${r.keyword}"** - Found in: ${r.results.files.join(', ')} - Key findings: ${r.insights} `).join('\n')} #### Next Steps - Generate testable hypotheses - Add instrumentation - Await reproduction --- ## Current Consolidated Understanding ${initialConsolidatedUnderstanding} ``` #### Step 1.3: Generate Hypotheses Analyze the bug and generate 3-5 testable hypotheses: ```javascript // Hypothesis generation based on error pattern const HYPOTHESIS_PATTERNS = { "not found|missing|undefined|ๆœชๆ‰พๅˆฐ": "data_mismatch", "0|empty|zero|registered": "logic_error", "timeout|connection|sync": "integration_issue", "type|format|parse": "type_mismatch" } function generateHypotheses(bugDescription, affectedLocations) { // Generate targeted hypotheses based on error analysis // Each hypothesis includes: // - id: H1, H2, ... // - description: What might be wrong // - testable_condition: What to log // - logging_point: Where to add instrumentation // - evidence_criteria: What confirms/rejects it return hypotheses } ``` Save to `hypotheses.json`: ```json { "iteration": 1, "timestamp": "2025-01-21T10:00:00+08:00", "hypotheses": [ { "id": "H1", "description": "Data structure mismatch - expected key not present", "testable_condition": "Check if target key exists in dict", "logging_point": "file.py:func:42", "evidence_criteria": { "confirm": "data shows missing key", "reject": "key exists with valid value" }, "likelihood": 1, "status": "pending" } ] } ``` #### Step 1.4: Add NDJSON Instrumentation For each hypothesis, add logging at the specified location: **Python template**: ```python # region debug [H{n}] try: import json, time _dbg = { "sid": "{sessionId}", "hid": "H{n}", "loc": "{file}:{line}", "msg": "{testable_condition}", "data": { # Capture relevant values here }, "ts": int(time.time() * 1000) } with open(r"{debugLogPath}", "a", encoding="utf-8") as _f: _f.write(json.dumps(_dbg, ensure_ascii=False) + "\n") except: pass # endregion ``` **JavaScript/TypeScript template**: ```javascript // region debug [H{n}] try { require('fs').appendFileSync("{debugLogPath}", JSON.stringify({ sid: "{sessionId}", hid: "H{n}", loc: "{file}:{line}", msg: "{testable_condition}", data: { /* Capture relevant values */ }, ts: Date.now() }) + "\n"); } catch(_) {} // endregion ``` #### Step 1.5: Output to User ``` ## Hypotheses Generated Based on error "$BUG", generated {n} hypotheses: {hypotheses.map(h => ` ### ${h.id}: ${h.description} - Logging at: ${h.logging_point} - Testing: ${h.testable_condition} - Evidence to confirm: ${h.evidence_criteria.confirm} - Evidence to reject: ${h.evidence_criteria.reject} `).join('')} **Debug log**: ${debugLogPath} **Next**: Run reproduction steps, then come back for analysis. ``` ### Analyze Mode #### Step 2.1: Parse Debug Log ```javascript // Parse NDJSON log const entries = Read(debugLogPath).split('\n') .filter(l => l.trim()) .map(l => JSON.parse(l)) // Group by hypothesis const byHypothesis = groupBy(entries, 'hid') // Validate each hypothesis for (const [hid, logs] of Object.entries(byHypothesis)) { const hypothesis = hypotheses.find(h => h.id === hid) const latestLog = logs[logs.length - 1] // Check if evidence confirms or rejects hypothesis const verdict = evaluateEvidence(hypothesis, latestLog.data) // Returns: 'confirmed' | 'rejected' | 'inconclusive' } ``` #### Step 2.2: Analyze Evidence and Correct Understanding Review the debug log and evaluate each hypothesis: 1. Parse all log entries 2. Group by hypothesis ID 3. Compare evidence against expected criteria 4. Determine verdict: confirmed | rejected | inconclusive 5. Identify incorrect assumptions from previous understanding 6. Generate corrections #### Step 2.3: Update Understanding with Corrections Append new iteration to `understanding.md`: ```markdown ### Iteration ${n} - Evidence Analysis (${timestamp}) #### Log Analysis Results ${results.map(r => ` **${r.id}**: ${r.verdict.toUpperCase()} - Evidence: ${JSON.stringify(r.evidence)} - Reasoning: ${r.reason} `).join('\n')} #### Corrected Understanding Previous misunderstandings identified and corrected: ${corrections.map(c => ` - ~~${c.wrong}~~ โ†’ ${c.corrected} - Why wrong: ${c.reason} - Evidence: ${c.evidence} `).join('\n')} #### New Insights ${newInsights.join('\n- ')} ${confirmedHypothesis ? ` #### Root Cause Identified **${confirmedHypothesis.id}**: ${confirmedHypothesis.description} Evidence supporting this conclusion: ${confirmedHypothesis.supportingEvidence} ` : ` #### Next Steps ${nextSteps} `} --- ## Current Consolidated Understanding (Updated) ${consolidatedUnderstanding} ``` #### Step 2.4: Update hypotheses.json ```json { "iteration": 2, "timestamp": "2025-01-21T10:15:00+08:00", "hypotheses": [ { "id": "H1", "status": "rejected", "verdict_reason": "Evidence shows key exists with valid value", "evidence": {...} }, { "id": "H2", "status": "confirmed", "verdict_reason": "Log data confirms timing issue", "evidence": {...} } ], "corrections": [ { "wrong_assumption": "...", "corrected_to": "...", "reason": "..." } ] } ``` ### Fix & Verification #### Step 3.1: Apply Fix Based on confirmed hypothesis, implement the fix in the affected files. #### Step 3.2: Document Resolution Append to `understanding.md`: ```markdown ### Iteration ${n} - Resolution (${timestamp}) #### Fix Applied - Modified files: ${modifiedFiles.join(', ')} - Fix description: ${fixDescription} - Root cause addressed: ${rootCause} #### Verification Results ${verificationResults} #### Lessons Learned What we learned from this debugging session: 1. ${lesson1} 2. ${lesson2} 3. ${lesson3} #### Key Insights for Future - ${insight1} - ${insight2} ``` #### Step 3.3: Cleanup Remove debug instrumentation by searching for region markers: ```javascript const instrumentedFiles = Grep({ pattern: "# region debug|// region debug",
View on GitHub
This SKILL.md is very large, so SkillsMP previews the first section here. View on GitHub