@wbline/pi-plan-build 0.0.4 → 0.0.6

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,47 @@
4
4
 
5
5
  格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本遵循语义化版本。
6
6
 
7
+ ## [0.0.6] - 2026-10-20
8
+
9
+ ### 新增
10
+
11
+ - **`plan_task revise`:build 中途修订计划的专用通道**:此前 build 模式下计划文件受保护、agent 又无法自行切回 plan(`new` 在已有计划时报错),修订单行计划要经历"被拦 → 求用户手动 /plan → 改文件 → 手动切回"的循环。现在 `plan_task revise` 弹确认门切回 plan(对称于 `new` 的 build 确认门;无 UI 时一致跳过),改完 `plan_exit` 重新提请审批;分步执行进行中仍须先 `plan_step_control cancel`;守卫阻断文案与 include 成功提示同步指向该通道
12
+ - **验证问询改到下一条消息**:`awaiting_validation` 结算后不再在回合刚结束(用户还没验证)就弹"验证通过?"——改为监听 `input` 事件,在用户下一次空闲发消息时确认一次;未通过不自动重问,重新结算(`plan_set_outcome` / `plan_complete`)时重置。流式插话(steer/followUp)、斜杠命令、extension 触发不询问
13
+
14
+ ### 变更
15
+
16
+ - **守卫范围显式化**:只守卫 pi 内置工具与 JetBrains IDE 桥接工具(ide_ 前缀)——内置 8 个全量显式分类(bash/powershell 归入执行面、read/find/grep/ls 归入只读,不再落入管辖外兜底),事后对账武装条件统一为 execution 类别;管辖外仅剩第三方/未知扩展与 MCP 工具。codemode 的嵌套工具调用经 pi 同一 `tool_call` 管线(已核对 1.3.0 源码 `ctx.executeTool` → `_executeNestedToolCall`),守卫无旁路
17
+ - **只读动词白名单收紧**:`generate` 从动词表移除(未来 `generate_code` 类写方法被误放行的风险太高),已确证的纯生成方法(`_generate_psi_tree` / `_generate_inspection_kts_api` / `_generate_inspection_kts_examples`)改按方法后缀精确放行,未知 `generate_*` 保守按变更通道;新增**写动词优先**——名字含 `write / apply / create / edit / delete / rename / move / save / format` 任一段时,即使同时命中只读动词也按变更通道(堵 `apply_diff`、`move_files` 类组合名)
18
+ - **IDE 执行面工具与 shell 同层待遇**:终端命令、运行配置、构建、SQL 执行、inspection KTS、取消查询等进程执行类方法(目标不可提取、能力与 shell 等价)不再按文件变更通道硬拦——plan 模式提示词约束(`planReadonly` 同步点名执行类命令仅限只读调研,安装依赖/UPDATE 等写操作留到 build),build 模式放行并纳入事后对账;桥接注解与 `toolGuard.mutating` 仍可强制拦回。此前 plan 模式硬拦 IDE 执行通道却放行 bash,拦不住想绕的、只摩擦守规矩的模型
19
+ - **无 UI(print/json)行为一致化**:`plan_task new` 入口询问与 `plan_exit` 审批门在无交互 UI 时一致跳过——`plan_exit` 此前一律视为"留在 plan",agent 永远拿不到实现授权(脚本场景死锁),现在自动选「本会话连续实现」并在结果中显式标注;审批对话框被取消(Esc)与主动选择「留在 plan」区分开,取消时模型会向用户询问意图
20
+ - **工具描述压缩并支持双语**:7 个工具的描述与参数描述集中到 `tools/descriptions.ts`,按 `lang` 设置在注册时选用 zh/en(此前只有中文);工作流规则交给 context 注入,描述只保留动作语义与硬约束。语言切换后需 /reload 生效(注册时固化)
21
+ - **fromFile 恢复不再产生无主副本**:`plan_task new fromFile` 恢复 plans 目录内的文件时原地接管(不再复制出新文件);恢复外部文件时复制到 canonical 路径并在原文件文末追加「已接管」状态块(`list` 可见),避免两份同内容文件分不清哪份有效
22
+ - **scope 注入截断**:context 注入的计划范围超过 2000 字符时截断并提示"完整内容以计划文件为准",长计划(尤其 fromFile 全文恢复)不再无限膨胀上下文;同一内容截断结果稳定,不影响前缀缓存命中
23
+ - **expectedAttached 不匹配的报错可自愈**:从"请重读 show 后重试"改为同时给出当前 seq——无副作用动作可直接改用新 seq 重试,include 等范围类动作仍建议先 show 核对,减少一轮往返
24
+
25
+ ### 修复
26
+
27
+ - **写入目标与计划路径统一做 symlink 解析**:此前只有计划路径过 `realpathLike`,写入目标不做——项目路径含 junction/symlink 成分(Windows 目录联接、macOS `/tmp`、WSL)时,经链接路径写计划文件会被判为「目标 ≠ 计划文件」误拦(plan 流程死锁)。`realpathLike` 同时升级为逐级向上解析(兑现"最远存在父目录"的注释承诺,嵌套新目录不再漏解析)
28
+ - **apply_patch 补齐 unified diff 的源路径提取**:git rename diff 的旧路径只出现在 `--- a/<path>`(改名+改内容)或 `rename from <path>`(纯改名,无 `---`/`+++` 行),此前只扫 `+++`——build 模式下用 unified diff rename 可将受保护的计划文件改名带走(保护绕过)。现在 `---`/`+++` 成对解析(正文 `-`/`+` 开头的行不成对不误提)、`rename from/to` 补齐、`/dev/null` 占位头过滤
29
+
30
+ - **IDE 桥接工具目标提取不再写死 webstorm 产品名**:`extractMutationTargets` 改按方法后缀匹配(`_create_new_file` / `_reformat_file` / `_apply_patch` / `_rename_refactoring`),产品段任意(webstorm / intellij / pycharm / goland / rider / …)。此前 IDEA、PyCharm 等产品的同类工具全部落入「波及面无法验证」:build 模式靠事后对账兜底尚可,plan 模式则连写计划文件本身都被拦——IntelliJ-first 桥接下原生写通道被禁用,plan 流程会死锁在 `plan_exit` 的写盘校验。`_rename_refactoring` 显式排除在 `pathInProject` 参数形状兜底之外(语义重命名波及全部引用处,任何产品下都不可验证);未知方法名只要按约定带 `pathInProject` 即可精确提取,认不出的仍返回 undefined(宁可误拦不可放行)。分类层面本就只认 `ide_` 前缀,不受影响
31
+
32
+ ## [0.0.5] - 2026-10-17
33
+
34
+ ### 新增
35
+
36
+ - 对称确认门:build 模式调用 `plan_task new` 先弹窗确认切到 plan 模式(拒绝则保持 build 并提示可直接实现);plan 模式守卫拦截文件修改时也弹确认门——用户确认即切 build 放行本次修改,拒绝则本回合只拦不再问(agent_settled 重置),守卫文案同步补上入口闸路径
37
+ - 连跑授权:`plan_step_control start` 支持 `advance: "all"`——一次批准连跑剩余步骤,`plan_step_complete` 后自动推进下一步(注入切换为连跑提示词),遇 `plan_set_outcome` 记录的阻塞才停;默认仍为每步等批准
38
+ - 历史计划可见可续:`plan_task list` 扫描 plans 目录列出历史计划(标题 + 终态归档结局 + 日期,未收尾标注);`plan_task new` 支持 `fromFile` 恢复既有计划文件(复制内容到 canonical 路径并标记已写盘),换会话后可接着干
39
+ - 入口询问(与 `plan_exit` 出口审批对称):plan 模式且无当前计划时,`plan_task new` 在用户未明确要求规划(未传 `planningRequested: true`)时先弹窗让用户选「创建计划 / 直接执行」——选直接执行自动切 build 并放弃建计划,取消则不建计划等待指示;无 UI(print/json)环境跳过询问维持原行为。`taskSelection` 提示词、工具描述、README 同步,冒烟补 3 个用例;计划标题约束"标题内不用冒号"(避免与弹窗标题分隔符撞车)
40
+ - 终态归档:计划收尾(`plan_complete` / 分步最后一步完成 / `awaiting_validation` 验证通过确认)或放弃(`plan_task abandon` / 菜单)时,在计划文件文末追加状态块——`> **状态:已完成/已放弃**(本地日期)` + 摘要或原因,plans 目录的历史文件单看即可知结局。append-only 不改已审阅内容;集中在 `engine.apply` 一处覆盖全部收尾调用点,文件为空或写失败静默跳过(状态为准);归档结果透出到工具结果(`lastArchive` 每次 apply 重置),模型可如实汇报。冒烟补 2 个用例
41
+
42
+ ### 变更
43
+
44
+ - 步骤进度符号统一为等宽中文标签:侧栏 widget 的 `○◉◐●↷`(几何圆圈 + 箭头混排,CJK 环境下宽度歧义)改为 `[待办]/[就绪]/[进行]/[完成]/[跳过]`;状态栏的 `▶`/`⏸`(易被 emoji 化渲染)改为分数 + `(暂停)` 后缀
45
+ - 模式切换不再发对话通知:`mode.set` 转移不再携带 `note`(notify 在 IDE/ACP 桥接下渲染成对话消息,每次 /plan、/build、Alt+M 都刷屏);模式反馈由状态栏徽标实时承载,plan_exit 审批与入口闸"直接执行"的对话框本身就是反馈
46
+ - 审批对话框措辞统一为「动作,后果」风格、去掉括号:入口「创建计划,审阅后再实现 / 直接执行」,出口「本会话连续实现,完成后验证 / 分步实现,每步等待批准 / 留在 plan 模式,暂不实现」;出口标题改为「请选择计划的实现方式:〈标题〉」,与入口「请选择新任务的处理方式:〈标题〉」句式对称
47
+
7
48
  ## [0.0.4] - 2026-10-16
8
49
 
9
50
  ### 文档
package/README.md CHANGED
@@ -19,10 +19,10 @@ pi install npm:@wbline/pi-plan-build
19
19
  零配置,装上即用。计划文件自动落在当前项目 `.pi/agent/plans/`(`<创建时刻>-<标题>.md`,随项目走)。30 秒体验完整闭环:
20
20
 
21
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`,回合结束后主动弹窗问你
22
+ 2. 让 agent 规划:`plan_task new` 建计划(你未明确要求规划时,会先弹窗确认:创建计划还是直接执行)→ 写完整计划文件(含验证小节与实现步骤)→ `plan_exit` 提请审批
23
+ 3. 你三选一:**本会话连续实现 / 分步实现 / 留在 plan**——选择之前 agent 劫不了代码
24
+ 4. build 模式实现:计划文件受保护;分步模式默认每步等点头,说「剩下的都做完」可授权连跑
25
+ 5. 验证闭环:能自动验证的当场跑;只能你验证的(登录、硬件、线上效果)记为 `awaiting_validation`,你下一条消息时主动弹窗确认,通过才收尾
26
26
 
27
27
  ## 它解决什么问题
28
28
 
@@ -36,12 +36,13 @@ pi install npm:@wbline/pi-plan-build
36
36
  ## 核心机制
37
37
 
38
38
  - 🔒 **双模式权限守卫**:`tool_call` 前拦截,路径归一化(`@`/`~`/相对路径)+ symlink 解析。plan 模式只许写计划文件,无路径或波及面无法验证(未知工具、语义重命名)一律阻断——宁可误拦不可放行
39
- - 🏷️ **动态工具分类**:不写死工具名单,按配置覆盖 > 注解(`readOnlyHint`)> 名字动词约定分类;新增 IDE 变更工具不再漏拦
39
+ - 🏷️ **动态工具分类**:不写死工具名单,按配置覆盖 > 注解(`readOnlyHint`)> 方法后缀 > 动词约定(写动词优先)分类;新增 IDE 变更工具不再漏拦
40
40
  - ⏱️ **时序硬闸**:`plan_task` 生命周期转移未收尾时,依赖它的文件变更与生命周期工具一律先等——把"转移先于依赖动作"从提示词约束升级为硬拦截
41
+ - 🚪 **全链路显式决策**:`plan_task new` 先问「创建计划还是直接执行」(明确要求规划可传参跳过),`plan_exit` 后问「本会话/分步/留下」;build 模式建计划、build 中途修订计划(`plan_task revise`)、plan 模式被守卫拦截时各有一道确认门——每次模式转换都由用户一键拍板
41
42
  - 📒 **事后对账**:放行波及面无法验证的工具(IDE 终端命令、shell)前记录计划文件基线,回合结束时文件被改动即警告核对
42
- - 🪜 **分步执行**:计划里的实现步骤逐个就绪,你说"继续"才开工;侧栏实时显示 `○◉◐●↷` 进度
43
- - ✅ **验证闭环**:`awaiting_validation` 结算后自动确认"必需验证是否通过?",通过才收尾,否则计划保持开放
44
- - 🌐 **中英双语提示词**:菜单一键切换;7 个工具全模式常驻(稳定工具目录),模式切换不抖动工具列表,prompt cache 持续命中
43
+ - 🪜 **分步执行**:计划里的实现步骤逐个就绪,你说"继续"才开工,说「剩下的都做完」即授权连跑自动推进;侧栏实时显示 `[待办]/[就绪]/[进行]/[完成]/[跳过]` 进度
44
+ - ✅ **验证闭环**:`awaiting_validation` 结算后,在你下一条消息时确认一次「必需验证通过了吗?」,通过才收尾,否则计划保持开放——不会在你还没开始验证时就弹窗
45
+ - 🌐 **中英双语提示词与工具描述**:菜单一键切换;7 个工具全模式常驻(稳定工具目录),模式切换不抖动工具列表,prompt cache 持续命中
45
46
 
46
47
  ## 命令
47
48
 
@@ -57,11 +58,11 @@ pi install npm:@wbline/pi-plan-build
57
58
 
58
59
  | 工具 | 说明 |
59
60
  |---|---|
60
- | `plan_task` | 任务生命周期:`new` 建计划(plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached` 做乐观并发(`new` 传 null,其余传当前 seq),不匹配即拒 |
61
- | `plan_exit` | **plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话实现 / 分步实现 / 留在 plan |
62
- | `plan_step_control` | 分步执行:`start` 批准就绪步、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
61
+ | `plan_task` | 任务生命周期:`new` 建计划(plan 模式)、`revise` 请求切回 plan 修订当前计划(弹窗确认,build 中途修计划的专用通道)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached` 做乐观并发(`new` 传 null,其余传当前 seq),不匹配即拒。`new` 内置入口询问:用户未明确要求规划(传 `planningRequested: true` 可跳过)时,先弹窗让用户选「创建计划 / 直接执行」,选直接执行即自动切 build、不建计划;build 模式调用 `new` 会先弹窗确认切到 plan。`new` 支持 `fromFile` 恢复既有计划文件(plans 目录内原地接管,外部文件复制并在原文件标记「已接管」;换会话后接着干);`list` 附带 plans 目录历史计划与归档结局 |
62
+ | `plan_exit` | **plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话连续实现 / 分步实现 / 留在 plan 模式。取消对话框 ≠ 主动留下(模型会向你询问意图);无交互 UI(print/json)时跳过审批门自动选本会话连续实现 |
63
+ | `plan_step_control` | 分步执行:`start` 批准就绪步(`advance: "all"` 一次授权连跑剩余步骤,遇阻塞才停)、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
63
64
  | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
64
- | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时 |
65
+ | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时。收尾时在计划文件文末写入状态块(`> **状态:已完成**(日期)` + 摘要),放弃同理(含原因),历史计划单看文件即可知结局 |
65
66
  | `plan_set_outcome` | 记录未完成结局并保持计划开放:`awaiting_validation`(必填精确的 userAction)/ `blocked` / `waiting_for_input` / `still_working` |
66
67
  | `plan_question` | 结构化选择题,收集决策;无交互 UI 时自动降级为文本提问 |
67
68
 
@@ -80,22 +81,24 @@ pi install npm:@wbline/pi-plan-build
80
81
 
81
82
  守卫在 `tool_call` 前拦截,路径先归一化再做 symlink 解析,不存在的文件解析最远存在父目录:
82
83
 
83
- - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单;**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行
84
- - **时序硬闸**:最近一条 assistant 消息里 `plan_task` 结构转移(new/include/update/exclude/abandon)未收尾时,文件变更与生命周期工具一律先等转移收尾(`list/show` 只读动作不拦)
85
- - **事后对账**:build 模式放行波及面无法验证的变更工具前记录计划文件内容基线,结算(agent_settled)时发现文件被改动即警告提示核对;bash/powershell 改写计划文件同样纳入
86
- - **模式边界**:`plan_task new` 仅限 plan 模式(build 下创建的计划无法走 plan_exit 审批);分步执行进行中禁止切回 plan 模式(避免"只读 + 实现第 N 步"的矛盾注入)
87
- - **build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 plan 模式;未列入的 IDE 变更工具同样过守卫(无法验证目标时放行)
88
- - **bash/powershell/终端命令不做分类沙箱**:plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
89
- - 扩展自身对计划文件的修订(步骤 revise)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕
84
+ - **管辖范围**:只守卫 pi 内置工具与 JetBrains IDE 桥接工具(`ide_` 前缀)——内置 8 个全量显式分类(edit/write 变更、bash/powershell 执行面、read/find/grep/ls 只读),`ide_*` 动态分类;其它扩展/MCP 工具不守卫(codemode 的嵌套调用走 pi 同一 tool_call 管线,仍受守卫约束)
85
+ - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单;**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行;有 UI 时拦截会弹确认门,用户确认即切 build 放行本次修改,拒绝则本回合只拦不再问(回合结束重置)
86
+ - **时序硬闸**:最近一条 assistant 消息里 `plan_task` 结构转移(new/revise/include/update/exclude/abandon 等非只读动作)未收尾时,文件变更与生命周期工具一律先等转移收尾(`list/show` 只读动作不拦)
87
+ - **事后对账**:build 模式放行波及面无法验证的变更工具前记录计划文件内容基线,结算(agent_settled)时发现文件被改动即警告提示核对;bash/powershell 与 IDE 执行面工具改写计划文件同样纳入
88
+ - **模式边界**:`plan_task new` 仅限 plan 模式(build 下创建的计划无法走 plan_exit 审批);分步执行进行中禁止切回 plan 模式(避免"只读 + 实现第 N 步"的矛盾注入);plan 模式且无计划时,`new` 先弹窗询问「创建计划 / 直接执行」(用户明确要求规划可跳过),选直接执行自动切 build;build 模式调用 `new` 也会弹窗确认切到 plan(拒绝则保持 build);build 中途修订计划走 `plan_task revise`(弹窗确认切回 plan)——所有模式转换都由用户拍板
89
+ - **build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划调用 `plan_task revise`(确认门切回 plan)或由用户 /plan;未列入的 IDE 变更工具同样过守卫(无法验证目标时放行)
90
+ - **bash/powershell 与 IDE 执行面工具不做分类沙箱**:终端命令、运行配置、构建、SQL 执行、inspection KTS 的目标不可提取且能力与 shell 等价——plan 模式为提示词约束,build 模式放行并纳入事后对账;诚实标注而非冒充沙箱
91
+ - 扩展自身对计划文件的修订(步骤 revise、终态状态块)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕;终态归档 append-only,文件为空或写失败则静默跳过
90
92
 
91
93
  ## 设计取舍
92
94
 
93
95
  - **集中状态机而非分散闭包**:全部状态收敛为一个不可变 `State`(mode + plan + execution),唯一 `transition()` 入口,纯函数单测全覆盖。代价是新增行为必须先定义转移事件——换来任何状态变化都有唯一出处
94
96
  - **原生 UI 而非接管 composer**:只用 `setStatus` / `setWidget` / `ui.custom` / `ui.select`,不碰编辑器与消息栏——与任何其它扩展零冲突
95
- - **砍掉干净会话交接**:跨会话 transfer/reconcile 的多段状态机收益低、分支爆炸,不做。要换会话,新会话里重新规划即可——计划文件本身可以复用
97
+ - **砍掉干净会话交接**:跨会话 transfer/reconcile 的多段状态机收益低、分支爆炸,不做。换会话后用 `plan_task new fromFile` 恢复既有计划文件接着干(`list` 可查历史计划与结局)
96
98
  - **宽容步骤解析**:编号 / checkbox / 短横线都接受,重复步骤去重;解析失败不报错,而是返回一段模型可执行的修复指引
97
99
  - **上下文锚定注入**:计划块作为 user 消息插在最后一条真实用户消息之前,位置与内容稳定——前缀缓存持续命中
98
- - **awaiting_validation 问询只发一次**:内存 once 标志防重放(reload 后不重问),比误重问的选择框更安静
100
+ - **验证问询等下一条消息**:`awaiting_validation` 结算后不在回合刚结束时弹窗(那时你还没验证),而在你下一次发消息时确认一次;未通过不自动重问,重新结算才重置——比误重问的选择框更安静
101
+ - **无 UI 跳过审批门**:print/json 模式没有可交互的用户,入口询问与 `plan_exit` 审批门一致跳过(后者自动选本会话连续实现)——不会出现"计划建了却永远拿不到实现授权"的死锁
99
102
 
100
103
  ## 开发
101
104
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wbline/pi-plan-build",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
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
@@ -10,6 +10,15 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
10
10
  import type { PromptPack } from "./core/prompts.ts";
11
11
  import { type State, statusLine } from "./core/state.ts";
12
12
 
13
+ /** scope 注入上限(字符):超出截断并指向计划文件;同一内容截断结果稳定,不破坏前缀缓存。 */
14
+ const SCOPE_INJECT_LIMIT = 2000;
15
+
16
+ function clampScope(scope: string): string {
17
+ return scope.length <= SCOPE_INJECT_LIMIT
18
+ ? scope
19
+ : `${scope.slice(0, SCOPE_INJECT_LIMIT)}\n…(范围过长已截断,完整内容以计划文件为准)`;
20
+ }
21
+
13
22
  export function buildContextBlock(
14
23
  state: State,
15
24
  P: PromptPack,
@@ -29,7 +38,7 @@ export function buildContextBlock(
29
38
 
30
39
  const plan = state.plan;
31
40
  if (!plan) return undefined; // 收窄:plan 模式无计划已在上方返回
32
- parts.push(``, `## 范围`, plan.scope);
41
+ parts.push(``, `## 范围`, clampScope(plan.scope));
33
42
  if (plan.outcome) {
34
43
  if (plan.outcome.kind === "awaiting_validation") {
35
44
  parts.push(
@@ -60,7 +69,9 @@ export function buildContextBlock(
60
69
  state.execution.paused
61
70
  ? P.stepPaused
62
71
  : active
63
- ? P.stepActive(active.n, total, active.text)
72
+ ? state.execution.auto
73
+ ? P.stepAuto(active.n, total, active.text)
74
+ : P.stepActive(active.n, total, active.text)
64
75
  : ready
65
76
  ? P.stepReady(ready.n, total, ready.text)
66
77
  : `分步执行等待指令。`,
@@ -0,0 +1,87 @@
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
+ /** fromFile 外部恢复的接管标记:原文件文末追加「已接管」块(append-only,失败静默)。 */
29
+ export function markSuperseded(sourcePath: string, newPath: string): boolean {
30
+ try {
31
+ if (!fs.readFileSync(sourcePath, "utf8").trim()) return false;
32
+ const d = new Date();
33
+ const p = (n: number) => String(n).padStart(2, "0");
34
+ const date = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
35
+ fs.appendFileSync(
36
+ sourcePath,
37
+ `\n---\n\n> **状态:已接管**(${date}):此计划已复制到新计划文件继续:${newPath}\n`,
38
+ );
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ export interface HistoricalPlan {
46
+ path: string;
47
+ title: string;
48
+ /** 文末状态块的结局与日期;未收尾为 undefined(「已接管」= 已被新计划文件取代)。 */
49
+ status?: "已完成" | "已放弃" | "已接管";
50
+ date?: string;
51
+ mtimeMs: number;
52
+ }
53
+
54
+ /** 扫描 plans 目录的历史计划(按修改时间倒序):标题取首个一级标题,结局读文末状态块。 */
55
+ export function listPlanFiles(cwd: string, limit = 20): HistoricalPlan[] {
56
+ const dir = path.join(cwd, ".pi", "agent", "plans");
57
+ let names: string[];
58
+ try {
59
+ names = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
60
+ } catch {
61
+ return [];
62
+ }
63
+ const items: HistoricalPlan[] = [];
64
+ for (const name of names) {
65
+ const p = path.join(dir, name);
66
+ try {
67
+ const st = fs.statSync(p);
68
+ const content = fs.readFileSync(p, "utf8");
69
+ const title =
70
+ /^#\s+(.+)$/m.exec(content)?.[1]?.trim() || name.replace(/\.md$/, "");
71
+ let status: HistoricalPlan["status"];
72
+ let date: string | undefined;
73
+ // 取最后一次出现的终态块(恢复后再收尾的文件会有多块,最后一块为准)
74
+ for (const m of content.matchAll(
75
+ /\*\*状态:(已完成|已放弃|已接管)\*\*((\d{4}-\d{2}-\d{2}))/g,
76
+ )) {
77
+ status = m[1] as HistoricalPlan["status"];
78
+ date = m[2];
79
+ }
80
+ items.push({ path: p, title, status, date, mtimeMs: st.mtimeMs });
81
+ } catch {
82
+ // 单个文件读失败不影响整体列表
83
+ }
84
+ }
85
+ items.sort((a, b) => b.mtimeMs - a.mtimeMs);
86
+ return items.slice(0, limit);
87
+ }
package/src/core/guard.ts CHANGED
@@ -2,19 +2,29 @@
2
2
  * 权限守卫(路径判定纯函数 + tool_call 接线放 lifecycle)。
3
3
  *
4
4
  * 语义沿用参考项目的边界,收敛为可测纯函数:
5
+ * - 管辖范围刻意限定:pi 内置工具 + JetBrains IDE 桥接工具(ide_ 前缀)。
6
+ * 内置 8 个全量显式分类,不靠"没点到的就放行"兜底;其余扩展/MCP 工具
7
+ * outOfScope 不守卫(codemode 的嵌套调用经 pi 同一 tool_call 管线,仍受
8
+ * 守卫约束,无旁路)。
5
9
  * - Plan 模式:文件变更通道(原生 edit/write 与 IDE 桥接工具)只许写
6
- * 当前计划文件;IDE 工具动态分类(注解 > 名字动词约定 > 配置覆盖),
7
- * 无法验证目标(语义重命名/未知工具)一律阻断——宁可误拦不可放行。
10
+ * 当前计划文件;IDE 工具动态分类(配置覆盖 > 注解 > 方法后缀 > 动词约定,
11
+ * 写动词优先),无法验证目标(语义重命名/未知工具)一律阻断——宁可误拦
12
+ * 不可放行。
8
13
  * - Build 模式:保护计划文件不被改写(修订请回 Plan 模式)。
9
- * - bash/powershell/终端命令不做硬沙箱(Plan 的只读由提示词约束,
10
- * 这里不做任意命令分类——诚实标注而非冒充沙箱)。
14
+ * - bash/powershell 与执行面 IDE 方法(terminal/run/build/sql/KTS)不做
15
+ * 硬沙箱(Plan 的只读由提示词约束,Build 放行并纳入事后对账——诚实
16
+ * 标注而非冒充沙箱)。
11
17
  */
12
18
 
13
19
  import fs from "node:fs";
14
20
  import os from "node:os";
15
21
  import path from "node:path";
16
22
 
17
- /** 原生文件编辑工具(pi 1.3.0 实际存在的变更类工具)。 */
23
+ /**
24
+ * 原生文件编辑工具(pi 1.3.0 实际存在的变更类工具)。
25
+ * 升级 pi 时对照其 dist/core/tools/ 核对本名单——内置全集为
26
+ * bash/edit/find/grep/ls/read/write/powershell,新增写类工具需补进此处。
27
+ */
18
28
  export const FILE_MUTATION_TOOLS = new Set(["edit", "write"]);
19
29
 
20
30
  /** 守卫关心的 MCP 风格注解最小子集(来自 pi.getAllTools() 的 ToolAnnotations)。 */
@@ -29,7 +39,11 @@ export interface ToolGuardOverride {
29
39
  mutating?: string[];
30
40
  }
31
41
 
32
- export type ToolGuardKind = "mutation" | "readonly" | "outOfScope";
42
+ export type ToolGuardKind =
43
+ | "mutation"
44
+ | "readonly"
45
+ | "execution"
46
+ | "outOfScope";
33
47
 
34
48
  /**
35
49
  * 只读动词段:IDE 只读工具几乎都用这些动词命名。未命中的 ide_* 工具
@@ -62,16 +76,43 @@ const READONLY_VERBS: ReadonlySet<string> = new Set([
62
76
  "node",
63
77
  "impact",
64
78
  "diagnose",
65
- "generate",
66
79
  "test",
67
80
  "symbol",
68
81
  "files",
69
82
  "repositories",
70
83
  ]);
71
84
 
85
+ /**
86
+ * 写动词段:优先于只读动词——堵 `apply_diff`(apply 写 + diff 只读)、
87
+ * `move_files`(move 写 + files 只读)这类组合名被动词表误放行。
88
+ */
89
+ const WRITE_VERBS: ReadonlySet<string> = new Set([
90
+ "write",
91
+ "apply",
92
+ "create",
93
+ "edit",
94
+ "delete",
95
+ "rename",
96
+ "move",
97
+ "save",
98
+ "format",
99
+ ]);
100
+
101
+ /**
102
+ * 已知只读方法后缀:`generate` 不进只读动词表(`generate_code` 类未来写
103
+ * 方法被洗白的风险太高),确证的纯生成方法按后缀精确放行,产品段无关;
104
+ * 未知 `generate_*` 保守按变更通道。
105
+ */
106
+ const READONLY_SUFFIXES: readonly string[] = [
107
+ "_generate_psi_tree",
108
+ "_generate_inspection_kts_api",
109
+ "_generate_inspection_kts_examples",
110
+ ];
111
+
72
112
  /**
73
113
  * 工具分类(纯函数):是否按"文件变更通道"守卫。
74
- * - 优先级:配置覆盖 > 注解(readOnlyHint)> 名字动词约定。
114
+ * - 优先级:配置覆盖 > 注解(readOnlyHint)> 方法后缀 > 动词约定
115
+ * (写动词优先于只读动词,防组合名被洗白)。
75
116
  * - 管辖范围:原生 edit/write 与 ide_* 桥接工具;其它自定义工具
76
117
  * (如第三方 MCP)维持现状不守卫(outOfScope,README 注明局限)。
77
118
  */
@@ -83,17 +124,42 @@ export function classifyToolCall(
83
124
  if (override?.mutating?.includes(toolName)) return "mutation";
84
125
  if (override?.readonly?.includes(toolName)) return "readonly";
85
126
  if (FILE_MUTATION_TOOLS.has(toolName)) return "mutation";
127
+ if (SHELL_TOOLS.has(toolName)) return "execution";
128
+ if (BUILTIN_READONLY.has(toolName)) return "readonly";
86
129
  if (!toolName.startsWith("ide_")) return "outOfScope";
87
130
  if (annotations?.readOnlyHint === true) return "readonly";
88
131
  if (annotations?.readOnlyHint === false) return "mutation";
132
+ if (EXECUTION_SUFFIXES.some((s) => toolName.endsWith(s))) return "execution";
89
133
  const segments = toolName.toLowerCase().split("_");
134
+ // 写动词优先:apply_diff / move_files 这类组合名不被只读动词洗白
135
+ if (segments.some((s) => WRITE_VERBS.has(s))) return "mutation";
136
+ // generate 不在动词表里:已确证的纯生成方法按后缀放行
137
+ if (READONLY_SUFFIXES.some((s) => toolName.endsWith(s))) return "readonly";
90
138
  if (segments.some((s) => READONLY_VERBS.has(s))) return "readonly";
91
139
  return "mutation";
92
140
  }
93
141
 
94
- /** 原生 shell 工具:不做硬沙箱,但 build 模式纳入事后对账(改动计划文件可被发现)。 */
142
+ /** 原生 shell 工具:执行面(execution),不做硬沙箱;build 模式纳入事后对账。 */
95
143
  export const SHELL_TOOLS: ReadonlySet<string> = new Set(["bash", "powershell"]);
96
144
 
145
+ /** 原生只读工具:显式归类,不落入管辖外兜底。 */
146
+ export const BUILTIN_READONLY: ReadonlySet<string> = new Set([
147
+ "read",
148
+ "find",
149
+ "grep",
150
+ "ls",
151
+ ]);
152
+
153
+ /** 执行面 IDE 方法后缀:进程执行而非文件写入(可间接落盘),目标不可提取。 */
154
+ export const EXECUTION_SUFFIXES: readonly string[] = [
155
+ "_execute_terminal_command",
156
+ "_execute_run_configuration",
157
+ "_execute_sql_query",
158
+ "_build_project",
159
+ "_run_inspection_kts",
160
+ "_cancel_sql_query",
161
+ ];
162
+
97
163
  /** 本扩展生命周期工具:plan_task 转移未收尾时与变更通道一同被时序闸拦住。 */
98
164
  export const LIFECYCLE_TOOLS: ReadonlySet<string> = new Set([
99
165
  "plan_exit",
@@ -166,56 +232,72 @@ export function extractMutationTargets(
166
232
  const inp = (input ?? {}) as Record<string, unknown>;
167
233
  const one = (v: unknown): string[] =>
168
234
  typeof v === "string" && v.trim() ? [normalizePath(v, cwd)] : [];
169
- switch (toolName) {
170
- case "edit":
171
- case "write":
172
- return one(inp.path);
173
- case "ide_webstorm_create_new_file":
174
- return one(inp.pathInProject);
175
- case "ide_webstorm_reformat_file": {
176
- const files = inp.files;
177
- if (!Array.isArray(files)) return [];
178
- return files
179
- .filter((f): f is string => typeof f === "string" && f.trim() !== "")
180
- .map((f) => normalizePath(f, cwd));
181
- }
182
- case "ide_webstorm_apply_patch": {
183
- const text =
184
- typeof inp.input === "string"
185
- ? inp.input
186
- : typeof inp.patch === "string"
187
- ? inp.patch
188
- : "";
189
- if (!text.trim()) return [];
190
- const targets = new Set<string>();
191
- // codex apply_patch 格式:*** Update/Add/Delete File: <path>(*** Move to: 为重命名目标)
192
- for (const m of text.matchAll(
193
- /^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm,
194
- ))
195
- targets.add(m[1].trim());
196
- for (const m of text.matchAll(/^\*\*\* Move to: (.+)$/gm))
197
- targets.add(m[1].trim());
198
- // unified diff:+++ b/<path>
199
- for (const m of text.matchAll(/^\+\+\+\s+(?:b\/)?(.+?)(?:\t.*)?\s*$/gm))
200
- targets.add(m[1].trim());
201
- return [...targets].map((p) => normalizePath(p, cwd));
235
+ if (toolName === "edit" || toolName === "write") return one(inp.path);
236
+ // IDE 桥接工具按方法后缀匹配:桥接层方法集跨 JetBrains 产品一致,产品段
237
+ // 随 IDE 不同(webstorm/intellij/pycharm/goland/rider/…)——写全名会把
238
+ // 其它产品的同类工具漏进"波及面无法验证"(plan 模式下连计划文件都写不了)。
239
+ if (!toolName.startsWith("ide_")) return undefined;
240
+ if (toolName.endsWith("_create_new_file")) return one(inp.pathInProject);
241
+ if (toolName.endsWith("_reformat_file")) {
242
+ const files = inp.files;
243
+ if (!Array.isArray(files)) return [];
244
+ return files
245
+ .filter((f): f is string => typeof f === "string" && f.trim() !== "")
246
+ .map((f) => normalizePath(f, cwd));
247
+ }
248
+ if (toolName.endsWith("_apply_patch")) {
249
+ const text =
250
+ typeof inp.input === "string"
251
+ ? inp.input
252
+ : typeof inp.patch === "string"
253
+ ? inp.patch
254
+ : "";
255
+ if (!text.trim()) return [];
256
+ const targets = new Set<string>();
257
+ // codex apply_patch 格式:*** Update/Add/Delete File: <path>(*** Move to: 为重命名目标)
258
+ for (const m of text.matchAll(
259
+ /^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm,
260
+ ))
261
+ targets.add(m[1].trim());
262
+ for (const m of text.matchAll(/^\*\*\* Move to: (.+)$/gm))
263
+ targets.add(m[1].trim());
264
+ // unified diff:---/+++ 成对提取(改名的源路径只出现在 ---;正文里
265
+ // -/+ 开头的行会伪装成文件头,成对出现才认);/dev/null 是新增/删除
266
+ // 文件的占位头,不是写入目标;纯 rename 无 ---/+++,由 rename from/to 补齐。
267
+ const lines = text.split(/\r?\n/);
268
+ for (let i = 0; i < lines.length - 1; i++) {
269
+ const del = (lines[i] ?? "").match(/^--- (?:a\/)?(.+?)(?:\t.*)?$/);
270
+ if (!del) continue;
271
+ const add = (lines[i + 1] ?? "").match(/^\+\+\+ (?:b\/)?(.+?)(?:\t.*)?$/);
272
+ if (!add) continue;
273
+ for (const p of [del[1], add[1]]) {
274
+ const v = p.trim();
275
+ if (v && v !== "/dev/null") targets.add(v);
276
+ }
202
277
  }
203
- case "ide_webstorm_rename_refactoring":
204
- return undefined; // 语义重命名波及全部引用处,无法验证
205
- default:
206
- return undefined;
278
+ for (const m of text.matchAll(/^rename (?:from|to) (.+)$/gm))
279
+ targets.add(m[1].trim());
280
+ return [...targets].map((p) => normalizePath(p, cwd));
207
281
  }
282
+ // 语义重命名波及全部引用处,任何产品下都不可验证——排除在兜底之外。
283
+ if (toolName.endsWith("_rename_refactoring")) return undefined;
284
+ // 参数形状兜底:未知 ide_* 方法只要按约定带 pathInProject 即可精确提取;
285
+ // 认不出的仍返回 undefined(波及面无法验证 → plan 模式阻断)。
286
+ if (typeof inp.pathInProject === "string") return one(inp.pathInProject);
287
+ return undefined;
208
288
  }
209
289
 
210
290
  export type GuardDecision =
211
291
  | { action: "allow" }
212
- | { action: "block"; reason: string };
292
+ | { action: "block"; reason: string; summary: string };
213
293
 
214
294
  /**
215
295
  * 变更裁决。targets 为 extractMutationTargets 的结果:
216
296
  * - Plan 模式:全部目标都必须是当前计划文件;undefined/空 一律阻断。
217
297
  * - Build 模式:已写盘的计划文件受保护;无法验证的目标放行(沿用原语义)。
218
298
  * 调用方先用 classifyToolCall 圈定变更通道;本函数只按 targets 与模式裁决。
299
+ * block 的 reason 面向模型(指引下一步),summary 面向用户(确认门正文)——
300
+ * 两者受众不同,指引必须对模型可执行、对用户可理解,不共用一段文本。
219
301
  */
220
302
  export function decideFileMutation(
221
303
  toolName: string,
@@ -232,7 +314,8 @@ export function decideFileMutation(
232
314
  return mode === "plan"
233
315
  ? {
234
316
  action: "block",
235
- reason: `plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`,
317
+ reason: `plan 模式只读:${toolName} 的写入波及面无法验证,被阻断。修改项目文件需经 plan_exit 审批进入实现(无计划则先 plan_task new),或由用户切换到 build 模式(/build)。`,
318
+ summary: `${toolName} 要写入文件,但无法确认它会改动哪些文件`,
236
319
  }
237
320
  : { action: "allow" };
238
321
  }
@@ -240,6 +323,7 @@ export function decideFileMutation(
240
323
  return {
241
324
  action: "block",
242
325
  reason: `${toolName} 调用没有可见的文件路径,无法验证写入目标。请使用带路径参数的编辑工具,明确指向目标文件。`,
326
+ summary: `${toolName} 调用没有可见的文件路径,无法确认写入目标`,
243
327
  };
244
328
  }
245
329
  const ts = targets.map((t) => normCase(normalizePath(t, process.cwd())));
@@ -249,8 +333,11 @@ export function decideFileMutation(
249
333
  return {
250
334
  action: "block",
251
335
  reason: planPath
252
- ? `plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,请先通过 plan_exit 审批切换到 build 模式。`
336
+ ? `plan 模式只读:${toolName} 仅允许写当前计划文件。修改项目文件需经 plan_exit 审批进入实现(无计划则先 plan_task new),或由用户切换到 build 模式(/build)。`
253
337
  : `plan 模式只读:${toolName} 被阻断。先创建计划(plan_task new)后才能写计划文件本身。`,
338
+ summary: planPath
339
+ ? `${toolName} 要修改计划文件以外的项目文件`
340
+ : `还没有计划:plan 模式下任何文件写入都被阻断`,
254
341
  };
255
342
  }
256
343
 
@@ -259,23 +346,24 @@ export function decideFileMutation(
259
346
  return {
260
347
  action: "block",
261
348
  reason:
262
- "计划文件在 build 模式受保护。修订计划请切回 plan 模式(/plan)后再改。",
349
+ "计划文件在 build 模式受保护。修订计划:调用 plan_task revise(用户确认后切回 plan),或由用户 /plan 切换。",
350
+ summary: `${toolName} 要改写受保护的计划文件`,
263
351
  };
264
352
  }
265
353
  return { action: "allow" };
266
354
  }
267
355
 
268
- /** symlink 解析(fs 侧,非纯):存在则返回真实路径,否则逐级解析父目录。 */
356
+ /** symlink 解析(fs 侧,非纯):存在则返回真实路径;不存在则找到最远存在的父目录,解析其 symlink 后拼接剩余路径。 */
269
357
  export function realpathLike(target: string): string {
270
- try {
271
- return fs.realpathSync(target);
272
- } catch {
273
- // 不存在的文件:解析最远存在的父目录
274
- const parent = path.dirname(target);
358
+ let current = target;
359
+ for (let depth = 0; depth < 32; depth++) {
275
360
  try {
276
- return path.join(fs.realpathSync(parent), path.basename(target));
361
+ return fs.realpathSync(current) + target.slice(current.length);
277
362
  } catch {
278
- return target;
363
+ const parent = path.dirname(current);
364
+ if (parent === current) return target; // 已到根仍不存在:放弃解析
365
+ current = parent;
279
366
  }
280
367
  }
368
+ return target;
281
369
  }