aif-fix

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Fix - Bug Fix Workflow

修复 - Bug修复工作流

Fix a specific bug or problem in the codebase. Supports two modes: immediate fix or plan-first approach.
修复代码库中的特定Bug或问题。支持两种模式:立即修复或先制定计划的方法。

Workflow

工作流

Step 0: Check for Existing Fix Plan

步骤0:检查是否存在现有修复计划

BEFORE anything else, check if
.ai-factory/FIX_PLAN.md
exists.
If the file EXISTS:
  • Read
    .ai-factory/FIX_PLAN.md
  • Inform the user: "Found existing fix plan. Executing fix based on the plan."
  • Skip Steps 0.1 through 1 — go directly to Step 2: Investigate the Codebase, using the plan as your guide
  • Follow each step of the plan sequentially
  • After the fix is fully applied and verified, delete
    .ai-factory/FIX_PLAN.md
    :
    bash
    rm .ai-factory/FIX_PLAN.md
  • Continue to Step 4 (Verify), Step 5 (Test suggestion), Step 6 (Patch)
If the file DOES NOT exist AND
$ARGUMENTS
is empty:
  • Tell the user: "No fix plan found and no problem description provided. Please either provide a bug description (
    /aif-fix <description>
    ) or create a fix plan first."
  • STOP.
If the file DOES NOT exist AND
$ARGUMENTS
is provided:
  • Continue to Step 0.1 below.
在进行任何操作之前,检查
.ai-factory/FIX_PLAN.md
是否存在。
如果文件存在:
  • 读取
    .ai-factory/FIX_PLAN.md
  • 告知用户:“找到现有修复计划。将根据该计划执行修复。”
  • 跳过步骤0.1至步骤1——直接进入步骤2:调查代码库,以该计划为指导
  • 依次遵循计划中的每个步骤
  • 修复完全应用并验证后,删除
    .ai-factory/FIX_PLAN.md
    bash
    rm .ai-factory/FIX_PLAN.md
  • 继续执行步骤4(验证)、步骤5(测试建议)、步骤6(补丁)
如果文件不存在且
$ARGUMENTS
为空:
  • 告知用户:“未找到修复计划,且未提供问题描述。请提供Bug描述(
    /aif-fix <描述>
    )或先创建修复计划。”
  • 停止操作。
如果文件不存在且提供了
$ARGUMENTS
  • 继续执行下方的步骤0.1。

Step 0.1: Load Project Context & Past Experience

步骤0.1:加载项目上下文与过往经验

Read
.ai-factory/DESCRIPTION.md
if it exists to understand:
  • Tech stack (language, framework, database)
  • Project architecture
  • Coding conventions
Read all patches from
.ai-factory/patches/
if the directory exists:
  • Use
    Glob
    to find all
    *.md
    files in
    .ai-factory/patches/
  • Read each patch file to learn from past fixes
  • Pay attention to recurring patterns, root causes, and solutions
  • If the current problem resembles a past patch — apply the same approach or avoid the same mistakes
  • This is your accumulated experience. Use it.
如果
.ai-factory/DESCRIPTION.md
存在,读取该文件以了解:
  • 技术栈(语言、框架、数据库)
  • 项目架构
  • 编码规范
如果
.ai-factory/patches/
目录存在,读取该目录下的所有补丁
  • 使用
    Glob
    查找
    .ai-factory/patches/
    中的所有
    *.md
    文件
  • 读取每个补丁文件,从过往修复中学习
  • 注意重复出现的模式、根本原因和解决方案
  • 如果当前问题与过往补丁类似——采用相同方法或避免重复错误
  • 这是你的累积经验,请加以利用。

Step 1: Understand the Problem & Choose Mode

步骤1:理解问题并选择模式

From
$ARGUMENTS
, identify:
  • Error message or unexpected behavior
  • Where it occurs (file, function, endpoint)
  • Steps to reproduce (if provided)
If unclear, ask:
To fix this effectively, I need more context:

1. What is the expected behavior?
2. What actually happens?
3. Can you share the error message/stack trace?
4. When did this start happening?
After understanding the problem, ask the user to choose a mode using
AskUserQuestion
:
Question: "How would you like to proceed with the fix?"
Options:
  1. Fix now — Investigate and apply the fix immediately
  2. Plan first — Create a fix plan for review, then fix later
If user chooses "Plan first":
  • Proceed to Step 1.1: Create Fix Plan
If user chooses "Fix now":
  • Skip Step 1.1, proceed directly to Step 2: Investigate the Codebase
$ARGUMENTS
中确定:
  • 错误消息或意外行为
  • 问题发生位置(文件、函数、端点)
  • 重现步骤(如果提供)
如果信息不明确,询问:
为了有效修复该问题,我需要更多上下文:

1. 预期行为是什么?
2. 实际发生了什么?
3. 能否分享错误消息/堆栈跟踪?
4. 这个问题是什么时候开始出现的?
理解问题后,使用
AskUserQuestion
让用户选择模式:
问题:“你希望如何进行修复?”
选项:
  1. 立即修复——立即调查并应用修复
  2. 先制定计划——创建修复计划以供审核,之后再进行修复
如果用户选择“先制定计划”:
  • 继续执行步骤1.1:创建修复计划
如果用户选择“立即修复”:
  • 跳过步骤1.1,直接进入步骤2:调查代码库

Step 1.1: Create Fix Plan

步骤1.1:创建修复计划

Investigate the codebase enough to understand the problem and create a plan.
Use the same parallel exploration approach as Step 2 — launch Explore agents to investigate the problem area, related code, and past patterns simultaneously.
After agents return, synthesize findings to:
  1. Identify the root cause (or most likely candidates)
  2. Map affected files and functions
  3. Assess impact scope
Then create
.ai-factory/FIX_PLAN.md
with this structure:
markdown
undefined
充分调查代码库以理解问题并制定计划。
使用与步骤2相同的并行探索方法——启动Explore代理同时调查问题区域、相关代码和过往模式。
代理返回结果后,综合发现以:
  1. 确定根本原因(或最可能的候选原因)
  2. 绘制受影响的文件和函数
  3. 评估影响范围
然后创建
.ai-factory/FIX_PLAN.md
,结构如下:
markdown
undefined

Fix Plan: [Brief title]

修复计划:[简短标题]

Problem: [What's broken — from user's description] Created: YYYY-MM-DD HH:mm
问题: [存在的问题——来自用户描述] 创建时间: YYYY-MM-DD HH:mm

Analysis

分析

What was found during investigation:
  • Root cause (or suspected root cause)
  • Affected files and functions
  • Impact scope
调查过程中的发现:
  • 根本原因(或疑似根本原因)
  • 受影响的文件和函数
  • 影响范围

Fix Steps

修复步骤

Step-by-step plan for implementing the fix:
  1. Step one — what to change and why
  2. Step two — ...
  3. Step three — ...
实施修复的分步计划:
  1. 第一步——需要修改什么以及原因
  2. 第二步——...
  3. 第三步——...

Files to Modify

需要修改的文件

  • path/to/file.ts
    — what changes are needed
  • path/to/another.ts
    — what changes are needed
  • path/to/file.ts
    ——需要进行的修改
  • path/to/another.ts
    ——需要进行的修改

Risks & Considerations

风险与注意事项

  • Potential side effects
  • Things to verify after the fix
  • Edge cases to watch for
  • 潜在副作用
  • 修复后需要验证的内容
  • 需要注意的边缘情况

Test Coverage

测试覆盖

  • What tests should be added
  • What edge cases to cover

**After creating the plan, output:**
  • 需要添加哪些测试
  • 需要覆盖哪些边缘情况

**创建计划后,输出:**

Fix Plan Created ✅

修复计划已创建 ✅

Plan saved to
.ai-factory/FIX_PLAN.md
.
Review the plan and when you're ready to execute, run:
/aif-fix

**STOP here. Do NOT apply the fix.**
计划已保存至
.ai-factory/FIX_PLAN.md
请审核该计划,准备好执行时运行:
/aif-fix

**在此停止操作,不要应用修复。**

Step 2: Investigate the Codebase

步骤2:调查代码库

Use
Task
tool with
subagent_type: Explore
to investigate the problem in parallel.
This keeps the main context clean and allows simultaneous investigation of multiple angles.
Launch 2-3 Explore agents simultaneously:
Agent 1 — Locate the problem area:
Task(subagent_type: Explore, model: sonnet, prompt:
  "Find code related to [error location / affected functionality].
   Read the relevant functions, trace the data flow.
   Thoroughness: medium.")

Agent 2 — Related code & side effects:
Task(subagent_type: Explore, model: sonnet, prompt:
  "Find all callers/consumers of [affected function/module].
   Identify what else might break or be affected.
   Thoroughness: medium.")

Agent 3 — Similar past patterns (if patches exist):
Task(subagent_type: Explore, model: sonnet, prompt:
  "Search for similar error patterns or related fixes in the codebase.
   Check git log for recent changes to [affected files].
   Thoroughness: quick.")
After agents return, synthesize findings to identify:
  • The root cause (not just symptoms)
  • Related code that might be affected
  • Existing error handling
Fallback: If Task tool is unavailable, investigate directly:
  • Find relevant files using Glob/Grep
  • Read the code around the issue
  • Trace the data flow
  • Check for similar patterns elsewhere
**使用
Task
工具并设置
subagent_type: Explore
来并行调查问题。**这能保持主上下文整洁,并允许同时从多个角度进行调查。
同时启动2-3个Explore代理:
代理1——定位问题区域:
Task(subagent_type: Explore, model: sonnet, prompt:
  "查找与[错误位置/受影响功能]相关的代码。
   阅读相关函数,跟踪数据流。
   详细程度:中等。")

代理2——相关代码与副作用:
Task(subagent_type: Explore, model: sonnet, prompt:
  "查找[受影响函数/模块]的所有调用方/使用者。
   确定可能会被破坏或受影响的其他内容。
   详细程度:中等。")

代理3——类似的过往模式(如果存在补丁):
Task(subagent_type: Explore, model: sonnet, prompt:
  "在代码库中搜索类似的错误模式或相关修复。
   检查git日志中[受影响文件]的最近更改。
   详细程度:快速。")
代理返回结果后,综合发现以确定:
  • 根本原因(而非仅症状)
  • 可能受影响的相关代码
  • 现有的错误处理机制
**备选方案:**如果Task工具不可用,直接进行调查:
  • 使用Glob/Grep查找相关文件
  • 阅读问题周围的代码
  • 跟踪数据流
  • 检查其他地方是否存在类似模式

Step 3: Implement the Fix

步骤3:实施修复

Apply the fix with logging:
typescript
// ✅ REQUIRED: Add logging around the fix
console.log('[FIX] Processing user input', { userId, input });

try {
  // The actual fix
  const result = fixedLogic(input);
  console.log('[FIX] Success', { userId, result });
  return result;
} catch (error) {
  console.error('[FIX] Error in fixedLogic', {
    userId,
    input,
    error: error.message,
    stack: error.stack
  });
  throw error;
}
Logging is MANDATORY because:
  • User needs to verify the fix works
  • If it doesn't work, logs help debug further
  • Feedback loop: user provides logs → we iterate
应用修复并添加日志:
typescript
// ✅ 必需:在修复周围添加日志
console.log('[FIX] Processing user input', { userId, input });

try {
  // 实际修复内容
  const result = fixedLogic(input);
  console.log('[FIX] Success', { userId, result });
  return result;
} catch (error) {
  console.error('[FIX] Error in fixedLogic', {
    userId,
    input,
    error: error.message,
    stack: error.stack
  });
  throw error;
}
日志是强制性的,原因如下:
  • 用户需要验证修复是否有效
  • 如果修复无效,日志有助于进一步调试
  • 反馈循环:用户提供日志→我们迭代优化

Step 4: Verify the Fix

步骤4:验证修复

  • Check the code compiles/runs
  • Verify the logic is correct
  • Ensure no regressions introduced
  • 检查代码是否能编译/运行
  • 验证逻辑是否正确
  • 确保未引入回归问题

Step 5: Suggest Test Coverage

步骤5:建议测试覆盖

ALWAYS suggest covering this case with a test:
undefined
始终建议为此案例添加测试:
undefined

Fix Applied ✅

修复已应用 ✅

The issue was: [brief explanation] Fixed by: [what was changed]
问题是:[简短说明] 修复方式:[进行了哪些修改]

Logging Added

已添加日志

The fix includes logging with prefix
[FIX]
. Please test and share any logs if issues persist.
修复包含前缀为
[FIX]
的日志。 请进行测试,如果问题仍然存在,请分享相关日志。

Recommended: Add a Test

推荐:添加测试

This bug should be covered by a test to prevent regression:
```typescript describe('functionName', () => { it('should handle [the edge case that caused the bug]', () => { // Arrange const input = /* the problematic input */;
// Act
const result = functionName(input);

// Assert
expect(result).toBe(/* expected */);
}); }); ```
Would you like me to create this test?
  • Yes, create the test
  • No, skip for now
undefined
此Bug应通过测试覆盖,以防止回归:
```typescript describe('functionName', () => { it('should handle [the edge case that caused the bug]', () => { // 准备 const input = /* 有问题的输入 */;
// 执行
const result = functionName(input);

// 断言
expect(result).toBe(/* 预期结果 */);
}); }); ```
是否需要我创建此测试?
  • 是,创建测试
  • 否,暂时跳过
undefined

Logging Requirements

日志要求

All fixes MUST include logging:
  1. Log prefix: Use
    [FIX]
    or
    [FIX:<issue-id>]
    for easy filtering
  2. Log inputs: What data was being processed
  3. Log success: Confirm the fix worked
  4. Log errors: Full context if something fails
  5. Configurable: Use LOG_LEVEL if available
typescript
// Pattern for fixes
const LOG_FIX = process.env.LOG_LEVEL === 'debug' || process.env.DEBUG_FIX;

function fixedFunction(input) {
  if (LOG_FIX) console.log('[FIX] Input:', input);

  // ... fix logic ...

  if (LOG_FIX) console.log('[FIX] Output:', result);
  return result;
}
所有修复必须包含日志:
  1. 日志前缀:使用
    [FIX]
    [FIX:<issue-id>]
    以便于过滤
  2. 日志输入:正在处理的数据
  3. 日志成功状态:确认修复生效
  4. 日志错误信息:如果出现故障,记录完整上下文
  5. 可配置:如果可用,使用LOG_LEVEL
typescript
// 修复的模式
const LOG_FIX = process.env.LOG_LEVEL === 'debug' || process.env.DEBUG_FIX;

function fixedFunction(input) {
  if (LOG_FIX) console.log('[FIX] Input:', input);

  // ... 修复逻辑 ...

  if (LOG_FIX) console.log('[FIX] Output:', result);
  return result;
}

Examples

示例

Example 1: Null Reference Error

示例1:空引用错误

User:
/aif-fix TypeError: Cannot read property 'name' of undefined in UserProfile
Actions:
  1. Search for UserProfile component/function
  2. Find where
    .name
    is accessed
  3. Add null check with logging
  4. Suggest test for null user case
用户:
/aif-fix TypeError: Cannot read property 'name' of undefined in UserProfile
操作:
  1. 搜索UserProfile组件/函数
  2. 查找访问
    .name
    的位置
  3. 添加空检查和日志
  4. 建议为空用户案例添加测试

Example 2: API Returns Wrong Data

示例2:API返回错误数据

User:
/aif-fix /api/orders returns empty array for authenticated users
Actions:
  1. Find orders API endpoint
  2. Trace the query logic
  3. Find the bug (e.g., wrong filter)
  4. Fix with logging
  5. Suggest integration test
用户:
/aif-fix /api/orders returns empty array for authenticated users
操作:
  1. 查找订单API端点
  2. 跟踪查询逻辑
  3. 找到Bug(例如,错误的过滤器)
  4. 应用修复并添加日志
  5. 建议集成测试

Example 3: Form Validation Not Working

示例3:表单验证无效

User:
/aif-fix email validation accepts invalid emails
Actions:
  1. Find email validation logic
  2. Check regex or validation library usage
  3. Fix the validation
  4. Add logging for validation failures
  5. Suggest unit test with edge cases
用户:
/aif-fix email validation accepts invalid emails
操作:
  1. 查找邮箱验证逻辑
  2. 检查正则表达式或验证库的使用
  3. 修复验证逻辑
  4. 为验证失败添加日志
  5. 建议包含边缘情况的单元测试

Important Rules

重要规则

  1. Check FIX_PLAN.md first - Always check for existing plan before anything else
  2. Plan mode = plan only - When user chooses "Plan first", create the plan and STOP. Do NOT fix.
  3. Execute mode = follow the plan - When FIX_PLAN.md exists, follow it step by step, then delete it
  4. NO reports - Don't create summary documents (patches are learning artifacts, not reports)
  5. ALWAYS log - Every fix must have logging for feedback
  6. ALWAYS suggest tests - Help prevent regressions
  7. Root cause - Fix the actual problem, not symptoms
  8. Minimal changes - Don't refactor unrelated code
  9. One fix at a time - Don't scope creep
  10. Clean up - Delete FIX_PLAN.md after successful fix execution
  1. 首先检查FIX_PLAN.md——在进行任何操作之前,始终检查是否存在现有计划
  2. 计划模式=仅制定计划——当用户选择“先制定计划”时,创建计划并停止,不要进行修复
  3. 执行模式=遵循计划——当FIX_PLAN.md存在时,逐步遵循计划,然后删除该文件
  4. 不生成报告——不要创建摘要文档(补丁是学习工件,不是报告)
  5. 始终添加日志——每个修复必须包含日志以获取反馈
  6. 始终建议测试——帮助防止回归
  7. 根本原因——修复实际问题,而非仅症状
  8. 最小化修改——不要重构无关代码
  9. 一次修复一个问题——不要扩大范围
  10. 清理——成功执行修复后,删除FIX_PLAN.md

After Fixing

修复完成后

undefined
undefined

Fix Applied ✅

修复已应用 ✅

Issue: [what was broken] Cause: [why it was broken] Fix: [what was changed]
Files modified:
  • path/to/file.ts (line X)
Logging added: Yes, prefix
[FIX]
Test suggested: Yes
Please test the fix and share logs if any issues.
To add the suggested test:
  • Yes, create test
  • No, skip
undefined
问题: [存在的问题] 原因: 问题出现的原因 修复: 进行的修改
修改的文件:
  • path/to/file.ts(第X行)
已添加日志: 是,前缀为
[FIX]
已建议测试:
请测试修复,如果有任何问题,请分享日志。
要添加建议的测试:
  • 是,创建测试
  • 否,跳过
undefined

Step 6: Create Self-Improvement Patch

步骤6:创建自我改进补丁

ALWAYS create a patch after every fix. This builds a knowledge base for future fixes.
Create the patch:
  1. Create directory if it doesn't exist:
    bash
    mkdir -p .ai-factory/patches
  2. Create a patch file with the current timestamp as filename. Format:
    YYYY-MM-DD-HH.mm.md
    (e.g.,
    2026-02-07-14.30.md
    )
  3. Use this template:
markdown
undefined
**每次修复后始终创建补丁。**这会为未来的修复构建知识库。
创建补丁:
  1. 如果目录不存在,创建目录:
    bash
    mkdir -p .ai-factory/patches
  2. 创建一个以当前时间戳为文件名的补丁文件。 格式:
    YYYY-MM-DD-HH.mm.md
    (例如,
    2026-02-07-14.30.md
  3. 使用以下模板:
markdown
undefined

[Brief title describing the fix]

[描述修复的简短标题]

Date: YYYY-MM-DD HH:mm Files: list of modified files Severity: low | medium | high | critical
日期: YYYY-MM-DD HH:mm 文件: 修改的文件列表 严重程度: low | medium | high | critical

Problem

问题

What was broken. How it manifested (error message, wrong behavior). Be specific — include the actual error or symptom.
存在的问题。问题的表现形式(错误消息、异常行为)。 请具体说明——包含实际错误或症状。

Root Cause

根本原因

WHY the problem occurred. This is the most valuable part. Not "what was wrong" but "why it was wrong":
  • Logic error? Why was the logic incorrect?
  • Missing check? Why was it missing?
  • Wrong assumption? What was assumed?
  • Race condition? What sequence caused it?
问题出现的原因。这是最有价值的部分。 不是“哪里错了”而是“为什么会错”:
  • 逻辑错误?为什么逻辑不正确?
  • 缺少检查?为什么会缺少?
  • 错误的假设?假设了什么?
  • 竞态条件?什么序列导致了问题?

Solution

解决方案

How the fix was implemented. Key code changes and reasoning. Include the approach, not just "changed line X".
修复的实施方式。关键代码更改和推理。 说明方法,而非仅“修改了第X行”。

Prevention

预防措施

How to prevent this class of problems in the future:
  • What pattern/practice should be followed?
  • What should be checked during code review?
  • What test would catch this?
未来如何防止此类问题:
  • 应遵循什么模式/实践?
  • 代码审查时应检查什么?
  • 什么测试可以发现此类问题?

Tags

标签

Space-separated tags for categorization, e.g.:
#null-check
#async
#validation
#typescript
#api
#database

**Example patch:**

```markdown
用于分类的空格分隔标签,例如:
#null-check
#async
#validation
#typescript
#api
#database

**补丁示例:**

```markdown

Null reference in UserProfile when user has no avatar

UserProfile中用户无头像时的空引用

Date: 2026-02-07 14:30 Files: src/components/UserProfile.tsx Severity: medium
日期: 2026-02-07 14:30 文件: src/components/UserProfile.tsx 严重程度: medium

Problem

问题

TypeError: Cannot read property 'url' of undefined when rendering UserProfile for users without an uploaded avatar.
渲染无上传头像的用户的UserProfile时出现TypeError: Cannot read property 'url' of undefined。

Root Cause

根本原因

The
user.avatar
field is optional in the database schema but the component accessed
user.avatar.url
without a null check. This was introduced in commit abc123 when avatar display was added — the developer tested only with users that had avatars.
数据库架构中
user.avatar
字段是可选的,但组件在未进行空检查的情况下访问了
user.avatar.url
。该问题在提交abc123中添加头像显示功能时引入——开发者仅测试了有头像的用户。

Solution

解决方案

Added optional chaining:
user.avatar?.url
with a fallback to a default avatar URL. Also added a null check in the Avatar sub-component.
添加可选链:
user.avatar?.url
,并回退到默认头像URL。同时在Avatar子组件中添加了空检查。

Prevention

预防措施

  • Always check if database fields marked as
    nullable
    /
    optional
    are handled with null checks in the UI layer
  • Add test cases for "empty state" — user with minimal data
  • Consider a lint rule for accessing nested optional properties
  • 始终检查数据库中标记为
    nullable
    /
    optional
    的字段是否在UI层进行了空检查处理
  • 为“空状态”添加测试用例——数据最少的用户
  • 考虑为访问嵌套可选属性添加lint规则

Tags

标签

#null-check
#react
#optional-field
#typescript

**This is NOT optional.** Every fix generates a patch. The patch is your learning.
#null-check
#react
#optional-field
#typescript

**这不是可选操作。**每次修复都会生成一个补丁,补丁是你的学习成果。

Context Cleanup

上下文清理

Context is heavy after investigation, fix, and patch generation. All results are saved — suggest freeing space:
AskUserQuestion: Free up context before continuing?

Options:
1. /clear — Full reset (recommended)
2. /compact — Compress history
3. Continue as is

DO NOT:
  • ❌ Apply a fix when user chose "Plan first" — only create FIX_PLAN.md and stop
  • ❌ Skip the FIX_PLAN.md check at the start
  • ❌ Leave FIX_PLAN.md after successful fix execution — always delete it
  • ❌ Generate reports or summaries (patches are NOT reports — they are learning artifacts)
  • ❌ Refactor unrelated code
  • ❌ Add features while fixing
  • ❌ Skip logging
  • ❌ Skip test suggestion
  • ❌ Skip patch creation
经过调查、修复和补丁生成后,上下文会变得庞大。所有结果已保存——建议释放空间:
AskUserQuestion: 继续之前释放上下文空间?

选项:
1. /clear — 完全重置(推荐)
2. /compact — 压缩历史记录
3. 保持当前状态继续

禁止:
  • ❌ 当用户选择“先制定计划”时应用修复——仅创建FIX_PLAN.md并停止
  • ❌ 跳过开始时的FIX_PLAN.md检查
  • ❌ 成功执行修复后保留FIX_PLAN.md——始终删除该文件
  • ❌ 生成报告或摘要(补丁不是报告——它们是学习工件)
  • ❌ 重构无关代码
  • ❌ 修复时添加功能
  • ❌ 跳过日志
  • ❌ 跳过测试建议
  • ❌ 跳过补丁创建