@wbline/pi-plan-build 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,9 +4,30 @@
4
4
 
5
5
  格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本遵循语义化版本。
6
6
 
7
- ## [Unreleased]
7
+ ## [0.0.3] - 2026-10-16
8
8
 
9
- (暂无)
9
+ 借鉴 pi-plan-build 参考项目的两道硬机制(时序闸、事后对账),并对双模式链路做四轮深入排查(模式转移、守卫、对账、持久化、提示词、工具契约、测试卫生)。
10
+
11
+ ### 新增
12
+
13
+ - 时序硬闸:最近一条 assistant 消息里 `plan_task` 结构转移(new/include/update/exclude/abandon)未收尾时,文件变更与生命周期工具一律先等转移收尾——"生命周期转移必须先于依赖它的写入/命令单独完成"从提示词约束升级为硬拦截(借鉴参考项目的 dependent-actions 闸)
14
+ - 事后对账:build 模式放行波及面无法验证的变更工具(IDE 终端命令、bash/powershell 等)前记录计划文件内容基线,agent_settled 结算时文件被改动即警告提示核对(借鉴参考项目的 reconciliation,简化为 sha256 内容摘要比对);用户关闭 `protectPlanFile` 时不武装;新会话(startup/new)不继承上一会话基线,防误报
15
+ - 工具守卫去写死名单:`tool_call` 时经 `pi.getAllTools()` 动态读取工具注解(`readOnlyHint`),无注解时按名字动词约定分类(`get/search/list/…` 只读放行,其余 `ide_*` 保守视为变更通道——plan 阻断 / build 放行);设置文件 `toolGuard.readonly / mutating` 可强制覆盖,新增 IDE 变更工具不再漏拦
16
+
17
+ ### 变更
18
+
19
+ - **模式转移收紧(堵死角)**:`plan_task new` 仅限 plan 模式——此前 build 模式可创建计划但 `plan_exit` 拒绝执行,计划成孤儿;分步执行进行中禁止切回 plan 模式——此前会产生"只读约束 + 实现第 N 步"的自相矛盾注入
20
+ - 显示名统一为小写 `plan` / `build`:状态栏徽标 `📋 plan` / `🔨 build`、命令/工具描述、守卫阻断文案、zh/en 提示词、工具 label、`plan_exit` 审批选项与 README 全部同步;ID/协议层本就保持小写,不受影响
21
+
22
+ ### 修复
23
+
24
+ - **`expectedAttached` 契约与实现不符**:文档与工具描述声称"必须带、过期即拒",代码却允许不传跳过校验——现严格强制(new 必须显式 null,其余必须等于当前 seq)
25
+ - **`exec.start` 清遗留结局**:blocked 等结局记录后重新分步实现,旧结局与新执行并存造成矛盾注入——开始执行即失效
26
+ - **崩溃窗口状态不一致**:`plan_exit` 先开执行后切 build,两段持久化之间崩溃会留下"plan 模式 + 执行态"的转移不可达组合——交换顺序,且 `decodeState` 拒绝该组合(恢复回退到最近合法条目)
27
+ - **corrupt 状态下事件 handler 不再抛未捕获异常**:session_start 默认模式应用与验证通过回调改用 tryApply,错误以通知呈现
28
+ - **提示词动作名纠错**:zh/en `taskBoundary` 引用不存在的 `discussion` 动作(参考项目词汇残留)——实际动作为 `exclude`
29
+ - **`plan_task include` 在 build 模式的指引**:成功消息补充"计划文件受保护:先 /plan 切回再修订"——此前模型直接改计划文件会被守卫拦截,陷入循环
30
+ - **冒烟测试目录卫生**:smoke 此前用真实项目 cwd,每次运行在项目 `.pi/agent/plans/` 残留空占位文件——改用临时目录并在收尾清理
10
31
 
11
32
  ## [0.0.2] - 2026-10-16
12
33
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-plan-build
2
2
 
3
- [Pi coding agent](https://github.com/earendil-works/pi-mono) 的 Plan/Build 双模式扩展: **只读规划 → 显式审批 →
3
+ [Pi coding agent](https://github.com/earendil-works/pi-mono) 的 plan/build 双模式扩展: **只读规划 → 显式审批 →
4
4
  分步/整段实现 → 验证闭环**,针对 pi 1.3.0 重新设计。
5
5
 
6
6
  无需任何配置——装上即用,计划文件自动落在**当前项目** `.pi/agent/plans/`,命名为 `<创建时刻yyyyMMdd-HHmm>-<计划标题>.md`(如 `20251008-1432-售电信息三模块后端接口.md`,同名自动追加 `-2`),随项目走、看文件名即知内容。提示词内置中文/英文双语,菜单里一键切换。
@@ -16,12 +16,12 @@ pi install npm:@wbline/pi-plan-build
16
16
  | 命令 / 快捷键 | 说明 |
17
17
  |---------------|--------------------------------------------------------------------------------------------------------------|
18
18
  | `/plan-build` | 交互菜单:切换模式 / 查看状态 / 标记完成 / 放弃计划(原因必填,文件保留)/ 语言切换 / 设置文件 |
19
- | `/plan` `/build` | 直切 Plan/Build 模式;IDE(ACP)桥接层按命令名调用,JetBrains AI 聊天的模式选择器依赖这两个命令 |
19
+ | `/plan` `/build` | 直切 plan/build 模式;IDE(ACP)桥接层按命令名调用,JetBrains AI 聊天的模式选择器依赖这两个命令 |
20
20
  | `Alt+M` | 直接切换模式;默认模式由设置 `defaultMode` 决定 |
21
21
 
22
- 模式徽标(`📋 Plan` / `🔨 Build` + 计划标题与进度)显示在**底部状态栏**:Plan 为警告色、Build 为强调色。分步执行时步骤列表 widget 同步显示。
22
+ 模式徽标(`📋 plan` / `🔨 build` + 计划标题与进度)显示在**底部状态栏**:plan 为警告色、build 为强调色。分步执行时步骤列表 widget 同步显示。
23
23
 
24
- 设置文件 `~/.pi/agent/pi-plan-build.json`:`{ "lang": "zh", "defaultMode": "build", "protectPlanFile": true }`。
24
+ 设置文件 `~/.pi/agent/pi-plan-build.json`:`{ "lang": "zh", "defaultMode": "build", "protectPlanFile": true, "toolGuard": { "readonly": [], "mutating": [] } }`(`toolGuard` 可省略;列出的工具名强制按只读/变更通道分类)。
25
25
 
26
26
  菜单项按状态动态出现(无计划时没有"完成/放弃");TUI 里 ↑↓ 选择、Enter 执行、Esc 关闭,RPC 客户端降级为原生选择框。
27
27
 
@@ -29,8 +29,8 @@ pi install npm:@wbline/pi-plan-build
29
29
 
30
30
  | 工具 | 说明 |
31
31
  |----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
32
- | `plan_task` | 任务生命周期:`new` 建计划(Plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached`(当前 seq)做乐观并发,过期即拒 |
33
- | `plan_exit` | **Plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话实现 / 分步实现 / 留在 Plan |
32
+ | `plan_task` | 任务生命周期:`new` 建计划(plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached` 做乐观并发(`new` 传 null,其余传当前 seq),不匹配即拒 |
33
+ | `plan_exit` | **plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话实现 / 分步实现 / 留在 plan |
34
34
  | `plan_step_control` | 分步执行:`start` 批准就绪步、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
35
35
  | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
36
36
  | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时 |
@@ -41,7 +41,7 @@ pi install npm:@wbline/pi-plan-build
41
41
 
42
42
  ## 工作流
43
43
 
44
- 1. `/plan-build` 菜单选"切换模式"(或 Alt+M)进入 Plan 模式:只读调研讨论;`edit/write` 只允许写计划文件本身。
44
+ 1. `/plan-build` 菜单选"切换模式"(或 Alt+M)进入 plan 模式:只读调研讨论;`edit/write` 只允许写计划文件本身。
45
45
  2. 让 agent 规划:`plan_task new` 拿到 canonical 路径 → 写完整计划(含 `## 验证` 小节与文末 `## 实现步骤` 编号列表)→
46
46
  `plan_exit`。
47
47
  3. 审批三选一。选分步后:步骤 1 就绪 → 你说"继续" → `plan_step_control start` → 只做该步 → `plan_step_complete` →
@@ -54,17 +54,20 @@ pi install npm:@wbline/pi-plan-build
54
54
 
55
55
  守卫在 `tool_call` 前拦截,路径先归一化(`@` 前缀、`~`、相对路径)再做 symlink 解析,不存在的文件解析最远存在父目录:
56
56
 
57
- - **Plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 通道
58
- `ide_webstorm_apply_patch / create_new_file / reformat_file`)只许目标为当前计划文件;
59
- **无路径或波及面无法验证(如语义重命名)的调用一律阻断**——宁可误拦不可放行
60
- - **Build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 Plan 模式
61
- - **bash/powershell/终端命令不做分类沙箱**:Plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
62
- - 扩展自身对计划文件的修订(步骤 revise)走同一文件队列,绕过守卫但不绕过记录
57
+ - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单,优先级:设置文件
58
+ `toolGuard.readonly / mutating` 覆盖 > 工具注解
59
+ (`readOnlyHint`)> 名字动词约定(`get/search/list/…` 视为只读,未命中的 `ide_*` 保守视为变更通道);**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行
60
+ - **时序硬闸**:最近一条 assistant 消息里 `plan_task` 结构转移(new/include/update/exclude/abandon)未收尾时,文件变更与生命周期工具一律先等转移收尾(`list/show` 只读动作不拦)
61
+ - **事后对账**:build 模式放行波及面无法验证的变更工具(如 IDE 终端命令)前记录计划文件内容基线,结算(agent_settled)时发现文件被改动即警告提示核对
62
+ - **模式边界**:`plan_task new` 仅限 plan 模式(build 下创建的计划无法走 plan_exit 审批);分步执行进行中禁止切回 plan 模式(避免"只读 + 实现第 N 步"的矛盾注入);bash/powershell 改写计划文件同样纳入事后对账(`protectPlanFile: false` 时对账一并关闭)
63
+ - **build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 plan 模式;未列入的 IDE 变更工具同样过守卫(无法验证目标时放行)
64
+ - **bash/powershell/终端命令不做分类沙箱**:plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
65
+ - 扩展自身对计划文件的修订(步骤 revise)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕
63
66
 
64
67
  ## 设计取舍
65
68
 
66
69
  - **集中状态机而非分散闭包**:全部状态收敛为一个不可变 `State`(mode + plan + execution),唯一 `transition()` 入口返回
67
- `{ state, effects }`,纯函数 18 个单测全覆盖。代价是新增行为必须先定义转移事件——但换来任何状态变化都有唯一出处
70
+ `{ state, effects }`,纯函数单测全覆盖。代价是新增行为必须先定义转移事件——但换来任何状态变化都有唯一出处
68
71
  - **原生 UI 而非接管 composer**:只用 `setStatus` / `setWidget` / `ui.custom` / `ui.select`,不碰编辑器与消息栏。代价是没有花哨的
69
72
  composer 边框与消息轨道;换来与任何其它扩展零冲突,无需兼容降级代码
70
73
  - **砍掉干净会话交接**:跨会话 transfer/reconcile/announce 的多段状态机收益低、分支爆炸,不做。替代:`/plan-build`
@@ -80,7 +83,7 @@ pi install npm:@wbline/pi-plan-build
80
83
  ```bash
81
84
  npm install # 安装开发依赖(含 pi 1.3.0 类型)
82
85
  npm run check # biome + tsc 双检查
83
- npm test # 18 个纯函数单测:状态机 / 步骤解析 / 路径守卫 / 持久化解码
86
+ npm test # 26 个纯函数单测:状态机 / 步骤解析 / 路径守卫 / 持久化解码
84
87
  npm run smoke # 装配冒烟:stub ExtensionAPI 走完整流程(注册、守卫、菜单、注入)
85
88
  ```
86
89
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wbline/pi-plan-build",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Plan/Build dual-mode for the Pi coding agent: read-only planning, explicit approval, step-wise execution.",
5
5
  "license": "MIT",
6
6
  "author": "wongbin",
package/src/config.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
+ import type { ToolGuardOverride } from "./core/guard.ts";
8
9
  import type { Lang } from "./core/prompts.ts";
9
10
  import type { Mode } from "./core/state.ts";
10
11
 
@@ -13,6 +14,8 @@ export interface Config {
13
14
  defaultMode: Mode;
14
15
  /** Build 模式是否保护计划文件(默认开)。 */
15
16
  protectPlanFile: boolean;
17
+ /** 工具守卫分类覆盖:强制只读 / 强制按变更通道处理的自定义工具名。 */
18
+ toolGuard?: ToolGuardOverride;
16
19
  }
17
20
 
18
21
  const DEFAULTS: Config = {
@@ -31,6 +34,22 @@ export function configPath(): string {
31
34
  return path.join(agentDir(), "pi-plan-build.json");
32
35
  }
33
36
 
37
+ function parseToolGuard(v: unknown): ToolGuardOverride | undefined {
38
+ if (typeof v !== "object" || v === null) return undefined;
39
+ const o = v as Record<string, unknown>;
40
+ const names = (x: unknown): string[] | undefined =>
41
+ Array.isArray(x)
42
+ ? x.filter((s): s is string => typeof s === "string" && s.trim() !== "")
43
+ : undefined;
44
+ const readonly = names(o.readonly);
45
+ const mutating = names(o.mutating);
46
+ if (!readonly && !mutating) return undefined;
47
+ const out: ToolGuardOverride = {};
48
+ if (readonly) out.readonly = readonly;
49
+ if (mutating) out.mutating = mutating;
50
+ return out;
51
+ }
52
+
34
53
  function loadRaw(): { config: Config; warning?: string } {
35
54
  try {
36
55
  const text = fs.readFileSync(configPath(), "utf8");
@@ -40,6 +59,7 @@ function loadRaw(): { config: Config; warning?: string } {
40
59
  lang: parsed.lang === "en" ? "en" : "zh",
41
60
  defaultMode: parsed.defaultMode === "plan" ? "plan" : "build",
42
61
  protectPlanFile: parsed.protectPlanFile !== false,
62
+ toolGuard: parseToolGuard(parsed.toolGuard),
43
63
  },
44
64
  };
45
65
  } catch (e) {
package/src/core/guard.ts CHANGED
@@ -2,9 +2,9 @@
2
2
  * 权限守卫(路径判定纯函数 + tool_call 接线放 lifecycle)。
3
3
  *
4
4
  * 语义沿用参考项目的边界,收敛为可测纯函数:
5
- * - Plan 模式:文件变更通道(原生 edit/write 与 IDE 的
6
- * apply_patch/create_new_file/reformat_file)只许写当前计划文件;
7
- * 无法验证目标(如语义重命名)一律阻断——宁可误拦不可放行。
5
+ * - Plan 模式:文件变更通道(原生 edit/write 与 IDE 桥接工具)只许写
6
+ * 当前计划文件;IDE 工具动态分类(注解 > 名字动词约定 > 配置覆盖),
7
+ * 无法验证目标(语义重命名/未知工具)一律阻断——宁可误拦不可放行。
8
8
  * - Build 模式:保护计划文件不被改写(修订请回 Plan 模式)。
9
9
  * - bash/powershell/终端命令不做硬沙箱(Plan 的只读由提示词约束,
10
10
  * 这里不做任意命令分类——诚实标注而非冒充沙箱)。
@@ -17,14 +17,128 @@ import path from "node:path";
17
17
  /** 原生文件编辑工具(pi 1.3.0 实际存在的变更类工具)。 */
18
18
  export const FILE_MUTATION_TOOLS = new Set(["edit", "write"]);
19
19
 
20
- /** IDE(IntelliJ-first/ACP)会话的正规文件变更通道,Plan 守卫同等拦截。 */
21
- export const IDE_MUTATION_TOOLS = new Set([
22
- "ide_webstorm_apply_patch",
23
- "ide_webstorm_create_new_file",
24
- "ide_webstorm_reformat_file",
25
- "ide_webstorm_rename_refactoring",
20
+ /** 守卫关心的 MCP 风格注解最小子集(来自 pi.getAllTools() 的 ToolAnnotations)。 */
21
+ export interface ToolAnnotationsLike {
22
+ readonly readOnlyHint?: boolean;
23
+ readonly destructiveHint?: boolean;
24
+ }
25
+
26
+ /** 用户配置覆盖:强制分类的自定义工具名(优先级高于注解与名字约定)。 */
27
+ export interface ToolGuardOverride {
28
+ readonly?: string[];
29
+ mutating?: string[];
30
+ }
31
+
32
+ export type ToolGuardKind = "mutation" | "readonly" | "outOfScope";
33
+
34
+ /**
35
+ * 只读动词段:IDE 只读工具几乎都用这些动词命名。未命中的 ide_* 工具
36
+ * 一律按变更通道保守处理(宁可误拦不可放行);配置 toolGuard 可兜底。
37
+ */
38
+ const READONLY_VERBS: ReadonlySet<string> = new Set([
39
+ "read",
40
+ "get",
41
+ "search",
42
+ "list",
43
+ "find",
44
+ "grep",
45
+ "ls",
46
+ "preview",
47
+ "fetch",
48
+ "lint",
49
+ "analyze",
50
+ "analyse",
51
+ "introspect",
52
+ "describe",
53
+ "info",
54
+ "problems",
55
+ "status",
56
+ "tree",
57
+ "history",
58
+ "diff",
59
+ "callers",
60
+ "callees",
61
+ "explore",
62
+ "node",
63
+ "impact",
64
+ "diagnose",
65
+ "generate",
66
+ "test",
67
+ "symbol",
68
+ "files",
69
+ "repositories",
26
70
  ]);
27
71
 
72
+ /**
73
+ * 工具分类(纯函数):是否按"文件变更通道"守卫。
74
+ * - 优先级:配置覆盖 > 注解(readOnlyHint)> 名字动词约定。
75
+ * - 管辖范围:原生 edit/write 与 ide_* 桥接工具;其它自定义工具
76
+ * (如第三方 MCP)维持现状不守卫(outOfScope,README 注明局限)。
77
+ */
78
+ export function classifyToolCall(
79
+ toolName: string,
80
+ annotations?: ToolAnnotationsLike | undefined,
81
+ override?: ToolGuardOverride | undefined,
82
+ ): ToolGuardKind {
83
+ if (override?.mutating?.includes(toolName)) return "mutation";
84
+ if (override?.readonly?.includes(toolName)) return "readonly";
85
+ if (FILE_MUTATION_TOOLS.has(toolName)) return "mutation";
86
+ if (!toolName.startsWith("ide_")) return "outOfScope";
87
+ if (annotations?.readOnlyHint === true) return "readonly";
88
+ if (annotations?.readOnlyHint === false) return "mutation";
89
+ const segments = toolName.toLowerCase().split("_");
90
+ if (segments.some((s) => READONLY_VERBS.has(s))) return "readonly";
91
+ return "mutation";
92
+ }
93
+
94
+ /** 原生 shell 工具:不做硬沙箱,但 build 模式纳入事后对账(改动计划文件可被发现)。 */
95
+ export const SHELL_TOOLS: ReadonlySet<string> = new Set(["bash", "powershell"]);
96
+
97
+ /** 本扩展生命周期工具:plan_task 转移未收尾时与变更通道一同被时序闸拦住。 */
98
+ export const LIFECYCLE_TOOLS: ReadonlySet<string> = new Set([
99
+ "plan_exit",
100
+ "plan_step_control",
101
+ "plan_step_complete",
102
+ "plan_complete",
103
+ "plan_set_outcome",
104
+ ]);
105
+
106
+ export interface ToolCallPartLike {
107
+ type?: string;
108
+ name?: string;
109
+ arguments?: { action?: string };
110
+ }
111
+
112
+ /**
113
+ * 时序闸(纯函数):最近一条消息若是 assistant 且带 plan_task 结构转移
114
+ * (非 list/show 只读动作),依赖动作必须等转移收尾后再单独执行——把
115
+ * "生命周期转移必须先于依赖它的写入/命令单独完成"从提示词约束升级为硬拦截。
116
+ */
117
+ export function planTaskPendingInLastAssistant(
118
+ entries: readonly {
119
+ type?: string;
120
+ message?: {
121
+ role?: string;
122
+ content?: readonly ToolCallPartLike[];
123
+ };
124
+ }[],
125
+ ): boolean {
126
+ for (let i = entries.length - 1; i >= 0; i--) {
127
+ const e = entries[i];
128
+ if (e?.type !== "message") continue;
129
+ const m = e.message;
130
+ if (m?.role !== "assistant") return false;
131
+ return (m.content ?? []).some(
132
+ (part) =>
133
+ part?.type === "toolCall" &&
134
+ part.name === "plan_task" &&
135
+ part.arguments?.action !== "list" &&
136
+ part.arguments?.action !== "show",
137
+ );
138
+ }
139
+ return false;
140
+ }
141
+
28
142
  /** 归一化模型给的路径:@ 前缀、~、相对路径 → 绝对路径。 */
29
143
  export function normalizePath(raw: string, cwd: string): string {
30
144
  let p = raw.trim();
@@ -101,6 +215,7 @@ export type GuardDecision =
101
215
  * 变更裁决。targets 为 extractMutationTargets 的结果:
102
216
  * - Plan 模式:全部目标都必须是当前计划文件;undefined/空 一律阻断。
103
217
  * - Build 模式:已写盘的计划文件受保护;无法验证的目标放行(沿用原语义)。
218
+ * 调用方先用 classifyToolCall 圈定变更通道;本函数只按 targets 与模式裁决。
104
219
  */
105
220
  export function decideFileMutation(
106
221
  toolName: string,
@@ -109,8 +224,6 @@ export function decideFileMutation(
109
224
  planSaved: boolean,
110
225
  targets: string[] | undefined,
111
226
  ): GuardDecision {
112
- if (!FILE_MUTATION_TOOLS.has(toolName) && !IDE_MUTATION_TOOLS.has(toolName))
113
- return { action: "allow" };
114
227
  const plan = planPath
115
228
  ? normCase(normalizePath(planPath, process.cwd()))
116
229
  : null;
@@ -119,7 +232,7 @@ export function decideFileMutation(
119
232
  return mode === "plan"
120
233
  ? {
121
234
  action: "block",
122
- reason: `Plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。如需修改项目文件,请先通过 plan_exit 审批切换到 Build 模式。`,
235
+ reason: `plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`,
123
236
  }
124
237
  : { action: "allow" };
125
238
  }
@@ -136,8 +249,8 @@ export function decideFileMutation(
136
249
  return {
137
250
  action: "block",
138
251
  reason: planPath
139
- ? `Plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,请先通过 plan_exit 审批切换到 Build 模式。`
140
- : `Plan 模式只读:${toolName} 被阻断。先创建计划(plan_task new)后才能写计划文件本身。`,
252
+ ? `plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`
253
+ : `plan 模式只读:${toolName} 被阻断。先创建计划(plan_task new)后才能写计划文件本身。`,
141
254
  };
142
255
  }
143
256
 
@@ -146,7 +259,7 @@ export function decideFileMutation(
146
259
  return {
147
260
  action: "block",
148
261
  reason:
149
- "计划文件在 Build 模式受保护。修订计划请切回 Plan 模式(/plan)后再改。",
262
+ "计划文件在 build 模式受保护。修订计划请切回 plan 模式(/plan)后再改。",
150
263
  };
151
264
  }
152
265
  return { action: "allow" };
@@ -20,11 +20,11 @@ export interface PromptPack {
20
20
  }
21
21
 
22
22
  const ZH: PromptPack = {
23
- planReadonly: `Plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
23
+ planReadonly: `plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
24
24
  taskSelection: `模式切换不产生任务。没有当前计划时,仅当用户要求规划交付物或接受了具体修改方案,才调用 plan_task new(expectedAttached 传 null),用"动作+对象"式单一标题和详细 scope;先等返回的 canonical 路径再写文件。已有未完成计划时绝不另开新任务;完成或放弃都只能由用户明确指示。未获回答的提问不构成同意。`,
25
- taskBoundary: `任务身份一次建立:用户批准的追加用 plan_task include(给完整合并后的 scope);update 仅用于改名、身份纠错或对现有交付物的实质修正;discussion 记录明确排除的话题。相关问题、岔题、调研视为延续;对独立交付物,先问是否并入或结束当前计划。生命周期转移必须先于依赖它的写入/命令单独完成。计划文件是指令,不是进度记录。`,
26
- planWorkflow: `在 Plan 模式完成只读调研并收敛方案:推荐一个方案、列出关键文件、写完整计划文件(含 ## 验证 小节和文末 "## 实现步骤" 编号列表),然后调用 plan_exit 展示审阅。用户接受范围 ≠ 授权实现;不要在讨论未收敛或文件未写盘时调用 plan_exit。`,
27
- buildWorkflow: `Build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;当前范围以计划元数据为准,修订文件内容需回 Plan 模式。没有当前计划时是普通模式,小改动无需走计划流程。`,
25
+ taskBoundary: `任务身份一次建立:用户批准的追加用 plan_task include(给完整合并后的 scope);update 仅用于改名、身份纠错或对现有交付物的实质修正;exclude 记录明确排除的话题。相关问题、岔题、调研视为延续;对独立交付物,先问是否并入或结束当前计划。生命周期转移必须先于依赖它的写入/命令单独完成。计划文件是指令,不是进度记录。`,
26
+ planWorkflow: `在 plan 模式完成只读调研并收敛方案:推荐一个方案、列出关键文件、写完整计划文件(含 ## 验证 小节和文末 "## 实现步骤" 编号列表),然后调用 plan_exit 展示审阅。用户接受范围 ≠ 授权实现;不要在讨论未收敛或文件未写盘时调用 plan_exit。`,
27
+ buildWorkflow: `build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;当前范围以计划元数据为准,修订文件内容需回 plan 模式。没有当前计划时是普通模式,小改动无需走计划流程;需要新计划时先切回 plan 模式(/plan),plan_task new 仅在 plan 模式可用。`,
28
28
  completionRouting: `完成路由:用户明确说整计划完成 → plan_complete;明确指认某一步完成 → plan_step_control acknowledge;语义含糊的"完成"先澄清。工作与必需检查全部通过前不要调用 plan_complete;仍有未竟事项用 plan_set_outcome(awaiting_validation / blocked / waiting_for_input / still_working),绝不因空闲推断成功。`,
29
29
  verificationPolicy: `验证策略:按计划 ## 验证 小节用最小充分检查,然后停止。优先一个聚焦的行为验证(有可观察结果);构建/类型检查不能单独证明运行时行为。只为具体风险或明确要求增加检查。如实报告通过/受阻/未执行的检查,绝不弱化或谎报。只能由用户执行的必要验证:用 plan_set_outcome awaiting_validation 记录精确操作步骤,保持计划开放等用户回报;可选反馈不阻塞完成。`,
30
30
  stepActive: (n, total, text) =>
@@ -36,11 +36,11 @@ const ZH: PromptPack = {
36
36
  };
37
37
 
38
38
  const EN: PromptPack = {
39
- planReadonly: `Plan mode active: observe, analyze, discuss, and plan only. The only permitted write is saving the complete plan to the current plan file (finalization or explicitly requested revision). Answer normally during research; do not write files or call plan_exit mid-discussion.`,
39
+ planReadonly: `plan mode active: observe, analyze, discuss, and plan only. The only permitted write is saving the complete plan to the current plan file (finalization or explicitly requested revision). Answer normally during research; do not write files or call plan_exit mid-discussion.`,
40
40
  taskSelection: `Mode changes do not create tasks. With no current plan, call plan_task new (expectedAttached: null) only when the user requests a planning deliverable or accepts a concrete proposed change, with one action-led title and detailed scope; wait for the returned canonical path before writing. Never start another task while one is unfinished. Unanswered questions grant no consent.`,
41
- taskBoundary: `Establish identity once: plan_task include for user-approved additions (complete merged scope); update only for renames, identity corrections, or material constraints; discussion for explicit exclusions. Questions, tangents, and research assume continuity. Lifecycle transitions finish before dependent writes or shell calls. Plan Markdown is instructions, not progress.`,
42
- planWorkflow: `In Plan mode, finish read-only investigation, recommend one approach with key files, write the complete plan file (including a "## Verification" section and a numbered "## Implementation Steps" list), then call plan_exit for review. Accepting scope does not authorize implementation. Never call plan_exit before the file is saved or while discussion should continue.`,
43
- buildWorkflow: `Build mode: discuss and implement within approved authorization. The plan file is protected; current scope lives in plan metadata. Without a current plan this is ordinary mode — small fixes need no plan.`,
41
+ taskBoundary: `Establish identity once: plan_task include for user-approved additions (complete merged scope); update only for renames, identity corrections, or material constraints; exclude for explicit exclusions. Questions, tangents, and research assume continuity. Lifecycle transitions finish before dependent writes or shell calls. The plan Markdown is instructions, not progress.`,
42
+ planWorkflow: `In plan mode, finish read-only investigation, recommend one approach with key files, write the complete plan file (including a "## Verification" section and a numbered "## Implementation Steps" list), then call plan_exit for review. Accepting scope does not authorize implementation. Never call plan_exit before the file is saved or while discussion should continue.`,
43
+ buildWorkflow: `build mode: discuss and implement within approved authorization. The plan file is protected; current scope lives in plan metadata. Without a current plan this is ordinary mode — small fixes need no plan. Switch back to plan mode (/plan) when a new plan is needed; plan_task new only works in plan mode.`,
44
44
  completionRouting: `Completion routing: explicit whole-plan completion → plan_complete; an identified step → plan_step_control acknowledge; clarify ambiguous bare completion. Never call plan_complete before all approved work and required checks pass; otherwise use plan_set_outcome (awaiting_validation / blocked / waiting_for_input / still_working). Never infer success from idleness.`,
45
45
  verificationPolicy: `Verification: follow the plan's ## Verification section with the smallest sufficient check, then stop. Prefer one focused behavioral check with an observable result; build/type-check alone does not prove runtime behavior. Add checks only for concrete risks or explicit requirements. Report passed, blocked, and unperformed checks truthfully. For essential user-only checks use plan_set_outcome awaiting_validation with the exact action and keep the plan open until the user reports back; optional feedback never blocks completion.`,
46
46
  stepActive: (n, total, text) =>
@@ -37,6 +37,8 @@ export function decodeState(data: unknown): State | undefined {
37
37
  // 手写最小校验(TypeBox 运行时校验器依赖 value 包,不引额外依赖)
38
38
  if (data.version !== 2) return undefined;
39
39
  if (data.mode !== "plan" && data.mode !== "build") return undefined;
40
+ // 转移不可达组合(plan_exit 先切 build 再开执行):视为损坏,走恢复兜底
41
+ if (data.mode === "plan" && data.execution !== null) return undefined;
40
42
  if (data.plan === null) {
41
43
  if (data.execution !== null) return undefined;
42
44
  return { version: 2, mode: data.mode, plan: null, execution: null };
package/src/core/state.ts CHANGED
@@ -154,17 +154,25 @@ export function transition(prev: State, ev: Transition): TransitionResult {
154
154
  switch (ev.t) {
155
155
  case "mode.set": {
156
156
  if (s.mode === ev.mode) return { state: prev };
157
+ if (ev.mode === "plan" && s.execution)
158
+ throw new TransitionError(
159
+ "分步执行进行中:先 plan_step_control cancel(或完成/标记完成)再切回 plan 模式。",
160
+ );
157
161
  s.mode = ev.mode;
158
162
  return {
159
163
  state: s,
160
164
  note:
161
165
  ev.mode === "plan"
162
- ? "已切换到 Plan 模式(只读规划)"
163
- : "已切换到 Build 模式",
166
+ ? "已切换到 plan 模式(只读规划)"
167
+ : "已切换到 build 模式",
164
168
  };
165
169
  }
166
170
 
167
171
  case "plan.create": {
172
+ if (s.mode !== "plan")
173
+ throw new TransitionError(
174
+ "计划只能在 plan 模式创建:先 /plan(或 Alt+M)切换,再 plan_task new。",
175
+ );
168
176
  if (s.plan)
169
177
  throw new TransitionError(
170
178
  "已有未完成计划,须先完成或放弃(plan_complete / plan_task abandon)。",
@@ -248,6 +256,7 @@ export function transition(prev: State, ev: Transition): TransitionResult {
248
256
  }));
249
257
  if (steps.length === 0) throw new TransitionError("未解析出任何步骤。");
250
258
  s.execution = { steps, paused: false };
259
+ p.outcome = undefined; // 重新进入实现:旧的未完成结局(blocked 等)失效
251
260
  return { state: s, note: `分步执行开始:共 ${steps.length} 步` };
252
261
  }
253
262
 
@@ -358,7 +367,7 @@ export function currentSeq(s: State): number | null {
358
367
 
359
368
  /** 人类可读的一行状态(状态栏用)。 */
360
369
  export function statusLine(s: State): string {
361
- const mode = s.mode === "plan" ? "📋 Plan" : "🔨 Build";
370
+ const mode = s.mode === "plan" ? "📋 plan" : "🔨 build";
362
371
  if (!s.plan) return mode;
363
372
  if (s.execution) {
364
373
  const done = s.execution.steps.filter(
package/src/engine.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * 持久化(appendEntry)、UI 刷新(setStatus/setWidget/notify)。
4
4
  * 对比参考项目:不再有几十个闭包变量,所有变化都经过 apply()。
5
5
  */
6
+ import { createHash } from "node:crypto";
6
7
  import fs from "node:fs";
7
8
  import path from "node:path";
8
9
  import type {
@@ -32,12 +33,32 @@ export class PlanEngine {
32
33
  validationAsked = false;
33
34
  /** 状态损坏只读保护。 */
34
35
  corrupt = false;
36
+ /** 事后对账:不可验证变更工具放行前记录的计划文件基线(首次武装为准)。 */
37
+ reconciliation: { tool: string; baseline: string } | undefined;
35
38
 
36
39
  constructor(pi: ExtensionAPI, config: Config) {
37
40
  this.pi = pi;
38
41
  this.config = config;
39
42
  }
40
43
 
44
+ /** build 模式放行波及面无法验证的变更工具前,记录计划文件内容基线。 */
45
+ armReconciliation(toolName: string): void {
46
+ const p = this.state.plan;
47
+ if (!p?.saved || this.reconciliation) return;
48
+ this.reconciliation = { tool: toolName, baseline: planFileDigest(p.path) };
49
+ }
50
+
51
+ /** agent_settled 结算:计划文件被无法验证的工具改动则返回警告文本。 */
52
+ settleReconciliation(): string | undefined {
53
+ const armed = this.reconciliation;
54
+ this.reconciliation = undefined;
55
+ const p = this.state.plan;
56
+ if (!armed || !p?.saved) return undefined;
57
+ return planFileDigest(p.path) === armed.baseline
58
+ ? undefined
59
+ : `检测到计划文件可能被无法验证的工具(${armed.tool})改动,请核对计划内容是否仍然准确;必要时回 plan 模式修订。`;
60
+ }
61
+
41
62
  get P(): PromptPack {
42
63
  return prompts(this.config.lang);
43
64
  }
@@ -128,6 +149,15 @@ export class PlanEngine {
128
149
  }
129
150
  }
130
151
 
152
+ /** 计划文件内容摘要;文件缺失/不可读返回空串(与任何内容基线不同 → 视为被改动)。 */
153
+ function planFileDigest(planPath: string): string {
154
+ try {
155
+ return createHash("sha256").update(fs.readFileSync(planPath)).digest("hex");
156
+ } catch {
157
+ return "";
158
+ }
159
+ }
160
+
131
161
  /** canonical 计划文件路径:<cwd>/.pi/agent/plans/<yyyyMMdd-HHmm>-<标题slug>.md(随项目走,语义化命名) */
132
162
  export function nextPlanPath(cwd: string, title: string): string {
133
163
  const dir = path.join(cwd, ".pi", "agent", "plans");
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export default function planBuild(pi: ExtensionAPI): void {
28
28
 
29
29
  // --- 唯一命令:交互菜单 ---
30
30
  pi.registerCommand("plan-build", {
31
- description: "Plan/Build 菜单:切换模式、状态、完成、放弃、语言、设置",
31
+ description: "plan/build 菜单:切换模式、状态、完成、放弃、语言、设置",
32
32
  handler: async (_args, ctx) => {
33
33
  await openMenu(engine, ctx);
34
34
  },
@@ -40,11 +40,11 @@ export default function planBuild(pi: ExtensionAPI): void {
40
40
  if ("error" in r) ctx.ui.notify(r.error, "error");
41
41
  };
42
42
  pi.registerCommand("plan", {
43
- description: "切换到 Plan 模式(只读规划)",
43
+ description: "切换到 plan 模式(只读规划)",
44
44
  handler: (_args, ctx) => setMode("plan", ctx),
45
45
  });
46
46
  pi.registerCommand("build", {
47
- description: "切换到 Build 模式",
47
+ description: "切换到 build 模式",
48
48
  handler: (_args, ctx) => setMode("build", ctx),
49
49
  });
50
50
 
@@ -54,7 +54,7 @@ export default function planBuild(pi: ExtensionAPI): void {
54
54
 
55
55
  // --- 快捷键:Alt+M 切换模式(全局,不碰编辑器补全)---
56
56
  pi.registerShortcut(Key.alt("m"), {
57
- description: "切换 Plan/Build 模式",
57
+ description: "切换 plan/build 模式",
58
58
  handler: async (ctx) => {
59
59
  const next = engine.state.mode === "plan" ? "build" : "plan";
60
60
  const r = engine.tryApply({ t: "mode.set", mode: next }, ctx);
@@ -67,10 +67,13 @@ export default function planBuild(pi: ExtensionAPI): void {
67
67
  // startup(进程启动)与 new(/new 新会话)都是全新状态,应用默认模式;
68
68
  // resume/fork/reload 尊重恢复出的状态
69
69
  if (event.reason !== "startup" && event.reason !== "new") return;
70
+ engine.reconciliation = undefined; // 新会话不继承上一会话的对账基线(防误报)
70
71
  const mode =
71
72
  engine.state.mode === "plan" ? "plan" : loaded.config.defaultMode;
72
- if (mode !== engine.state.mode) engine.apply({ t: "mode.set", mode }, ctx);
73
- else engine.refreshUI(ctx);
73
+ if (mode !== engine.state.mode) {
74
+ const r = engine.tryApply({ t: "mode.set", mode }, ctx);
75
+ if ("error" in r) ctx.ui.notify(r.error, "error");
76
+ } else engine.refreshUI(ctx);
74
77
  });
75
78
 
76
79
  if (loaded.warning) {
@@ -89,7 +92,7 @@ function buildMenuItems(s: State): { id: MenuAction; label: string }[] {
89
92
  const items: { id: MenuAction; label: string }[] = [
90
93
  {
91
94
  id: "toggle",
92
- label: `切换模式 → ${s.mode === "plan" ? "Build" : "Plan"}`,
95
+ label: `切换模式 → ${s.mode === "plan" ? "build" : "plan"}`,
93
96
  },
94
97
  { id: "status", label: "查看状态" },
95
98
  ];
@@ -117,7 +120,7 @@ async function openMenu(
117
120
  // RPC:原生 select 单次选择
118
121
  const items = buildMenuItems(engine.state);
119
122
  const choice = await ctx.ui.select(
120
- "Plan/Build 菜单",
123
+ "plan/build 菜单",
121
124
  items.map((x) => x.label),
122
125
  );
123
126
  const selected = items.find((x) => x.label === choice);
@@ -193,7 +196,7 @@ function statusBody(s: State): string {
193
196
  );
194
197
  }
195
198
  } else {
196
- lines.push("没有当前计划。Plan 模式下让 agent 规划,或直接讨论。");
199
+ lines.push("没有当前计划。plan 模式下让 agent 规划,或直接讨论。");
197
200
  }
198
201
  return lines.join("\n");
199
202
  }
@@ -221,7 +224,7 @@ class MenuComponent {
221
224
  render(width: number): string[] {
222
225
  const th = this.theme;
223
226
  const items = buildMenuItems(this.state);
224
- const lines: string[] = ["", ` ${th.fg("accent", "Plan/Build")}`, ""];
227
+ const lines: string[] = ["", ` ${th.fg("accent", "plan/build")}`, ""];
225
228
  items.forEach((item, i) => {
226
229
  const row =
227
230
  i === this.selected
package/src/lifecycle.ts CHANGED
@@ -5,14 +5,30 @@
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
6
  import { buildContextBlock, injectContext } from "./context.ts";
7
7
  import {
8
+ classifyToolCall,
8
9
  decideFileMutation,
9
10
  extractMutationTargets,
10
- FILE_MUTATION_TOOLS,
11
- IDE_MUTATION_TOOLS,
11
+ LIFECYCLE_TOOLS,
12
+ planTaskPendingInLastAssistant,
12
13
  realpathLike,
14
+ SHELL_TOOLS,
15
+ type ToolAnnotationsLike,
13
16
  } from "./core/guard.ts";
14
17
  import type { PlanEngine } from "./engine.ts";
15
18
 
19
+ /** 动态查工具注解(pi.getAllTools());旧宿主/stub 无此 API 时按名字约定兜底。 */
20
+ function toolAnnotations(
21
+ pi: ExtensionAPI,
22
+ toolName: string,
23
+ ): ToolAnnotationsLike | undefined {
24
+ if (typeof pi.getAllTools !== "function") return undefined;
25
+ try {
26
+ return pi.getAllTools().find((t) => t.name === toolName)?.annotations;
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
16
32
  export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
17
33
  // --- 会话恢复 ---
18
34
  pi.on("session_start", (_event, ctx) => {
@@ -37,10 +53,33 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
37
53
  // --- 权限守卫(tool_call 可拦截)---
38
54
  pi.on("tool_call", (event, ctx) => {
39
55
  const s = engine.state;
40
- const guarded =
41
- FILE_MUTATION_TOOLS.has(event.toolName) ||
42
- IDE_MUTATION_TOOLS.has(event.toolName);
43
- if (!guarded) return;
56
+ const kind = classifyToolCall(
57
+ event.toolName,
58
+ toolAnnotations(pi, event.toolName),
59
+ engine.config.toolGuard,
60
+ );
61
+ // 时序闸:plan_task 结构转移未收尾前,依赖动作(变更通道/生命周期工具)先等
62
+ if (
63
+ (kind === "mutation" || LIFECYCLE_TOOLS.has(event.toolName)) &&
64
+ planTaskPendingInLastAssistant(lastMessageEntries(ctx))
65
+ ) {
66
+ return {
67
+ block: true,
68
+ reason:
69
+ "上一条消息的 plan_task 转移尚未收尾:先等其返回(canonical 路径/转移结果),依赖动作必须在下一轮单独执行。",
70
+ };
71
+ }
72
+ if (kind !== "mutation") {
73
+ // shell 通道不硬拦(诚实标注),但纳入事后对账:改动计划文件可被发现
74
+ if (
75
+ s.mode === "build" &&
76
+ engine.config.protectPlanFile &&
77
+ s.plan?.saved &&
78
+ SHELL_TOOLS.has(event.toolName)
79
+ )
80
+ engine.armReconciliation(event.toolName);
81
+ return;
82
+ }
44
83
  if (s.mode === "build" && !engine.config.protectPlanFile) return; // 用户关闭保护
45
84
  const planPath = s.plan?.path ? realpathLike(s.plan.path) : null;
46
85
  const targets = extractMutationTargets(
@@ -57,6 +96,14 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
57
96
  );
58
97
  if (decision.action === "block")
59
98
  return { block: true, reason: decision.reason };
99
+ // 事后对账:build 放行波及面无法验证的变更工具前记录计划文件基线
100
+ if (
101
+ s.mode === "build" &&
102
+ engine.config.protectPlanFile &&
103
+ s.plan?.saved &&
104
+ targets === undefined
105
+ )
106
+ engine.armReconciliation(event.toolName);
60
107
  });
61
108
 
62
109
  // --- 上下文注入(prompt cache 友好)---
@@ -68,6 +115,9 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
68
115
 
69
116
  // --- 验证问询:awaiting_validation 结算后问一次 ---
70
117
  pi.on("agent_settled", async (_event, ctx) => {
118
+ // 事后对账先行:不可验证工具改动了计划文件要立即提示
119
+ const reconciled = engine.settleReconciliation();
120
+ if (reconciled) ctx.ui.notify(reconciled, "warning");
71
121
  const outcome = engine.state.plan?.outcome;
72
122
  if (outcome?.kind !== "awaiting_validation" || engine.validationAsked)
73
123
  return;
@@ -78,8 +128,11 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
78
128
  outcome.userAction,
79
129
  );
80
130
  if (passed && engine.state.plan?.outcome?.kind === "awaiting_validation") {
81
- engine.apply({ t: "plan.complete" }, ctx);
82
- ctx.ui.notify("验证通过,计划已标记完成。", "info");
131
+ const r = engine.tryApply({ t: "plan.complete" }, ctx);
132
+ ctx.ui.notify(
133
+ "error" in r ? r.error : "验证通过,计划已标记完成。",
134
+ "error" in r ? "error" : "info",
135
+ );
83
136
  }
84
137
  // 未通过/取消:什么都不做,计划保持开放;用户会在对话里说明失败详情。
85
138
  });
@@ -90,3 +143,12 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
90
143
  ctx.ui.setWidget("plan-build-steps", undefined);
91
144
  });
92
145
  }
146
+
147
+ /** 取会话分支条目(形状宽松,交给纯函数判别)。 */
148
+ function lastMessageEntries(ctx: {
149
+ sessionManager: { getBranch(): unknown };
150
+ }): Parameters<typeof planTaskPendingInLastAssistant>[0] {
151
+ return ctx.sessionManager.getBranch() as Parameters<
152
+ typeof planTaskPendingInLastAssistant
153
+ >[0];
154
+ }
@@ -12,19 +12,19 @@ const Params = Type.Object({});
12
12
 
13
13
  const HERE = "本会话实现";
14
14
  const STEPWISE = "分步实现";
15
- const STAY = "留在 Plan 模式";
15
+ const STAY = "留在 plan 模式";
16
16
 
17
17
  export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
18
18
  pi.registerTool({
19
19
  name: "plan_exit",
20
- label: "Plan Exit",
20
+ label: "plan exit",
21
21
  description:
22
- "Plan 模式专用:完整计划写盘且讨论收敛后调用。展示计划并请求实现授权(本会话/分步/留下)。接受范围不等于开始实现之外的授权;不要在文件未保存或讨论未完成时调用。",
22
+ "plan 模式专用:完整计划写盘且讨论收敛后调用。展示计划并请求实现授权(本会话/分步/留下)。接受范围不等于开始实现之外的授权;不要在文件未保存或讨论未完成时调用。",
23
23
  parameters: Params,
24
24
  async execute(_id, _params, _signal, _onUpdate, ctx: ExtensionToolContext) {
25
25
  const s = engine.state;
26
26
  if (s.mode !== "plan") {
27
- return fail("plan_exit 仅在 Plan 模式可用。");
27
+ return fail("plan_exit 仅在 plan 模式可用。");
28
28
  }
29
29
  const plan = s.plan;
30
30
  if (!plan) return fail("没有当前计划。先 plan_task new。");
@@ -56,7 +56,7 @@ export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
56
56
  }
57
57
  if (!choice || choice === STAY) {
58
58
  return ok(
59
- `${review}\n\n---\n已留在 Plan 模式。等待用户进一步指示;不要开始实现。`,
59
+ `${review}\n\n---\n已留在 plan 模式。等待用户进一步指示;不要开始实现。`,
60
60
  );
61
61
  }
62
62
 
@@ -66,18 +66,19 @@ export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
66
66
  `${review}\n\n---\n分步执行需要步骤列表:${parsed.error}`,
67
67
  );
68
68
  }
69
- const r = engine.apply({ t: "exec.start", steps: parsed.steps }, ctx);
70
69
  engine.apply({ t: "mode.set", mode: "build" }, ctx);
70
+ // 先切 build 再开执行:两段持久化之间崩溃不会留下"plan 模式 + 执行态"的不可达组合
71
+ const r = engine.apply({ t: "exec.start", steps: parsed.steps }, ctx);
71
72
  const n = r.state.execution?.steps.length ?? parsed.steps.length;
72
73
  return ok(
73
- `${review}\n\n---\n用户批准分步实现(共 ${n} 步),已切换到 Build 模式。第 1 步就绪但未开始:向用户简述第 1 步并等待其明确批准(如"继续"),批准后调用 plan_step_control start。`,
74
+ `${review}\n\n---\n用户批准分步实现(共 ${n} 步),已切换到 build 模式。第 1 步就绪但未开始:向用户简述第 1 步并等待其明确批准(如"继续"),批准后调用 plan_step_control start。`,
74
75
  );
75
76
  }
76
77
 
77
78
  // 本会话实现
78
79
  engine.apply({ t: "mode.set", mode: "build" }, ctx);
79
80
  return ok(
80
- `${review}\n\n---\n用户批准在本会话实现,已切换到 Build 模式。请在批准的范围内实现全部工作,按计划 ## 验证 小节执行必需检查,完成后调用 plan_complete(或 plan_set_outcome 记录未竟事项)。`,
81
+ `${review}\n\n---\n用户批准在本会话实现,已切换到 build 模式。请在批准的范围内实现全部工作,按计划 ## 验证 小节执行必需检查,完成后调用 plan_complete(或 plan_set_outcome 记录未竟事项)。`,
81
82
  );
82
83
  },
83
84
  });
@@ -40,7 +40,7 @@ export function registerPlanOutcome(
40
40
  ): void {
41
41
  pi.registerTool({
42
42
  name: "plan_complete",
43
- label: "Plan Complete",
43
+ label: "plan complete",
44
44
  description:
45
45
  "标记整个计划完成:仅在全部批准工作与必需检查通过后,或用户明确指示整计划完成时调用(分步执行进行中也允许,会如实收尾)。绝不虚构未执行的检查。",
46
46
  parameters: CompleteParams,
@@ -59,7 +59,7 @@ export function registerPlanOutcome(
59
59
 
60
60
  pi.registerTool({
61
61
  name: "plan_set_outcome",
62
- label: "Plan Set Outcome",
62
+ label: "plan set outcome",
63
63
  description:
64
64
  "记录未完成结局并保持计划开放:awaiting_validation(必需的用户验证,userAction 必填)、blocked / waiting_for_input / still_working(reason 必填)。绝不因空闲推断成功。",
65
65
  parameters: FinishParams,
@@ -25,7 +25,7 @@ const Params = Type.Object({
25
25
  export function registerQuestion(pi: ExtensionAPI): void {
26
26
  pi.registerTool({
27
27
  name: "plan_question",
28
- label: "Plan Question",
28
+ label: "plan question",
29
29
  description:
30
30
  "向用户提出结构化选择题,收集决策/澄清歧义。推荐选项放第一个并在 label 尾部加“(推荐)”。",
31
31
  parameters: Params,
@@ -42,7 +42,7 @@ export function registerPlanStepTools(
42
42
  ): void {
43
43
  pi.registerTool({
44
44
  name: "plan_step_control",
45
- label: "Plan Step Control",
45
+ label: "plan step control",
46
46
  description:
47
47
  "分步执行控制:start 批准并开始就绪步;acknowledge 指认用户声明的已完成步(当前步无需先 start;记录既有事实,不授权新工作,AI 自己完成当前步用 plan_step_complete);skip 跳过;revise 修订未完成步文本;pause/resume 暂停恢复;cancel 取消分步执行(计划保留)。一次一个转移。",
48
48
  parameters: ControlParams,
@@ -119,7 +119,7 @@ export function registerPlanStepTools(
119
119
 
120
120
  pi.registerTool({
121
121
  name: "plan_step_complete",
122
- label: "Plan Step Complete",
122
+ label: "plan step complete",
123
123
  description:
124
124
  "完成当前进行中的分步(仅在本步实现与适用检查完成后调用)。摘要必填。完成立即生效,不等待用户验收;绝不开始下一步。",
125
125
  parameters: CompleteParams,
@@ -40,9 +40,9 @@ const Params = Type.Object({
40
40
  export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
41
41
  pi.registerTool({
42
42
  name: "plan_task",
43
- label: "Plan Task",
43
+ label: "plan task",
44
44
  description:
45
- "计划任务生命周期:new 建计划(Plan 模式);update 改名;include 追加用户批准的范围;exclude 记录排除话题;abandon 显式放弃(须用户指示);list/show 查看状态。转移必须先于依赖它的写入/命令单独完成。",
45
+ "计划任务生命周期:new 建计划(plan 模式);update 改名;include 追加用户批准的范围;exclude 记录排除话题;abandon 显式放弃(须用户指示);list/show 查看状态。转移必须先于依赖它的写入/命令单独完成。",
46
46
  parameters: Params,
47
47
  async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
48
48
  const s = engine.state;
@@ -72,7 +72,7 @@ export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
72
72
  // 并发守卫:除 list/show 外都要匹配 expectedAttached
73
73
  const expected = params.expectedAttached;
74
74
  if (params.action === "new") {
75
- if (expected !== null && expected !== undefined) {
75
+ if (expected !== null) {
76
76
  return err("plan_task new 需要 expectedAttached: null。");
77
77
  }
78
78
  if (!params.title)
@@ -103,9 +103,9 @@ export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
103
103
  }
104
104
 
105
105
  if (!s.plan) return err("当前没有计划。先 plan_task new。");
106
- if (expected !== undefined && expected !== s.plan.seq) {
106
+ if (expected !== s.plan.seq) {
107
107
  return err(
108
- `expectedAttached=${expected} 已过期,当前 seq=${s.plan.seq}。请重读 plan_task show 后重试,不要盲目换目标。`,
108
+ `expectedAttached=${expected ?? "(未传)"} 与当前 seq=${s.plan.seq} 不匹配。请重读 plan_task show 后重试,不要盲目换目标。`,
109
109
  );
110
110
  }
111
111
 
@@ -132,7 +132,7 @@ export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
132
132
  return "error" in r
133
133
  ? err(r.error)
134
134
  : text(
135
- `范围已追加(seq=${r.state.plan?.seq ?? 1})。请相应更新计划文件;若文件已审阅过,需重新 plan_exit。`,
135
+ `范围已追加(seq=${r.state.plan?.seq ?? 1})。请相应更新计划文件;若文件已审阅过,需重新 plan_exit。${r.state.mode === "build" ? "(build 模式下计划文件受保护:先 /plan 切回再修订,改完 plan_exit。)" : ""}`,
136
136
  );
137
137
  }
138
138
  case "exclude": {