关于 debug-with-file
debug-with-file 是通过记录证据和迭代假设来调查复杂问题的调试 Skill。它将发现写入文件,并依据日志修正判断、记录修复与验证过程。
主要功能
- 01生成可测试的假设
- 02记录 NDJSON 调试证据
- 03在 understanding.md 中记录调查过程
- 04跟踪假设结论与历史
- 05修复验证及清理调试插桩
适用场景
- 01分多轮调查复杂问题
- 02为团队记录证据与推理过程
- 03保存可能复发问题的根因发现
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ catlog22/ claude-code-workflow --skill debug-with-file安装后在 Claude Code 中输入/debug-with-file确认已加载。
详细介绍
Codex 文件辅助调试提示词
概述
增强基于证据的调试,并记录探索过程。记录理解的演变、整合洞见,并利用分析纠正误解。
核心工作流:探索 → 记录 → 记录日志 → 分析 → 修正理解 → 修复 → 验证
相较于 /prompts:debug 的主要增强:
- understanding.md:记录探索和学习过程的时间线
- 分析辅助修正:验证并修正假设
- 整合:简化已证实错误的理解,避免内容冗杂
- 保留经验:保留已学到的内容,即使来自失败的尝试
目标 Bug
$BUG
项目上下文
运行 ccw spec load --category debug,了解已知问题、解决方法和根因说明。
执行流程
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
实现细节
会话设置与模式检测
步骤 0:确定项目根目录
检测项目根目录,确保 .workflow/ 产物位置正确:
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
优先通过 git 获取仓库根目录;非 git 项目回退到 pwd 取当前绝对路径。
存储为 {projectRoot},后续所有 .workflow/ 路径必须以此为前缀。
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}`)
}
探索模式
步骤 1.1:定位错误来源
// 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)
步骤 1.2:记录初步理解
创建 understanding.md:
# 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}
步骤 1.3:生成假设
分析 Bug 并生成 3-5 个可测试的假设:
// 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
}
保存到 hypotheses.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"
}
]
}
步骤 1.4:添加 NDJSON 插桩
为每个假设,在指定位置添加日志记录:
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 模板:
// 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
步骤 1.5:向用户输出
## 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.
分析模式
步骤 2.1:解析调试日志
// 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'
}
步骤 2.2:分析证据并修正理解
检查调试日志并评估每个假设:
- 解析所有日志条目
- 按假设 ID 分组
- 将证据与预期标准进行比较
- 判定结论:已确认 | 已否定 | 无定论
- 找出先前理解中的错误假设
- 生成修正内容
步骤 2.3:根据修正更新理解
在 understanding.md 中追加新一轮记录:
### 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}
步骤 2.4:更新 hypotheses.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": "..."
}
]
}
修复与验证
步骤 3.1:应用修复
根据已确认的假设,在受影响的文件中实施修复。
步骤 3.2:记录解决方案
在 understanding.md 中追加:
### 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}
步骤 3.3:清理
搜索区域标记并移除调试插桩:
const instrumentedFiles = Grep({
pattern: "# region debug|// region debug",
output_mode: "files_with_matches"
})
for (const file of instrumentedFiles) {
// Remove content between region markers
removeDebugRegions(file)
}
会话文件夹结构
{projectRoot}/.workflow/.debug/DBG-{date}-{slug}/
├── debug.log # NDJSON log (execution evidence)
├── understanding.md # Exploration timeline + consolidated understanding
└── hypotheses.json # Hypothesis history with verdicts
理解文档模板
# Understanding Document
**Session ID**: DBG-xxx-2025-01-21
**Bug Description**: [original description]
**Started**: 2025-01-21T10:00:00+08:00
---
## Exploration Timeline
### Iteration 1 - Initial Exploration (2025-01-21 10:00)
#### Current Understanding
...
#### Evidence from Code Search
...
#### Hypotheses Generated
...
### Iteration 2 - Evidence Analysis (2025-01-21 10:15)
#### Log Analysis Results
...
#### Corrected Understanding
- ~~[wrong]~~ → [corrected]
#### Analysis Results
...
---
## Current Consolidated Understanding
### What We Know
- [valid understanding points]
### What Was Disproven
- ~~[disproven assumptions]~~
### Current Investigation Focus
[current focus]
### Remaining Questions
- [open questions]
调试日志格式(NDJSON)
每行都是一个 JSON 对象:
{"sid":"DBG-xxx-2025-01-21","hid":"H1","loc":"file.py:func:42","msg":"Check dict keys","data":{"keys":["a","b"],"target":"c","found":false},"ts":1734567890123}
| 字段 | 描述 |
|---|---|
sid | 会话 ID |
hid | 假设 ID(H1、H2……) |
loc | 代码位置 |
msg | 正在测试的内容 |
data | 捕获的值 |
ts | 时间戳(毫秒) |
迭代流程
First Call (BUG="error"):
├─ No session exists → Explore mode
├─ Extract error keywords, search codebase
├─ Document initial understanding in understanding.md
├─ Generate hypotheses
├─ Add logging instrumentation
└─ Await user reproduction
After Reproduction (BUG="error"):
├─ Session exists + debug.log has content → Analyze mode
├─ Parse log, evaluate hypotheses
├─ Update understanding.md with:
│ ├─ Evidence analysis results
│ ├─ Corrected misunderstandings (strikethrough)
│ ├─ New insights
│ └─ Updated consolidated understanding
├─ Update hypotheses.json with verdicts
└─ Decision:
├─ Confirmed → Fix → Document resolution
├─ Inconclusive → Add logging, document next steps
└─ All rejected → Assisted new hypotheses
Output:
├─ {projectRoot}/.workflow/.debug/DBG-{date}-{slug}/debug.log
├─ {projectRoot}/.workflow/.debug/DBG-{date}-{slug}/understanding.md (evolving document)
└─ {projectRoot}/.workflow/.debug/DBG-{date}-{slug}/hypotheses.json (history)
错误处理
| 情况 | 操作 |
|---|---|
| debug.log 为空 | 确认复现过程是否触发了该代码路径 |
| 所有假设都被否定 | 根据已被证伪的假设生成新假设 |
| 修复无效 | 记录失败的修复尝试,并基于修正后的理解继续迭代 |
| 迭代次数 >5 | 检查整合后的理解,并附上完整上下文升级处理 |
| 理解内容过长 | 大幅整合,将较早的迭代记录存档到单独的文件 |
整合规则
更新“当前整合后的理解”时:
- 简化已证伪的内容:移至“已证伪的内容”,并用一句话概括
- 保留有效洞见:将已确认的发现移至“已知内容”
- 避免重复:不要在整合部分重复时间线详情
- 聚焦当前状态:关注我们现在知道什么,而不是经历了什么
- 保留关键修正:保留重要的错误→正确转变,以供学习
反面示例(内容杂乱):
## Current Consolidated Understanding
In iteration 1 we thought X, but in iteration 2 we found Y, then in iteration 3...
Also we checked A and found B, and then we checked C...
正面示例(已整合):
## Current Consolidated Understanding
### What We Know
- Error occurs during runtime update, not initialization
- Config value is None (not missing key)
### What Was Disproven
- ~~Initialization error~~ (Timing evidence)
- ~~Missing key hypothesis~~ (Key exists)
### Current Investigation Focus
Why is config value None during update?
主要功能
| 功能 | 说明 |
|---|---|
| NDJSON 日志记录 | 带有假设追踪的结构化调试日志 |
| 假设生成 | 借助分析创建假设 |
| 探索文档 | 带时间线的 understanding.md |
| 理解演进 | 时间线 + 修正追踪 |
| 错误修正 | 对错误假设使用删除线并说明原因 |
| 汇总学习成果 | 当前理解部分 |
| 假设历史 | 带结论的 hypotheses.json |
| 分析验证 | 在关键决策点进行 |
适用场景
最适合用于:
- 需要多轮调查的复杂 Bug
- 从调试过程中学习很有价值
- 团队需要了解调试的理由
- Bug 可能再次出现,文档有助于预防
现在执行针对 Bug 的 debug-with-file 工作流:$BUG
评论
支持 Markdown