debug-with-file
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCodex Debug-With-File Prompt
Codex Debug-With-File 提示词
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
基于证据增强的调试,附带可追溯的探索过程记录。记录认知演变过程,整合洞察信息,并通过分析修正错误认知。
核心工作流:探索 → 记录 → 日志 → 分析 → 修正认知 → 修复 → 验证
相较于/prompts:debug的关键增强点:
- understanding.md:探索与学习的时间线记录
- 分析辅助修正:验证并修正假设
- 信息整合:简化已被证伪的认知,避免内容杂乱
- 知识留存:保留从失败尝试中获得的经验
Target Bug
目标Bug
$BUG
$BUG
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会话检测:
├─ 检查该bug是否存在调试会话
├─ 已存在 + understanding.md存在 → 继续模式
└─ 不存在 → 探索模式
探索模式:
├─ 在代码库中定位错误源
├─ 在understanding.md中记录初始认知
├─ 生成带分析验证的可测试假设
├─ 添加NDJSON日志埋点
└─ 输出:假设列表 + 等待用户复现
分析模式:
├─ 解析debug.log,验证每个假设
├─ 通过分析评估假设并修正认知
├─ 更新understanding.md,包含:
│ ├─ 新证据
│ ├─ 已修正的错误认知(删除线标注+修正内容)
│ └─ 整合后的当前认知
└─ 决策:
├─ 假设已确认 → 修复根因
├─ 证据不充分 → 添加更多日志,迭代探索
└─ 所有假设被证伪 → 辅助生成新假设
修复与清理:
├─ 基于已确认的假设应用修复
├─ 用户验证修复效果
├─ 记录最终认知 + 经验总结
├─ 移除调试埋点
└─ 修复未生效 → 返回分析模式Implementation Details
实现细节
Session Setup & Mode Detection
会话设置与模式检测
Step 0: Determine Project Root
步骤0:确定项目根目录
检测项目根目录,确保 产物位置正确:
.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-${bugSlug}-${dateStr}`
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}`)
}检测项目根目录,确保产物位置正确:
.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-${bugSlug}-${dateStr}`
const sessionFolder = `${projectRoot}/.workflow/.debug/${sessionId}`
const debugLogPath = `${sessionFolder}/debug.log`
const understandingPath = `${sessionFolder}/understanding.md`
const hypothesesPath = `${sessionFolder}/hypotheses.json`
// 自动检测模式
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
步骤1.1:定位错误源
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)javascript
// 从bug描述中提取关键词
const keywords = extractErrorKeywords("$BUG")
// 在代码库中搜索错误位置
const searchResults = []
for (const keyword of keywords) {
const results = Grep({ pattern: keyword, path: ".", output_mode: "content", "-C": 3 })
searchResults.push({ keyword, results })
}
// 识别受影响的文件和函数
const affectedLocations = analyzeSearchResults(searchResults)Step 1.2: Document Initial Understanding
步骤1.2:记录初始认知
Create :
understanding.mdmarkdown
undefined创建:
understanding.mdmarkdown
undefinedUnderstanding Document
认知记录文档
Session ID: ${sessionId}
Bug Description: $BUG
Started: ${getUtc8ISOString()}
会话ID:${sessionId}
Bug描述:$BUG
开始时间:${getUtc8ISOString()}
Exploration Timeline
探索时间线
Iteration 1 - Initial Exploration (${timestamp})
迭代1 - 初始探索(${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}
基于bug描述和初始代码搜索:
- 错误模式:${errorPattern}
- 受影响区域:${affectedLocations.map(l => l.file).join(', ')}
- 初始假设:${initialThoughts}
Evidence from Code Search
代码搜索证据
${searchResults.map(r => `
Keyword: "${r.keyword}"
- Found in: ${r.results.files.join(', ')}
- Key findings: ${r.insights} `).join('\n')}
${searchResults.map(r => `
关键词:"${r.keyword}"
- 出现位置:${r.results.files.join(', ')}
- 关键发现:${r.insights} `).join('\n')}
Next Steps
下一步计划
- Generate testable hypotheses
- Add instrumentation
- Await reproduction
- 生成可测试假设
- 添加调试埋点
- 等待用户复现
Current Consolidated Understanding
当前整合后的认知
${initialConsolidatedUnderstanding}
undefined${initialConsolidatedUnderstanding}
undefinedStep 1.3: Generate Hypotheses
步骤1.3:生成假设
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.jsonjson
{
"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"
}
]
}分析bug并生成3-5个可测试假设:
javascript
// 基于错误模式生成假设
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) {
// 基于错误分析生成针对性假设
// 每个假设包含:
// - id: H1, H2, ...
// - description: 可能的问题点
// - testable_condition: 需要记录的内容
// - logging_point: 埋点位置
// - evidence_criteria: 确认/证伪的依据
return hypotheses
}保存到:
hypotheses.jsonjson
{
"iteration": 1,
"timestamp": "2025-01-21T10:00:00+08:00",
"hypotheses": [
{
"id": "H1",
"description": "数据结构不匹配 - 预期键不存在",
"testable_condition": "检查字典中是否存在目标键",
"logging_point": "file.py:func:42",
"evidence_criteria": {
"confirm": "数据显示键缺失",
"reject": "键存在且值有效"
},
"likelihood": 1,
"status": "pending"
}
]
}Step 1.4: Add NDJSON Instrumentation
步骤1.4:添加NDJSON调试埋点
For each hypothesis, add logging at the specified location:
Python template:
python
undefined为每个假设在指定位置添加日志:
Python模板:
python
undefinedregion debug [H{n}]
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
try:
import json, time
_dbg = {
"sid": "{sessionId}",
"hid": "H{n}",
"loc": "{file}:{line}",
"msg": "{testable_condition}",
"data": {
# 在此处捕获相关值
},
"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
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
**JavaScript/TypeScript模板**:
```javascript
// region debug [H{n}]
try {
require('fs').appendFileSync("{debugLogPath}", JSON.stringify({
sid: "{sessionId}",
hid: "H{n}",
loc: "{file}:{line}",
msg: "{testable_condition}",
data: { /* 捕获相关值 */ },
ts: Date.now()
}) + "\n");
} catch(_) {}
// endregionStep 1.5: Output to User
步骤1.5:输出给用户
undefinedundefinedHypotheses Generated
已生成假设
Based on error "$BUG", generated {n} hypotheses:
{hypotheses.map(h => `
基于错误"$BUG",生成了{n}个假设:
{hypotheses.map(h => `
${h.id}: ${h.description}
${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.
undefined- 日志位置:${h.logging_point}
- 测试内容:${h.testable_condition}
- 确认依据:${h.evidence_criteria.confirm}
- 证伪依据:${h.evidence_criteria.reject} `).join('')}
调试日志:${debugLogPath}
下一步:执行复现步骤,之后返回进行分析。
undefinedAnalyze Mode
分析模式
Step 2.1: Parse Debug Log
步骤2.1:解析调试日志
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'
}javascript
// 解析NDJSON日志
const entries = Read(debugLogPath).split('\n')
.filter(l => l.trim())
.map(l => JSON.parse(l))
// 按假设分组
const byHypothesis = groupBy(entries, 'hid')
// 验证每个假设
for (const [hid, logs] of Object.entries(byHypothesis)) {
const hypothesis = hypotheses.find(h => h.id === hid)
const latestLog = logs[logs.length - 1]
// 检查证据是否确认或证伪假设
const verdict = evaluateEvidence(hypothesis, latestLog.data)
// 返回值:'confirmed' | 'rejected' | 'inconclusive'
}Step 2.2: Analyze Evidence and Correct Understanding
步骤2.2:分析证据并修正认知
Review the debug log and evaluate each hypothesis:
- Parse all log entries
- Group by hypothesis ID
- Compare evidence against expected criteria
- Determine verdict: confirmed | rejected | inconclusive
- Identify incorrect assumptions from previous understanding
- Generate corrections
查看调试日志并评估每个假设:
- 解析所有日志条目
- 按假设ID分组
- 将证据与预期标准对比
- 判定结果:已确认 | 已证伪 | 证据不足
- 识别之前认知中的错误假设
- 生成修正内容
Step 2.3: Update Understanding with Corrections
步骤2.3:更新认知记录并添加修正
Append new iteration to :
understanding.mdmarkdown
undefined在中追加新迭代内容:
understanding.mdmarkdown
undefinedIteration ${n} - Evidence Analysis (${timestamp})
迭代${n} - 证据分析(${timestamp})
Log Analysis Results
日志分析结果
${results.map(r => `
${r.id}: ${r.verdict.toUpperCase()}
- Evidence: ${JSON.stringify(r.evidence)}
- Reasoning: ${r.reason} `).join('\n')}
${results.map(r => `
${r.id}:${r.verdict.toUpperCase()}
- 证据:${JSON.stringify(r.evidence)}
- 推理过程:${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')}
已识别并修正之前的错误假设:
${corrections.map(c => `
${c.wrong}→ ${c.corrected}- 错误原因:${c.reason}
- 证据:${c.evidence} `).join('\n')}
New Insights
新洞察
${newInsights.join('\n- ')}
${confirmedHypothesis ? `
${newInsights.join('\n- ')}
${confirmedHypothesis ? `
Root Cause Identified
已定位根因
${confirmedHypothesis.id}: ${confirmedHypothesis.description}
Evidence supporting this conclusion:
${confirmedHypothesis.supportingEvidence}
:${confirmedHypothesis.id}:${confirmedHypothesis.description}
支持该结论的证据:
${confirmedHypothesis.supportingEvidence}
:Next Steps
下一步计划
${nextSteps}
`}
${nextSteps}
`}
Current Consolidated Understanding (Updated)
当前整合后的认知(已更新)
${consolidatedUnderstanding}
undefined${consolidatedUnderstanding}
undefinedStep 2.4: Update hypotheses.json
步骤2.4:更新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": "..."
}
]
}json
{
"iteration": 2,
"timestamp": "2025-01-21T10:15:00+08:00",
"hypotheses": [
{
"id": "H1",
"status": "rejected",
"verdict_reason": "证据显示键存在且值有效",
"evidence": {...}
},
{
"id": "H2",
"status": "confirmed",
"verdict_reason": "日志数据确认存在时序问题",
"evidence": {...}
}
],
"corrections": [
{
"wrong_assumption": "...",
"corrected_to": "...",
"reason": "..."
}
]
}Fix & Verification
修复与验证
Step 3.1: Apply Fix
步骤3.1:应用修复
Based on confirmed hypothesis, implement the fix in the affected files.
基于已确认的假设,在受影响文件中实现修复。
Step 3.2: Document Resolution
步骤3.2:记录修复结果
Append to :
understanding.mdmarkdown
undefined在中追加内容:
understanding.mdmarkdown
undefinedIteration ${n} - Resolution (${timestamp})
迭代${n} - 问题解决(${timestamp})
Fix Applied
已应用修复
- Modified files: ${modifiedFiles.join(', ')}
- Fix description: ${fixDescription}
- Root cause addressed: ${rootCause}
- 修改文件:${modifiedFiles.join(', ')}
- 修复说明:${fixDescription}
- 解决的根因:${rootCause}
Verification Results
验证结果
${verificationResults}
${verificationResults}
Lessons Learned
经验总结
What we learned from this debugging session:
- ${lesson1}
- ${lesson2}
- ${lesson3}
从本次调试会话中学到的内容:
- ${lesson1}
- ${lesson2}
- ${lesson3}
Key Insights for Future
未来调试参考
- ${insight1}
- ${insight2}
undefined- ${insight1}
- ${insight2}
undefinedStep 3.3: Cleanup
步骤3.3:清理工作
Remove debug instrumentation by searching for region markers:
javascript
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)
}通过区域标记移除调试埋点:
javascript
const instrumentedFiles = Grep({
pattern: "# region debug|// region debug",
output_mode: "files_with_matches"
})
for (const file of instrumentedFiles) {
// 移除区域标记之间的内容
removeDebugRegions(file)
}Session Folder Structure
会话文件夹结构
{projectRoot}/.workflow/.debug/DBG-{slug}-{date}/
├── debug.log # NDJSON log (execution evidence)
├── understanding.md # Exploration timeline + consolidated understanding
└── hypotheses.json # Hypothesis history with verdicts{projectRoot}/.workflow/.debug/DBG-{slug}-{date}/
├── debug.log # NDJSON格式日志(执行证据)
├── understanding.md # 探索时间线 + 整合后的认知
└── hypotheses.json # 假设历史及判定结果Understanding Document Template
认知记录文档模板
markdown
undefinedmarkdown
undefinedUnderstanding Document
认知记录文档
Session ID: DBG-xxx-2025-01-21
Bug Description: [original description]
Started: 2025-01-21T10:00:00+08:00
会话ID:DBG-xxx-2025-01-21
Bug描述:[原始描述]
开始时间:2025-01-21T10:00:00+08:00
Exploration Timeline
探索时间线
Iteration 1 - Initial Exploration (2025-01-21 10:00)
迭代1 - 初始探索(2025-01-21 10:00)
Current Understanding
当前认知
...
...
Evidence from Code Search
代码搜索证据
...
...
Hypotheses Generated
已生成假设
...
...
Iteration 2 - Evidence Analysis (2025-01-21 10:15)
迭代2 - 证据分析(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]
undefined- [未解决的疑问]
undefinedDebug Log Format (NDJSON)
调试日志格式(NDJSON)
Each line is a JSON object:
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}| Field | Description |
|---|---|
| Session ID |
| Hypothesis ID (H1, H2, ...) |
| Code location |
| What's being tested |
| Captured values |
| Timestamp (ms) |
每行是一个JSON对象:
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}| 字段 | 描述 |
|---|---|
| 会话ID |
| 假设ID(H1, H2, ...) |
| 代码位置 |
| 测试内容 |
| 捕获的变量值 |
| 时间戳(毫秒) |
Iteration Flow
迭代流程
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-{slug}-{date}/debug.log
├─ {projectRoot}/.workflow/.debug/DBG-{slug}-{date}/understanding.md (evolving document)
└─ {projectRoot}/.workflow/.debug/DBG-{slug}-{date}/hypotheses.json (history)首次调用(BUG="error"):
├─ 无会话存在 → 探索模式
├─ 提取错误关键词,搜索代码库
├─ 在understanding.md中记录初始认知
├─ 生成假设
├─ 添加日志埋点
└─ 等待用户复现
复现后调用(BUG="error"):
├─ 会话存在 + debug.log有内容 → 分析模式
├─ 解析日志,评估假设
├─ 更新understanding.md,包含:
│ ├─ 证据分析结果
│ ├─ 已修正的错误认知(删除线标注)
│ ├─ 新洞察
│ └─ 更新后的整合认知
├─ 更新hypotheses.json中的判定结果
└─ 决策:
├─ 假设已确认 → 修复 → 记录解决过程
├─ 证据不足 → 添加更多日志,记录下一步计划
└─ 所有假设被证伪 → 辅助生成新假设
输出产物:
├─ {projectRoot}/.workflow/.debug/DBG-{slug}-{date}/debug.log
├─ {projectRoot}/.workflow/.debug/DBG-{slug}-{date}/understanding.md(动态更新的文档)
└─ {projectRoot}/.workflow/.debug/DBG-{slug}-{date}/hypotheses.json(历史记录)Error Handling
异常处理
| Situation | Action |
|---|---|
| Empty debug.log | Verify reproduction triggered the code path |
| All hypotheses rejected | Generate new hypotheses based on disproven assumptions |
| Fix doesn't work | Document failed fix attempt, iterate with refined understanding |
| >5 iterations | Review consolidated understanding, escalate with full context |
| Understanding too long | Consolidate aggressively, archive old iterations to separate file |
| 场景 | 处理方式 |
|---|---|
| debug.log为空 | 验证复现操作是否触发了目标代码路径 |
| 所有假设被证伪 | 基于已推翻的假设生成新假设 |
| 修复未生效 | 记录失败的修复尝试,基于优化后的认知重新迭代 |
| 迭代次数>5 | 回顾整合后的认知,携带完整上下文升级处理 |
| 认知记录过长 | 主动整合内容,将旧迭代归档到单独文件 |
Consolidation Rules
整合规则
When updating "Current Consolidated Understanding":
- Simplify disproven items: Move to "What Was Disproven" with single-line summary
- Keep valid insights: Promote confirmed findings to "What We Know"
- Avoid duplication: Don't repeat timeline details in consolidated section
- Focus on current state: What do we know NOW, not the journey
- Preserve key corrections: Keep important wrong→right transformations for learning
Bad (cluttered):
markdown
undefined更新「当前整合后的认知」时:
- 简化已证伪内容:将其移至「已证伪的假设」区域,仅保留单行摘要
- 保留有效洞察:将已确认的发现提升至「已确认的信息」区域
- 避免重复:不在整合区域重复时间线细节
- 聚焦当前状态:记录我们现在知道的内容,而非探索过程
- 保留关键修正:保留重要的错误→正确的认知转变,用于经验积累
反面示例(内容杂乱):
markdown
undefinedCurrent 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...
**Good (consolidated)**:
```markdown迭代1中我们认为是X,但迭代2中发现是Y,然后迭代3中...
另外我们检查了A发现是B,之后又检查了C...
**正面示例(已整合)**:
```markdownCurrent Consolidated Understanding
当前整合后的认知
What We Know
已确认的信息
- Error occurs during runtime update, not initialization
- Config value is None (not missing key)
- 错误发生在运行时更新阶段,而非初始化阶段
- 配置值为None(并非键缺失)
What Was Disproven
已证伪的假设
Initialization error(Timing evidence)Missing key hypothesis(Key exists)
初始化错误(时序证据)键缺失假设(键实际存在)
Current Investigation Focus
当前调查重点
Why is config value None during update?
undefined为什么更新阶段配置值为None?
undefinedKey Features
核心特性
| Feature | Description |
|---|---|
| NDJSON logging | Structured debug log with hypothesis tracking |
| Hypothesis generation | Analysis-assisted hypothesis creation |
| Exploration documentation | understanding.md with timeline |
| Understanding evolution | Timeline + corrections tracking |
| Error correction | Strikethrough + reasoning for wrong assumptions |
| Consolidated learning | Current understanding section |
| Hypothesis history | hypotheses.json with verdicts |
| Analysis validation | At key decision points |
| 特性 | 描述 |
|---|---|
| NDJSON日志 | 带假设追踪的结构化调试日志 |
| 假设生成 | 基于分析的假设创建 |
| 探索记录 | 带时间线的understanding.md文档 |
| 认知演变 | 时间线 + 修正记录追踪 |
| 错误修正 | 对错误假设添加删除线标注及推理过程 |
| 整合式学习 | 当前认知汇总区域 |
| 假设历史 | 带判定结果的hypotheses.json |
| 分析验证 | 在关键决策点进行验证 |
When to Use
适用场景
Best suited for:
- Complex bugs requiring multiple investigation rounds
- Learning from debugging process is valuable
- Team needs to understand debugging rationale
- Bug might recur, documentation helps prevention
Now execute the debug-with-file workflow for bug: $BUG
最适合以下场景:
- 需要多轮调查的复杂Bug
- 调试过程的经验积累有价值
- 团队需要理解调试的推理逻辑
- Bug可能复发,文档有助于预防
现在针对Bug执行debug-with-file工作流:$BUG