@wbline/pi-plan-build 0.0.0-stage → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wongbin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # pi-plan-build
2
+
3
+ [Pi coding agent](https://github.com/earendil-works/pi-mono) 的 Plan/Build 双模式扩展: **只读规划 → 显式审批 →
4
+ 分步/整段实现 → 验证闭环**,针对 pi 1.3.0 重新设计。
5
+
6
+ 无需任何配置——装上即用,计划文件自动落在**当前项目** `.pi/agent/plans/`,命名为 `<创建时刻yyyyMMdd-HHmm>-<计划标题>.md`(如 `20251008-1432-售电信息三模块后端接口.md`,同名自动追加 `-2`),随项目走、看文件名即知内容。提示词内置中文/英文双语,菜单里一键切换。
7
+
8
+ ## 安装
9
+
10
+ ```bash
11
+ pi install npm:@wbline/pi-plan-build
12
+ ```
13
+
14
+ ## 命令
15
+
16
+ | 命令 / 快捷键 | 说明 |
17
+ |---------------|--------------------------------------------------------------------------------------------------------------|
18
+ | `/plan-build` | 唯一命令,打开交互菜单:切换模式 / 查看状态 / 标记完成 / 放弃计划(原因必填,文件保留)/ 语言切换 / 设置文件 |
19
+ | `Alt+M` | 直接切换模式;默认模式由设置 `defaultMode` 决定 |
20
+
21
+ 模式徽标(`📋 plan` / `🔨 build` + 计划标题与进度)显示在**底部状态栏**:plan 为警告色、build 为强调色。分步执行时步骤列表 widget 同步显示。
22
+
23
+ 设置文件 `~/.pi/agent/pi-plan-build.json`:`{ "lang": "zh", "defaultMode": "build", "protectPlanFile": true }`。
24
+
25
+ 菜单项按状态动态出现(无计划时没有"完成/放弃");TUI 里 ↑↓ 选择、Enter 执行、Esc 关闭,RPC 客户端降级为原生选择框。
26
+
27
+ ## 工具
28
+
29
+ | 工具 | 说明 |
30
+ |----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
31
+ | `plan_task` | 任务生命周期:`new` 建计划(Plan 模式)、`include` 追加用户批准的范围、`update` 改名、`exclude` 记录排除、`abandon`、`list/show`。所有转移必须带 `expectedAttached`(当前 seq)做乐观并发,过期即拒 |
32
+ | `plan_exit` | **Plan 模式终点**。要求计划文件已写盘,然后弹出审批:本会话实现 / 分步实现 / 留在 Plan |
33
+ | `plan_step_control` | 分步执行:`start` 批准就绪步、`acknowledge` 指认用户声明的已完成步、`skip`、`revise` 修订未完成步(同步改文件)、`pause/resume`、`cancel`。一次只许一个转移 |
34
+ | `plan_step_complete` | 完成当前进行中的步(摘要必填),立即生效不等待验收;最后一步完成即自动收尾整计划 |
35
+ | `plan_complete` | 标记整计划完成——仅在全部工作与必需检查通过,或用户明确指示时 |
36
+ | `plan_set_outcome` | 记录未完成结局并保持计划开放:`awaiting_validation`(必填精确的 userAction)/ `blocked` / `waiting_for_input` / `still_working` |
37
+ | `plan_question` | 结构化选择题,收集决策;无交互 UI 时自动降级为文本提问 |
38
+
39
+ 7 个工具全模式常驻(稳定工具目录),模式合法性由执行时守卫保证——模型看到的工具列表从不抖动,prompt cache 不因模式切换失效。
40
+
41
+ ## 工作流
42
+
43
+ 1. `/plan-build` 菜单选"切换模式"(或 Alt+M)进入 Plan 模式:只读调研讨论;`edit/write` 只允许写计划文件本身。
44
+ 2. 让 agent 规划:`plan_task new` 拿到 canonical 路径 → 写完整计划(含 `## 验证` 小节与文末 `## 实现步骤` 编号列表)→
45
+ `plan_exit`。
46
+ 3. 审批三选一。选分步后:步骤 1 就绪 → 你说"继续" → `plan_step_control start` → 只做该步 → `plan_step_complete` →
47
+ 下一步等待。侧栏实时显示 `○◉◐●↷` 进度。
48
+ 4. 只能由你执行的验证(登录、硬件、线上效果):agent 用 `plan_set_outcome awaiting_validation` 记录精确步骤,本轮回合结束后弹 **"
49
+ 必需验证是否通过?"**——确认即收尾,否则计划保持开放等你回报失败详情。
50
+ 5. 完成后计划归档;`/plan-build` 菜单"查看状态"随时回看,历史进度在分步摘要里。
51
+
52
+ ## 权限边界
53
+
54
+ 守卫在 `tool_call` 前拦截,路径先归一化(`@` 前缀、`~`、相对路径)再做 symlink 解析,不存在的文件解析最远存在父目录:
55
+
56
+ - **Plan 模式**:文件编辑器(`edit/write/replace/insert/undo_last_change`)只许目标为当前计划文件;
57
+ **无路径编辑调用一律阻断**——目标无法验证,宁可误拦不可放行
58
+ - **Build 模式**:已写盘的计划文件受保护(`protectPlanFile: false` 可关);修订计划请回 Plan 模式
59
+ - **bash/powershell 不做命令分类沙箱**:Plan 模式的只读对 shell 是提示词约束而非硬拦截——与 pi 现有能力一致,诚实标注而非冒充沙箱
60
+ - 扩展自身对计划文件的修订(步骤 revise)走同一文件队列,绕过守卫但不绕过记录
61
+
62
+ ## 设计取舍
63
+
64
+ - **集中状态机而非分散闭包**:全部状态收敛为一个不可变 `State`(mode + plan + execution),唯一 `transition()` 入口返回
65
+ `{ state, effects }`,纯函数 18 个单测全覆盖。代价是新增行为必须先定义转移事件——但换来任何状态变化都有唯一出处
66
+ - **原生 UI 而非接管 composer**:只用 `setStatus` / `setWidget` / `ui.custom` / `ui.select`,不碰编辑器与消息栏。代价是没有花哨的
67
+ composer 边框与消息轨道;换来与任何其它扩展零冲突,无需兼容降级代码
68
+ - **砍掉干净会话交接**:跨会话 transfer/reconcile/announce 的多段状态机收益低、分支爆炸,不做。替代:`/plan-build`
69
+ 菜单"查看状态"随时回看;要换会话,新会话里重新规划即可——计划文件本身可以复用
70
+ - **宽容步骤解析**:编号 / checkbox /
71
+ 短横线都接受,重复步骤去重;解析失败不报错,而是返回一段模型可执行的修复指引("在文件末尾追加 ##
72
+ 实现步骤……")。代价是极端格式(嵌套列表)被忽略——它要求的是平铺的离散步骤
73
+ - **上下文锚定注入**:计划块作为 user 消息插在最后一条真实用户消息之前,文本不含时间戳等易变因素——块位置与内容稳定,前缀缓存持续命中;锚点被压缩/树导航移除时自然前移
74
+ - **awaiting_validation 问询只发一次**:内存 once 标志防重放(reload 后不重问)。代价是重启后需用户在对话里主动回报——比误重问的选择框更安静
75
+
76
+ ## 开发
77
+
78
+ ```bash
79
+ npm install # 安装开发依赖(含 pi 1.3.0 类型)
80
+ npm run check # biome + tsc 双检查
81
+ npm test # 18 个纯函数单测:状态机 / 步骤解析 / 路径守卫 / 持久化解码
82
+ npm run smoke # 装配冒烟:stub ExtensionAPI 走完整流程(注册、守卫、菜单、注入)
83
+ ```
84
+
85
+ ## License
86
+
87
+ MIT
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
- {
2
- "name": "@wbline/pi-plan-build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@wbline/pi-plan-build",
3
+ "version": "0.0.1",
4
+ "description": "Plan/Build dual-mode for the Pi coding agent: read-only planning, explicit approval, step-wise execution.",
5
+ "license": "MIT",
6
+ "author": "wongbin",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-extension",
10
+ "plan-mode",
11
+ "build-mode",
12
+ "planning",
13
+ "task-management"
14
+ ],
15
+ "type": "module",
16
+ "main": "./src/index.ts",
17
+ "engines": {
18
+ "node": ">=22.6"
19
+ },
20
+ "pi": {
21
+ "extensions": [
22
+ "./src/index.ts"
23
+ ]
24
+ },
25
+ "files": [
26
+ "src",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "scripts": {
31
+ "check": "biome check src test && tsc --noEmit",
32
+ "test": "node --test test/state.test.ts test/steps-guard.test.ts",
33
+ "test:watch": "node --test --watch test/state.test.ts test/steps-guard.test.ts",
34
+ "smoke": "node test/smoke.mjs",
35
+ "prepack": "npm run check && npm test"
36
+ },
37
+ "peerDependencies": {
38
+ "@earendil-works/pi-coding-agent": ">=1.3.0",
39
+ "@earendil-works/pi-tui": "*",
40
+ "typebox": "*"
41
+ },
42
+ "devDependencies": {
43
+ "@biomejs/biome": "^2.5.15",
44
+ "@earendil-works/pi-coding-agent": "1.3.0",
45
+ "@earendil-works/pi-tui": "1.3.0",
46
+ "@types/node": "^22.0.0",
47
+ "jiti": "^2.7.0",
48
+ "typebox": "^1.3.27",
49
+ "typescript": "^5.9.3"
50
+ }
51
+ }
package/src/config.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 设置:~/.pi/agent/pi-plan-build.json(尊重 PI_CODING_AGENT_DIR)。
3
+ * 极简:三项配置;损坏文件不覆盖(提示后用默认值)。
4
+ */
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import type { Lang } from "./core/prompts.ts";
9
+ import type { Mode } from "./core/state.ts";
10
+
11
+ export interface Config {
12
+ lang: Lang;
13
+ defaultMode: Mode;
14
+ /** Build 模式是否保护计划文件(默认开)。 */
15
+ protectPlanFile: boolean;
16
+ }
17
+
18
+ const DEFAULTS: Config = {
19
+ lang: "zh",
20
+ defaultMode: "build",
21
+ protectPlanFile: true,
22
+ };
23
+
24
+ export function agentDir(): string {
25
+ return (
26
+ process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent")
27
+ );
28
+ }
29
+
30
+ export function configPath(): string {
31
+ return path.join(agentDir(), "pi-plan-build.json");
32
+ }
33
+
34
+ function loadRaw(): { config: Config; warning?: string } {
35
+ try {
36
+ const text = fs.readFileSync(configPath(), "utf8");
37
+ const parsed = JSON.parse(text) as Partial<Config>;
38
+ return {
39
+ config: {
40
+ lang: parsed.lang === "en" ? "en" : "zh",
41
+ defaultMode: parsed.defaultMode === "plan" ? "plan" : "build",
42
+ protectPlanFile: parsed.protectPlanFile !== false,
43
+ },
44
+ };
45
+ } catch (e) {
46
+ const err = e as NodeJS.ErrnoException;
47
+ if (err.code !== "ENOENT")
48
+ return {
49
+ config: DEFAULTS,
50
+ warning: `设置文件解析失败,使用默认值:${configPath()}`,
51
+ };
52
+ return { config: DEFAULTS };
53
+ }
54
+ }
55
+
56
+ export function loadConfig(): { config: Config; warning?: string } {
57
+ return loadRaw();
58
+ }
59
+
60
+ export function saveConfig(patch: Partial<Config>): Config {
61
+ const { config } = loadRaw();
62
+ const next = { ...config, ...patch };
63
+ fs.mkdirSync(path.dirname(configPath()), { recursive: true });
64
+ fs.writeFileSync(configPath(), `${JSON.stringify(next, null, "\t")}\n`);
65
+ return next;
66
+ }
package/src/context.ts ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 上下文注入:pi.on("context") 在每次模型请求前插入"当前计划块"。
3
+ *
4
+ * 沿用参考项目验证过的 prompt cache 策略:
5
+ * - 注入为 user 角色消息,放在最后一条真实用户消息之前(没有则放开头);
6
+ * - 文本不随时间/调用变化,块位置稳定 → 前缀缓存命中;
7
+ * - 锚点(最后一条用户消息)被压缩/树导航移除时自然前移,无需额外处理。
8
+ */
9
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
10
+ import type { PromptPack } from "./core/prompts.ts";
11
+ import { type State, statusLine } from "./core/state.ts";
12
+
13
+ export function buildContextBlock(
14
+ state: State,
15
+ P: PromptPack,
16
+ ): string | undefined {
17
+ // Build 无当前计划:普通模式,不注入(与参考项目语义一致)
18
+ if (!state.plan && state.mode === "build") return undefined;
19
+ const parts: string[] = [
20
+ `<system-reminder>`,
21
+ `# 计划状态:${statusLine(state)}`,
22
+ ];
23
+
24
+ if (!state.plan) {
25
+ // Plan 无计划:告诉模型边界与如何创建
26
+ parts.push(``, P.planReadonly, ``, P.taskSelection, `</system-reminder>`);
27
+ return parts.join("\n");
28
+ }
29
+
30
+ const plan = state.plan;
31
+ if (!plan) return undefined; // 收窄:plan 模式无计划已在上方返回
32
+ parts.push(``, `## 范围`, plan.scope);
33
+ if (plan.outcome) {
34
+ if (plan.outcome.kind === "awaiting_validation") {
35
+ parts.push(
36
+ ``,
37
+ P.awaitingValidation,
38
+ ``,
39
+ `需要用户执行:${plan.outcome.userAction}`,
40
+ );
41
+ } else {
42
+ parts.push(
43
+ ``,
44
+ `计划结局(${plan.outcome.kind}):${plan.outcome.reason}`,
45
+ );
46
+ }
47
+ }
48
+ parts.push(``, state.mode === "plan" ? P.planReadonly : P.buildWorkflow);
49
+ if (state.mode === "plan")
50
+ parts.push(``, P.taskSelection, ``, P.taskBoundary, ``, P.planWorkflow);
51
+ else parts.push(``, P.completionRouting);
52
+ parts.push(``, `## 验证`, P.verificationPolicy);
53
+
54
+ if (state.execution) {
55
+ const total = state.execution.steps.length;
56
+ const active = state.execution.steps.find((x) => x.status === "active");
57
+ const ready = state.execution.steps.find((x) => x.status === "ready");
58
+ parts.push(
59
+ ``,
60
+ state.execution.paused
61
+ ? P.stepPaused
62
+ : active
63
+ ? P.stepActive(active.n, total, active.text)
64
+ : ready
65
+ ? P.stepReady(ready.n, total, ready.text)
66
+ : `分步执行等待指令。`,
67
+ );
68
+ }
69
+
70
+ parts.push(`</system-reminder>`);
71
+ return parts.join("\n");
72
+ }
73
+
74
+ /**
75
+ * 返回注入后的消息数组(不修改入参)。
76
+ * 注入点:最后一条 role==="user" 的真实用户消息之前;没有则最前。
77
+ */
78
+ export function injectContext(
79
+ messages: readonly AgentMessage[],
80
+ block: string,
81
+ ): AgentMessage[] {
82
+ const result = [...messages];
83
+ let insertAt = 0;
84
+ for (let i = result.length - 1; i >= 0; i--) {
85
+ if (result[i]?.role === "user") {
86
+ insertAt = i;
87
+ break;
88
+ }
89
+ }
90
+ const blockMessage = {
91
+ role: "user" as const,
92
+ content: block,
93
+ timestamp: Date.now(),
94
+ } as unknown as AgentMessage;
95
+ result.splice(insertAt, 0, blockMessage);
96
+ return result;
97
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 权限守卫(路径判定纯函数 + tool_call 接线放 lifecycle)。
3
+ *
4
+ * 语义沿用参考项目的边界,收敛为可测纯函数:
5
+ * - Plan 模式:文件编辑器只许写当前计划文件;无路径编辑器(无法验证目标)一律阻断。
6
+ * - Build 模式:保护计划文件不被普通编辑器改写(修订请回 Plan 模式)。
7
+ * - bash/powershell 不做硬沙箱(Plan 的只读由提示词约束,这里不做任意命令分类)。
8
+ */
9
+
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+
14
+ export const FILE_MUTATION_TOOLS = new Set([
15
+ "edit",
16
+ "write",
17
+ "replace",
18
+ "insert",
19
+ "undo_last_change",
20
+ ]);
21
+
22
+ /** 归一化模型给的路径:@ 前缀、~、相对路径 → 绝对路径。 */
23
+ export function normalizePath(raw: string, cwd: string): string {
24
+ let p = raw.trim();
25
+ if (p.startsWith("@")) p = p.slice(1).trim();
26
+ if (p.startsWith("~/") || p === "~") p = path.join(os.homedir(), p.slice(1));
27
+ if (!path.isAbsolute(p)) p = path.resolve(cwd, p);
28
+ return path.normalize(p);
29
+ }
30
+
31
+ export type GuardDecision =
32
+ | { action: "allow" }
33
+ | { action: "block"; reason: string };
34
+
35
+ /** 计划文件是否可写(含尚不存在的目标,且解析父目录别名由调用方先做 realpath)。 */
36
+ export function decideFileMutation(
37
+ toolName: string,
38
+ mode: "plan" | "build",
39
+ planPath: string | null,
40
+ planSaved: boolean,
41
+ target: string | undefined,
42
+ ): GuardDecision {
43
+ if (!FILE_MUTATION_TOOLS.has(toolName)) return { action: "allow" };
44
+ const plan = planPath ? normalizePath(planPath, process.cwd()) : null;
45
+
46
+ if (target === undefined || target === "") {
47
+ return {
48
+ action: "block",
49
+ reason: `${toolName} 调用没有可见的文件路径,无法验证写入目标。请使用带 path 参数的编辑工具,明确指向目标文件。`,
50
+ };
51
+ }
52
+ const t = normalizePath(target, process.cwd());
53
+
54
+ if (mode === "plan") {
55
+ if (plan && t === plan) return { action: "allow" };
56
+ return {
57
+ action: "block",
58
+ reason: planPath
59
+ ? `Plan 模式只读:${toolName} 仅允许写当前计划文件。如需修改项目文件,请先通过 plan_exit 审批切换到 Build 模式。`
60
+ : `Plan 模式只读:${toolName} 被阻断。先创建计划(plan_task new)后才能写计划文件本身。`,
61
+ };
62
+ }
63
+
64
+ // build 模式:保护计划文件
65
+ if (plan && t === plan && planSaved) {
66
+ return {
67
+ action: "block",
68
+ reason:
69
+ "计划文件在 Build 模式受保护。修订计划请切回 Plan 模式(/plan)后再改。",
70
+ };
71
+ }
72
+ return { action: "allow" };
73
+ }
74
+
75
+ /** symlink 解析(fs 侧,非纯):存在则返回真实路径,否则逐级解析父目录。 */
76
+ export function realpathLike(target: string): string {
77
+ try {
78
+ return fs.realpathSync(target);
79
+ } catch {
80
+ // 不存在的文件:解析最远存在的父目录
81
+ const parent = path.dirname(target);
82
+ try {
83
+ return path.join(fs.realpathSync(parent), path.basename(target));
84
+ } catch {
85
+ return target;
86
+ }
87
+ }
88
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 提示词集中层:全部面向模型的指引在这里,支持 zh/en 切换。
3
+ * 借鉴参考项目经过打磨的语义(只读边界 / 任务边界 / 完成路由 / 验证策略),压缩为更短的文本。
4
+ */
5
+
6
+ export type Lang = "zh" | "en";
7
+
8
+ export interface PromptPack {
9
+ readonly planReadonly: string;
10
+ readonly taskSelection: string;
11
+ readonly taskBoundary: string;
12
+ readonly planWorkflow: string;
13
+ readonly buildWorkflow: string;
14
+ readonly completionRouting: string;
15
+ readonly verificationPolicy: string;
16
+ readonly stepActive: (n: number, total: number, text: string) => string;
17
+ readonly stepReady: (n: number, total: number, text: string) => string;
18
+ readonly stepPaused: string;
19
+ readonly awaitingValidation: string;
20
+ }
21
+
22
+ const ZH: PromptPack = {
23
+ planReadonly: `Plan 模式激活:只观察、分析、讨论和规划,不要改动系统/配置/提交。唯一允许的写操作是把完整计划写入当前计划文件(仅为定稿或用户明确要求的修订)。研究或讨论期间正常回答,不要写文件、不要调用 plan_exit。`,
24
+ taskSelection: `模式切换不产生任务。没有当前计划时,仅当用户要求规划交付物或接受了具体修改方案,才调用 plan_task new(expectedAttached 传 null),用"动作+对象"式单一标题和详细 scope;先等返回的 canonical 路径再写文件。已有未完成计划时绝不另开新任务;完成或放弃都只能由用户明确指示。未获回答的提问不构成同意。`,
25
+ taskBoundary: `任务身份一次建立:用户批准的追加用 plan_task include(给完整合并后的 scope);update 仅用于改名、身份纠错或对现有交付物的实质修正;discussion 记录明确排除的话题。相关问题、岔题、调研视为延续;对独立交付物,先问是否并入或结束当前计划。生命周期转移必须先于依赖它的写入/命令单独完成。计划文件是指令,不是进度记录。`,
26
+ planWorkflow: `在 Plan 模式完成只读调研并收敛方案:推荐一个方案、列出关键文件、写完整计划文件(含 ## 验证 小节和文末 "## 实现步骤" 编号列表),然后调用 plan_exit 展示审阅。用户接受范围 ≠ 授权实现;不要在讨论未收敛或文件未写盘时调用 plan_exit。`,
27
+ buildWorkflow: `Build 模式:在已批准授权范围内讨论与实现。计划文件受保护不要改写;当前范围以计划元数据为准,修订文件内容需回 Plan 模式。没有当前计划时是普通模式,小改动无需走计划流程。`,
28
+ completionRouting: `完成路由:用户明确说整计划完成 → plan_complete;明确指认某一步完成 → plan_step_control acknowledge;语义含糊的"完成"先澄清。工作与必需检查全部通过前不要调用 plan_complete;仍有未竟事项用 plan_set_outcome(awaiting_validation / blocked / waiting_for_input / still_working),绝不因空闲推断成功。`,
29
+ verificationPolicy: `验证策略:按计划 ## 验证 小节用最小充分检查,然后停止。优先一个聚焦的行为验证(有可观察结果);构建/类型检查不能单独证明运行时行为。只为具体风险或明确要求增加检查。如实报告通过/受阻/未执行的检查,绝不弱化或谎报。只能由用户执行的必要验证:用 plan_set_outcome awaiting_validation 记录精确操作步骤,保持计划开放等用户回报;可选反馈不阻塞完成。`,
30
+ stepActive: (n, total, text) =>
31
+ `分步执行中:只实现第 ${n}/${total} 步 —— ${text}\n完成本步及其适用检查后调用 plan_step_complete(摘要必填);不要开始后续步骤,不要改计划文件。依赖后续步骤的检查要显式说明推迟,不得谎报通过。`,
32
+ stepReady: (n, total, text) =>
33
+ `第 ${n}/${total} 步已就绪等待批准:${text}\n用户说"继续/proceed"之类时调用 plan_step_control start 开始本步;在批准前不要做项目改动。`,
34
+ stepPaused: `分步执行已暂停:保留进度但没有任何实现授权。用户明确要求恢复后再继续(plan_step_control resume 由其自然语言指令触发)。`,
35
+ awaitingValidation: `计划处于"待验证":实现已完成,正在等待用户执行必要验证。不要继续改动;用户回报通过后(或明确说标记完成)才调用 plan_complete。`,
36
+ };
37
+
38
+ const EN: PromptPack = {
39
+ planReadonly: `Plan mode active: observe, analyze, discuss, and plan only. The only permitted write is saving the complete plan to the current plan file (finalization or explicitly requested revision). Answer normally during research; do not write files or call plan_exit mid-discussion.`,
40
+ taskSelection: `Mode changes do not create tasks. With no current plan, call plan_task new (expectedAttached: null) only when the user requests a planning deliverable or accepts a concrete proposed change, with one action-led title and detailed scope; wait for the returned canonical path before writing. Never start another task while one is unfinished. Unanswered questions grant no consent.`,
41
+ taskBoundary: `Establish identity once: plan_task include for user-approved additions (complete merged scope); update only for renames, identity corrections, or material constraints; discussion for explicit exclusions. Questions, tangents, and research assume continuity. Lifecycle transitions finish before dependent writes or shell calls. Plan Markdown is instructions, not progress.`,
42
+ planWorkflow: `In Plan mode, finish read-only investigation, recommend one approach with key files, write the complete plan file (including a "## Verification" section and a numbered "## Implementation Steps" list), then call plan_exit for review. Accepting scope does not authorize implementation. Never call plan_exit before the file is saved or while discussion should continue.`,
43
+ buildWorkflow: `Build mode: discuss and implement within approved authorization. The plan file is protected; current scope lives in plan metadata. Without a current plan this is ordinary mode — small fixes need no plan.`,
44
+ completionRouting: `Completion routing: explicit whole-plan completion → plan_complete; an identified step → plan_step_control acknowledge; clarify ambiguous bare completion. Never call plan_complete before all approved work and required checks pass; otherwise use plan_set_outcome (awaiting_validation / blocked / waiting_for_input / still_working). Never infer success from idleness.`,
45
+ verificationPolicy: `Verification: follow the plan's ## Verification section with the smallest sufficient check, then stop. Prefer one focused behavioral check with an observable result; build/type-check alone does not prove runtime behavior. Add checks only for concrete risks or explicit requirements. Report passed, blocked, and unperformed checks truthfully. For essential user-only checks use plan_set_outcome awaiting_validation with the exact action and keep the plan open until the user reports back; optional feedback never blocks completion.`,
46
+ stepActive: (n, total, text) =>
47
+ `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
+ 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.`,
50
+ stepPaused: `Step execution is paused: progress is retained but there is no implementation authority. Resume only on the user's explicit instruction.`,
51
+ 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
+ };
53
+
54
+ export function prompts(lang: Lang): PromptPack {
55
+ return lang === "en" ? EN : ZH;
56
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 持久化 schema:版本化会话条目的解码与恢复。
3
+ *
4
+ * 对比参考项目的改进:状态是结构化 data(非 JSON 字符串);
5
+ * decode 集中在纯函数里,一次校验完整结构;不做 legacy 兼容。
6
+ */
7
+ import {
8
+ type Execution,
9
+ initialState,
10
+ type PlanOutcome,
11
+ type State,
12
+ type Step,
13
+ type StepStatus,
14
+ } from "./state.ts";
15
+
16
+ export const STATE_ENTRY_TYPE = "pi-plan-build:state";
17
+
18
+ const stepStatusValues = [
19
+ "pending",
20
+ "ready",
21
+ "active",
22
+ "completed",
23
+ "skipped",
24
+ ] as const;
25
+
26
+ function isRecord(v: unknown): v is Record<string, unknown> {
27
+ return typeof v === "object" && v !== null;
28
+ }
29
+
30
+ /** 解码条目 data;返回 undefined 表示损坏(外层进入只读保护模式)。 */
31
+ export function decodeState(data: unknown): State | undefined {
32
+ if (!isRecord(data)) return undefined;
33
+ // 手写最小校验(TypeBox 运行时校验器依赖 value 包,不引额外依赖)
34
+ if (data.version !== 2) return undefined;
35
+ if (data.mode !== "plan" && data.mode !== "build") return undefined;
36
+ if (data.plan === null) {
37
+ if (data.execution !== null) return undefined;
38
+ return { version: 2, mode: data.mode, plan: null, execution: null };
39
+ }
40
+ const p = data.plan;
41
+ if (!isRecord(p)) return undefined;
42
+ if (
43
+ typeof p.seq !== "number" ||
44
+ typeof p.title !== "string" ||
45
+ typeof p.scope !== "string" ||
46
+ typeof p.path !== "string" ||
47
+ typeof p.saved !== "boolean"
48
+ )
49
+ return undefined;
50
+ if (p.seq < 1 || !p.title || !p.path) return undefined;
51
+ const outcome = decodeOutcome(p.outcome);
52
+ if (p.outcome !== undefined && !outcome) return undefined;
53
+ if (data.execution === null) {
54
+ return {
55
+ version: 2,
56
+ mode: data.mode,
57
+ plan: {
58
+ seq: p.seq,
59
+ title: p.title,
60
+ scope: p.scope,
61
+ path: p.path,
62
+ saved: p.saved,
63
+ ...(outcome ? { outcome } : {}),
64
+ },
65
+ execution: null,
66
+ };
67
+ }
68
+ const execution = decodeExecution(data.execution);
69
+ if (!execution) return undefined;
70
+ return {
71
+ version: 2,
72
+ mode: data.mode,
73
+ plan: {
74
+ seq: p.seq,
75
+ title: p.title,
76
+ scope: p.scope,
77
+ path: p.path,
78
+ saved: p.saved,
79
+ ...(outcome ? { outcome } : {}),
80
+ },
81
+ execution,
82
+ };
83
+ }
84
+
85
+ function decodeOutcome(v: unknown): PlanOutcome | undefined {
86
+ if (v === undefined) return undefined;
87
+ if (!isRecord(v)) return undefined;
88
+ if (
89
+ v.kind === "awaiting_validation" &&
90
+ typeof v.userAction === "string" &&
91
+ v.userAction
92
+ ) {
93
+ return { kind: "awaiting_validation", userAction: v.userAction };
94
+ }
95
+ if (
96
+ (v.kind === "blocked" ||
97
+ v.kind === "waiting_for_input" ||
98
+ v.kind === "still_working") &&
99
+ typeof v.reason === "string" &&
100
+ v.reason
101
+ ) {
102
+ return { kind: v.kind, reason: v.reason };
103
+ }
104
+ return undefined;
105
+ }
106
+
107
+ function decodeExecution(v: unknown): Execution | null | undefined {
108
+ if (v === null) return null;
109
+ if (!isRecord(v) || !Array.isArray(v.steps) || typeof v.paused !== "boolean")
110
+ return undefined;
111
+ const steps: Step[] = [];
112
+ for (const raw of v.steps) {
113
+ if (!isRecord(raw)) return undefined;
114
+ if (typeof raw.n !== "number" || typeof raw.text !== "string")
115
+ return undefined;
116
+ const status = raw.status as StepStatus;
117
+ if (!stepStatusValues.includes(status)) return undefined;
118
+ steps.push({
119
+ n: raw.n,
120
+ text: raw.text,
121
+ status,
122
+ ...(typeof raw.summary === "string" ? { summary: raw.summary } : {}),
123
+ });
124
+ }
125
+ if (steps.length === 0) return undefined;
126
+ return { steps, paused: v.paused };
127
+ }
128
+
129
+ /** 恢复:扫描分支条目取最新有效状态。 */
130
+ export function restoreFromBranch(
131
+ entries: readonly { customType?: string; data?: unknown }[],
132
+ ): State {
133
+ let restored: State | undefined;
134
+ for (const entry of entries) {
135
+ if (entry.customType !== STATE_ENTRY_TYPE) continue;
136
+ const s = decodeState(entry.data);
137
+ if (s) restored = s;
138
+ }
139
+ return restored ?? initialState;
140
+ }