@wbline/pi-plan-build 0.0.3 → 0.0.5

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,6 +4,28 @@
4
4
 
5
5
  格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本遵循语义化版本。
6
6
 
7
+ ## [0.0.5] - 2026-10-17
8
+
9
+ ### 新增
10
+
11
+ - 对称确认门:build 模式调用 `plan_task new` 先弹窗确认切到 plan 模式(拒绝则保持 build 并提示可直接实现);plan 模式守卫拦截文件修改时也弹确认门——用户确认即切 build 放行本次修改,拒绝则本回合只拦不再问(agent_settled 重置),守卫文案同步补上入口闸路径
12
+ - 连跑授权:`plan_step_control start` 支持 `advance: "all"`——一次批准连跑剩余步骤,`plan_step_complete` 后自动推进下一步(注入切换为连跑提示词),遇 `plan_set_outcome` 记录的阻塞才停;默认仍为每步等批准
13
+ - 历史计划可见可续:`plan_task list` 扫描 plans 目录列出历史计划(标题 + 终态归档结局 + 日期,未收尾标注);`plan_task new` 支持 `fromFile` 恢复既有计划文件(复制内容到 canonical 路径并标记已写盘),换会话后可接着干
14
+ - 入口询问(与 `plan_exit` 出口审批对称):plan 模式且无当前计划时,`plan_task new` 在用户未明确要求规划(未传 `planningRequested: true`)时先弹窗让用户选「创建计划 / 直接执行」——选直接执行自动切 build 并放弃建计划,取消则不建计划等待指示;无 UI(print/json)环境跳过询问维持原行为。`taskSelection` 提示词、工具描述、README 同步,冒烟补 3 个用例;计划标题约束"标题内不用冒号"(避免与弹窗标题分隔符撞车)
15
+ - 终态归档:计划收尾(`plan_complete` / 分步最后一步完成 / `awaiting_validation` 验证通过确认)或放弃(`plan_task abandon` / 菜单)时,在计划文件文末追加状态块——`> **状态:已完成/已放弃**(本地日期)` + 摘要或原因,plans 目录的历史文件单看即可知结局。append-only 不改已审阅内容;集中在 `engine.apply` 一处覆盖全部收尾调用点,文件为空或写失败静默跳过(状态为准);归档结果透出到工具结果(`lastArchive` 每次 apply 重置),模型可如实汇报。冒烟补 2 个用例
16
+
17
+ ### 变更
18
+
19
+ - 步骤进度符号统一为等宽中文标签:侧栏 widget 的 `○◉◐●↷`(几何圆圈 + 箭头混排,CJK 环境下宽度歧义)改为 `[待办]/[就绪]/[进行]/[完成]/[跳过]`;状态栏的 `▶`/`⏸`(易被 emoji 化渲染)改为分数 + `(暂停)` 后缀
20
+ - 模式切换不再发对话通知:`mode.set` 转移不再携带 `note`(notify 在 IDE/ACP 桥接下渲染成对话消息,每次 /plan、/build、Alt+M 都刷屏);模式反馈由状态栏徽标实时承载,plan_exit 审批与入口闸"直接执行"的对话框本身就是反馈
21
+ - 审批对话框措辞统一为「动作,后果」风格、去掉括号:入口「创建计划,审阅后再实现 / 直接执行」,出口「本会话连续实现,完成后验证 / 分步实现,每步等待批准 / 留在 plan 模式,暂不实现」;出口标题改为「请选择计划的实现方式:〈标题〉」,与入口「请选择新任务的处理方式:〈标题〉」句式对称
22
+
23
+ ## [0.0.4] - 2026-10-16
24
+
25
+ ### 文档
26
+
27
+ - README 面向 [pi.dev/packages](https://pi.dev/packages) 画廊首页重写:一句话价值主张 + plan→审批→build 全流程图、"它解决什么问题"对照表、核心机制速览、设置表格化,技术细节(工具表/权限边界/设计取舍)完整保留后置。无代码变更
28
+
7
29
  ## [0.0.3] - 2026-10-16
8
30
 
9
31
  借鉴 pi-plan-build 参考项目的两道硬机制(时序闸、事后对账),并对双模式链路做四轮深入排查(模式转移、守卫、对账、持久化、提示词、工具契约、测试卫生)。
package/README.md CHANGED
@@ -1,82 +1,102 @@
1
1
  # pi-plan-build
2
2
 
3
- [Pi coding agent](https://github.com/earendil-works/pi-mono) 的 plan/build 双模式扩展: **只读规划 → 显式审批 →
4
- 分步/整段实现 → 验证闭环**,针对 pi 1.3.0 重新设计。
3
+ > 让 agent 先规划、经你审批、再动手。为 [Pi coding agent](https://github.com/earendil-works/pi-mono) 设计的 plan/build 双模式工作流扩展。
5
4
 
6
- 无需任何配置——装上即用,计划文件自动落在**当前项目** `.pi/agent/plans/`,命名为 `<创建时刻yyyyMMdd-HHmm>-<计划标题>.md`(如 `20251008-1432-售电信息三模块后端接口.md`,同名自动追加 `-2`),随项目走、看文件名即知内容。提示词内置中文/英文双语,菜单里一键切换。
5
+ **只读规划 → 显式审批 → 分步/整段实现 → 验证闭环。** 规划期间 agent 改不了你的项目;审批之前没有实现;每一步的完成与验证都有据可查。
7
6
 
8
- ## 安装
7
+ ```text
8
+ plan 模式(只读) 审批(三选一) build 模式
9
+ 调研讨论 → 写计划文件 ──▶ plan_exit ──▶ 本会话 / 分步 / 留在 plan ──▶ 实现 → 验证 → plan_complete
10
+ ▲ 守卫:只许写计划文件 ▲ 守卫:计划文件只读
11
+ ```
12
+
13
+ ## 快速开始
9
14
 
10
15
  ```bash
11
16
  pi install npm:@wbline/pi-plan-build
12
17
  ```
13
18
 
19
+ 零配置,装上即用。计划文件自动落在当前项目 `.pi/agent/plans/`(`<创建时刻>-<标题>.md`,随项目走)。30 秒体验完整闭环:
20
+
21
+ 1. **Alt+M** 切到 plan 模式:只读调研讨论,agent 的文件写入被守卫拦截
22
+ 2. 让 agent 规划:`plan_task new` 建计划(你未明确要求规划时,会先弹窗确认:创建计划还是直接执行)→ 写完整计划文件(含验证小节与实现步骤)→ `plan_exit` 提请审批
23
+ 3. 你三选一:**本会话连续实现 / 分步实现 / 留在 plan**——选择之前 agent 劫不了代码
24
+ 4. build 模式实现:计划文件受保护;分步模式默认每步等点头,说「剩下的都做完」可授权连跑
25
+ 5. 验证闭环:能自动验证的当场跑;只能你验证的(登录、硬件、线上效果)记为 `awaiting_validation`,回合结束后主动弹窗问你
26
+
27
+ ## 它解决什么问题
28
+
29
+ | 没有 plan-build | 有了 plan-build |
30
+ |---|---|
31
+ | agent 听完需求直接开改 | 规划期只读,写文件被守卫拦截 |
32
+ | "方案同意了"就等于开写 | 审批是显式的三选一,选择前零改动 |
33
+ | 计划与实现混在一个上下文里 | 双模式状态机,计划随会话持久化、可恢复 |
34
+ | "做完了"全靠 agent 自述 | 验证策略内置,必需的用户验证主动发问 |
35
+
36
+ ## 核心机制
37
+
38
+ - 🔒 **双模式权限守卫**:`tool_call` 前拦截,路径归一化(`@`/`~`/相对路径)+ symlink 解析。plan 模式只许写计划文件,无路径或波及面无法验证(未知工具、语义重命名)一律阻断——宁可误拦不可放行
39
+ - 🏷️ **动态工具分类**:不写死工具名单,按配置覆盖 > 注解(`readOnlyHint`)> 名字动词约定分类;新增 IDE 变更工具不再漏拦
40
+ - ⏱️ **时序硬闸**:`plan_task` 生命周期转移未收尾时,依赖它的文件变更与生命周期工具一律先等——把"转移先于依赖动作"从提示词约束升级为硬拦截
41
+ - 🚪 **全链路显式决策**:`plan_task new` 先问「创建计划还是直接执行」(明确要求规划可传参跳过),`plan_exit` 后问「本会话/分步/留下」;build 模式建计划、plan 模式被守卫拦截时也各有一道确认门——每次模式转换都由用户一键拍板
42
+ - 📒 **事后对账**:放行波及面无法验证的工具(IDE 终端命令、shell)前记录计划文件基线,回合结束时文件被改动即警告核对
43
+ - 🪜 **分步执行**:计划里的实现步骤逐个就绪,你说"继续"才开工,说「剩下的都做完」即授权连跑自动推进;侧栏实时显示 `[待办]/[就绪]/[进行]/[完成]/[跳过]` 进度
44
+ - ✅ **验证闭环**:`awaiting_validation` 结算后自动确认"必需验证是否通过?",通过才收尾,否则计划保持开放
45
+ - 🌐 **中英双语提示词**:菜单一键切换;7 个工具全模式常驻(稳定工具目录),模式切换不抖动工具列表,prompt cache 持续命中
46
+
14
47
  ## 命令
15
48
 
16
- | 命令 / 快捷键 | 说明 |
17
- |---------------|--------------------------------------------------------------------------------------------------------------|
49
+ | 命令 / 快捷键 | 说明 |
50
+ |---|---|
18
51
  | `/plan-build` | 交互菜单:切换模式 / 查看状态 / 标记完成 / 放弃计划(原因必填,文件保留)/ 语言切换 / 设置文件 |
19
- | `/plan` `/build` | 直切 plan/build 模式;IDE(ACP)桥接层按命令名调用,JetBrains AI 聊天的模式选择器依赖这两个命令 |
20
- | `Alt+M` | 直接切换模式;默认模式由设置 `defaultMode` 决定 |
52
+ | `/plan` `/build` | 直切模式;IDE(ACP)桥接层按命令名调用,JetBrains AI 聊天的模式选择器依赖这两个命令 |
53
+ | `Alt+M` | 直接切换模式;新会话默认模式由设置 `defaultMode` 决定 |
21
54
 
22
- 模式徽标(`📋 plan` / `🔨 build` + 计划标题与进度)显示在**底部状态栏**:plan 为警告色、build 为强调色。分步执行时步骤列表 widget 同步显示。
55
+ 状态栏徽标(`📋 plan` / `🔨 build` + 计划标题与进度)显示在底部;分步执行时步骤列表 widget 同步显示。
23
56
 
24
- 设置文件 `~/.pi/agent/pi-plan-build.json`:`{ "lang": "zh", "defaultMode": "build", "protectPlanFile": true, "toolGuard": { "readonly": [], "mutating": [] } }`(`toolGuard` 可省略;列出的工具名强制按只读/变更通道分类)。
57
+ ## 工具
25
58
 
26
- 菜单项按状态动态出现(无计划时没有"完成/放弃");TUI 里 ↑↓ 选择、Enter 执行、Esc 关闭,RPC 客户端降级为原生选择框。
59
+ | 工具 | 说明 |
60
+ |---|---|
61
+ | `plan_task` | 任务生命周期:`new` 建计划(plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached` 做乐观并发(`new` 传 null,其余传当前 seq),不匹配即拒。`new` 内置入口询问:用户未明确要求规划(传 `planningRequested: true` 可跳过)时,先弹窗让用户选「创建计划 / 直接执行」,选直接执行即自动切 build、不建计划;build 模式调用 `new` 会先弹窗确认切到 plan。`new` 支持 `fromFile` 恢复既有计划文件(换会话后接着干);`list` 附带 plans 目录历史计划与归档结局 |
62
+ | `plan_exit` | **plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话连续实现 / 分步实现 / 留在 plan 模式 |
63
+ | `plan_step_control` | 分步执行:`start` 批准就绪步(`advance: "all"` 一次授权连跑剩余步骤,遇阻塞才停)、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
64
+ | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
65
+ | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时。收尾时在计划文件文末写入状态块(`> **状态:已完成**(日期)` + 摘要),放弃同理(含原因),历史计划单看文件即可知结局 |
66
+ | `plan_set_outcome` | 记录未完成结局并保持计划开放:`awaiting_validation`(必填精确的 userAction)/ `blocked` / `waiting_for_input` / `still_working` |
67
+ | `plan_question` | 结构化选择题,收集决策;无交互 UI 时自动降级为文本提问 |
27
68
 
28
- ## 工具
69
+ ## 设置
70
+
71
+ `~/.pi/agent/pi-plan-build.json`,全部可省略:
29
72
 
30
- | 工具 | 说明 |
31
- |----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
32
- | `plan_task` | 任务生命周期:`new` 建计划(plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached` 做乐观并发(`new` 传 null,其余传当前 seq),不匹配即拒 |
33
- | `plan_exit` | **plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话实现 / 分步实现 / 留在 plan |
34
- | `plan_step_control` | 分步执行:`start` 批准就绪步、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
35
- | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
36
- | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时 |
37
- | `plan_set_outcome` | 记录未完成结局并保持计划开放:`awaiting_validation`(必填精确的 userAction)/ `blocked` / `waiting_for_input` / `still_working` |
38
- | `plan_question` | 结构化选择题,收集决策;无交互 UI 时自动降级为文本提问 |
39
-
40
- 7 个工具全模式常驻(稳定工具目录),模式合法性由执行时守卫保证——模型看到的工具列表从不抖动,prompt cache 不因模式切换失效。
41
-
42
- ## 工作流
43
-
44
- 1. `/plan-build` 菜单选"切换模式"(或 Alt+M)进入 plan 模式:只读调研讨论;`edit/write` 只允许写计划文件本身。
45
- 2. 让 agent 规划:`plan_task new` 拿到 canonical 路径 → 写完整计划(含 `## 验证` 小节与文末 `## 实现步骤` 编号列表)→
46
- `plan_exit`。
47
- 3. 审批三选一。选分步后:步骤 1 就绪 → 你说"继续" → `plan_step_control start` → 只做该步 → `plan_step_complete` →
48
- 下一步等待。侧栏实时显示 `○◉◐●↷` 进度。
49
- 4. 只能由你执行的验证(登录、硬件、线上效果):agent 用 `plan_set_outcome awaiting_validation` 记录精确步骤,本轮回合结束后弹 **"
50
- 必需验证是否通过?"**——确认即收尾,否则计划保持开放等你回报失败详情。
51
- 5. 完成后计划归档;`/plan-build` 菜单"查看状态"随时回看,历史进度在分步摘要里。
73
+ | 字段 | 默认 | 说明 |
74
+ |---|---|---|
75
+ | `lang` | `"zh"` | 提示词语言:`"zh"` / `"en"` |
76
+ | `defaultMode` | `"build"` | 新会话默认模式(startup/new 生效;resume 尊重恢复出的状态) |
77
+ | `protectPlanFile` | `true` | build 模式是否保护计划文件(关闭后对账一并停用) |
78
+ | `toolGuard` | — | 工具分类强制覆盖:`{ "readonly": [], "mutating": [] }`,列出的工具名优先级最高 |
52
79
 
53
80
  ## 权限边界
54
81
 
55
- 守卫在 `tool_call` 前拦截,路径先归一化(`@` 前缀、`~`、相对路径)再做 symlink 解析,不存在的文件解析最远存在父目录:
82
+ 守卫在 `tool_call` 前拦截,路径先归一化再做 symlink 解析,不存在的文件解析最远存在父目录:
56
83
 
57
- - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单,优先级:设置文件
58
- `toolGuard.readonly / mutating` 覆盖 > 工具注解
59
- (`readOnlyHint`)> 名字动词约定(`get/search/list/…` 视为只读,未命中的 `ide_*` 保守视为变更通道);**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行
84
+ - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单;**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行;有 UI 时拦截会弹确认门,用户确认即切 build 放行本次修改,拒绝则本回合只拦不再问(回合结束重置)
60
85
  - **时序硬闸**:最近一条 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` 时对账一并关闭)
86
+ - **事后对账**:build 模式放行波及面无法验证的变更工具前记录计划文件内容基线,结算(agent_settled)时发现文件被改动即警告提示核对;bash/powershell 改写计划文件同样纳入
87
+ - **模式边界**:`plan_task new` 仅限 plan 模式(build 下创建的计划无法走 plan_exit 审批);分步执行进行中禁止切回 plan 模式(避免"只读 + 实现第 N 步"的矛盾注入);plan 模式且无计划时,`new` 先弹窗询问「创建计划 / 直接执行」(用户明确要求规划可跳过),选直接执行自动切 build;build 模式调用 `new` 也会弹窗确认切到 plan(拒绝则保持 build)——两个方向的模式转换都由用户拍板
63
88
  - **build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 plan 模式;未列入的 IDE 变更工具同样过守卫(无法验证目标时放行)
64
89
  - **bash/powershell/终端命令不做分类沙箱**:plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
65
- - 扩展自身对计划文件的修订(步骤 revise)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕
90
+ - 扩展自身对计划文件的修订(步骤 revise、终态状态块)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕;终态归档 append-only,文件为空或写失败则静默跳过
66
91
 
67
92
  ## 设计取舍
68
93
 
69
- - **集中状态机而非分散闭包**:全部状态收敛为一个不可变 `State`(mode + plan + execution),唯一 `transition()` 入口返回
70
- `{ state, effects }`,纯函数单测全覆盖。代价是新增行为必须先定义转移事件——但换来任何状态变化都有唯一出处
71
- - **原生 UI 而非接管 composer**:只用 `setStatus` / `setWidget` / `ui.custom` / `ui.select`,不碰编辑器与消息栏。代价是没有花哨的
72
- composer 边框与消息轨道;换来与任何其它扩展零冲突,无需兼容降级代码
73
- - **砍掉干净会话交接**:跨会话 transfer/reconcile/announce 的多段状态机收益低、分支爆炸,不做。替代:`/plan-build`
74
- 菜单"查看状态"随时回看;要换会话,新会话里重新规划即可——计划文件本身可以复用
75
- - **宽容步骤解析**:编号 / checkbox /
76
- 短横线都接受,重复步骤去重;解析失败不报错,而是返回一段模型可执行的修复指引("在文件末尾追加 ##
77
- 实现步骤……")。代价是极端格式(嵌套列表)被忽略——它要求的是平铺的离散步骤
78
- - **上下文锚定注入**:计划块作为 user 消息插在最后一条真实用户消息之前,文本不含时间戳等易变因素——块位置与内容稳定,前缀缓存持续命中;锚点被压缩/树导航移除时自然前移
79
- - **awaiting_validation 问询只发一次**:内存 once 标志防重放(reload 后不重问)。代价是重启后需用户在对话里主动回报——比误重问的选择框更安静
94
+ - **集中状态机而非分散闭包**:全部状态收敛为一个不可变 `State`(mode + plan + execution),唯一 `transition()` 入口,纯函数单测全覆盖。代价是新增行为必须先定义转移事件——换来任何状态变化都有唯一出处
95
+ - **原生 UI 而非接管 composer**:只用 `setStatus` / `setWidget` / `ui.custom` / `ui.select`,不碰编辑器与消息栏——与任何其它扩展零冲突
96
+ - **砍掉干净会话交接**:跨会话 transfer/reconcile 的多段状态机收益低、分支爆炸,不做。换会话后用 `plan_task new fromFile` 恢复既有计划文件接着干(`list` 可查历史计划与结局)
97
+ - **宽容步骤解析**:编号 / checkbox / 短横线都接受,重复步骤去重;解析失败不报错,而是返回一段模型可执行的修复指引
98
+ - **上下文锚定注入**:计划块作为 user 消息插在最后一条真实用户消息之前,位置与内容稳定——前缀缓存持续命中
99
+ - **awaiting_validation 问询只发一次**:内存 once 标志防重放(reload 后不重问),比误重问的选择框更安静
80
100
 
81
101
  ## 开发
82
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wbline/pi-plan-build",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
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/context.ts CHANGED
@@ -60,7 +60,9 @@ export function buildContextBlock(
60
60
  state.execution.paused
61
61
  ? P.stepPaused
62
62
  : active
63
- ? P.stepActive(active.n, total, active.text)
63
+ ? state.execution.auto
64
+ ? P.stepAuto(active.n, total, active.text)
65
+ : P.stepActive(active.n, total, active.text)
64
66
  : ready
65
67
  ? P.stepReady(ready.n, total, ready.text)
66
68
  : `分步执行等待指令。`,
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 计划终态归档:收尾时在计划文件文末追加状态块(append-only,不改已审阅内容)。
3
+ * 状态为准:文件缺失/为空占位/写失败一律跳过,不阻塞收尾流程。
4
+ */
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ export function archivePlanFile(
9
+ path: string,
10
+ status: "已完成" | "已放弃",
11
+ detail?: string,
12
+ ): boolean {
13
+ try {
14
+ if (!fs.readFileSync(path, "utf8").trim()) return false;
15
+ // 本地日期(与计划文件名 formatStamp 的本地时刻约定一致;toISOString 是 UTC)
16
+ const d = new Date();
17
+ const p = (n: number) => String(n).padStart(2, "0");
18
+ const date = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
19
+ const lines = ["", "---", "", `> **状态:${status}**(${date})`];
20
+ if (detail?.trim()) lines.push(`> ${detail.trim()}`);
21
+ fs.appendFileSync(path, `${lines.join("\n")}\n`);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ export interface HistoricalPlan {
29
+ path: string;
30
+ title: string;
31
+ /** 文末状态块的结局与日期;未收尾为 undefined。 */
32
+ status?: "已完成" | "已放弃";
33
+ date?: string;
34
+ mtimeMs: number;
35
+ }
36
+
37
+ /** 扫描 plans 目录的历史计划(按修改时间倒序):标题取首个一级标题,结局读文末状态块。 */
38
+ export function listPlanFiles(cwd: string, limit = 20): HistoricalPlan[] {
39
+ const dir = path.join(cwd, ".pi", "agent", "plans");
40
+ let names: string[];
41
+ try {
42
+ names = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
43
+ } catch {
44
+ return [];
45
+ }
46
+ const items: HistoricalPlan[] = [];
47
+ for (const name of names) {
48
+ const p = path.join(dir, name);
49
+ try {
50
+ const st = fs.statSync(p);
51
+ const content = fs.readFileSync(p, "utf8");
52
+ const title =
53
+ /^#\s+(.+)$/m.exec(content)?.[1]?.trim() || name.replace(/\.md$/, "");
54
+ let status: HistoricalPlan["status"];
55
+ let date: string | undefined;
56
+ // 取最后一次出现的终态块(恢复后再收尾的文件会有多块,最后一块为准)
57
+ for (const m of content.matchAll(
58
+ /\*\*状态:(已完成|已放弃)\*\*((\d{4}-\d{2}-\d{2}))/g,
59
+ )) {
60
+ status = m[1] as HistoricalPlan["status"];
61
+ date = m[2];
62
+ }
63
+ items.push({ path: p, title, status, date, mtimeMs: st.mtimeMs });
64
+ } catch {
65
+ // 单个文件读失败不影响整体列表
66
+ }
67
+ }
68
+ items.sort((a, b) => b.mtimeMs - a.mtimeMs);
69
+ return items.slice(0, limit);
70
+ }
package/src/core/guard.ts CHANGED
@@ -232,7 +232,7 @@ export function decideFileMutation(
232
232
  return mode === "plan"
233
233
  ? {
234
234
  action: "block",
235
- reason: `plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`,
235
+ reason: `plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。如需修改项目文件,可调 plan_task new(入口弹窗选「直接执行」即切 build 直接修改),或经 plan_exit 审批后实现。`,
236
236
  }
237
237
  : { action: "allow" };
238
238
  }
@@ -249,7 +249,7 @@ export function decideFileMutation(
249
249
  return {
250
250
  action: "block",
251
251
  reason: planPath
252
- ? `plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`
252
+ ? `plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,可调 plan_task new(入口弹窗选「直接执行」即切 build 直接修改),或经 plan_exit 审批后实现。`
253
253
  : `plan 模式只读:${toolName} 被阻断。先创建计划(plan_task new)后才能写计划文件本身。`,
254
254
  };
255
255
  }
@@ -14,6 +14,7 @@ export interface PromptPack {
14
14
  readonly completionRouting: string;
15
15
  readonly verificationPolicy: string;
16
16
  readonly stepActive: (n: number, total: number, text: string) => string;
17
+ readonly stepAuto: (n: number, total: number, text: string) => string;
17
18
  readonly stepReady: (n: number, total: number, text: string) => string;
18
19
  readonly stepPaused: string;
19
20
  readonly awaitingValidation: string;
@@ -21,7 +22,7 @@ export interface PromptPack {
21
22
 
22
23
  const ZH: PromptPack = {
23
24
  planReadonly: `plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
24
- taskSelection: `模式切换不产生任务。没有当前计划时,仅当用户要求规划交付物或接受了具体修改方案,才调用 plan_task new(expectedAttached 传 null),用"动作+对象"式单一标题和详细 scope;先等返回的 canonical 路径再写文件。已有未完成计划时绝不另开新任务;完成或放弃都只能由用户明确指示。未获回答的提问不构成同意。`,
25
+ taskSelection: `模式切换不产生任务。没有当前计划且用户要求规划交付物或接受了具体修改方案时,才调用 plan_task new(expectedAttached 传 null;planningRequested 仅在用户明确要求规划时传 true)。用户未明确要求规划时,工具会先弹窗让用户选「创建计划 / 直接执行」:返回说已切到 build 就放弃建计划、直接实现;用户取消就等待指示,不要自行规划。用"动作+对象"式单一标题(标题内不用冒号)和详细 scope;先等返回的 canonical 路径再写文件。已有未完成计划时绝不另开新任务;完成或放弃都只能由用户明确指示。未获回答的提问不构成同意。`,
25
26
  taskBoundary: `任务身份一次建立:用户批准的追加用 plan_task include(给完整合并后的 scope);update 仅用于改名、身份纠错或对现有交付物的实质修正;exclude 记录明确排除的话题。相关问题、岔题、调研视为延续;对独立交付物,先问是否并入或结束当前计划。生命周期转移必须先于依赖它的写入/命令单独完成。计划文件是指令,不是进度记录。`,
26
27
  planWorkflow: `在 plan 模式完成只读调研并收敛方案:推荐一个方案、列出关键文件、写完整计划文件(含 ## 验证 小节和文末 "## 实现步骤" 编号列表),然后调用 plan_exit 展示审阅。用户接受范围 ≠ 授权实现;不要在讨论未收敛或文件未写盘时调用 plan_exit。`,
27
28
  buildWorkflow: `build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;当前范围以计划元数据为准,修订文件内容需回 plan 模式。没有当前计划时是普通模式,小改动无需走计划流程;需要新计划时先切回 plan 模式(/plan),plan_task new 仅在 plan 模式可用。`,
@@ -30,14 +31,16 @@ const ZH: PromptPack = {
30
31
  stepActive: (n, total, text) =>
31
32
  `分步执行中:只实现第 ${n}/${total} 步 —— ${text}\n完成本步及其适用检查后调用 plan_step_complete(摘要必填);不要开始后续步骤,不要改计划文件。依赖后续步骤的检查要显式说明推迟,不得谎报通过。`,
32
33
  stepReady: (n, total, text) =>
33
- `第 ${n}/${total} 步已就绪等待批准:${text}\n用户说"继续/proceed"之类时调用 plan_step_control start 开始本步;在批准前不要做项目改动。`,
34
+ `第 ${n}/${total} 步已就绪等待批准:${text}\n用户说"继续/proceed"之类时调用 plan_step_control start 开始本步;用户明确要求连续执行(如"剩下的都做完""全部继续")时传 advance: "all" 一次授权连跑。在批准前不要做项目改动。`,
35
+ stepAuto: (n, total, text) =>
36
+ `连跑授权中:只实现第 ${n}/${total} 步 —— ${text}\n完成本步及适用检查后调用 plan_step_complete,然后直接开始下一步的实现,无需等待用户批准;遇到只有用户能解决的阻塞用 plan_set_outcome 记录并停下,不要绕过。`,
34
37
  stepPaused: `分步执行已暂停:保留进度但没有任何实现授权。用户明确要求恢复后再继续(plan_step_control resume 由其自然语言指令触发)。`,
35
38
  awaitingValidation: `计划处于"待验证":实现已完成,正在等待用户执行必要验证。不要继续改动;用户回报通过后(或明确说标记完成)才调用 plan_complete。`,
36
39
  };
37
40
 
38
41
  const EN: PromptPack = {
39
42
  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
- 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.`,
43
+ taskSelection: `Mode changes do not create tasks. With no current plan, call plan_task new (expectedAttached: null; pass planningRequested: true only when the user explicitly asked to plan) only when the user requests a planning deliverable or accepts a concrete proposed change. Otherwise the tool first asks the user to choose "create plan / execute directly": if the result says build mode is active, drop plan creation and implement directly; if the user cancels, wait for instructions instead of planning on your own. One action-led title (no colons) 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
44
  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
45
  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
46
  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.`,
@@ -46,7 +49,9 @@ const EN: PromptPack = {
46
49
  stepActive: (n, total, text) =>
47
50
  `Step-by-step execution: implement only step ${n}/${total} — ${text}\nWhen this step and its applicable checks finish, call plan_step_complete with a summary. Do not start later steps or edit the plan file. Defer checks that depend on later steps and say so; never claim a deferred check passed.`,
48
51
  stepReady: (n, total, text) =>
49
- `Step ${n}/${total} is ready and awaiting approval: ${text}\nWhen the user says "proceed", call plan_step_control start. No project mutations before approval.`,
52
+ `Step ${n}/${total} is ready and awaiting approval: ${text}\nWhen the user says "proceed", call plan_step_control start; when the user explicitly asks for continuous execution (e.g. "do the rest", "continue all"), pass advance: "all" to authorize auto-run. No project mutations before approval.`,
53
+ stepAuto: (n, total, text) =>
54
+ `Auto-run authorized: implement only step ${n}/${total} — ${text}\nWhen this step and its applicable checks finish, call plan_step_complete, then immediately start the next step without waiting for approval; if blocked by something only the user can resolve, record it with plan_set_outcome and stop.`,
50
55
  stepPaused: `Step execution is paused: progress is retained but there is no implementation authority. Resume only on the user's explicit instruction.`,
51
56
  awaitingValidation: `The plan is awaiting the user's required validation. Implementation is done; do not make further changes. Call plan_complete only after the user reports success or explicitly asks to mark it complete.`,
52
57
  };
@@ -114,6 +114,7 @@ function decodeExecution(v: unknown): Execution | null | undefined {
114
114
  if (v === null) return null;
115
115
  if (!isRecord(v) || !Array.isArray(v.steps) || typeof v.paused !== "boolean")
116
116
  return undefined;
117
+ if (v.auto !== undefined && typeof v.auto !== "boolean") return undefined;
117
118
  const steps: Step[] = [];
118
119
  for (const raw of v.steps) {
119
120
  if (!isRecord(raw)) return undefined;
@@ -129,7 +130,7 @@ function decodeExecution(v: unknown): Execution | null | undefined {
129
130
  });
130
131
  }
131
132
  if (steps.length === 0) return undefined;
132
- return { steps, paused: v.paused };
133
+ return { steps, paused: v.paused, auto: v.auto === true };
133
134
  }
134
135
 
135
136
  /** 恢复:扫描分支条目取最新有效状态。 */
package/src/core/state.ts CHANGED
@@ -46,6 +46,8 @@ export interface Step {
46
46
  export interface Execution {
47
47
  steps: Step[];
48
48
  paused: boolean;
49
+ /** 连跑授权:plan_step_control start advance="all" 时置位,complete 后自动推进下一步。 */
50
+ auto: boolean;
49
51
  }
50
52
 
51
53
  export interface State {
@@ -74,7 +76,7 @@ export type Transition =
74
76
  | { t: "plan.finish"; outcome: PlanOutcome }
75
77
  | { t: "plan.abandon"; reason: string }
76
78
  | { t: "exec.start"; steps: string[] }
77
- | { t: "exec.step.start" }
79
+ | { t: "exec.step.start"; advance?: "one" | "all" }
78
80
  | { t: "exec.step.complete"; summary?: string }
79
81
  | { t: "exec.step.ack"; summary?: string }
80
82
  | { t: "exec.step.skip" }
@@ -134,10 +136,12 @@ function finishStep(
134
136
  cur.summary = summary;
135
137
  const next = nextPending(ex.steps);
136
138
  if (next) {
137
- next.status = "ready";
139
+ next.status = ex.auto ? "active" : "ready";
138
140
  return {
139
141
  state: s,
140
- note: `第 ${cur.n} 步完成;第 ${next.n} 步就绪(等待批准)`,
142
+ note: ex.auto
143
+ ? `第 ${cur.n} 步完成;第 ${next.n} 步自动继续(已授权连跑)`
144
+ : `第 ${cur.n} 步完成;第 ${next.n} 步就绪(等待批准)`,
141
145
  };
142
146
  }
143
147
  const done = ex.steps
@@ -159,13 +163,9 @@ export function transition(prev: State, ev: Transition): TransitionResult {
159
163
  "分步执行进行中:先 plan_step_control cancel(或完成/标记完成)再切回 plan 模式。",
160
164
  );
161
165
  s.mode = ev.mode;
162
- return {
163
- state: s,
164
- note:
165
- ev.mode === "plan"
166
- ? "已切换到 plan 模式(只读规划)"
167
- : "已切换到 build 模式",
168
- };
166
+ // 不发 note:模式反馈由状态栏徽标实时承载;notify 在 IDE/ACP 桥接下
167
+ // 会渲染成对话消息,用户主动切换(/plan /build Alt+M)不该刷屏
168
+ return { state: s };
169
169
  }
170
170
 
171
171
  case "plan.create": {
@@ -255,7 +255,7 @@ export function transition(prev: State, ev: Transition): TransitionResult {
255
255
  status: i === 0 ? "ready" : "pending",
256
256
  }));
257
257
  if (steps.length === 0) throw new TransitionError("未解析出任何步骤。");
258
- s.execution = { steps, paused: false };
258
+ s.execution = { steps, paused: false, auto: false };
259
259
  p.outcome = undefined; // 重新进入实现:旧的未完成结局(blocked 等)失效
260
260
  return { state: s, note: `分步执行开始:共 ${steps.length} 步` };
261
261
  }
@@ -270,7 +270,13 @@ export function transition(prev: State, ev: Transition): TransitionResult {
270
270
  if (!cur) throw new TransitionError("没有就绪的步骤。");
271
271
  if (cur.status === "active") return { state: prev };
272
272
  cur.status = "active";
273
- return { state: s, note: `第 ${cur.n}/${ex.steps.length} 步开始` };
273
+ if (ev.advance === "all") ex.auto = true;
274
+ return {
275
+ state: s,
276
+ note: `第 ${cur.n}/${ex.steps.length} 步开始${
277
+ ev.advance === "all" ? "(已授权连跑,后续步自动推进)" : ""
278
+ }`,
279
+ };
274
280
  }
275
281
 
276
282
  case "exec.step.complete": {
@@ -373,8 +379,8 @@ export function statusLine(s: State): string {
373
379
  const done = s.execution.steps.filter(
374
380
  (x) => x.status === "completed" || x.status === "skipped",
375
381
  ).length;
376
- const tag = s.execution.paused ? "⏸" : "▶";
377
- return `${mode} ${tag} ${done}/${s.execution.steps.length} ${s.plan.title}`;
382
+ const paused = s.execution.paused ? "(暂停)" : "";
383
+ return `${mode} ${done}/${s.execution.steps.length} ${s.plan.title}${paused}`;
378
384
  }
379
385
  const suffix = s.plan.outcome
380
386
  ? `(${outcomeLabel(s.plan.outcome)})`
@@ -400,19 +406,18 @@ export function outcomeLabel(o: PlanOutcome): string {
400
406
  /** 侧栏 widget 行(原生 setWidget)。 */
401
407
  export function widgetLines(s: State): string[] | undefined {
402
408
  if (!s.plan || !s.execution) return undefined;
409
+ // 等宽中文标签:几何圆圈(○◉◐●)在 CJK 环境是歧义宽度字符、箭头(↷)风格不搭,
410
+ // 统一为 [标签] 前缀,每行前缀定宽对齐
403
411
  const marks: Record<StepStatus, string> = {
404
- pending: "○",
405
- ready: "◉",
406
- active: "◐",
407
- completed: "●",
408
- skipped: "↷",
412
+ pending: "[待办]",
413
+ ready: "[就绪]",
414
+ active: "[进行]",
415
+ completed: "[完成]",
416
+ skipped: "[跳过]",
409
417
  };
410
418
  const head = s.execution.paused ? "分步执行(暂停)" : "分步执行";
411
419
  return [
412
420
  `${head} · ${s.plan.title}`,
413
- ...s.execution.steps.map(
414
- (x) =>
415
- `${marks[x.status]} ${x.n}. ${x.text}${x.status === "skipped" ? "(跳过)" : ""}`,
416
- ),
421
+ ...s.execution.steps.map((x) => `${marks[x.status]} ${x.n}. ${x.text}`),
417
422
  ];
418
423
  }
package/src/engine.ts CHANGED
@@ -11,6 +11,7 @@ import type {
11
11
  ExtensionContext,
12
12
  } from "@earendil-works/pi-coding-agent";
13
13
  import type { Config } from "./config.ts";
14
+ import { archivePlanFile } from "./core/archive.ts";
14
15
  import { type PromptPack, prompts } from "./core/prompts.ts";
15
16
  import { decodeState, STATE_ENTRY_TYPE } from "./core/schema.ts";
16
17
  import {
@@ -35,6 +36,10 @@ export class PlanEngine {
35
36
  corrupt = false;
36
37
  /** 事后对账:不可验证变更工具放行前记录的计划文件基线(首次武装为准)。 */
37
38
  reconciliation: { tool: string; baseline: string } | undefined;
39
+ /** 最近一次收尾的归档结果(每次 apply 重置,仅收尾转移置值;工具结果透出用)。 */
40
+ lastArchive?: { path: string; ok: boolean };
41
+ /** 本回合用户已拒绝"拦截即切 build"的确认门:之后只拦不再问(agent_settled 重置)。 */
42
+ gateDeclined = false;
38
43
 
39
44
  constructor(pi: ExtensionAPI, config: Config) {
40
45
  this.pi = pi;
@@ -109,9 +114,49 @@ export class PlanEngine {
109
114
  this.state = result.state;
110
115
  if (result.state !== prev) this.persist(); // 幂等转移不写重复条目
111
116
  this.refreshUI(c, result.note);
117
+ this.lastArchive = undefined;
118
+ this.archiveOnFinish(ev, prev);
112
119
  return result;
113
120
  }
114
121
 
122
+ /** 终态归档:计划被清空(完成/放弃/分步收尾)时,在计划文件文末追加状态块。 */
123
+ private archiveOnFinish(ev: Transition, prev: State): void {
124
+ const plan = prev.plan;
125
+ if (!plan || this.state.plan) return; // 仅"存在 → 清空"的收尾转移
126
+ if (ev.t === "plan.abandon") {
127
+ this.lastArchive = {
128
+ path: plan.path,
129
+ ok: archivePlanFile(plan.path, "已放弃", `原因:${ev.reason}`),
130
+ };
131
+ return;
132
+ }
133
+ if (ev.t === "plan.complete") {
134
+ this.lastArchive = {
135
+ path: plan.path,
136
+ ok: archivePlanFile(
137
+ plan.path,
138
+ "已完成",
139
+ ev.summary ? `摘要:${ev.summary}` : undefined,
140
+ ),
141
+ };
142
+ return;
143
+ }
144
+ if (ev.t === "exec.step.complete" || ev.t === "exec.step.ack") {
145
+ // finishStep 收尾:被完成的步是转移前的 active 步
146
+ const cur = prev.execution?.steps.find((x) => x.status === "active");
147
+ this.lastArchive = {
148
+ path: plan.path,
149
+ ok: archivePlanFile(
150
+ plan.path,
151
+ "已完成",
152
+ cur
153
+ ? `最后完成:第 ${cur.n} 步${ev.summary ? `:${ev.summary}` : ""}`
154
+ : undefined,
155
+ ),
156
+ };
157
+ }
158
+ }
159
+
115
160
  tryApply(
116
161
  ev: Transition,
117
162
  ctx?: ExtensionContext,
package/src/lifecycle.ts CHANGED
@@ -51,7 +51,7 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
51
51
  pi.on("session_info_changed", (_event, ctx) => engine.attachContext(ctx));
52
52
 
53
53
  // --- 权限守卫(tool_call 可拦截)---
54
- pi.on("tool_call", (event, ctx) => {
54
+ pi.on("tool_call", async (event, ctx) => {
55
55
  const s = engine.state;
56
56
  const kind = classifyToolCall(
57
57
  event.toolName,
@@ -94,8 +94,31 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
94
94
  s.plan?.saved ?? false,
95
95
  targets,
96
96
  );
97
- if (decision.action === "block")
97
+ if (decision.action === "block") {
98
+ // plan 模式只读拦截 → 轻量确认门:用户确认即切 build 并放行本次修改(死墙变门)
99
+ if (
100
+ s.mode === "plan" &&
101
+ !engine.corrupt &&
102
+ !engine.gateDeclined &&
103
+ ctx.hasUI
104
+ ) {
105
+ const okSwitch = await ctx.ui.confirm(
106
+ "plan 模式只读拦截",
107
+ `${decision.reason}\n是否切换到 build 模式并放行本次修改?`,
108
+ );
109
+ if (okSwitch) {
110
+ const sw = engine.tryApply({ t: "mode.set", mode: "build" }, ctx);
111
+ if (!("error" in sw)) return undefined; // 已切 build:放行本次调用
112
+ return { block: true, reason: sw.error };
113
+ }
114
+ engine.gateDeclined = true; // 本回合只拦不再问,防重复弹窗
115
+ return {
116
+ block: true,
117
+ reason: `用户拒绝切换,保持 plan 模式只读。${decision.reason} 不要再次尝试写项目文件;继续讨论或建议用户手动 /build。`,
118
+ };
119
+ }
98
120
  return { block: true, reason: decision.reason };
121
+ }
99
122
  // 事后对账:build 放行波及面无法验证的变更工具前记录计划文件基线
100
123
  if (
101
124
  s.mode === "build" &&
@@ -115,6 +138,7 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
115
138
 
116
139
  // --- 验证问询:awaiting_validation 结算后问一次 ---
117
140
  pi.on("agent_settled", async (_event, ctx) => {
141
+ engine.gateDeclined = false; // 新回合重置确认门的拒绝记忆
118
142
  // 事后对账先行:不可验证工具改动了计划文件要立即提示
119
143
  const reconciled = engine.settleReconciliation();
120
144
  if (reconciled) ctx.ui.notify(reconciled, "warning");
@@ -10,9 +10,9 @@ import type { PlanEngine } from "../engine.ts";
10
10
 
11
11
  const Params = Type.Object({});
12
12
 
13
- const HERE = "本会话实现";
14
- const STEPWISE = "分步实现";
15
- const STAY = "留在 plan 模式";
13
+ const HERE = "本会话连续实现,完成后验证";
14
+ const STEPWISE = "分步实现,每步等待批准";
15
+ const STAY = "留在 plan 模式,暂不实现";
16
16
 
17
17
  export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
18
18
  pi.registerTool({
@@ -48,7 +48,7 @@ export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
48
48
 
49
49
  let choice: string | undefined;
50
50
  if (ctx.hasUI) {
51
- choice = await ctx.ui.select(`计划已就绪:${plan.title}`, [
51
+ choice = await ctx.ui.select(`请选择计划的实现方式:${plan.title}`, [
52
52
  HERE,
53
53
  STEPWISE,
54
54
  STAY,
@@ -75,7 +75,7 @@ export function registerPlanExit(pi: ExtensionAPI, engine: PlanEngine): void {
75
75
  );
76
76
  }
77
77
 
78
- // 本会话实现
78
+ // 本会话连续实现
79
79
  engine.apply({ t: "mode.set", mode: "build" }, ctx);
80
80
  return ok(
81
81
  `${review}\n\n---\n用户批准在本会话实现,已切换到 build 模式。请在批准的范围内实现全部工作,按计划 ## 验证 小节执行必需检查,完成后调用 plan_complete(或 plan_set_outcome 记录未竟事项)。`,
@@ -51,8 +51,11 @@ export function registerPlanOutcome(
51
51
  { t: "plan.complete", summary: params.summary },
52
52
  ctx,
53
53
  );
54
+ const arch = engine.lastArchive?.ok
55
+ ? `\n状态块已写入计划文件:${engine.lastArchive.path}`
56
+ : "";
54
57
  return ok(
55
- `计划已标记完成。${r.note ?? ""}${params.summary ? `\n摘要:${params.summary}` : ""}`,
58
+ `计划已标记完成。${r.note ?? ""}${params.summary ? `\n摘要:${params.summary}` : ""}${arch}`,
56
59
  );
57
60
  },
58
61
  });
@@ -23,6 +23,13 @@ const ControlParams = Type.Object({
23
23
  summary: Type.Optional(
24
24
  Type.String({ description: "acknowledge 的完成摘要" }),
25
25
  ),
26
+ /** start 专用:默认只开始当前步;用户明确要求连续执行时传 "all" 一次授权连跑。 */
27
+ advance: Type.Optional(
28
+ Type.Union([Type.Literal("one"), Type.Literal("all")], {
29
+ description:
30
+ 'start 专用:默认只开始当前步;用户明确要求连续执行(如"剩下的都做完""全部继续")时传 "all",一次授权连跑剩余步骤,遇到 plan_set_outcome 记录的阻塞才停。',
31
+ }),
32
+ ),
26
33
  step: Type.Optional(
27
34
  Type.Integer({
28
35
  minimum: 1,
@@ -40,16 +47,28 @@ export function registerPlanStepTools(
40
47
  pi: ExtensionAPI,
41
48
  engine: PlanEngine,
42
49
  ): void {
50
+ /** 终态归档透出:仅当本次转移收尾了计划(lastArchive 每次 apply 重置)。 */
51
+ const archiveSuffix = () =>
52
+ engine.lastArchive?.ok
53
+ ? `\n状态块已写入计划文件:${engine.lastArchive.path}`
54
+ : "";
55
+
43
56
  pi.registerTool({
44
57
  name: "plan_step_control",
45
58
  label: "plan step control",
46
59
  description:
47
- "分步执行控制:start 批准并开始就绪步;acknowledge 指认用户声明的已完成步(当前步无需先 start;记录既有事实,不授权新工作,AI 自己完成当前步用 plan_step_complete);skip 跳过;revise 修订未完成步文本;pause/resume 暂停恢复;cancel 取消分步执行(计划保留)。一次一个转移。",
60
+ '分步执行控制:start 批准并开始就绪步(用户明确要求连续执行时可传 advance: "all" 一次授权连跑剩余步骤);acknowledge 指认用户声明的已完成步(当前步无需先 start;记录既有事实,不授权新工作,AI 自己完成当前步用 plan_step_complete);skip 跳过;revise 修订未完成步文本;pause/resume 暂停恢复;cancel 取消分步执行(计划保留)。一次一个转移。',
48
61
  parameters: ControlParams,
49
62
  async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
50
63
  switch (params.action) {
51
64
  case "start": {
52
- const r = engine.tryApply({ t: "exec.step.start" }, ctx);
65
+ const r = engine.tryApply(
66
+ {
67
+ t: "exec.step.start",
68
+ advance: params.advance === "all" ? "all" : undefined,
69
+ },
70
+ ctx,
71
+ );
53
72
  if ("error" in r) return err(r.error);
54
73
  const st = r.state.execution?.steps.find(
55
74
  (x) => x.status === "active",
@@ -57,7 +76,9 @@ export function registerPlanStepTools(
57
76
  if (!st) return err("没有进行中的步骤。");
58
77
  const total = r.state.execution?.steps.length ?? 0;
59
78
  return ok(
60
- `第 ${st.n}/${total} 步已开始:${st.text}\n只实现本步,完成后调用 plan_step_complete。`,
79
+ r.state.execution?.auto
80
+ ? `第 ${st.n}/${total} 步已开始(连跑授权):${st.text}\n完成后调用 plan_step_complete,下一步将自动开始,无需等用户批准;遇阻用 plan_set_outcome 记录并停。`
81
+ : `第 ${st.n}/${total} 步已开始:${st.text}\n只实现本步,完成后调用 plan_step_complete。`,
61
82
  );
62
83
  }
63
84
  case "acknowledge": {
@@ -66,7 +87,7 @@ export function registerPlanStepTools(
66
87
  ctx,
67
88
  );
68
89
  if ("error" in r) return err(r.error);
69
- return ok(r.note ?? "步骤已记录完成。");
90
+ return ok((r.note ?? "步骤已记录完成。") + archiveSuffix());
70
91
  }
71
92
  case "skip": {
72
93
  const r = engine.tryApply({ t: "exec.step.skip" }, ctx);
@@ -130,7 +151,9 @@ export function registerPlanStepTools(
130
151
  );
131
152
  if ("error" in r) return err(r.error);
132
153
  if (!r.state.plan) {
133
- return ok(`全部步骤完成,计划已收尾。\n${r.note ?? ""}`);
154
+ return ok(
155
+ `${r.note ?? "全部步骤完成,计划已收尾。"}${archiveSuffix()}`,
156
+ );
134
157
  }
135
158
  const next = r.state.execution?.steps.find((x) => x.status === "ready");
136
159
  if (!next) return ok(`${r.note ?? "步骤完成。"}`);
@@ -1,12 +1,14 @@
1
1
  /** plan_task:任务生命周期元数据(new/title/include/exclude/abandon/list/show)。 */
2
2
 
3
3
  import fs from "node:fs";
4
+ import path from "node:path";
4
5
  import { StringEnum } from "@earendil-works/pi-ai";
5
6
  import type {
6
7
  ExtensionAPI,
7
8
  ExtensionToolContext,
8
9
  } from "@earendil-works/pi-coding-agent";
9
10
  import { Type } from "typebox";
11
+ import { listPlanFiles } from "../core/archive.ts";
10
12
  import { statusLine } from "../core/state.ts";
11
13
  import type { PlanEngine } from "../engine.ts";
12
14
  import { nextPlanPath } from "../engine.ts";
@@ -35,24 +37,52 @@ const Params = Type.Object({
35
37
  description: "当前计划 seq;new 传 null",
36
38
  }),
37
39
  ),
40
+ /** new 专用:恢复既有计划文件,以其内容为计划正文继续。 */
41
+ fromFile: Type.Optional(
42
+ Type.String({
43
+ description:
44
+ "new 专用:恢复既有计划文件(绝对或 cwd 相对路径),以其内容为计划正文继续(换会话后接着干);传了则 title 可省(默认取文件一级标题),scope 不需要。",
45
+ }),
46
+ ),
47
+ /** 仅当用户明确要求规划时传 true,跳过「创建计划 / 直接执行」入口询问。 */
48
+ planningRequested: Type.Optional(
49
+ Type.Boolean({
50
+ description:
51
+ '仅当用户明确要求规划(如"帮我规划""出个方案")时传 true,跳过入口询问;未传时工具会先弹窗让用户选择创建计划还是直接执行。',
52
+ }),
53
+ ),
38
54
  });
39
55
 
56
+ const PLAN_FIRST = "创建计划,审阅后再实现";
57
+ const DIRECT_EXECUTE = "直接执行";
58
+
40
59
  export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
41
60
  pi.registerTool({
42
61
  name: "plan_task",
43
62
  label: "plan task",
44
63
  description:
45
- "计划任务生命周期:new 建计划(plan 模式);update 改名;include 追加用户批准的范围;exclude 记录排除话题;abandon 显式放弃(须用户指示);list/show 查看状态。转移必须先于依赖它的写入/命令单独完成。",
64
+ "计划任务生命周期:new 建计划(plan 模式;build 模式调用会弹窗确认切换);用户未明确要求规划时 new 会先弹窗让用户选「创建计划 / 直接执行」,选直接执行则自动切 build 并放弃建计划;new 支持 fromFile 恢复既有计划文件;update 改名;include 追加用户批准的范围;exclude 记录排除话题;abandon 显式放弃(须用户指示);list 查看状态并附 plans 目录历史计划(含归档结局);show 查看详情。转移必须先于依赖它的写入/命令单独完成。",
46
65
  parameters: Params,
47
66
  async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
48
67
  const s = engine.state;
49
68
 
50
69
  if (params.action === "list") {
51
- return text(
70
+ const lines = [
52
71
  s.plan
53
72
  ? `当前计划:${statusLine(s)}\nseq=${s.plan.seq}`
54
73
  : "当前没有计划。",
74
+ ];
75
+ const hist = listPlanFiles(ctx.cwd).filter(
76
+ (h) => h.path !== s.plan?.path,
55
77
  );
78
+ if (hist.length > 0) {
79
+ lines.push("", "历史计划(.pi/agent/plans/,按修改时间倒序):");
80
+ for (const h of hist) {
81
+ const tag = h.status ? `${h.status}(${h.date})` : "未收尾";
82
+ lines.push(` ${tag} · ${h.title} — ${h.path}`);
83
+ }
84
+ }
85
+ return text(lines.join("\n"));
56
86
  }
57
87
  if (params.action === "show") {
58
88
  if (!s.plan) return text("当前没有计划。");
@@ -75,9 +105,93 @@ export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
75
105
  if (expected !== null) {
76
106
  return err("plan_task new 需要 expectedAttached: null。");
77
107
  }
108
+ // build 模式建计划 → 确认门:确认即自动切 plan(对称于 plan_exit 出口审批)
109
+ if (s.mode === "build" && !s.plan && ctx.hasUI) {
110
+ const label = params.fromFile
111
+ ? "恢复既有计划文件"
112
+ : `创建「${params.title ?? "(未命名)"}」`;
113
+ const okSwitch = await ctx.ui.confirm(
114
+ "创建计划需要 plan 模式",
115
+ `切换到 plan 模式(只读规划)并${label}?`,
116
+ );
117
+ if (!okSwitch) {
118
+ return err(
119
+ "用户拒绝切换:计划未创建。任务可直接完成就直接实现;需要规划时请用户 /plan 切换。",
120
+ );
121
+ }
122
+ const sw = engine.tryApply({ t: "mode.set", mode: "plan" }, ctx);
123
+ if ("error" in sw) return err(sw.error);
124
+ }
125
+ // fromFile 恢复:既有计划文件继续(换会话后接着干)
126
+ if (params.fromFile) {
127
+ const src = path.isAbsolute(params.fromFile)
128
+ ? params.fromFile
129
+ : path.join(ctx.cwd, params.fromFile);
130
+ let content: string;
131
+ try {
132
+ content = fs.readFileSync(src, "utf8");
133
+ } catch {
134
+ return err(`计划文件读取失败:${src}`);
135
+ }
136
+ if (!content.trim()) return err(`计划文件为空:${src}`);
137
+ const title =
138
+ params.title?.trim() ||
139
+ /^#\s+(.+)$/m.exec(content)?.[1]?.trim() ||
140
+ "恢复的计划";
141
+ const p = nextPlanPath(ctx.cwd, title);
142
+ fs.writeFileSync(p, content);
143
+ const r = engine.tryApply(
144
+ {
145
+ t: "plan.create",
146
+ title,
147
+ scope: content,
148
+ path: p,
149
+ },
150
+ ctx,
151
+ );
152
+ if ("error" in r) {
153
+ // 占位文件已分配但计划未建:回收空占位,不留孤儿文件
154
+ try {
155
+ if (fs.statSync(p).size === 0) fs.unlinkSync(p);
156
+ } catch {
157
+ // 回收失败不掩盖主错误
158
+ }
159
+ return err(r.error);
160
+ }
161
+ engine.apply({ t: "plan.saved" }, ctx);
162
+ return text(
163
+ `计划已从 ${src} 恢复(seq=1)。canonical 路径:${p}\n内容已就绪:可直接调用 plan_exit 提请审批;如需修订先改该文件(plan 模式允许写计划文件)再 plan_exit。`,
164
+ );
165
+ }
78
166
  if (!params.title)
79
167
  return err("new 需要 title(动作+对象式单一标题)。");
80
168
  if (!params.scope) return err("new 需要 scope(详细范围)。");
169
+ // 入口询问(镜像 plan_exit 出口审批):plan 模式且无计划时,用户未
170
+ // 明确要求规划就先让用户决定「创建计划 / 直接执行」,直接执行则切 build 不建计划
171
+ if (
172
+ s.mode === "plan" &&
173
+ !s.plan &&
174
+ params.planningRequested !== true &&
175
+ ctx.hasUI
176
+ ) {
177
+ const choice = await ctx.ui.select(
178
+ `请选择新任务的处理方式:${params.title}`,
179
+ [PLAN_FIRST, DIRECT_EXECUTE],
180
+ );
181
+ if (choice === DIRECT_EXECUTE) {
182
+ const sw = engine.tryApply({ t: "mode.set", mode: "build" }, ctx);
183
+ if ("error" in sw) return err(sw.error);
184
+ return text(
185
+ "用户选择直接执行:已切换到 build 模式,计划未创建。请直接实现该任务(普通 build 模式工作流);不要再次调用 plan_task new。",
186
+ );
187
+ }
188
+ if (choice === undefined) {
189
+ return text(
190
+ "用户取消了选择:计划未创建、模式未变。请等待用户进一步指示,不要自行开始规划或实现。",
191
+ );
192
+ }
193
+ // 选了「创建计划」:继续创建计划
194
+ }
81
195
  const p = nextPlanPath(ctx.cwd, params.title);
82
196
  const r = engine.tryApply(
83
197
  {
@@ -156,7 +270,9 @@ export function registerPlanTask(pi: ExtensionAPI, engine: PlanEngine): void {
156
270
  );
157
271
  return "error" in r
158
272
  ? err(r.error)
159
- : text(`计划已放弃。文件保留:${s.plan.path}`);
273
+ : text(
274
+ `计划已放弃。文件保留:${s.plan.path}${engine.lastArchive?.ok ? "(文末已写入状态块)" : ""}`,
275
+ );
160
276
  }
161
277
  default:
162
278
  return err("未知 action。");