debugger

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Debugger Skill

调试器技能

Systematically diagnose and fix software bugs through structured investigation, reproduction, root cause analysis, and targeted fixes.
通过结构化的调查、复现、根因分析和针对性修复,系统性地诊断并解决软件缺陷。

When to Use

适用场景

Use this skill for:
  • Runtime Errors: Exception handling, crashes, unhandled rejections
  • Test Failures: Unit tests, integration tests, E2E tests not passing
  • Type Errors: TypeScript compilation errors, type mismatches
  • Logic Bugs: Incorrect behavior, wrong output, edge cases
  • Performance Issues: Slow execution, memory leaks, bottlenecks
  • Integration Issues: API failures, database errors, third-party service issues
  • Race Conditions: Timing issues, async/await problems
  • State Management: Redux, Context, or hook state bugs
Don't use for:
  • New feature implementation (use feature-implementer)
  • Code refactoring without bugs (use refactorer)
  • Initial research (use Explore agent)
适用于:
  • 运行时错误:异常处理、崩溃、未捕获的拒绝
  • 测试失败:单元测试、集成测试、E2E测试不通过
  • 类型错误:TypeScript编译错误、类型不匹配
  • 逻辑缺陷:行为异常、输出错误、边缘情况
  • 性能问题:执行缓慢、内存泄漏、性能瓶颈
  • 集成问题:API失败、数据库错误、第三方服务问题
  • 竞态条件:时序问题、async/await使用问题
  • 状态管理:Redux、Context或Hook状态缺陷
不适用场景:
  • 新功能开发(使用feature-implementer)
  • 无缺陷的代码重构(使用refactorer)
  • 初步研究(使用Explore agent)

Quick Start

快速开始

Step 1: Issue Understanding

步骤1:问题理解

What: [Brief description of the bug]
Where: [File(s) and line number(s)]
When: [Conditions when it occurs]
Impact: [Severity: Critical/High/Medium/Low]
Evidence: [Error message, stack trace, or behavior]
What: [Brief description of the bug]
Where: [File(s) and line number(s)]
When: [Conditions when it occurs]
Impact: [Severity: Critical/High/Medium/Low]
Evidence: [Error message, stack trace, or behavior]

Step 2: Reproduce

步骤2:复现问题

Create minimal reproduction:
  • Identify exact steps to trigger
  • Document environment conditions
  • Capture before/after state
  • Note any workarounds
创建最小化复现案例:
  • 确定触发问题的精确步骤
  • 记录环境条件
  • 捕获前后状态
  • 记录任何临时解决方案

Step 3: Investigate

步骤3:调查分析

Use systematic approach:
  • Read relevant code
  • Trace execution flow
  • Check data values at key points
  • Verify assumptions
采用系统化方法:
  • 阅读相关代码
  • 追踪执行流程
  • 检查关键节点的数据值
  • 验证假设

Step 4: Root Cause

步骤4:根因定位

Identify the fundamental issue:
  • Why did it happen?
  • What was the incorrect assumption?
  • What edge case was missed?
识别根本问题:
  • 问题为何发生?
  • 存在哪些错误假设?
  • 遗漏了哪些边缘情况?

Step 5: Fix

步骤5:实施修复

Implement targeted solution:
  • Minimal change to fix root cause
  • Add safeguards against regression
  • Update tests if needed
执行针对性解决方案:
  • 最小化修改以修复根因
  • 添加防止回归的保障措施
  • 必要时更新测试用例

Step 6: Validate

步骤6:验证修复

Verify the fix:
  • Original reproduction no longer fails
  • Tests pass
  • No new issues introduced
  • Edge cases covered
验证修复效果:
  • 原复现案例不再失败
  • 测试用例全部通过
  • 未引入新问题
  • 覆盖边缘情况

Debugging Methodology

调试方法论

Phase 1: Gather Evidence

阶段1:收集证据

What to collect:
  • Error messages (complete text)
  • Stack traces (full trace, not truncated)
  • Log output (with timestamps)
  • State snapshots (variables, props, store)
  • Environment details (OS, browser, Node version)
Tools:
  • Logger service output
  • Browser DevTools console
  • Test runner output (Vitest, Playwright)
  • TypeScript compiler errors
  • Build output
Commands:
bash
undefined
需要收集的内容:
  • 错误信息(完整文本)
  • 堆栈跟踪(完整跟踪,不截断)
  • 日志输出(带时间戳)
  • 状态快照(变量、Props、Store)
  • 环境详情(操作系统、浏览器、Node版本)
工具:
  • 日志服务输出
  • 浏览器DevTools控制台
  • 测试运行器输出(Vitest、Playwright)
  • TypeScript编译器错误
  • 构建输出
命令:
bash
undefined

Run with verbose output

Run with verbose output

npm run test -- --reporter=verbose
npm run test -- --reporter=verbose

TypeScript with detailed errors

TypeScript with detailed errors

npx tsc --noEmit --pretty
npx tsc --noEmit --pretty

Build with stack traces

Build with stack traces

npm run build 2>&1 | tee build.log
undefined
npm run build 2>&1 | tee build.log
undefined

Phase 2: Reproduce Reliably

阶段2:可靠复现问题

Create minimal reproduction:
  1. Isolate the issue
    • Remove unrelated code
    • Use minimal data
    • Simplify conditions
  2. Document steps
    Reproduction Steps:
    1. [Action 1]
    2. [Action 2]
    3. [Action 3]
    Expected: [What should happen]
    Actual: [What actually happens]
  3. Verify consistency
    • Try 3-5 times
    • Note any variations
    • Check different environments
创建最小化复现案例:
  1. 隔离问题
    • 移除无关代码
    • 使用最小数据集
    • 简化条件
  2. 记录步骤
    Reproduction Steps:
    1. [Action 1]
    2. [Action 2]
    3. [Action 3]
    Expected: [What should happen]
    Actual: [What actually happens]
  3. 验证一致性
    • 尝试3-5次
    • 记录任何变化
    • 在不同环境中测试

Phase 3: Form Hypotheses

阶段3:形成假设

Ask systematic questions:
  • Is this a logic error, type error, or runtime error?
  • Is it a timing issue (race condition)?
  • Is it data-dependent?
  • Is it environment-specific?
  • Is it a regression (was it working before)?
Common root causes:
  • Incorrect assumptions about data shape
  • Missing null/undefined checks
  • Async/await misuse
  • Type coercion issues
  • Off-by-one errors
  • State mutation issues
  • Incorrect error handling
  • Missing dependencies in useEffect
提出系统化问题:
  • 这是逻辑错误、类型错误还是运行时错误?
  • 是否为时序问题(竞态条件)?
  • 是否与数据相关?
  • 是否特定于环境?
  • 是否为回归问题(之前正常工作)?
常见根因:
  • 对数据结构的错误假设
  • 缺失null/undefined检查
  • async/await误用
  • 类型强制转换问题
  • 差一错误
  • 状态突变问题
  • 错误处理不当
  • useEffect中缺失依赖项

Phase 4: Investigate

阶段4:调查分析

Read relevant code:
1. Start at error location
2. Trace backward to find data source
3. Trace forward to find impact
4. Check related components/functions
Add logging (temporarily):
typescript
// Use Logger service, not console.log
import { logger } from '@/lib/logging/logger';

logger.debug('Variable state', {
  component: 'ComponentName',
  value: myVar,
  type: typeof myVar,
});
Use debugger statements (for browser):
typescript
// Temporary debugging
if (condition) {
  debugger; // Browser will pause here
}
阅读相关代码:
1. Start at error location
2. Trace backward to find data source
3. Trace forward to find impact
4. Check related components/functions
添加日志(临时):
typescript
// Use Logger service, not console.log
import { logger } from '@/lib/logging/logger';

logger.debug('Variable state', {
  component: 'ComponentName',
  value: myVar,
  type: typeof myVar,
});
使用debugger语句(浏览器端):
typescript
// Temporary debugging
if (condition) {
  debugger; // Browser will pause here
}

Phase 5: Root Cause Analysis

阶段5:根因分析

Identify the true cause:
Not just: "Variable is undefined" But: "Function assumes input always has
.data
property, but API can return
null
on empty results"
Not just: "Test times out" But: "Async function doesn't resolve because mock doesn't implement
.then()
method"
Not just: "Type error on line 42" But: "Function returns
Promise<T>
but caller expects
T
because it's not awaiting"
Causal chain:
Root cause: [Fundamental issue]
Proximate cause: [Immediate trigger]
Symptom: [Observed error]
识别真正原因:
不只是:"变量未定义" 而是:"函数假设输入始终拥有
.data
属性,但API在结果为空时可能返回
null
"
不只是:"测试超时" 而是:"异步函数未解析,因为Mock未实现
.then()
方法"
不只是:"第42行类型错误" 而是:"函数返回
Promise<T>
,但调用者未使用await,因此期望得到
T
"
因果链:
Root cause: [Fundamental issue]
Proximate cause: [Immediate trigger]
Symptom: [Observed error]

Phase 6: Implement Fix

阶段6:实施修复

Fix principles:
  1. Targeted: Address root cause, not symptoms
    typescript
    // ❌ Bad: Suppress symptom
    try {
      doThing();
    } catch {
      /* ignore */
    }
    
    // ✅ Good: Fix root cause
    if (data?.hasProperty) {
      doThing();
    }
  2. Minimal: Smallest change that fixes issue
    • Don't refactor unrelated code
    • Don't add unnecessary features
    • Keep scope focused
  3. Defensive: Add safeguards
    typescript
    // Add validation
    if (!data || !data.items) {
      logger.warn('Invalid data structure', { data });
      return [];
    }
  4. Tested: Ensure it works
    • Original reproduction passes
    • Add test for regression prevention
    • Verify edge cases
Common fix patterns:
Null/undefined handling:
typescript
// ❌ Before
const result = data.items[0].value;

// ✅ After
const result = data?.items?.[0]?.value ?? defaultValue;
Async/await:
typescript
// ❌ Before
useEffect(() => {
  const data = await fetchData();
  setData(data);
}, []);

// ✅ After
useEffect(() => {
  const loadData = async () => {
    const data = await fetchData();
    setData(data);
  };
  void loadData();
}, []);
Type errors:
typescript
// ❌ Before
function process(value: string | null): string {
  return value.toUpperCase(); // Error: Object is possibly null
}

// ✅ After
function process(value: string | null): string {
  return value?.toUpperCase() ?? '';
}
修复原则:
  1. 针对性:解决根因,而非症状
    typescript
    // ❌ Bad: Suppress symptom
    try {
      doThing();
    } catch {
      /* ignore */
    }
    
    // ✅ Good: Fix root cause
    if (data?.hasProperty) {
      doThing();
    }
  2. 最小化:用最小的修改解决问题
    • 不要重构无关代码
    • 不要添加不必要的功能
    • 保持范围聚焦
  3. 防御性:添加保障措施
    typescript
    // Add validation
    if (!data || !data.items) {
      logger.warn('Invalid data structure', { data });
      return [];
    }
  4. 可测试:确保修复有效
    • 原复现案例通过
    • 添加防止回归的测试用例
    • 验证边缘情况
常见修复模式:
Null/undefined处理:
typescript
// ❌ Before
const result = data.items[0].value;

// ✅ After
const result = data?.items?.[0]?.value ?? defaultValue;
Async/await:
typescript
// ❌ Before
useEffect(() => {
  const data = await fetchData();
  setData(data);
}, []);

// ✅ After
useEffect(() => {
  const loadData = async () => {
    const data = await fetchData();
    setData(data);
  };
  void loadData();
}, []);
类型错误:
typescript
// ❌ Before
function process(value: string | null): string {
  return value.toUpperCase(); // Error: Object is possibly null
}

// ✅ After
function process(value: string | null): string {
  return value?.toUpperCase() ?? '';
}

Phase 7: Validate Fix

阶段7:验证修复

Validation checklist:
  • Original error no longer occurs
  • Tests pass (all, not just related ones)
  • Build succeeds
  • Lint passes
  • No new errors introduced
  • Edge cases work
  • Performance not degraded
Run validation:
bash
undefined
验证清单:
  • 原错误不再出现
  • 所有测试通过(不仅是相关测试)
  • 构建成功
  • 代码检查通过
  • 未引入新错误
  • 边缘情况正常工作
  • 性能未下降
执行验证:
bash
undefined

Full validation

Full validation

npm run lint && npm run test && npm run build
undefined
npm run lint && npm run test && npm run build
undefined

Debugging Patterns by Issue Type

按问题类型分类的调试模式

TypeScript Errors

TypeScript错误

Common issues:
  1. Type mismatch
  2. Property doesn't exist
  3. Object is possibly undefined
  4. Await outside async function
  5. Argument count mismatch
Debugging approach:
  1. Read error message carefully (TypeScript errors are descriptive)
  2. Check type definitions with
    Cmd+Click
    (VS Code)
  3. Verify actual type vs expected type
  4. Look for missing null checks
  5. Check async/await usage
Example fix:
typescript
// Error: Property 'name' does not exist on type 'User | null'
const userName = user.name;

// Fix: Add null check
const userName = user?.name ?? 'Anonymous';
常见问题:
  1. 类型不匹配
  2. 属性不存在
  3. 对象可能未定义
  4. 在异步函数外使用await
  5. 参数数量不匹配
调试方法:
  1. 仔细阅读错误信息(TypeScript错误描述性强)
  2. 使用VS Code的Cmd+Click查看类型定义
  3. 验证实际类型与预期类型
  4. 检查是否缺失null检查
  5. 检查async/await使用
修复示例:
typescript
// Error: Property 'name' does not exist on type 'User | null'
const userName = user.name;

// Fix: Add null check
const userName = user?.name ?? 'Anonymous';

Test Failures

测试失败

Common issues:
  1. Mock not configured correctly
  2. Async operation not awaited
  3. Test isolation issues (shared state)
  4. Timeout (async not resolving)
  5. Assertion mismatch
Debugging approach:
  1. Read test output carefully
  2. Run single test in isolation
  3. Check mock setup
  4. Verify async operations resolve
  5. Add console logging (temporarily)
Example fix:
typescript
// ❌ Test failing: Mock not properly awaitable
vi.mock('@/lib/service', () => ({
  fetchData: vi.fn(() => ({ data: 'test' })),
}));

// ✅ Fix: Return promise
vi.mock('@/lib/service', () => ({
  fetchData: vi.fn(() => Promise.resolve({ data: 'test' })),
}));
常见问题:
  1. Mock配置不正确
  2. 异步操作未被await
  3. 测试隔离问题(共享状态)
  4. 超时(异步操作未解析)
  5. 断言不匹配
调试方法:
  1. 仔细阅读测试输出
  2. 单独运行单个测试
  3. 检查Mock设置
  4. 验证异步操作是否解析
  5. 临时添加console日志
修复示例:
typescript
// ❌ Test failing: Mock not properly awaitable
vi.mock('@/lib/service', () => ({
  fetchData: vi.fn(() => ({ data: 'test' })),
}));

// ✅ Fix: Return promise
vi.mock('@/lib/service', () => ({
  fetchData: vi.fn(() => Promise.resolve({ data: 'test' })),
}));

Runtime Errors

运行时错误

Common issues:
  1. Uncaught exception
  2. Unhandled promise rejection
  3. Cannot read property of undefined
  4. Function not defined
  5. Network request failure
Debugging approach:
  1. Check stack trace for error origin
  2. Verify data shape at error point
  3. Add defensive checks
  4. Check for race conditions
  5. Verify dependencies loaded
Example fix:
typescript
// ❌ Error: Cannot read property 'length' of undefined
const count = items.length;

// ✅ Fix: Add defensive check
const count = items?.length ?? 0;
常见问题:
  1. 未捕获的异常
  2. 未处理的Promise拒绝
  3. 无法读取未定义属性
  4. 函数未定义
  5. 网络请求失败
调试方法:
  1. 检查堆栈跟踪以确定错误来源
  2. 验证错误发生点的数据结构
  3. 添加防御性检查
  4. 检查竞态条件
  5. 验证依赖是否加载
修复示例:
typescript
// ❌ Error: Cannot read property 'length' of undefined
const count = items.length;

// ✅ Fix: Add defensive check
const count = items?.length ?? 0;

Performance Issues

性能问题

Common issues:
  1. Infinite loop
  2. Unnecessary re-renders
  3. Memory leak
  4. Large data processing
  5. Blocking operations
Debugging approach:
  1. Use React DevTools Profiler
  2. Check useEffect dependencies
  3. Look for missing memoization
  4. Profile with browser DevTools
  5. Check for cleanup functions
Example fix:
typescript
// ❌ Performance issue: Infinite re-render
useEffect(() => {
  setData(processData(data));
}, [data]); // Triggers on own update!

// ✅ Fix: Remove circular dependency
useEffect(() => {
  setData(processData(initialData));
}, [initialData]);
常见问题:
  1. 无限循环
  2. 不必要的重渲染
  3. 内存泄漏
  4. 大数据处理
  5. 阻塞操作
调试方法:
  1. 使用React DevTools Profiler
  2. 检查useEffect依赖项
  3. 检查是否缺失记忆化处理
  4. 使用浏览器DevTools进行性能分析
  5. 检查清理函数
修复示例:
typescript
// ❌ Performance issue: Infinite re-render
useEffect(() => {
  setData(processData(data));
}, [data]); // Triggers on own update!

// ✅ Fix: Remove circular dependency
useEffect(() => {
  setData(processData(initialData));
}, [initialData]);

Race Conditions

竞态条件

Common issues:
  1. State update after unmount
  2. Multiple async operations
  3. Callback with stale closure
  4. Event handler timing
Debugging approach:
  1. Check async operation lifecycle
  2. Add cleanup functions
  3. Use refs for latest values
  4. Add abort controllers
Example fix:
typescript
// ❌ Race condition: Update after unmount
useEffect(() => {
  fetchData().then(data => setData(data));
}, []);

// ✅ Fix: Add cleanup
useEffect(() => {
  let mounted = true;
  fetchData().then(data => {
    if (mounted) setData(data);
  });
  return () => {
    mounted = false;
  };
}, []);
常见问题:
  1. 组件卸载后更新状态
  2. 多个异步操作
  3. 闭包过时的回调
  4. 事件处理时序
调试方法:
  1. 检查异步操作生命周期
  2. 添加清理函数
  3. 使用Ref获取最新值
  4. 使用中止控制器
修复示例:
typescript
// ❌ Race condition: Update after unmount
useEffect(() => {
  fetchData().then(data => setData(data));
}, []);

// ✅ Fix: Add cleanup
useEffect(() => {
  let mounted = true;
  fetchData().then(data => {
    if (mounted) setData(data);
  });
  return () => {
    mounted = false;
  };
}, []);

Project-Specific Debugging

项目特定调试

Novelist.ai Specifics

Novelist.ai 特定说明

Logger Service (REQUIRED):
typescript
import { logger } from '@/lib/logging/logger';

// ❌ Never use console.log
console.log('Debug:', value);

// ✅ Always use logger
logger.debug('Debug message', {
  component: 'ComponentName',
  value,
});
Database Debugging:
typescript
// Check Turso connection
logger.debug('Database query', {
  component: 'ServiceName',
  table: 'table_name',
  params,
});
Test Debugging:
  • Vitest for unit tests
  • Playwright for E2E tests
  • Use
    data-testid
    attributes for selectors
Common Novelist.ai Issues:
  • LocalStorage vs Turso sync issues
  • Device ID generation in tests
  • Plot Engine state management
  • World Building data relationships
日志服务(必填):
typescript
import { logger } from '@/lib/logging/logger';

// ❌ Never use console.log
console.log('Debug:', value);

// ✅ Always use logger
logger.debug('Debug message', {
  component: 'ComponentName',
  value,
});
数据库调试:
typescript
// Check Turso connection
logger.debug('Database query', {
  component: 'ServiceName',
  table: 'table_name',
  params,
});
测试调试:
  • Vitest用于单元测试
  • Playwright用于E2E测试
  • 使用
    data-testid
    属性作为选择器
Novelist.ai 常见问题:
  • LocalStorage与Turso同步问题
  • 测试中的设备ID生成问题
  • Plot Engine状态管理
  • World Building数据关系

Advanced Debugging

高级调试

Binary Search Debugging

二分查找调试

For complex bugs, use binary search:
  1. Find known good state (e.g., working commit)
  2. Find known bad state (e.g., current broken state)
  3. Check midpoint
  4. Narrow down until isolated
bash
undefined
对于复杂缺陷,使用二分查找法:
  1. 找到已知正常状态(如可正常工作的提交)
  2. 找到已知异常状态(如当前崩溃状态)
  3. 检查中间点
  4. 逐步缩小范围直至隔离问题
bash
undefined

Git bisect for regressions

Git bisect for regressions

git bisect start git bisect bad HEAD git bisect good <known-good-commit>
git bisect start git bisect bad HEAD git bisect good <known-good-commit>

Git will checkout midpoint

Git will checkout midpoint

Test and mark good/bad until found

Test and mark good/bad until found

undefined
undefined

Heisenbug (Disappears when debugging)

海森堡缺陷(调试时消失)

Strategies:
  1. Add non-invasive logging
  2. Record state snapshots
  3. Check for timing dependencies
  4. Look for race conditions
  5. Test in production mode
应对策略:
  1. 添加非侵入式日志
  2. 记录状态快照
  3. 检查时序依赖
  4. 查找竞态条件
  5. 在生产模式下测试

Rubber Duck Debugging

橡皮鸭调试法

When stuck:
  1. Explain the problem out loud (or in writing)
  2. Describe what the code does line-by-line
  3. State your assumptions explicitly
  4. Often reveals the issue
遇到瓶颈时:
  1. 大声(或书面)解释问题
  2. 逐行描述代码功能
  3. 明确陈述你的假设
  4. 通常会发现问题所在

Best Practices

最佳实践

DO:

应该做:

✓ Read error messages completely ✓ Create minimal reproductions ✓ Form hypotheses before changing code ✓ Fix root cause, not symptoms ✓ Add tests for regressions ✓ Use Logger service (not console.log) ✓ Validate fixes thoroughly ✓ Document complex bugs
✓ 完整阅读错误信息 ✓ 创建最小化复现案例 ✓ 先形成假设再修改代码 ✓ 修复根因而非症状 ✓ 添加防止回归的测试用例 ✓ 使用日志服务(而非console.log) ✓ 彻底验证修复 ✓ 记录复杂缺陷

DON'T:

不应该做:

✗ Guess randomly ("try-and-see" debugging) ✗ Make multiple changes at once ✗ Skip reproduction step ✗ Fix symptoms without understanding cause ✗ Leave debug code in production ✗ Ignore test failures ✗ Over-complicate fixes
✗ 随机猜测("试错式"调试) ✗ 同时进行多项修改 ✗ 跳过复现步骤 ✗ 不理解根因就修复症状 ✗ 在生产环境中遗留调试代码 ✗ 忽略测试失败 ✗ 过度复杂化修复

Output Format

输出格式

When completing debugging, provide:
markdown
undefined
完成调试后,请提供:
markdown
undefined

Debug Report: [Issue Title]

Debug Report: [Issue Title]

Issue Summary

Issue Summary

  • What: [Brief description]
  • Where: [File:line]
  • Severity: [Critical/High/Medium/Low]
  • What: [Brief description]
  • Where: [File:line]
  • Severity: [Critical/High/Medium/Low]

Symptoms

Symptoms

  • [Observed error or behavior]
  • [Stack trace or error message]
  • [Observed error or behavior]
  • [Stack trace or error message]

Reproduction Steps

Reproduction Steps

  1. [Step 1]
  2. [Step 2]
  3. [Result]
  1. [Step 1]
  2. [Step 2]
  3. [Result]

Root Cause

Root Cause

[Explanation of fundamental issue]
[Explanation of fundamental issue]

Solution

Solution

[Description of fix applied]
Files Modified:
  • [File path 1] - [What was changed]
  • [File path 2] - [What was changed]
[Description of fix applied]
Files Modified:
  • [File path 1] - [What was changed]
  • [File path 2] - [What was changed]

Validation

Validation

  • [✓] Original issue resolved
  • [✓] Tests passing
  • [✓] Build succeeds
  • [✓] No regressions
  • [✓] Original issue resolved
  • [✓] Tests passing
  • [✓] Build succeeds
  • [✓] No regressions

Prevention

Prevention

[How to avoid this in the future]
undefined
[How to avoid this in the future]
undefined

Examples

示例

Example 1: Async/Await Error

示例1:Async/Await错误

Issue: Build fails with "await outside async function"
Investigation:
  1. Read error: Line 140 in useWritingAssistant.ts
  2. Found:
    await
    in useEffect callback
  3. Root cause: useEffect callbacks can't be async
Fix:
typescript
// Before
useEffect(() => {
  const data = await loadData();
  setData(data);
}, []);

// After
useEffect(() => {
  const load = async () => {
    const data = await loadData();
    setData(data);
  };
  void load();
}, []);
Validation: Build passes, tests pass ✓
问题:构建失败,提示"await outside async function"
调查
  1. 读取错误信息:useWritingAssistant.ts第140行
  2. 发现:useEffect回调中使用了await
  3. 根因:useEffect回调不能是异步函数
修复
typescript
// Before
useEffect(() => {
  const data = await loadData();
  setData(data);
}, []);

// After
useEffect(() => {
  const load = async () => {
    const data = await loadData();
    setData(data);
  };
  void load();
}, []);
验证:构建通过,测试通过 ✓

Example 2: Test Timeout

示例2:测试超时

Issue: Test times out after 10 seconds
Investigation:
  1. Test calls async function
  2. Mock returns object, not promise
  3. Test awaits forever
Root cause: Mock missing
.then()
method
Fix:
typescript
// Before
mock.fn(() => ({ data: 'test' }));

// After
mock.fn(() => Promise.resolve({ data: 'test' }));
Validation: Test passes in <100ms ✓
问题:测试10秒后超时
调查
  1. 测试调用了异步函数
  2. Mock返回对象而非Promise
  3. 测试一直处于等待状态
根因:Mock缺失
.then()
方法
修复
typescript
// Before
mock.fn(() => ({ data: 'test' }));

// After
mock.fn(() => Promise.resolve({ data: 'test' }));
验证:测试在100ms内通过 ✓

Example 3: Type Error

示例3:类型错误

Issue: Property 'items' doesn't exist on type 'Response | null'
Investigation:
  1. API can return null
  2. Code assumes always returns object
  3. No null check
Root cause: Missing null handling
Fix:
typescript
// Before
const items = response.items;

// After
const items = response?.items ?? [];
Validation: TypeScript compiles, runtime safe ✓
问题:类型'Response | null'上不存在属性'items'
调查
  1. API可能返回null
  2. 代码假设始终返回对象
  3. 缺失null检查
根因:缺失null处理
修复
typescript
// Before
const items = response.items;

// After
const items = response?.items ?? [];
验证:TypeScript编译通过,运行时安全 ✓

Integration with Other Skills

与其他技能的集成

  • iterative-refinement: For fixing multiple bugs in cycles
  • goap-agent: For coordinating complex debugging across multiple files
  • test-runner: For validating fixes
  • code-reviewer: For reviewing fix quality
  • iterative-refinement:用于循环修复多个缺陷
  • goap-agent:用于协调跨多个文件的复杂调试
  • test-runner:用于验证修复效果
  • code-reviewer:用于审核修复质量

Tools Available

可用工具

This skill has access to:
  • Read: Read source files
  • Grep: Search for patterns
  • Glob: Find files
  • Edit: Fix bugs
  • Bash: Run tests, build, validate
Use these tools systematically to diagnose and fix issues.
本技能可访问:
  • Read:读取源文件
  • Grep:搜索模式
  • Glob:查找文件
  • Edit:修复缺陷
  • Bash:运行测试、构建、验证
请系统化地使用这些工具来诊断和解决问题。