@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 +21 -0
- package/README.md +87 -3
- package/package.json +51 -6
- package/src/config.ts +66 -0
- package/src/context.ts +97 -0
- package/src/core/guard.ts +88 -0
- package/src/core/prompts.ts +56 -0
- package/src/core/schema.ts +140 -0
- package/src/core/state.ts +387 -0
- package/src/core/steps.ts +94 -0
- package/src/engine.ts +157 -0
- package/src/index.ts +241 -0
- package/src/lifecycle.ts +88 -0
- package/src/tools/index.ts +16 -0
- package/src/tools/plan-exit.ts +90 -0
- package/src/tools/plan-outcome.ts +120 -0
- package/src/tools/plan-question.ts +80 -0
- package/src/tools/plan-steps.ts +151 -0
- package/src/tools/plan-task.ts +168 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 集中状态机 —— 整个扩展唯一的可变状态与转移逻辑。
|
|
3
|
+
*
|
|
4
|
+
* 设计原则(对比参考项目的改进):
|
|
5
|
+
* - 全部状态收敛在一个不可变 State 对象里,转移只走 transition(),禁止散落闭包变量。
|
|
6
|
+
* - 纯函数:不碰 fs / UI / pi,全部可单测。
|
|
7
|
+
* - 转移函数返回 { state, effects },副作用(持久化、UI、通知)由外层执行。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type Mode = "plan" | "build";
|
|
11
|
+
|
|
12
|
+
/** 未完成结局;awaiting_validation 要求 userAction。 */
|
|
13
|
+
export type PlanOutcome =
|
|
14
|
+
| { kind: "awaiting_validation"; userAction: string }
|
|
15
|
+
| { kind: "blocked" | "waiting_for_input" | "still_working"; reason: string };
|
|
16
|
+
|
|
17
|
+
export interface PlanMeta {
|
|
18
|
+
/** 乐观并发代号:每次结构转移 +1,工具调用必须携带当前值。 */
|
|
19
|
+
seq: number;
|
|
20
|
+
title: string;
|
|
21
|
+
/** 完整合并范围(含用户批准的追加)。 */
|
|
22
|
+
scope: string;
|
|
23
|
+
/** canonical 计划文件绝对路径。 */
|
|
24
|
+
path: string;
|
|
25
|
+
/** Markdown 是否已写盘。 */
|
|
26
|
+
saved: boolean;
|
|
27
|
+
outcome?: PlanOutcome;
|
|
28
|
+
/** 完成时的备注摘要。 */
|
|
29
|
+
summary?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type StepStatus =
|
|
33
|
+
| "pending"
|
|
34
|
+
| "ready"
|
|
35
|
+
| "active"
|
|
36
|
+
| "completed"
|
|
37
|
+
| "skipped";
|
|
38
|
+
|
|
39
|
+
export interface Step {
|
|
40
|
+
n: number;
|
|
41
|
+
text: string;
|
|
42
|
+
status: StepStatus;
|
|
43
|
+
summary?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface Execution {
|
|
47
|
+
steps: Step[];
|
|
48
|
+
paused: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface State {
|
|
52
|
+
version: 2;
|
|
53
|
+
mode: Mode;
|
|
54
|
+
plan: PlanMeta | null;
|
|
55
|
+
execution: Execution | null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const initialState: State = {
|
|
59
|
+
version: 2,
|
|
60
|
+
mode: "build",
|
|
61
|
+
plan: null,
|
|
62
|
+
execution: null,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** 转移事件:所有合法状态变化。 */
|
|
66
|
+
export type Transition =
|
|
67
|
+
| { t: "mode.set"; mode: Mode }
|
|
68
|
+
| { t: "plan.create"; title: string; scope: string; path: string }
|
|
69
|
+
| { t: "plan.title"; title: string }
|
|
70
|
+
| { t: "plan.scope.append"; addition: string; note?: string }
|
|
71
|
+
| { t: "plan.exclude"; topic: string }
|
|
72
|
+
| { t: "plan.saved" }
|
|
73
|
+
| { t: "plan.complete"; summary?: string }
|
|
74
|
+
| { t: "plan.finish"; outcome: PlanOutcome }
|
|
75
|
+
| { t: "plan.abandon"; reason: string }
|
|
76
|
+
| { t: "exec.start"; steps: string[] }
|
|
77
|
+
| { t: "exec.step.start" }
|
|
78
|
+
| { t: "exec.step.complete"; summary?: string }
|
|
79
|
+
| { t: "exec.step.skip" }
|
|
80
|
+
| { t: "exec.step.revise"; n: number; text: string }
|
|
81
|
+
| { t: "exec.pause" }
|
|
82
|
+
| { t: "exec.resume" }
|
|
83
|
+
| { t: "exec.cancel" };
|
|
84
|
+
|
|
85
|
+
/** 转移需要的外部事实校验失败时抛错,消息面向模型。 */
|
|
86
|
+
export class TransitionError extends Error {}
|
|
87
|
+
|
|
88
|
+
export interface TransitionResult {
|
|
89
|
+
state: State;
|
|
90
|
+
/** 面向用户的简报(UI/notify 用)。 */
|
|
91
|
+
note?: string;
|
|
92
|
+
/** 面向模型的上下文要点(注入用)。 */
|
|
93
|
+
modelNote?: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function clone(s: State): State {
|
|
97
|
+
return {
|
|
98
|
+
...s,
|
|
99
|
+
plan: s.plan ? { ...s.plan } : null,
|
|
100
|
+
execution: s.execution
|
|
101
|
+
? { ...s.execution, steps: s.execution.steps.map((x) => ({ ...x })) }
|
|
102
|
+
: null,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function requirePlan(s: State): PlanMeta {
|
|
107
|
+
if (!s.plan)
|
|
108
|
+
throw new TransitionError("当前没有计划:先用 plan_task new 创建。");
|
|
109
|
+
return s.plan;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function requireExecution(s: State): Execution {
|
|
113
|
+
if (!s.plan) throw new TransitionError("当前没有计划。");
|
|
114
|
+
if (!s.execution)
|
|
115
|
+
throw new TransitionError(
|
|
116
|
+
"当前未处于分步执行。用 plan_exit 选择分步实现。",
|
|
117
|
+
);
|
|
118
|
+
return s.execution;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function nextPending(steps: Step[]): Step | undefined {
|
|
122
|
+
return steps.find((x) => x.status === "pending");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 唯一转移入口。 */
|
|
126
|
+
export function transition(prev: State, ev: Transition): TransitionResult {
|
|
127
|
+
const s = clone(prev);
|
|
128
|
+
switch (ev.t) {
|
|
129
|
+
case "mode.set": {
|
|
130
|
+
if (s.mode === ev.mode) return { state: prev };
|
|
131
|
+
s.mode = ev.mode;
|
|
132
|
+
return {
|
|
133
|
+
state: s,
|
|
134
|
+
note:
|
|
135
|
+
ev.mode === "plan"
|
|
136
|
+
? "已切换到 Plan 模式(只读规划)"
|
|
137
|
+
: "已切换到 Build 模式",
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
case "plan.create": {
|
|
142
|
+
if (s.plan)
|
|
143
|
+
throw new TransitionError(
|
|
144
|
+
"已有未完成计划,须先完成或放弃(plan_complete / plan_task abandon)。",
|
|
145
|
+
);
|
|
146
|
+
if (!ev.title.trim()) throw new TransitionError("计划标题不能为空。");
|
|
147
|
+
if (!ev.scope.trim()) throw new TransitionError("计划范围不能为空。");
|
|
148
|
+
s.plan = {
|
|
149
|
+
seq: 1,
|
|
150
|
+
title: ev.title.trim(),
|
|
151
|
+
scope: ev.scope.trim(),
|
|
152
|
+
path: ev.path,
|
|
153
|
+
saved: false,
|
|
154
|
+
};
|
|
155
|
+
return { state: s, modelNote: `计划已创建:${s.plan.title}` };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
case "plan.title": {
|
|
159
|
+
const p = requirePlan(s);
|
|
160
|
+
if (!ev.title.trim()) throw new TransitionError("标题不能为空。");
|
|
161
|
+
p.title = ev.title.trim();
|
|
162
|
+
return { state: s };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
case "plan.scope.append": {
|
|
166
|
+
const p = requirePlan(s);
|
|
167
|
+
if (!ev.addition.trim()) throw new TransitionError("追加范围不能为空。");
|
|
168
|
+
p.scope = `${p.scope}\n\n## 追加范围${ev.note ? `(${ev.note})` : "(用户批准)"}\n${ev.addition.trim()}`;
|
|
169
|
+
if (p.outcome) p.outcome = undefined; // 范围变化使旧结局失效
|
|
170
|
+
return {
|
|
171
|
+
state: s,
|
|
172
|
+
modelNote: "范围已追加;请相应更新计划文件后重新 plan_exit。",
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
case "plan.exclude": {
|
|
177
|
+
requirePlan(s);
|
|
178
|
+
return { state: s, modelNote: `已记录排除话题:${ev.topic}` };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
case "plan.saved": {
|
|
182
|
+
const p = requirePlan(s);
|
|
183
|
+
p.saved = true;
|
|
184
|
+
return { state: s };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
case "plan.complete": {
|
|
188
|
+
const p = requirePlan(s);
|
|
189
|
+
p.outcome = undefined;
|
|
190
|
+
p.summary = ev.summary;
|
|
191
|
+
const hadExecution = s.execution !== null;
|
|
192
|
+
s.execution = null;
|
|
193
|
+
s.plan = null;
|
|
194
|
+
return {
|
|
195
|
+
state: s,
|
|
196
|
+
note: hadExecution ? "计划完成(分步执行已收尾)" : "计划完成",
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
case "plan.finish": {
|
|
201
|
+
const p = requirePlan(s);
|
|
202
|
+
p.outcome = ev.outcome;
|
|
203
|
+
return { state: s };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
case "plan.abandon": {
|
|
207
|
+
requirePlan(s);
|
|
208
|
+
s.execution = null;
|
|
209
|
+
s.plan = null;
|
|
210
|
+
return { state: s, note: `计划已放弃(${ev.reason});文件保留在原处` };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
case "exec.start": {
|
|
214
|
+
const p = requirePlan(s);
|
|
215
|
+
if (!p.saved)
|
|
216
|
+
throw new TransitionError("计划文件尚未写盘,无法分步执行。");
|
|
217
|
+
if (s.execution) throw new TransitionError("分步执行已在进行。");
|
|
218
|
+
const steps: Step[] = ev.steps.map((text, i) => ({
|
|
219
|
+
n: i + 1,
|
|
220
|
+
text,
|
|
221
|
+
status: i === 0 ? "ready" : "pending",
|
|
222
|
+
}));
|
|
223
|
+
if (steps.length === 0) throw new TransitionError("未解析出任何步骤。");
|
|
224
|
+
s.execution = { steps, paused: false };
|
|
225
|
+
return { state: s, note: `分步执行开始:共 ${steps.length} 步` };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
case "exec.step.start": {
|
|
229
|
+
const ex = requireExecution(s);
|
|
230
|
+
if (ex.paused)
|
|
231
|
+
throw new TransitionError("执行已暂停,先 plan_step_control resume。");
|
|
232
|
+
const cur = ex.steps.find(
|
|
233
|
+
(x) => x.status === "ready" || x.status === "active",
|
|
234
|
+
);
|
|
235
|
+
if (!cur) throw new TransitionError("没有就绪的步骤。");
|
|
236
|
+
if (cur.status === "active") return { state: prev };
|
|
237
|
+
cur.status = "active";
|
|
238
|
+
return { state: s, note: `第 ${cur.n}/${ex.steps.length} 步开始` };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
case "exec.step.complete": {
|
|
242
|
+
const ex = requireExecution(s);
|
|
243
|
+
const cur = ex.steps.find((x) => x.status === "active");
|
|
244
|
+
if (!cur)
|
|
245
|
+
throw new TransitionError(
|
|
246
|
+
"没有进行中的步骤。先 plan_step_control start。",
|
|
247
|
+
);
|
|
248
|
+
cur.status = "completed";
|
|
249
|
+
cur.summary = ev.summary;
|
|
250
|
+
const next = nextPending(ex.steps);
|
|
251
|
+
if (next) {
|
|
252
|
+
next.status = "ready";
|
|
253
|
+
return {
|
|
254
|
+
state: s,
|
|
255
|
+
note: `第 ${cur.n} 步完成;第 ${next.n} 步就绪(等待批准)`,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
// 最后一步完成 → 计划整体完成
|
|
259
|
+
const done = ex.steps
|
|
260
|
+
.map((x) => ` ${x.n}. ${x.summary ?? x.text}`)
|
|
261
|
+
.join("\n");
|
|
262
|
+
s.execution = null;
|
|
263
|
+
s.plan = null;
|
|
264
|
+
return { state: s, note: `全部步骤完成,计划已收尾。\n${done}` };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
case "exec.step.skip": {
|
|
268
|
+
const ex = requireExecution(s);
|
|
269
|
+
const cur = ex.steps.find(
|
|
270
|
+
(x) => x.status === "ready" || x.status === "active",
|
|
271
|
+
);
|
|
272
|
+
if (!cur) throw new TransitionError("没有可跳过的步骤。");
|
|
273
|
+
cur.status = "skipped";
|
|
274
|
+
const next = nextPending(ex.steps);
|
|
275
|
+
if (next) {
|
|
276
|
+
next.status = "ready";
|
|
277
|
+
return { state: s, note: `第 ${cur.n} 步已跳过;第 ${next.n} 步就绪` };
|
|
278
|
+
}
|
|
279
|
+
const done = ex.steps
|
|
280
|
+
.map(
|
|
281
|
+
(x) =>
|
|
282
|
+
` ${x.n}. ${x.status === "skipped" ? "(跳过)" : (x.summary ?? x.text)}`,
|
|
283
|
+
)
|
|
284
|
+
.join("\n");
|
|
285
|
+
s.execution = null;
|
|
286
|
+
s.plan = null;
|
|
287
|
+
return { state: s, note: `全部步骤处理完毕,计划已收尾。\n${done}` };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
case "exec.step.revise": {
|
|
291
|
+
const ex = requireExecution(s);
|
|
292
|
+
const st = ex.steps.find((x) => x.n === ev.n);
|
|
293
|
+
if (!st) throw new TransitionError(`不存在第 ${ev.n} 步。`);
|
|
294
|
+
if (st.status === "completed" || st.status === "active") {
|
|
295
|
+
throw new TransitionError(
|
|
296
|
+
`第 ${ev.n} 步已${st.status === "active" ? "在进行" : "完成"},不能修订。`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
st.text = ev.text;
|
|
300
|
+
return { state: s, note: `第 ${ev.n} 步已修订` };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
case "exec.pause": {
|
|
304
|
+
const ex = requireExecution(s);
|
|
305
|
+
if (ex.paused) return { state: prev };
|
|
306
|
+
ex.paused = true;
|
|
307
|
+
return { state: s, note: "分步执行已暂停(保留进度,无实现授权)" };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
case "exec.resume": {
|
|
311
|
+
const ex = requireExecution(s);
|
|
312
|
+
if (!ex.paused) return { state: prev };
|
|
313
|
+
ex.paused = false;
|
|
314
|
+
return { state: s, note: "分步执行已恢复" };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
case "exec.cancel": {
|
|
318
|
+
requireExecution(s);
|
|
319
|
+
s.execution = null;
|
|
320
|
+
return { state: s, note: "分步执行已取消(计划保留,处于未完成)" };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
default: {
|
|
324
|
+
// 编译期穷尽检查:新增转移未处理时在此报错
|
|
325
|
+
throw new TransitionError(
|
|
326
|
+
`未知转移 ${JSON.stringify(ev satisfies never)}`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 工具守卫用的当前计划代号。 */
|
|
333
|
+
export function currentSeq(s: State): number | null {
|
|
334
|
+
return s.plan?.seq ?? null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** 人类可读的一行状态(状态栏用)。 */
|
|
338
|
+
export function statusLine(s: State): string {
|
|
339
|
+
const mode = s.mode === "plan" ? "📋 plan" : "🔨 build";
|
|
340
|
+
if (!s.plan) return mode;
|
|
341
|
+
if (s.execution) {
|
|
342
|
+
const done = s.execution.steps.filter(
|
|
343
|
+
(x) => x.status === "completed" || x.status === "skipped",
|
|
344
|
+
).length;
|
|
345
|
+
const tag = s.execution.paused ? "⏸" : "▶";
|
|
346
|
+
return `${mode} ${tag} ${done}/${s.execution.steps.length} ${s.plan.title}`;
|
|
347
|
+
}
|
|
348
|
+
const suffix = s.plan.outcome
|
|
349
|
+
? `(${outcomeLabel(s.plan.outcome)})`
|
|
350
|
+
: s.plan.saved
|
|
351
|
+
? ""
|
|
352
|
+
: "(未写盘)";
|
|
353
|
+
return `${mode} ${s.plan.title}${suffix}`;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function outcomeLabel(o: PlanOutcome): string {
|
|
357
|
+
switch (o.kind) {
|
|
358
|
+
case "awaiting_validation":
|
|
359
|
+
return "待验证";
|
|
360
|
+
case "blocked":
|
|
361
|
+
return "受阻";
|
|
362
|
+
case "waiting_for_input":
|
|
363
|
+
return "等输入";
|
|
364
|
+
case "still_working":
|
|
365
|
+
return "进行中";
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 侧栏 widget 行(原生 setWidget)。 */
|
|
370
|
+
export function widgetLines(s: State): string[] | undefined {
|
|
371
|
+
if (!s.plan || !s.execution) return undefined;
|
|
372
|
+
const marks: Record<StepStatus, string> = {
|
|
373
|
+
pending: "○",
|
|
374
|
+
ready: "◉",
|
|
375
|
+
active: "◐",
|
|
376
|
+
completed: "●",
|
|
377
|
+
skipped: "↷",
|
|
378
|
+
};
|
|
379
|
+
const head = s.execution.paused ? "分步执行(暂停)" : "分步执行";
|
|
380
|
+
return [
|
|
381
|
+
`${head} · ${s.plan.title}`,
|
|
382
|
+
...s.execution.steps.map(
|
|
383
|
+
(x) =>
|
|
384
|
+
`${marks[x.status]} ${x.n}. ${x.text}${x.status === "skipped" ? "(跳过)" : ""}`,
|
|
385
|
+
),
|
|
386
|
+
];
|
|
387
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宽容的步骤解析与修订(纯函数)。
|
|
3
|
+
*
|
|
4
|
+
* 对比参考项目的改进:不再要求精确的 `## Implementation Steps` + 编号列表;
|
|
5
|
+
* 编号 / checkbox / 短横线均接受,节标题多种写法均可;
|
|
6
|
+
* 解析失败返回修复指引而非裸错误。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const HEADING_RE =
|
|
10
|
+
/^#{1,4}\s*(?:implementation\s+steps?|实施步骤|实现步骤|步骤)\s*:?\s*$/i;
|
|
11
|
+
const NEXT_HEADING_RE = /^#{1,4}\s+/;
|
|
12
|
+
// checkbox 分支必须先于裸短横线分支,否则 "- [ ] x" 会被短横线分支吃掉标记
|
|
13
|
+
const ITEM_RE = /^(?:[-*]\s+\[\s?]\s+|\d+[.)]\s+|-+\s+)(\S.*?)\s*$/;
|
|
14
|
+
|
|
15
|
+
export interface StepParseResult {
|
|
16
|
+
steps: string[];
|
|
17
|
+
/** 解析失败时的模型可执行修复指引。 */
|
|
18
|
+
error?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
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) {
|
|
31
|
+
return {
|
|
32
|
+
steps: [],
|
|
33
|
+
error:
|
|
34
|
+
'计划文件缺少步骤小节。请在文件末尾追加一个小节(如 "## 实现步骤" 或 "## Implementation Steps"),\n下面每行一步,用 "1. ..."、"- ..." 或 "- [ ] ..." 开头,然后重新调用 plan_exit。',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const steps: string[] = [];
|
|
38
|
+
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();
|
|
45
|
+
if (!text) continue;
|
|
46
|
+
const key = text.toLowerCase();
|
|
47
|
+
if (seen.has(key)) continue; // 重复步骤去重而非报错
|
|
48
|
+
seen.add(key);
|
|
49
|
+
steps.push(text);
|
|
50
|
+
}
|
|
51
|
+
if (steps.length === 0) {
|
|
52
|
+
return {
|
|
53
|
+
steps: [],
|
|
54
|
+
error:
|
|
55
|
+
'步骤小节存在但没有解析出条目:每行用 "1. ..."、"- ..." 或 "- [ ] ..." 开头,然后重新调用 plan_exit。',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return { steps };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 修订文件中的第 n 步文本(1 基),返回替换后的全文;失败返回 null。 */
|
|
62
|
+
export function reviseStepInMarkdown(
|
|
63
|
+
plan: string,
|
|
64
|
+
n: number,
|
|
65
|
+
newText: string,
|
|
66
|
+
): string | null {
|
|
67
|
+
const lines = plan.split(/\r?\n/);
|
|
68
|
+
let heading = -1;
|
|
69
|
+
for (let i = 0; i < lines.length; i++) {
|
|
70
|
+
if (HEADING_RE.test((lines[i] ?? "").trim())) {
|
|
71
|
+
heading = i;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (heading < 0) return null;
|
|
76
|
+
let index = 0;
|
|
77
|
+
for (let i = heading + 1; i < lines.length; i++) {
|
|
78
|
+
const line = lines[i] ?? "";
|
|
79
|
+
if (NEXT_HEADING_RE.test(line.trim())) break;
|
|
80
|
+
if (!ITEM_RE.test(line.trim())) continue;
|
|
81
|
+
index++;
|
|
82
|
+
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}`;
|
|
90
|
+
return lines.join("\n");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PlanEngine:扩展运行时中枢。持有当前状态,执行转移并统一处理
|
|
3
|
+
* 持久化(appendEntry)、UI 刷新(setStatus/setWidget/notify)。
|
|
4
|
+
* 对比参考项目:不再有几十个闭包变量,所有变化都经过 apply()。
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import type {
|
|
9
|
+
ExtensionAPI,
|
|
10
|
+
ExtensionContext,
|
|
11
|
+
} from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import type { Config } from "./config.ts";
|
|
13
|
+
import { type PromptPack, prompts } from "./core/prompts.ts";
|
|
14
|
+
import { decodeState, STATE_ENTRY_TYPE } from "./core/schema.ts";
|
|
15
|
+
import {
|
|
16
|
+
initialState,
|
|
17
|
+
type State,
|
|
18
|
+
statusLine,
|
|
19
|
+
type Transition,
|
|
20
|
+
TransitionError,
|
|
21
|
+
type TransitionResult,
|
|
22
|
+
transition,
|
|
23
|
+
widgetLines,
|
|
24
|
+
} from "./core/state.ts";
|
|
25
|
+
|
|
26
|
+
export class PlanEngine {
|
|
27
|
+
state: State = initialState;
|
|
28
|
+
readonly pi: ExtensionAPI;
|
|
29
|
+
private ctx: ExtensionContext | undefined;
|
|
30
|
+
config: Config;
|
|
31
|
+
/** awaiting_validation 的问询是否已在本次运行发过(防重放)。 */
|
|
32
|
+
validationAsked = false;
|
|
33
|
+
/** 状态损坏只读保护。 */
|
|
34
|
+
corrupt = false;
|
|
35
|
+
|
|
36
|
+
constructor(pi: ExtensionAPI, config: Config) {
|
|
37
|
+
this.pi = pi;
|
|
38
|
+
this.config = config;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
get P(): PromptPack {
|
|
42
|
+
return prompts(this.config.lang);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
setConfig(patch: Partial<Config>): void {
|
|
46
|
+
this.config = { ...this.config, ...patch };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
attachContext(ctx: ExtensionContext): void {
|
|
50
|
+
this.ctx = ctx;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** session_start:从分支条目恢复。 */
|
|
54
|
+
restore(entries: readonly { customType?: string; data?: unknown }[]): {
|
|
55
|
+
restored: boolean;
|
|
56
|
+
corruptEntry?: boolean;
|
|
57
|
+
} {
|
|
58
|
+
let sawCorrupt = false;
|
|
59
|
+
let restoredState: State | undefined;
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
if (entry.customType === STATE_ENTRY_TYPE && entry.data !== undefined) {
|
|
62
|
+
const decoded = decodeState(entry.data);
|
|
63
|
+
if (decoded) restoredState = decoded;
|
|
64
|
+
else sawCorrupt = true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
this.state = restoredState ?? initialState;
|
|
68
|
+
this.corrupt = false;
|
|
69
|
+
return { restored: restoredState !== undefined, corruptEntry: sawCorrupt };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
apply(ev: Transition, ctx?: ExtensionContext): TransitionResult {
|
|
73
|
+
const c = ctx ?? this.ctx;
|
|
74
|
+
if (this.corrupt)
|
|
75
|
+
throw new TransitionError(
|
|
76
|
+
"持久化状态损坏,处于只读保护。请 /reload 或手工修复后重试。",
|
|
77
|
+
);
|
|
78
|
+
const prev = this.state;
|
|
79
|
+
const result = transition(this.state, ev);
|
|
80
|
+
this.state = result.state;
|
|
81
|
+
if (result.state !== prev) this.persist(); // 幂等转移不写重复条目
|
|
82
|
+
this.refreshUI(c, result.note);
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
tryApply(
|
|
87
|
+
ev: Transition,
|
|
88
|
+
ctx?: ExtensionContext,
|
|
89
|
+
): TransitionResult | { error: string } {
|
|
90
|
+
try {
|
|
91
|
+
return this.apply(ev, ctx);
|
|
92
|
+
} catch (e) {
|
|
93
|
+
if (e instanceof TransitionError) return { error: e.message };
|
|
94
|
+
throw e;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private persist(): void {
|
|
99
|
+
this.pi.appendEntry(STATE_ENTRY_TYPE, this.state);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
refreshUI(ctx?: ExtensionContext, note?: string): void {
|
|
103
|
+
const c = ctx ?? this.ctx;
|
|
104
|
+
if (!c) return;
|
|
105
|
+
// 模式徽标:底部状态栏(Plan=警告色,Build=强调色)
|
|
106
|
+
c.ui.setStatus(
|
|
107
|
+
"plan-build",
|
|
108
|
+
c.ui.theme.fg(
|
|
109
|
+
this.state.mode === "plan" ? "warning" : "accent",
|
|
110
|
+
statusLine(this.state),
|
|
111
|
+
),
|
|
112
|
+
);
|
|
113
|
+
c.ui.setWidget("plan-build-steps", widgetLines(this.state));
|
|
114
|
+
if (note) c.ui.notify(note, "info");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** canonical 计划文件路径:<cwd>/.pi/agent/plans/<yyyyMMdd-HHmm>-<标题slug>.md(随项目走,语义化命名) */
|
|
119
|
+
export function nextPlanPath(cwd: string, title: string): string {
|
|
120
|
+
const dir = path.join(cwd, ".pi", "agent", "plans");
|
|
121
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
122
|
+
const base = `${formatStamp(new Date())}-${titleSlug(title)}`;
|
|
123
|
+
for (let i = 0; i < 100; i++) {
|
|
124
|
+
const suffix = i === 0 ? "" : `-${i + 1}`;
|
|
125
|
+
const p = path.join(dir, `${base}${suffix}.md`);
|
|
126
|
+
try {
|
|
127
|
+
fs.writeFileSync(p, "", { flag: "wx" }); // 分配即占位,防同名重复分配
|
|
128
|
+
return p;
|
|
129
|
+
} catch {
|
|
130
|
+
/* 已存在 → 尝试下一个后缀 */
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const fallback = path.join(dir, `${base}-${Date.now()}.md`);
|
|
134
|
+
fs.writeFileSync(fallback, "", { flag: "wx" });
|
|
135
|
+
return fallback;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 本地时刻戳:20251008-1432 */
|
|
139
|
+
function formatStamp(d: Date): string {
|
|
140
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
141
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 标题 → 文件名安全 slug:去非法字符、空白折叠为 -、截 40 字符、去首尾点。 */
|
|
145
|
+
function titleSlug(title: string): string {
|
|
146
|
+
const cleaned = title
|
|
147
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: 清理文件名中的控制字符正是本处目的
|
|
148
|
+
.replace(/[\\/:*?"<>|\x00-\x1f]/g, "")
|
|
149
|
+
.trim()
|
|
150
|
+
.replace(/\s+/g, "-");
|
|
151
|
+
return (
|
|
152
|
+
cleaned
|
|
153
|
+
.slice(0, 40)
|
|
154
|
+
.replace(/^[.-]+|[.-]+$/g, "")
|
|
155
|
+
.trim() || "plan"
|
|
156
|
+
);
|
|
157
|
+
}
|