# 模式简化与目标驱动修复循环 — 实施计划

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** 将 KCode Harness 模式从 lite/standard/strict 简化为 quick/normal，并用 `/kd goal` 取代 kd_verify_result。

**架构：** 类型层 → 门禁层 → 核心逻辑 → /kd goal 新功能 → 清理旧命令 → 测试文档

**涉及文件（共 ~25 个）：** src/harness/*.ts（15 个）+ extensions/*.ts（1 个）+ prompts/*.md（1 个）+ scripts/*.ts（若干）+ docs/*.md（若干）

---

## Wave 0：类型与门禁基础

### Task 0-1：types.ts — 替换 KdHarnessMode 类型和 MODE_PHASE_ORDER

**文件：** `src/harness/types.ts:4-5, 188-196`

- [ ] **Step 1：替换类型定义**

```typescript
// 替换
export type KdHarnessMode = "lite" | "standard" | "strict";
// 为
export type KdHarnessMode = "quick" | "normal";
```

- [ ] **Step 2：替换阶段顺序表**

```typescript
// 替换
export const MODE_PHASE_ORDER: Record<KdHarnessMode, KdPhase[]> = {
  lite: ["discuss", "plan", "execute", "verify"],
  standard: ["discuss", "spec", "plan", "execute", "verify"],
  strict: ["discuss", "spec", "plan", "execute", "verify", "ship"],
};
// 为
export const MODE_PHASE_ORDER: Record<KdHarnessMode, KdPhase[]> = {
  quick: ["execute"],
  normal: ["discuss", "plan", "execute", "verify"],
};
```

- [ ] **Step 3：提交**

```bash
git add src/harness/types.ts && git commit -m "refactor: replace mode types with quick/normal"
```

### Task 0-2：mode-policy.ts — 替换推断逻辑

**文件：** `src/harness/mode-policy.ts`

- [ ] **Step 1：修改 `inferHarnessMode`，移除旧关键词匹配，简化为默认 normal**

```typescript
export function inferHarnessMode(goal: string | undefined): KdHarnessMode {
  const text = goal ?? "";
  // 文档类、只读类操作 → quick
  if (/文档|说明|README|更新日志|CHANGELOG|提示词|规则|只读|审查|review|分析|排查|诊断|整理/i.test(text)) return "quick";
  // 一切涉及代码的 → normal（用户也可强制指定）
  return "normal";
}
```

- [ ] **Step 2：移除 `strictModeRequiredReason` 函数（不再需要强制 strict 升级）**

```typescript
// 整个函数删除
export function strictModeRequiredReason(...) { ... }
```

- [ ] **Step 3：移除 `STRICT_MODE_KEYWORDS`、`LITE_MODE_KEYWORDS`、`SIMPLE_PLUGIN_KEYWORDS`、`ENGINEERING_MODE_KEYWORDS`、`PRODUCT_IMPLEMENTATION_KEYWORDS` 常量**

- [ ] **Step 4：提交**

```bash
git add src/harness/mode-policy.ts && git commit -m "refactor: simplify mode inference for quick/normal"
```

### Task 0-3：run-sanitizer.ts — 移除旧模式迁移逻辑

**文件：** `src/harness/run-sanitizer.ts`

- [ ] **Step 1：查找所有 lite/standard/strict 字符串引用，移除旧模式迁移/hydration 逻辑**
- [ ] **Step 2：替换 `hydrateRun` 中恢复旧模式的代码，不再做旧模式兼容**
- [ ] **Step 3：提交**

```bash
git add src/harness/run-sanitizer.ts && git commit -m "refactor: remove old mode migration from run-sanitizer"
```

### Task 0-4：gates.ts — quick 模式跳过所有门禁

**文件：** `src/harness/gates.ts`

- [ ] **Step 1：在 `inspectGate` 函数开头添加 quick 短路**

```typescript
// 在函数入口处
if (run.mode === "quick") {
  return { passed: true, checkedAt: new Date().toISOString() };
}
```

- [ ] **Step 2：移除所有 `mode === "strict"` 或 `mode === "lite"` 的条件分支**
- [ ] **Step 3：提交**

```bash
git add src/harness/gates.ts && git commit -m "refactor: quick mode skips all gates"
```

---

## Wave 1：Harness 核心 — 替换模式引用

### Task 1-1：state.ts — 替换 run 创建中的模式引用

**文件：** `src/harness/state.ts`

- [ ] **Step 1：搜索所有 `"lite"`、`"standard"`、`"strict"` 字符串引用**
- [ ] **Step 2：将 createRun/startRun 相关逻辑中的模式处理改为 quick/normal**
- [ ] **Step 3：提交**

```bash
git add src/harness/state.ts && git commit -m "refactor: replace mode refs in state.ts"
```

### Task 1-2：prompt-policy.ts — 替换 strict 指令

**文件：** `src/harness/prompt-policy.ts`

- [ ] **Step 1：搜索 `"lite"`、`"standard"`、`"strict"`、`strictModeRequiredInstruction` 等引用**
- [ ] **Step 2：将 strict-mode 专用提示改为 normal-mode 提示**
- [ ] **Step 3：提交**

```bash
git add src/harness/prompt-policy.ts && git commit -m "refactor: replace strict mode instruction with normal"
```

### Task 1-3：批量替换 — 剩下 10 个 harness 文件

**文件（同一模式修改，一次性提交）：**
- `src/harness/demand-loop.ts`
- `src/harness/prompt.ts`
- `src/harness/control-frame.ts`
- `src/harness/context-compiler.ts`
- `src/harness/format.ts`
- `src/harness/messages.ts`
- `src/harness/action-router.ts`
- `src/harness/domain-planner.ts`
- `src/harness/audit.ts`
- `src/harness/consistency.ts`
- `src/harness/risk-policy.ts`
- `src/harness/data-source-policy.ts`
- `src/harness/sdk-policy.ts`
- `src/harness/transcript-eval.ts`

- [ ] **Step 1：对每个文件搜索 `"lite"`、`"standard"`、`"strict"` 字符串**
- [ ] **Step 2：将所有条件判断更新为 quick/normal：**
  - `run.mode === "strict"` → `run.mode === "normal"`（或删除严格模式专用分支）
  - `run.mode === "lite"` → `run.mode === "quick"`
  - 移除 `strictModeRequiredReason` 调用

- [ ] **Step 3：提交**

```bash
git add src/harness/demand-loop.ts src/harness/prompt.ts src/harness/control-frame.ts src/harness/context-compiler.ts src/harness/format.ts src/harness/messages.ts src/harness/action-router.ts src/harness/domain-planner.ts src/harness/audit.ts src/harness/consistency.ts src/harness/risk-policy.ts src/harness/data-source-policy.ts src/harness/sdk-policy.ts src/harness/transcript-eval.ts && git commit -m "refactor: replace mode refs across all harness files"
```

### Task 1-4：extension-args.ts — 更新模式解析

**文件：** `src/harness/extension-args.ts`

- [ ] **Step 1：找到 `parseStartArgs` 中模式解析逻辑，移除 lite/standard/strict，保留 quick/normal**

```typescript
// 在 token 解析部分，将模式值映射更新
if (token === "quick" || token === "normal") {
  mode = token;
  continue;
}
// 移除 lite/standard/strict 的处理
```

- [ ] **Step 2：提交**

```bash
git add src/harness/extension-args.ts && git commit -m "refactor: update mode arg parsing for quick/normal"
```

---

## Wave 2：/kd goal — 新功能

### Task 2-1：创建 goal-loop.ts

**文件：**
- 创建：`src/harness/goal-loop.ts`

- [ ] **Step 1：实现 `parseGoal(text)`**

```typescript
export interface ParsedGoal {
  command: string;      // 验证命令，如 "npm run check"
  condition: string;    // 条件描述，如 "通过"
}

export function parseGoal(text: string): ParsedGoal | null {
  // 尝试提取命令：npm run xxx、npx xxx、tsc 等
  const cmdMatch = text.match(/(npm\s+(?:run\s+)?\S+|npx\s+\S+|tsc\s+\S*|dotnet\s+\S+|gradle\s+\S+)/i);
  if (cmdMatch) {
    return { command: cmdMatch[1].trim(), condition: "exitCode=0" };
  }
  return null; // 无法解析，由 LLM 推断
}
```

- [ ] **Step 2：实现 `resolveVerifyCommand(goal, scripts)` — 从 package.json scripts 推断命令**

```typescript
export function resolveVerifyCommand(goal: string, availableScripts: string[]): string {
  const goalLower = goal.toLowerCase();
  // 关键词匹配
  if (/type(script|check)|tsc/.test(goalLower)) {
    const found = availableScripts.find(s => /check|type/.test(s));
    if (found) return `npm run ${found}`;
  }
  if (/test/.test(goalLower)) {
    const found = availableScripts.find(s => /test/.test(s));
    if (found) return `npm run ${found}`;
  }
  if (/lint/.test(goalLower)) {
    const found = availableScripts.find(s => /lint/.test(s));
    if (found) return `npm run ${found}`;
  }
  if (/build/.test(goalLower)) {
    const found = availableScripts.find(s => /build/.test(s));
    if (found) return `npm run ${found}`;
  }
  return ""; // 无法推断
}
```

- [ ] **Step 3：实现 `executeGoal(cwd, run, goal)` — 核心循环**

```typescript
import { spawnSync } from "node:child_process";
import type { ActiveRun } from "./types.ts";
import { recordVerifyResult } from "./repair.ts";

export interface GoalResult {
  achieved: boolean;
  attempts: number;
  message: string;
}

export function executeGoal(cwd: string, run: ActiveRun, goal: string): GoalResult {
  const parsed = parseGoal(goal);
  if (!parsed) {
    return { achieved: false, attempts: 0, message: "无法解析目标中的验证命令。请指定命令，如：/kd goal \"npm run check 通过\"" };
  }

  const maxAttempts = run.repair?.maxAttempts ?? 3;
  let attempts = run.repair?.status === "repairing" ? (run.repair?.attempts ?? 0) : 0;

  while (attempts < maxAttempts) {
    attempts++;
    console.log(`[${attempts}/${maxAttempts}] 执行 ${parsed.command}...`);

    const result = spawnSync(parsed.command, [], { cwd, encoding: "utf8", shell: true, timeout: 120_000 });
    const outcome = recordVerifyResult(cwd, run, {
      command: parsed.command,
      exitCode: result.status ?? 1,
      stdout: result.stdout?.toString() ?? "",
      stderr: result.stderr?.toString() ?? "",
      summary: result.status === 0 ? "验证通过" : `退出码 ${result.status}`,
    });

    if (outcome.status === "passed") {
      return { achieved: true, attempts, message: `目标达成（${attempts}/${maxAttempts}）` };
    }

    if (outcome.status === "blocked") {
      return { achieved: false, attempts, message: `已达到最大修复轮次 ${maxAttempts}，已创建阻断问题。` };
    }

    // outcome.status === "repairing" → 继续循环
    console.log(`  [失败] exit ${result.status}，进入修复（${attempts}/${maxAttempts}）`);
  }

  return { achieved: false, attempts, message: `修复循环结束，状态：${run.repair?.status}` };
}
```

- [ ] **Step 4：实现 `/kd goal` 命令入口**

```typescript
export function handleGoalCommand(cwd: string, goalText: string): string {
  const run = readActiveRun(cwd);
  if (!run) return "当前没有 active run。先用 /kd quick <需求> 或 /kd normal <需求> 开始。";

  // 中断续跑：复用上次的 goal 和 failed evidence
  if (run.repair?.status === "repairing" && run.repair.goal) {
    return executeGoal(cwd, run, run.repair.goal).message;
  }

  // 新目标
  const result = executeGoal(cwd, run, goalText);

  // 保存 goal 到 repair state
  if (result.attempts > 0) {
    run.repair = { ...run.repair, goal: goalText } as any;
    writeActiveRun(cwd, run);
  }

  return result.message;
}
```

- [ ] **Step 5：提交**

```bash
git add src/harness/goal-loop.ts && git commit -m "feat: add goal-driven auto-repair loop"
```

### Task 2-2：repair.ts — 保留内部逻辑，移除 kd_verify_result 入口

**文件：** `src/harness/repair.ts`

- [ ] **Step 1：保留 `recordVerifyResult`、`recordVerifyPass`、`recordVerifyFailure` 内部函数**
- [ ] **Step 2：移除 `VerifyResultInput` 和 `VerifyResultOutcome` 导出（移至 goal-loop 内部使用）**
- [ ] **Step 3：移除 `verifyResultBlockReason` 中关于 kd_verify_result 的命令校验（不再需要阻止非 verify 阶段调用，因为 goal-loop 自动管理阶段）**
- [ ] **Step 4：提交**

```bash
git add src/harness/repair.ts && git commit -m "refactor: strip kd_verify_result from repair.ts"
```

### Task 2-3：注册 /kd goal 工具

**文件：** `extensions/kingdee-harness-tools.ts:261`

- [ ] **Step 1：找到 `kd_verify_result` 工具定义（~line 261），替换为 `kd_goal` 工具**

```typescript
{
  name: "kd_goal",
  description: "设定自动验证目标。系统会自动执行验证命令、分析失败、修复、重新验证，直到通过或达到最大轮次。支持中断后续跑。",
  parameters: {
    type: "object",
    properties: {
      goal: {
        type: "string",
        description: "目标描述，如 'npm run check 通过'",
      },
    },
    required: ["goal"],
  },
}
```

- [ ] **Step 2：将 handler 指向 `handleGoalCommand`**
- [ ] **Step 3：移除 `kd_verify_result` 工具注册**

- [ ] **Step 4：提交**

```bash
git add extensions/kingdee-harness-tools.ts && git commit -m "feat: replace kd_verify_result with kd_goal tool"
```

### Task 2-4：清理 prompts 中的 kd_verify_result 引用

**文件：** `prompts/kd-verify.md`，以及 `src/harness/delegation.ts`、`src/harness/action-router.ts`、`src/harness/messages.ts`、`src/harness/format.ts`、`src/harness/demand-loop.ts`、`src/harness/prompt.ts`、`src/harness/prompt-policy.ts`

- [ ] **Step 1：删除 `prompts/kd-verify.md`（不再需要专门的 kd-verify 提示）**
- [ ] **Step 2：修改各 prompt 指令，将"运行验证命令并调用 kd_verify_result"替换为"使用 /kd goal 设定验证目标"**

修改 `src/harness/demand-loop.ts:49, 52, 88, 91` 等处的提示文本：
```typescript
// 替换前："修复后运行同一验证命令并调用 kd_verify_result"
// 替换后："修复后调用 /kd goal 重新验证"
```

- [ ] **Step 3：提交**

```bash
git rm prompts/kd-verify.md && git add src/harness/demand-loop.ts src/harness/prompt.ts src/harness/prompt-policy.ts src/harness/messages.ts && git commit -m "refactor: replace kd_verify_result refs with kd_goal"
```

---

## Wave 3：测试与文档

### Task 3-1：修复 smoke 测试

**文件：** `scripts/smoke-harness*.ts`、`scripts/e2e-*.ts`

- [ ] **Step 1：搜索所有测试文件中 `"lite"`、`"standard"`、`"strict"`、`kd_verify_result` 的引用**
- [ ] **Step 2：批量替换：**
  - `"strict"` → `"normal"`
  - `"lite"` → `"quick"`
  - 移除 kd_verify_result 相关断言
  - 添加 /kd goal 相关断言

- [ ] **Step 3：运行测试验证修改正确**

```bash
npx tsx scripts/smoke-harness.ts 2>&1
npx tsx scripts/smoke-kcode-command.ts 2>&1
```

- [ ] **Step 4：提交**

```bash
git add scripts/ && git commit -m "test: update smoke tests for quick/normal and kd_goal"
```

### Task 3-2：更新文档

**文件：**
- `docs/COMMAND_REFERENCE.md` — 更新模式说明、添加 /kd goal
- `docs/USER_GUIDE.md` — 更新快速开始和模式说明
- `docs/HARNESS_WORKFLOW.md` — 更新工作流说明
- `docs/EVIDENCE_AND_GATES.md` — 更新门禁说明

- [ ] **Step 1：逐文件将 lite/standard/strict 说明改为 quick/normal，添加 /kd goal 章节**
- [ ] **Step 2：提交**

```bash
git add docs/COMMAND_REFERENCE.md docs/USER_GUIDE.md docs/HARNESS_WORKFLOW.md docs/EVIDENCE_AND_GATES.md && git commit -m "docs: update for quick/normal modes and kd_goal"
```

### Task 3-3：最终验证

- [ ] **Step 1：TypeScript 类型检查**

```bash
npx tsc --noEmit
```

- [ ] **Step 2：运行全部 smoke 测试**

```bash
npm run check
npm run smoke:harness
npm run smoke:kcode-command
```

- [ ] **Step 3：确认无残留旧模式引用**

```bash
grep -r "lite\|standard\|strict" --include="*.ts" src/ | grep -v "node_modules" | grep -v ".d.ts"
# 期望：无匹配（除注释或文档字符串中的必要引用）
```

---

## 依赖关系

```
Task 0-1 (types) ──────────────────┐
Task 0-2 (mode-policy) ────────────┤
Task 0-3 (run-sanitizer) ──────────┤
Task 0-4 (gates) ──────────────────┤
                                    ↓
Task 1-1 到 1-4 (harness 核心) ─────┤
                                    ↓
Task 2-1 (goal-loop.ts) ───────────┤
Task 2-2 (repair.ts) ←─────────────┤
Task 2-3 (extension) ←────────────┤
Task 2-4 (prompts) ←──────────────┤
                                    ↓
Task 3-1 (tests) ←─────────────────┘
Task 3-2 (docs)
Task 3-3 (final verify)
```

**Wave 0 → Wave 1 → Wave 2 → Wave 3** 严格串行。Wave 0 必须先做完，否则后续编译不过。

---

## 执行方式

两个选项：

1. **子 agent 逐任务执行（推荐）** — 每个 task 派发独立子 agent，边审边改，快速迭代
2. **当前会话直接执行** — 原地挨个 task 做

选哪个？
