@wbline/pi-plan-build 0.0.9 → 0.1.0

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/src/core/state.ts CHANGED
@@ -15,7 +15,7 @@ export type PlanOutcome =
15
15
  | { kind: "blocked" | "waiting_for_input" | "still_working"; reason: string };
16
16
 
17
17
  export interface PlanMeta {
18
- /** 乐观并发代号:每次结构转移 +1,工具调用必须携带当前值。 */
18
+ /** 乐观并发代号:每次结构转移(改名/追加范围/排除/记录排除话题)+1,工具调用必须携带当前值。 */
19
19
  seq: number;
20
20
  title: string;
21
21
  /** 完整合并范围(含用户批准的追加)。 */
@@ -24,6 +24,8 @@ export interface PlanMeta {
24
24
  path: string;
25
25
  /** Markdown 是否已写盘。 */
26
26
  saved: boolean;
27
+ /** 已记录的排除话题(plan.exclude 追加;持久化并注入 context)。 */
28
+ excludes?: string[];
27
29
  outcome?: PlanOutcome;
28
30
  /** 完成时的备注摘要。 */
29
31
  summary?: string;
@@ -67,6 +69,7 @@ export const initialState: State = {
67
69
  /** 转移事件:所有合法状态变化。 */
68
70
  export type Transition =
69
71
  | { t: "mode.set"; mode: Mode }
72
+ | { t: "state.reset" }
70
73
  | { t: "plan.create"; title: string; scope: string; path: string }
71
74
  | { t: "plan.title"; title: string }
72
75
  | { t: "plan.scope.append"; addition: string; note?: string }
@@ -168,6 +171,15 @@ export function transition(prev: State, ev: Transition): TransitionResult {
168
171
  return { state: s };
169
172
  }
170
173
 
174
+ case "state.reset": {
175
+ // 只读保护(状态损坏)的逃生门:丢弃计划元数据回到初始状态。
176
+ // 计划文件本体不受影响;分步执行进度与未完成结局一并丢弃。
177
+ return {
178
+ state: initialState,
179
+ note: "扩展状态已重置(回到 build 模式,无计划)",
180
+ };
181
+ }
182
+
171
183
  case "plan.create": {
172
184
  if (s.mode !== "plan")
173
185
  throw new TransitionError(
@@ -193,13 +205,21 @@ export function transition(prev: State, ev: Transition): TransitionResult {
193
205
  const p = requirePlan(s);
194
206
  if (!ev.title.trim()) throw new TransitionError("标题不能为空。");
195
207
  p.title = ev.title.trim();
208
+ p.seq += 1;
196
209
  return { state: s };
197
210
  }
198
211
 
199
212
  case "plan.scope.append": {
200
213
  const p = requirePlan(s);
201
214
  if (!ev.addition.trim()) throw new TransitionError("追加范围不能为空。");
215
+ // 幂等:同一追加内容已在范围内则忽略(seq 不动),防重复调用污染 scope
216
+ if (p.scope.includes(ev.addition.trim()))
217
+ return {
218
+ state: prev,
219
+ modelNote: "该追加内容已在范围内,忽略重复追加(seq 未变)。",
220
+ };
202
221
  p.scope = `${p.scope}\n\n## 追加范围${ev.note ? `(${ev.note})` : "(用户批准)"}\n${ev.addition.trim()}`;
222
+ p.seq += 1;
203
223
  if (p.outcome) p.outcome = undefined; // 范围变化使旧结局失效
204
224
  return {
205
225
  state: s,
@@ -208,8 +228,14 @@ export function transition(prev: State, ev: Transition): TransitionResult {
208
228
  }
209
229
 
210
230
  case "plan.exclude": {
211
- requirePlan(s);
212
- return { state: s, modelNote: `已记录排除话题:${ev.topic}` };
231
+ const p = requirePlan(s);
232
+ if (!ev.topic.trim()) throw new TransitionError("排除话题不能为空。");
233
+ const topic = ev.topic.trim();
234
+ if (p.excludes?.includes(topic))
235
+ return { state: prev, modelNote: `已排除过:${topic}(忽略重复)。` };
236
+ p.excludes = [...(p.excludes ?? []), topic];
237
+ p.seq += 1;
238
+ return { state: s, modelNote: `已记录排除话题:${topic}` };
213
239
  }
214
240
 
215
241
  case "plan.saved": {
@@ -268,13 +294,28 @@ export function transition(prev: State, ev: Transition): TransitionResult {
268
294
  (x) => x.status === "ready" || x.status === "active",
269
295
  );
270
296
  if (!cur) throw new TransitionError("没有就绪的步骤。");
271
- if (cur.status === "active") return { state: prev };
297
+ if (cur.status === "active") {
298
+ // 连跑中的当前步再 start:仅 advance:"one" 生效(显式撤回连跑授权),否则幂等
299
+ if (ev.advance === "one" && ex.auto) {
300
+ ex.auto = false;
301
+ return {
302
+ state: s,
303
+ note: `第 ${cur.n}/${ex.steps.length} 步进行中;连跑授权已撤回,后续步恢复逐个批准`,
304
+ };
305
+ }
306
+ return { state: prev };
307
+ }
272
308
  cur.status = "active";
273
309
  if (ev.advance === "all") ex.auto = true;
310
+ else if (ev.advance === "one") ex.auto = false; // 显式单步 = 撤回连跑授权
274
311
  return {
275
312
  state: s,
276
313
  note: `第 ${cur.n}/${ex.steps.length} 步开始${
277
- ev.advance === "all" ? "(已授权连跑,后续步自动推进)" : ""
314
+ ev.advance === "all"
315
+ ? "(已授权连跑,后续步自动推进)"
316
+ : ex.auto
317
+ ? "(保持连跑授权)"
318
+ : "(连跑授权已撤回,后续步恢复逐个批准)"
278
319
  }`,
279
320
  };
280
321
  }
package/src/core/steps.ts CHANGED
@@ -7,8 +7,10 @@
7
7
  */
8
8
 
9
9
  const HEADING_RE =
10
- /^#{1,4}\s*(?:implementation\s+steps?|实施步骤|实现步骤|步骤)\s*:?\s*$/i;
10
+ /^#{1,4}\s*(?:implementation\s+steps?|实施步骤|实现步骤)\s*:?\s*$/i;
11
11
  const NEXT_HEADING_RE = /^#{1,4}\s+/;
12
+ // 节名收紧:只认约定写法(实现/实施/Implementation Steps),裸"步骤"会误匹配
13
+ // "## 设计步骤"/"## 验证步骤"等用户自定义小节;指引文本已列出允许的节名。
12
14
  // checkbox 分支必须先于裸短横线分支,否则 "- [ ] x" 会被短横线分支吃掉标记
13
15
  const ITEM_RE = /^(?:[-*]\s+\[\s?]\s+|\d+[.)]\s+|-+\s+)(\S.*?)\s*$/;
14
16
 
@@ -19,15 +21,8 @@ export interface StepParseResult {
19
21
  }
20
22
 
21
23
  export function parseSteps(plan: string): StepParseResult {
22
- const lines = plan.split(/\r?\n/);
23
- let heading = -1;
24
- for (let i = 0; i < lines.length; i++) {
25
- if (HEADING_RE.test((lines[i] ?? "").trim())) {
26
- heading = i;
27
- break;
28
- }
29
- }
30
- if (heading < 0) {
24
+ const entries = stepEntries(plan);
25
+ if (!entries) {
31
26
  return {
32
27
  steps: [],
33
28
  error:
@@ -36,12 +31,8 @@ export function parseSteps(plan: string): StepParseResult {
36
31
  }
37
32
  const steps: string[] = [];
38
33
  const seen = new Set<string>();
39
- for (let i = heading + 1; i < lines.length; i++) {
40
- const line = lines[i] ?? "";
41
- if (NEXT_HEADING_RE.test(line.trim())) break;
42
- const m = ITEM_RE.exec(line.trim());
43
- if (!m) continue;
44
- const text = (m[1] ?? "").replace(/\s+/g, " ").trim();
34
+ for (const e of entries) {
35
+ const text = e.text;
45
36
  if (!text) continue;
46
37
  const key = text.toLowerCase();
47
38
  if (seen.has(key)) continue; // 重复步骤去重而非报错
@@ -58,12 +49,17 @@ export function parseSteps(plan: string): StepParseResult {
58
49
  return { steps };
59
50
  }
60
51
 
61
- /** 修订文件中的第 n 步文本(1 基),返回替换后的全文;失败返回 null。 */
62
- export function reviseStepInMarkdown(
63
- plan: string,
64
- n: number,
65
- newText: string,
66
- ): string | null {
52
+ interface StepEntry {
53
+ /** 条目所在行号(plan.split 后的索引)。 */
54
+ lineIndex: number;
55
+ /** 该行的列表标记("1. " / "- [ ] " / "- "),替换时保留。 */
56
+ marker: string;
57
+ /** 条目文本(去标记、折叠空白)。 */
58
+ text: string;
59
+ }
60
+
61
+ /** 与 parseSteps 完全相同的定位规则:找出步骤节内全部条目(不去重)。 */
62
+ function stepEntries(plan: string): StepEntry[] | null {
67
63
  const lines = plan.split(/\r?\n/);
68
64
  let heading = -1;
69
65
  for (let i = 0; i < lines.length; i++) {
@@ -73,20 +69,43 @@ export function reviseStepInMarkdown(
73
69
  }
74
70
  }
75
71
  if (heading < 0) return null;
76
- let index = 0;
72
+ const entries: StepEntry[] = [];
77
73
  for (let i = heading + 1; i < lines.length; i++) {
78
74
  const line = lines[i] ?? "";
79
75
  if (NEXT_HEADING_RE.test(line.trim())) break;
80
- if (!ITEM_RE.test(line.trim())) continue;
76
+ const m = ITEM_RE.exec(line.trim());
77
+ if (!m) continue;
78
+ const marker =
79
+ line
80
+ .trim()
81
+ .match(/^(?:([-*]\s+\[\s?]\s+)|(\d+[.)]\s+)|(-+\s+))/)
82
+ ?.slice(1)
83
+ .find((g) => g !== undefined) ?? "1. ";
84
+ const text = (m[1] ?? "").replace(/\s+/g, " ").trim();
85
+ entries.push({ lineIndex: i, marker, text });
86
+ }
87
+ return entries;
88
+ }
89
+
90
+ /** 修订文件中的第 n 步文本(1 基,与 parseSteps 同一套去重计数),返回替换后的全文;失败返回 null。 */
91
+ export function reviseStepInMarkdown(
92
+ plan: string,
93
+ n: number,
94
+ newText: string,
95
+ ): string | null {
96
+ const entries = stepEntries(plan);
97
+ if (!entries) return null;
98
+ // 与 parseSteps 相同的去重:重复文本只算一步,保证 state 步号与文件行不错位
99
+ const seen = new Set<string>();
100
+ let index = 0;
101
+ for (const e of entries) {
102
+ const key = e.text.toLowerCase();
103
+ if (!e.text || seen.has(key)) continue;
104
+ seen.add(key);
81
105
  index++;
82
106
  if (index === n) {
83
- const marker =
84
- line
85
- .trim()
86
- .match(/^(?:([-*]\s+\[\s?]\s+)|(\d+[.)]\s+)|(-+\s+))/)
87
- ?.slice(1)
88
- .find((g) => g !== undefined) ?? "1. ";
89
- lines[i] = `${marker}${newText}`;
107
+ const lines = plan.split(/\r?\n/);
108
+ lines[e.lineIndex] = `${e.marker}${newText}`;
90
109
  return lines.join("\n");
91
110
  }
92
111
  }
package/src/engine.ts CHANGED
@@ -80,13 +80,27 @@ export class PlanEngine {
80
80
  restore(entries: readonly { customType?: string; data?: unknown }[]): {
81
81
  restored: boolean;
82
82
  corruptEntry?: boolean;
83
+ versionReset?: boolean;
83
84
  } {
84
85
  // 仅"最新"状态条目损坏才视为损坏:更早的坏条目之后若有合法状态,不进入只读保护
85
86
  let restoredState: State | undefined;
86
87
  let corruptAfterLatest = false;
88
+ let versionMismatch = false;
87
89
  for (const entry of entries) {
88
90
  if (entry.customType !== STATE_ENTRY_TYPE || entry.data === undefined)
89
91
  continue;
92
+ // 版本不兼容(未来/未知版本写入的条目):不算损坏,降级重置而非锁死会话
93
+ if (
94
+ typeof entry.data === "object" &&
95
+ entry.data !== null &&
96
+ (entry.data as { version?: unknown }).version !== undefined &&
97
+ (entry.data as { version?: unknown }).version !== 2
98
+ ) {
99
+ versionMismatch = true;
100
+ restoredState = undefined;
101
+ corruptAfterLatest = false;
102
+ continue;
103
+ }
90
104
  const decoded = decodeState(entry.data);
91
105
  if (decoded) {
92
106
  restoredState = decoded;
@@ -100,18 +114,20 @@ export class PlanEngine {
100
114
  return {
101
115
  restored: restoredState !== undefined,
102
116
  corruptEntry: corruptAfterLatest,
117
+ versionReset: versionMismatch && restoredState === undefined,
103
118
  };
104
119
  }
105
120
 
106
121
  apply(ev: Transition, ctx?: ExtensionContext): TransitionResult {
107
122
  const c = ctx ?? this.ctx;
108
- if (this.corrupt)
123
+ if (this.corrupt && ev.t !== "state.reset")
109
124
  throw new TransitionError(
110
125
  "持久化状态损坏,处于只读保护。请 /reload 或手工修复后重试。",
111
126
  );
112
127
  const prev = this.state;
113
128
  const result = transition(this.state, ev);
114
129
  this.state = result.state;
130
+ if (ev.t === "state.reset") this.corrupt = false; // 逃生门:重置即解除只读保护
115
131
  if (result.state !== prev) this.persist(); // 幂等转移不写重复条目
116
132
  this.refreshUI(c, result.note);
117
133
  this.lastArchive = undefined;
@@ -141,16 +157,32 @@ export class PlanEngine {
141
157
  };
142
158
  return;
143
159
  }
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");
160
+ if (
161
+ ev.t === "exec.step.complete" ||
162
+ ev.t === "exec.step.ack" ||
163
+ ev.t === "exec.step.skip"
164
+ ) {
165
+ // finishStep 收尾:complete 的步是转移前 active 步;ack/skip 可能是 ready 步
166
+ const cur =
167
+ ev.t === "exec.step.complete"
168
+ ? prev.execution?.steps.find((x) => x.status === "active")
169
+ : prev.execution?.steps.find(
170
+ (x) => x.status === "ready" || x.status === "active",
171
+ );
172
+ const verb = ev.t === "exec.step.skip" ? "最后处理(跳过)" : "最后完成";
147
173
  this.lastArchive = {
148
174
  path: plan.path,
149
175
  ok: archivePlanFile(
150
176
  plan.path,
151
177
  "已完成",
152
178
  cur
153
- ? `最后完成:第 ${cur.n} 步${ev.summary ? `:${ev.summary}` : ""}`
179
+ ? `${verb}:第 ${cur.n} 步${
180
+ ev.t === "exec.step.skip"
181
+ ? ""
182
+ : ev.summary
183
+ ? `:${ev.summary}`
184
+ : ""
185
+ }`
154
186
  : undefined,
155
187
  ),
156
188
  };
@@ -172,10 +204,16 @@ export class PlanEngine {
172
204
  private persist(): void {
173
205
  // 桥接契约:pi-acp-jetbrain 读 data.selectedMode 判断当前模式;
174
206
  // decodeState 只挑已知字段,附加键不影响恢复。
175
- this.pi.appendEntry(STATE_ENTRY_TYPE, {
176
- ...this.state,
177
- selectedMode: this.state.mode,
178
- });
207
+ try {
208
+ this.pi.appendEntry(STATE_ENTRY_TYPE, {
209
+ ...this.state,
210
+ selectedMode: this.state.mode,
211
+ });
212
+ } catch (e) {
213
+ // 持久化失败不回滚内存状态(内存是最新意图);恢复时会回到上一
214
+ // 持久化状态,差异由用户重放。吞掉异常避免中断工具调用链。
215
+ console.error("[pi-plan-build] 状态持久化失败:", e);
216
+ }
179
217
  }
180
218
 
181
219
  refreshUI(ctx?: ExtensionContext, note?: string): void {
@@ -219,14 +257,20 @@ export function nextPlanPath(cwd: string, title: string): string {
219
257
  }
220
258
  }
221
259
  const fallback = path.join(dir, `${base}-${Date.now()}.md`);
222
- fs.writeFileSync(fallback, "", { flag: "wx" });
223
- return fallback;
260
+ try {
261
+ fs.writeFileSync(fallback, "", { flag: "wx" });
262
+ return fallback;
263
+ } catch {
264
+ throw new TransitionError(
265
+ `无法分配计划文件(${dir} 下同名占位冲突):请更换标题或清理 plans 目录。`,
266
+ );
267
+ }
224
268
  }
225
269
 
226
- /** 本地时刻戳:20251008-1432 */
270
+ /** 本地时刻戳:20251008-143205(秒级,降低同分钟并发分配冲突面) */
227
271
  function formatStamp(d: Date): string {
228
272
  const p = (n: number) => String(n).padStart(2, "0");
229
- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
273
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
230
274
  }
231
275
 
232
276
  /** 标题 → 文件名安全 slug:去非法字符、空白折叠为 -、截 40 字符、去首尾点。 */
package/src/index.ts CHANGED
@@ -13,14 +13,14 @@ import fs from "node:fs";
13
13
  import type {
14
14
  ExtensionAPI,
15
15
  ExtensionContext,
16
- Theme,
17
16
  } from "@earendil-works/pi-coding-agent";
18
- import { Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
17
+ import { Key, matchesKey } from "@earendil-works/pi-tui";
19
18
  import { configPath, loadConfig, saveConfig } from "./config.ts";
20
19
  import { type Mode, type State, statusLine } from "./core/state.ts";
21
20
  import { PlanEngine } from "./engine.ts";
22
21
  import { wireLifecycle } from "./lifecycle.ts";
23
22
  import { registerAllTools } from "./tools/index.ts";
23
+ import { selectWithDescriptions } from "./ui.ts";
24
24
 
25
25
  export default function planBuild(pi: ExtensionAPI): void {
26
26
  const loaded = loadConfig();
@@ -86,22 +86,66 @@ export default function planBuild(pi: ExtensionAPI): void {
86
86
 
87
87
  // ============ 菜单 ============
88
88
 
89
- type MenuAction = "toggle" | "status" | "done" | "abandon" | "lang" | "config";
89
+ type MenuAction =
90
+ | "toggle"
91
+ | "status"
92
+ | "done"
93
+ | "abandon"
94
+ | "lang"
95
+ | "config"
96
+ | "reset";
90
97
 
91
- function buildMenuItems(s: State): { id: MenuAction; label: string }[] {
92
- const items: { id: MenuAction; label: string }[] = [
98
+ function buildMenuItems(
99
+ s: State,
100
+ corrupt = false,
101
+ ): { id: MenuAction; label: string; description?: string }[] {
102
+ const items: {
103
+ id: MenuAction;
104
+ label: string;
105
+ description?: string;
106
+ }[] = [
93
107
  {
94
108
  id: "toggle",
95
109
  label: `切换模式 → ${s.mode === "plan" ? "build" : "plan"}`,
110
+ description:
111
+ s.mode === "plan"
112
+ ? "进入实现模式;plan 模式的只读限制解除"
113
+ : "切回只读规划模式:文件写入被拦截,只调研讨论",
114
+ },
115
+ {
116
+ id: "status",
117
+ label: "查看状态",
118
+ description: "显示当前模式、计划范围与分步进度",
96
119
  },
97
- { id: "status", label: "查看状态" },
98
120
  ];
121
+ if (corrupt)
122
+ items.push({
123
+ id: "reset",
124
+ label: "重置扩展状态(解锁只读保护,丢弃计划元数据)",
125
+ description: "状态条目损坏时的逃生门;计划文件本体不受影响",
126
+ });
99
127
  if (s.plan) {
100
- items.push({ id: "done", label: "标记计划完成" });
101
- items.push({ id: "abandon", label: "放弃计划…" });
128
+ items.push({
129
+ id: "done",
130
+ label: "标记计划完成",
131
+ description: "确认全部工作与检查通过后收尾,文件写入完成状态块",
132
+ });
133
+ items.push({
134
+ id: "abandon",
135
+ label: "放弃计划…",
136
+ description: "记录放弃原因并收尾;计划文件保留在原处",
137
+ });
102
138
  }
103
- items.push({ id: "lang", label: "提示词语言 → 中/EN 切换" });
104
- items.push({ id: "config", label: "设置文件…" });
139
+ items.push({
140
+ id: "lang",
141
+ label: "提示词语言 → 中/EN 切换",
142
+ description: "提示词与运行时文案立即切换;工具描述重启后生效",
143
+ });
144
+ items.push({
145
+ id: "config",
146
+ label: "设置文件…",
147
+ description: "查看 pi-plan-build.json 的路径与当前内容",
148
+ });
105
149
  return items;
106
150
  }
107
151
 
@@ -110,20 +154,9 @@ async function openMenu(
110
154
  ctx: ExtensionContext,
111
155
  ): Promise<void> {
112
156
  if (!ctx.hasUI) return; // print/json 模式:无交互面
113
- if (ctx.mode === "tui") {
114
- const action = await ctx.ui.custom<MenuAction | undefined>(
115
- (_tui, theme, _kb, done) => new MenuComponent(theme, engine.state, done),
116
- );
117
- await runAction(engine, ctx, action);
118
- return;
119
- }
120
- // RPC:原生 select 单次选择
121
- const items = buildMenuItems(engine.state);
122
- const choice = await ctx.ui.select(
123
- "plan/build 菜单",
124
- items.map((x) => x.label),
125
- );
126
- const selected = items.find((x) => x.label === choice);
157
+ const items = buildMenuItems(engine.state, engine.corrupt);
158
+ const idx = await selectWithDescriptions(ctx, "plan/build 菜单", items);
159
+ const selected = idx === undefined ? undefined : items[idx];
127
160
  if (selected) await runAction(engine, ctx, selected.id);
128
161
  }
129
162
 
@@ -182,6 +215,15 @@ async function runAction(
182
215
  showPanel(ctx, `${p}\n\n${body}`);
183
216
  return;
184
217
  }
218
+ case "reset": {
219
+ // 只读保护逃生门:丢弃计划元数据回初始状态(计划文件本体不受影响)
220
+ const r = engine.tryApply({ t: "state.reset" }, ctx);
221
+ ctx.ui.notify(
222
+ "error" in r ? r.error : "扩展状态已重置。",
223
+ "error" in r ? "error" : "info",
224
+ );
225
+ return;
226
+ }
185
227
  }
186
228
  }
187
229
 
@@ -201,44 +243,6 @@ function statusBody(s: State): string {
201
243
  return lines.join("\n");
202
244
  }
203
245
 
204
- /** TUI 菜单组件:↑↓ 选择、Enter 执行、Esc 关闭(执行后自动关闭)。 */
205
- class MenuComponent {
206
- private selected = 0;
207
- constructor(
208
- private readonly theme: Theme,
209
- private readonly state: State,
210
- private readonly done: (action: MenuAction | undefined) => void,
211
- ) {}
212
-
213
- handleInput(data: string): void {
214
- const count = buildMenuItems(this.state).length;
215
- if (matchesKey(data, "escape")) this.done(undefined);
216
- else if (matchesKey(data, "up"))
217
- this.selected = (this.selected - 1 + count) % count;
218
- else if (matchesKey(data, "down"))
219
- this.selected = (this.selected + 1) % count;
220
- else if (matchesKey(data, "return"))
221
- this.done(buildMenuItems(this.state)[this.selected]?.id);
222
- }
223
-
224
- render(width: number): string[] {
225
- const th = this.theme;
226
- const items = buildMenuItems(this.state);
227
- const lines: string[] = ["", ` ${th.fg("accent", "plan/build")}`, ""];
228
- items.forEach((item, i) => {
229
- const row =
230
- i === this.selected
231
- ? `${th.fg("accent", "❯ ")}${th.fg("accent", item.label)}`
232
- : ` ${item.label}`;
233
- lines.push(truncateToWidth(` ${row}`, width));
234
- });
235
- lines.push("", ` ${th.fg("dim", "↑↓ 选择 · Enter 执行 · Esc 关闭")}`, "");
236
- return lines;
237
- }
238
-
239
- invalidate() {}
240
- }
241
-
242
246
  function showPanel(ctx: ExtensionContext, body: string): void {
243
247
  if (ctx.mode === "tui") {
244
248
  void ctx.ui.custom<void>((_tui, _theme, _kb, done) => {
package/src/lifecycle.ts CHANGED
@@ -9,6 +9,7 @@ import { buildContextBlock, injectContext } from "./context.ts";
9
9
  import {
10
10
  classifyToolCall,
11
11
  decideFileMutation,
12
+ extractDeletionTargets,
12
13
  extractMutationTargets,
13
14
  LIFECYCLE_TOOLS,
14
15
  planTaskPendingInLastAssistant,
@@ -38,7 +39,7 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
38
39
  customType?: string;
39
40
  data?: unknown;
40
41
  }[];
41
- const { corruptEntry } = engine.restore(entries);
42
+ const { corruptEntry, versionReset } = engine.restore(entries);
42
43
  if (corruptEntry) {
43
44
  engine.corrupt = true;
44
45
  ctx.ui.notify(
@@ -46,6 +47,12 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
46
47
  "error",
47
48
  );
48
49
  }
50
+ if (versionReset) {
51
+ ctx.ui.notify(
52
+ "计划状态由不兼容版本写入,已重置为默认状态;计划文件不受影响,可用 plan_task new fromFile 恢复。",
53
+ "warning",
54
+ );
55
+ }
49
56
  engine.refreshUI(ctx);
50
57
  });
51
58
 
@@ -81,6 +88,26 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
81
88
  engine.armReconciliation(event.toolName);
82
89
  return;
83
90
  }
91
+ // 计划文件在任何模式下都不可删除(收尾走 plan_complete / plan_task abandon)
92
+ const planPathForDelete = s.plan?.path ? realpathLike(s.plan.path) : null;
93
+ if (planPathForDelete) {
94
+ const deletions = extractDeletionTargets(
95
+ event.toolName,
96
+ event.input,
97
+ ctx.cwd,
98
+ ).map(realpathLike); // 与计划路径同过 symlink 解析,链接路径不漏拦
99
+ // Windows 大小写不敏感,其余平台严格相等(与 decideFileMutation 同规则)
100
+ const samePath = (a: string, b: string) =>
101
+ process.platform === "win32"
102
+ ? a.toLowerCase() === b.toLowerCase()
103
+ : a === b;
104
+ if (deletions.some((d) => samePath(d, planPathForDelete)))
105
+ return {
106
+ block: true,
107
+ reason:
108
+ "计划文件不可删除。收尾请调用 plan_complete(完成)或 plan_task abandon(放弃,文件保留);修订请回 plan 模式。",
109
+ };
110
+ }
84
111
  if (s.mode === "build" && !engine.config.protectPlanFile) return; // 用户关闭保护
85
112
  const planPath = s.plan?.path ? realpathLike(s.plan.path) : null;
86
113
  const raw = extractMutationTargets(event.toolName, event.input, ctx.cwd);
@@ -123,7 +150,7 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
123
150
  s.mode === "build" &&
124
151
  engine.config.protectPlanFile &&
125
152
  s.plan?.saved &&
126
- targets === undefined
153
+ (targets === undefined || targets.length === 0)
127
154
  )
128
155
  engine.armReconciliation(event.toolName);
129
156
  });
@@ -155,10 +182,18 @@ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
155
182
  return;
156
183
  if (!ctx.hasUI) return;
157
184
  engine.validationAsked = true; // 只问一次;重新结算(plan_set_outcome/plan_complete)会重置
158
- const passed = await ctx.ui.confirm(
159
- "上一轮计划的必需验证通过了吗?",
160
- outcome.userAction,
161
- );
185
+ let passed: boolean;
186
+ try {
187
+ passed = await ctx.ui.confirm(
188
+ "上一轮计划的必需验证通过了吗?",
189
+ outcome.userAction,
190
+ );
191
+ } catch (e) {
192
+ // UI 异常时回滚问询标记,下一条消息重试(否则问询被永久跳过)
193
+ engine.validationAsked = false;
194
+ console.error("[pi-plan-build] 验证问询弹窗失败:", e);
195
+ return;
196
+ }
162
197
  if (passed && engine.state.plan?.outcome?.kind === "awaiting_validation") {
163
198
  const r = engine.tryApply({ t: "plan.complete" }, ctx);
164
199
  ctx.ui.notify(
@@ -48,17 +48,17 @@ const ZH: ToolTexts = {
48
48
  planExit:
49
49
  "plan 模式终点:完整计划写盘且讨论收敛后调用。展示计划并请求实现授权(本会话连续 / 分步 / 留在 plan);无交互 UI 时跳过审批门自动选本会话连续实现。文件未写盘或讨论未收敛时不要调用。",
50
50
  stepControl:
51
- '分步执行控制,一次一个转移:start 批准就绪步(advance: "all" 一次授权连跑剩余步骤,遇阻塞才停);acknowledge 指认用户声明的已完成步(无需先 start);skip 跳过;revise 修订未完成步文本(同步计划文件);pause/resume 暂停恢复;cancel 取消分步(计划保留)。',
51
+ '分步执行控制,一次一个转移:start 批准就绪步(advance: "all" 一次授权连跑剩余步骤,遇阻塞才停;advance: "one" 撤回连跑授权,后续步恢复逐个批准);acknowledge 指认用户声明的已完成步(无需先 start);skip 跳过;revise 修订未完成步文本(同步计划文件);pause/resume 暂停恢复;cancel 取消分步(计划保留)。',
52
52
  stepAckSummary: "acknowledge 的完成摘要",
53
53
  stepAdvance:
54
- 'start 专用:默认只开始当前步;用户明确要求连续执行(如"剩下的都做完""全部继续")时传 "all",一次授权连跑剩余步骤,遇到 plan_set_outcome 记录的阻塞才停。',
54
+ 'start 专用:默认只开始当前步;用户明确要求连续执行(如"剩下的都做完""全部继续")时传 "all",一次授权连跑剩余步骤,遇到 plan_set_outcome 记录的阻塞才停;用户要收回连跑(如"还是一步步来")时传 "one" 撤回授权。',
55
55
  stepReviseStep: "revise 的步骤号(默认当前就绪步)",
56
56
  stepReviseText: "revise 的新步骤文本",
57
57
  stepComplete:
58
58
  "完成当前进行中的分步(仅在本步实现与适用检查完成后调用)。完成立即生效、不等待验收,绝不开始下一步。",
59
59
  stepSummary: "本步实现与验证的简明摘要",
60
60
  planComplete:
61
- "标记整个计划完成:仅在全部批准工作与必需检查通过、或用户明确指示时调用(分步执行进行中也允许,会如实收尾)。绝不虚构未执行的检查。",
61
+ "标记整个计划完成:仅在全部批准工作与必需检查通过、或用户明确指示时调用(有交互 UI 时会弹确认门,用户拒绝则计划保持开放;分步执行进行中也允许,会如实收尾)。绝不虚构未执行的检查。",
62
62
  completeSummary: "事实性完成摘要(可选),随历史记录保留",
63
63
  planOutcome:
64
64
  "记录未完成结局并保持计划开放:awaiting_validation(userAction 必填:用户要执行的精确验证步骤)、blocked / waiting_for_input / still_working(reason 必填)。绝不因空闲推断成功。",
@@ -91,17 +91,17 @@ const EN: ToolTexts = {
91
91
  planExit:
92
92
  "plan-mode endpoint: call once the full plan is saved and the discussion has converged. Presents the plan and asks for implementation authorization (this session / step-by-step / stay in plan); without interactive UI the gate is skipped and this-session implementation is auto-approved. Never call with an unsaved file or an unsettled discussion.",
93
93
  stepControl:
94
- 'Step execution control, one transition at a time: start approves the ready step (advance: "all" authorizes auto-run of the remaining steps, stopping only on blockers); acknowledge records a step the user declared done (no start needed); skip; revise rewrites an unfinished step (syncs the plan file); pause/resume; cancel (plan retained).',
94
+ 'Step execution control, one transition at a time: start approves the ready step (advance: "all" authorizes auto-run of the remaining steps, stopping only on blockers; advance: "one" revokes auto-run so later steps require approval again); acknowledge records a step the user declared done (no start needed); skip; revise rewrites an unfinished step (syncs the plan file); pause/resume; cancel (plan retained).',
95
95
  stepAckSummary: "completion summary for acknowledge",
96
96
  stepAdvance:
97
- 'start only: defaults to starting just the current step; pass "all" only when the user explicitly asked for continuous execution (e.g. "do the rest"), authorizing the remaining steps in one go; stops only on blockers recorded via plan_set_outcome.',
97
+ 'start only: defaults to starting just the current step; pass "all" only when the user explicitly asked for continuous execution (e.g. "do the rest"), authorizing the remaining steps in one go; stops only on blockers recorded via plan_set_outcome; pass "one" when the user takes auto-run back (e.g. "go step by step again").',
98
98
  stepReviseStep: "step number for revise (defaults to the current ready step)",
99
99
  stepReviseText: "new step text for revise",
100
100
  stepComplete:
101
101
  "Complete the in-progress step (only after implementing it and running its applicable checks). Takes effect immediately without waiting for acceptance; never starts the next step.",
102
102
  stepSummary: "concise summary of this step's implementation and verification",
103
103
  planComplete:
104
- "Mark the whole plan complete: only after all approved work and required checks pass, or on explicit user instruction (also allowed during step execution; closes out truthfully). Never invent unperformed checks.",
104
+ "Mark the whole plan complete: only after all approved work and required checks pass, or on explicit user instruction (a confirmation dialog appears with interactive UI; if declined the plan stays open; also allowed during step execution, closing out truthfully). Never invent unperformed checks.",
105
105
  completeSummary: "factual completion summary (optional), kept in history",
106
106
  planOutcome:
107
107
  "Record an unfinished outcome and keep the plan open: awaiting_validation (userAction required: the exact validation the user must run), blocked / waiting_for_input / still_working (reason required). Never infer success from idleness.",