@wbline/pi-plan-build 0.0.5 → 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,31 @@
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
+
7
32
  ## [0.0.5] - 2026-10-17
8
33
 
9
34
  ### 新增
package/README.md CHANGED
@@ -22,7 +22,7 @@ pi install npm:@wbline/pi-plan-build
22
22
  2. 让 agent 规划:`plan_task new` 建计划(你未明确要求规划时,会先弹窗确认:创建计划还是直接执行)→ 写完整计划文件(含验证小节与实现步骤)→ `plan_exit` 提请审批
23
23
  3. 你三选一:**本会话连续实现 / 分步实现 / 留在 plan**——选择之前 agent 劫不了代码
24
24
  4. build 模式实现:计划文件受保护;分步模式默认每步等点头,说「剩下的都做完」可授权连跑
25
- 5. 验证闭环:能自动验证的当场跑;只能你验证的(登录、硬件、线上效果)记为 `awaiting_validation`,回合结束后主动弹窗问你
25
+ 5. 验证闭环:能自动验证的当场跑;只能你验证的(登录、硬件、线上效果)记为 `awaiting_validation`,你下一条消息时主动弹窗确认,通过才收尾
26
26
 
27
27
  ## 它解决什么问题
28
28
 
@@ -36,13 +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 模式建计划、plan 模式被守卫拦截时也各有一道确认门——每次模式转换都由用户一键拍板
41
+ - 🚪 **全链路显式决策**:`plan_task new` 先问「创建计划还是直接执行」(明确要求规划可传参跳过),`plan_exit` 后问「本会话/分步/留下」;build 模式建计划、build 中途修订计划(`plan_task revise`)、plan 模式被守卫拦截时各有一道确认门——每次模式转换都由用户一键拍板
42
42
  - 📒 **事后对账**:放行波及面无法验证的工具(IDE 终端命令、shell)前记录计划文件基线,回合结束时文件被改动即警告核对
43
43
  - 🪜 **分步执行**:计划里的实现步骤逐个就绪,你说"继续"才开工,说「剩下的都做完」即授权连跑自动推进;侧栏实时显示 `[待办]/[就绪]/[进行]/[完成]/[跳过]` 进度
44
- - ✅ **验证闭环**:`awaiting_validation` 结算后自动确认"必需验证是否通过?",通过才收尾,否则计划保持开放
45
- - 🌐 **中英双语提示词**:菜单一键切换;7 个工具全模式常驻(稳定工具目录),模式切换不抖动工具列表,prompt cache 持续命中
44
+ - ✅ **验证闭环**:`awaiting_validation` 结算后,在你下一条消息时确认一次「必需验证通过了吗?」,通过才收尾,否则计划保持开放——不会在你还没开始验证时就弹窗
45
+ - 🌐 **中英双语提示词与工具描述**:菜单一键切换;7 个工具全模式常驻(稳定工具目录),模式切换不抖动工具列表,prompt cache 持续命中
46
46
 
47
47
  ## 命令
48
48
 
@@ -58,8 +58,8 @@ pi install npm:@wbline/pi-plan-build
58
58
 
59
59
  | 工具 | 说明 |
60
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 模式 |
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
63
  | `plan_step_control` | 分步执行:`start` 批准就绪步(`advance: "all"` 一次授权连跑剩余步骤,遇阻塞才停)、`acknowledge` 指认用户声明的已完成步(无需先 start)、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
64
64
  | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
65
65
  | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时。收尾时在计划文件文末写入状态块(`> **状态:已完成**(日期)` + 摘要),放弃同理(含原因),历史计划单看文件即可知结局 |
@@ -81,12 +81,13 @@ pi install npm:@wbline/pi-plan-build
81
81
 
82
82
  守卫在 `tool_call` 前拦截,路径先归一化再做 symlink 解析,不存在的文件解析最远存在父目录:
83
83
 
84
+ - **管辖范围**:只守卫 pi 内置工具与 JetBrains IDE 桥接工具(`ide_` 前缀)——内置 8 个全量显式分类(edit/write 变更、bash/powershell 执行面、read/find/grep/ls 只读),`ide_*` 动态分类;其它扩展/MCP 工具不守卫(codemode 的嵌套调用走 pi 同一 tool_call 管线,仍受守卫约束)
84
85
  - **plan 模式**:文件变更通道(原生 `edit/write` 与 IDE 桥接工具)只许目标为当前计划文件。IDE 工具动态分类不写死名单;**无路径或波及面无法验证(未知变更工具、语义重命名)的调用一律阻断**——宁可误拦不可放行;有 UI 时拦截会弹确认门,用户确认即切 build 放行本次修改,拒绝则本回合只拦不再问(回合结束重置)
85
- - **时序硬闸**:最近一条 assistant 消息里 `plan_task` 结构转移(new/include/update/exclude/abandon)未收尾时,文件变更与生命周期工具一律先等转移收尾(`list/show` 只读动作不拦)
86
- - **事后对账**:build 模式放行波及面无法验证的变更工具前记录计划文件内容基线,结算(agent_settled)时发现文件被改动即警告提示核对;bash/powershell 改写计划文件同样纳入
87
- - **模式边界**:`plan_task new` 仅限 plan 模式(build 下创建的计划无法走 plan_exit 审批);分步执行进行中禁止切回 plan 模式(避免"只读 + 实现第 N 步"的矛盾注入);plan 模式且无计划时,`new` 先弹窗询问「创建计划 / 直接执行」(用户明确要求规划可跳过),选直接执行自动切 build;build 模式调用 `new` 也会弹窗确认切到 plan(拒绝则保持 build)——两个方向的模式转换都由用户拍板
88
- - **build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 plan 模式;未列入的 IDE 变更工具同样过守卫(无法验证目标时放行)
89
- - **bash/powershell/终端命令不做分类沙箱**:plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
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 模式放行并纳入事后对账;诚实标注而非冒充沙箱
90
91
  - 扩展自身对计划文件的修订(步骤 revise、终态状态块)不经 tool_call 守卫(守卫只拦模型调用),但受同一状态机校验并在计划文件上留痕;终态归档 append-only,文件为空或写失败则静默跳过
91
92
 
92
93
  ## 设计取舍
@@ -96,7 +97,8 @@ pi install npm:@wbline/pi-plan-build
96
97
  - **砍掉干净会话交接**:跨会话 transfer/reconcile 的多段状态机收益低、分支爆炸,不做。换会话后用 `plan_task new fromFile` 恢复既有计划文件接着干(`list` 可查历史计划与结局)
97
98
  - **宽容步骤解析**:编号 / checkbox / 短横线都接受,重复步骤去重;解析失败不报错,而是返回一段模型可执行的修复指引
98
99
  - **上下文锚定注入**:计划块作为 user 消息插在最后一条真实用户消息之前,位置与内容稳定——前缀缓存持续命中
99
- - **awaiting_validation 问询只发一次**:内存 once 标志防重放(reload 后不重问),比误重问的选择框更安静
100
+ - **验证问询等下一条消息**:`awaiting_validation` 结算后不在回合刚结束时弹窗(那时你还没验证),而在你下一次发消息时确认一次;未通过不自动重问,重新结算才重置——比误重问的选择框更安静
101
+ - **无 UI 跳过审批门**:print/json 模式没有可交互的用户,入口询问与 `plan_exit` 审批门一致跳过(后者自动选本会话连续实现)——不会出现"计划建了却永远拿不到实现授权"的死锁
100
102
 
101
103
  ## 开发
102
104
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wbline/pi-plan-build",
3
- "version": "0.0.5",
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(
@@ -25,11 +25,28 @@ export function archivePlanFile(
25
25
  }
26
26
  }
27
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
+
28
45
  export interface HistoricalPlan {
29
46
  path: string;
30
47
  title: string;
31
- /** 文末状态块的结局与日期;未收尾为 undefined。 */
32
- status?: "已完成" | "已放弃";
48
+ /** 文末状态块的结局与日期;未收尾为 undefined(「已接管」= 已被新计划文件取代)。 */
49
+ status?: "已完成" | "已放弃" | "已接管";
33
50
  date?: string;
34
51
  mtimeMs: number;
35
52
  }
@@ -55,7 +72,7 @@ export function listPlanFiles(cwd: string, limit = 20): HistoricalPlan[] {
55
72
  let date: string | undefined;
56
73
  // 取最后一次出现的终态块(恢复后再收尾的文件会有多块,最后一块为准)
57
74
  for (const m of content.matchAll(
58
- /\*\*状态:(已完成|已放弃)\*\*((\d{4}-\d{2}-\d{2}))/g,
75
+ /\*\*状态:(已完成|已放弃|已接管)\*\*((\d{4}-\d{2}-\d{2}))/g,
59
76
  )) {
60
77
  status = m[1] as HistoricalPlan["status"];
61
78
  date = m[2];
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_task new(入口弹窗选「直接执行」即切 build 直接修改),或经 plan_exit 审批后实现。`,
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_task new(入口弹窗选「直接执行」即切 build 直接修改),或经 plan_exit 审批后实现。`
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
  }
@@ -21,11 +21,11 @@ export interface PromptPack {
21
21
  }
22
22
 
23
23
  const ZH: PromptPack = {
24
- planReadonly: `plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
24
+ planReadonly: `plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。终端/构建/SQL 等执行命令仅限只读调研(如 git log、类型检查);会写项目、环境或数据库的操作(构建产物、跑测试、安装依赖、UPDATE/DDL)留到 build 模式。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
25
25
  taskSelection: `模式切换不产生任务。没有当前计划且用户要求规划交付物或接受了具体修改方案时,才调用 plan_task new(expectedAttached 传 null;planningRequested 仅在用户明确要求规划时传 true)。用户未明确要求规划时,工具会先弹窗让用户选「创建计划 / 直接执行」:返回说已切到 build 就放弃建计划、直接实现;用户取消就等待指示,不要自行规划。用"动作+对象"式单一标题(标题内不用冒号)和详细 scope;先等返回的 canonical 路径再写文件。已有未完成计划时绝不另开新任务;完成或放弃都只能由用户明确指示。未获回答的提问不构成同意。`,
26
26
  taskBoundary: `任务身份一次建立:用户批准的追加用 plan_task include(给完整合并后的 scope);update 仅用于改名、身份纠错或对现有交付物的实质修正;exclude 记录明确排除的话题。相关问题、岔题、调研视为延续;对独立交付物,先问是否并入或结束当前计划。生命周期转移必须先于依赖它的写入/命令单独完成。计划文件是指令,不是进度记录。`,
27
27
  planWorkflow: `在 plan 模式完成只读调研并收敛方案:推荐一个方案、列出关键文件、写完整计划文件(含 ## 验证 小节和文末 "## 实现步骤" 编号列表),然后调用 plan_exit 展示审阅。用户接受范围 ≠ 授权实现;不要在讨论未收敛或文件未写盘时调用 plan_exit。`,
28
- buildWorkflow: `build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;当前范围以计划元数据为准,修订文件内容需回 plan 模式。没有当前计划时是普通模式,小改动无需走计划流程;需要新计划时先切回 plan 模式(/plan),plan_task new 仅在 plan 模式可用。`,
28
+ buildWorkflow: `build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;需要修订计划时调用 plan_task revise(用户确认后切回 plan,改完再 plan_exit 重新提请审批)。没有当前计划时是普通模式,小改动无需走计划流程;需要新计划时调用 plan_task new(会弹窗确认切到 plan)。`,
29
29
  completionRouting: `完成路由:用户明确说整计划完成 → plan_complete;明确指认某一步完成 → plan_step_control acknowledge;语义含糊的"完成"先澄清。工作与必需检查全部通过前不要调用 plan_complete;仍有未竟事项用 plan_set_outcome(awaiting_validation / blocked / waiting_for_input / still_working),绝不因空闲推断成功。`,
30
30
  verificationPolicy: `验证策略:按计划 ## 验证 小节用最小充分检查,然后停止。优先一个聚焦的行为验证(有可观察结果);构建/类型检查不能单独证明运行时行为。只为具体风险或明确要求增加检查。如实报告通过/受阻/未执行的检查,绝不弱化或谎报。只能由用户执行的必要验证:用 plan_set_outcome awaiting_validation 记录精确操作步骤,保持计划开放等用户回报;可选反馈不阻塞完成。`,
31
31
  stepActive: (n, total, text) =>
@@ -39,11 +39,11 @@ const ZH: PromptPack = {
39
39
  };
40
40
 
41
41
  const EN: PromptPack = {
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.`,
42
+ planReadonly: `plan mode active: observe, analyze, discuss, and plan only; do not modify the system, configuration, or commits. Terminal/build/SQL commands are for read-only investigation only (git log, type checks); anything that writes the project, environment, or database (build artifacts, test runs, dependency installs, UPDATE/DDL) waits for build mode. 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.`,
43
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.`,
44
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.`,
45
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.`,
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
+ buildWorkflow: `build mode: discuss and implement within approved authorization. The plan file is protected; to revise the plan call plan_task revise (the user confirms switching back to plan mode; call plan_exit again after revising). Without a current plan this is ordinary mode — small fixes need no plan; for a new plan call plan_task new (a dialog confirms switching to plan mode).`,
47
47
  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.`,
48
48
  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.`,
49
49
  stepActive: (n, total, text) =>
package/src/engine.ts CHANGED
@@ -30,7 +30,7 @@ export class PlanEngine {
30
30
  readonly pi: ExtensionAPI;
31
31
  private ctx: ExtensionContext | undefined;
32
32
  config: Config;
33
- /** awaiting_validation 的问询是否已在本次运行发过(防重放)。 */
33
+ /** awaiting_validation 的确认是否已问过:用户下一次发消息时问一次,重新结算时重置。 */
34
34
  validationAsked = false;
35
35
  /** 状态损坏只读保护。 */
36
36
  corrupt = false;