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

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.
@@ -0,0 +1,144 @@
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
+ /**
17
+ * 会话条目类型。与 pi-acp-jetbrain 桥接层约定一致:
18
+ * ACP 模式选择器按此 customType 读 data.selectedMode 展示当前 Plan/Build 模式。
19
+ */
20
+ export const STATE_ENTRY_TYPE = "pi-plan-build-state";
21
+
22
+ const stepStatusValues = [
23
+ "pending",
24
+ "ready",
25
+ "active",
26
+ "completed",
27
+ "skipped",
28
+ ] as const;
29
+
30
+ function isRecord(v: unknown): v is Record<string, unknown> {
31
+ return typeof v === "object" && v !== null;
32
+ }
33
+
34
+ /** 解码条目 data;返回 undefined 表示损坏(外层进入只读保护模式)。 */
35
+ export function decodeState(data: unknown): State | undefined {
36
+ if (!isRecord(data)) return undefined;
37
+ // 手写最小校验(TypeBox 运行时校验器依赖 value 包,不引额外依赖)
38
+ if (data.version !== 2) return undefined;
39
+ if (data.mode !== "plan" && data.mode !== "build") return undefined;
40
+ if (data.plan === null) {
41
+ if (data.execution !== null) return undefined;
42
+ return { version: 2, mode: data.mode, plan: null, execution: null };
43
+ }
44
+ const p = data.plan;
45
+ if (!isRecord(p)) return undefined;
46
+ if (
47
+ typeof p.seq !== "number" ||
48
+ typeof p.title !== "string" ||
49
+ typeof p.scope !== "string" ||
50
+ typeof p.path !== "string" ||
51
+ typeof p.saved !== "boolean"
52
+ )
53
+ return undefined;
54
+ if (p.seq < 1 || !p.title || !p.path) return undefined;
55
+ const outcome = decodeOutcome(p.outcome);
56
+ if (p.outcome !== undefined && !outcome) return undefined;
57
+ if (data.execution === null) {
58
+ return {
59
+ version: 2,
60
+ mode: data.mode,
61
+ plan: {
62
+ seq: p.seq,
63
+ title: p.title,
64
+ scope: p.scope,
65
+ path: p.path,
66
+ saved: p.saved,
67
+ ...(outcome ? { outcome } : {}),
68
+ },
69
+ execution: null,
70
+ };
71
+ }
72
+ const execution = decodeExecution(data.execution);
73
+ if (!execution) return undefined;
74
+ return {
75
+ version: 2,
76
+ mode: data.mode,
77
+ plan: {
78
+ seq: p.seq,
79
+ title: p.title,
80
+ scope: p.scope,
81
+ path: p.path,
82
+ saved: p.saved,
83
+ ...(outcome ? { outcome } : {}),
84
+ },
85
+ execution,
86
+ };
87
+ }
88
+
89
+ function decodeOutcome(v: unknown): PlanOutcome | undefined {
90
+ if (v === undefined) return undefined;
91
+ if (!isRecord(v)) return undefined;
92
+ if (
93
+ v.kind === "awaiting_validation" &&
94
+ typeof v.userAction === "string" &&
95
+ v.userAction
96
+ ) {
97
+ return { kind: "awaiting_validation", userAction: v.userAction };
98
+ }
99
+ if (
100
+ (v.kind === "blocked" ||
101
+ v.kind === "waiting_for_input" ||
102
+ v.kind === "still_working") &&
103
+ typeof v.reason === "string" &&
104
+ v.reason
105
+ ) {
106
+ return { kind: v.kind, reason: v.reason };
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ function decodeExecution(v: unknown): Execution | null | undefined {
112
+ if (v === null) return null;
113
+ if (!isRecord(v) || !Array.isArray(v.steps) || typeof v.paused !== "boolean")
114
+ return undefined;
115
+ const steps: Step[] = [];
116
+ for (const raw of v.steps) {
117
+ if (!isRecord(raw)) return undefined;
118
+ if (typeof raw.n !== "number" || typeof raw.text !== "string")
119
+ return undefined;
120
+ const status = raw.status as StepStatus;
121
+ if (!stepStatusValues.includes(status)) return undefined;
122
+ steps.push({
123
+ n: raw.n,
124
+ text: raw.text,
125
+ status,
126
+ ...(typeof raw.summary === "string" ? { summary: raw.summary } : {}),
127
+ });
128
+ }
129
+ if (steps.length === 0) return undefined;
130
+ return { steps, paused: v.paused };
131
+ }
132
+
133
+ /** 恢复:扫描分支条目取最新有效状态。 */
134
+ export function restoreFromBranch(
135
+ entries: readonly { customType?: string; data?: unknown }[],
136
+ ): State {
137
+ let restored: State | undefined;
138
+ for (const entry of entries) {
139
+ if (entry.customType !== STATE_ENTRY_TYPE) continue;
140
+ const s = decodeState(entry.data);
141
+ if (s) restored = s;
142
+ }
143
+ return restored ?? initialState;
144
+ }
@@ -0,0 +1,409 @@
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.ack"; summary?: string }
80
+ | { t: "exec.step.skip" }
81
+ | { t: "exec.step.revise"; n: number; text: string }
82
+ | { t: "exec.pause" }
83
+ | { t: "exec.resume" }
84
+ | { t: "exec.cancel" };
85
+
86
+ /** 转移需要的外部事实校验失败时抛错,消息面向模型。 */
87
+ export class TransitionError extends Error {}
88
+
89
+ export interface TransitionResult {
90
+ state: State;
91
+ /** 面向用户的简报(UI/notify 用)。 */
92
+ note?: string;
93
+ /** 面向模型的上下文要点(注入用)。 */
94
+ modelNote?: string;
95
+ }
96
+
97
+ function clone(s: State): State {
98
+ return {
99
+ ...s,
100
+ plan: s.plan ? { ...s.plan } : null,
101
+ execution: s.execution
102
+ ? { ...s.execution, steps: s.execution.steps.map((x) => ({ ...x })) }
103
+ : null,
104
+ };
105
+ }
106
+
107
+ function requirePlan(s: State): PlanMeta {
108
+ if (!s.plan)
109
+ throw new TransitionError("当前没有计划:先用 plan_task new 创建。");
110
+ return s.plan;
111
+ }
112
+
113
+ function requireExecution(s: State): Execution {
114
+ if (!s.plan) throw new TransitionError("当前没有计划。");
115
+ if (!s.execution)
116
+ throw new TransitionError(
117
+ "当前未处于分步执行。用 plan_exit 选择分步实现。",
118
+ );
119
+ return s.execution;
120
+ }
121
+
122
+ function nextPending(steps: Step[]): Step | undefined {
123
+ return steps.find((x) => x.status === "pending");
124
+ }
125
+
126
+ /** 完成当前步并推进 ready;最后一步完成时整体收尾(complete/ack 共用)。 */
127
+ function finishStep(
128
+ s: State,
129
+ ex: Execution,
130
+ cur: Step,
131
+ summary?: string,
132
+ ): TransitionResult {
133
+ cur.status = "completed";
134
+ cur.summary = summary;
135
+ const next = nextPending(ex.steps);
136
+ if (next) {
137
+ next.status = "ready";
138
+ return {
139
+ state: s,
140
+ note: `第 ${cur.n} 步完成;第 ${next.n} 步就绪(等待批准)`,
141
+ };
142
+ }
143
+ const done = ex.steps
144
+ .map((x) => ` ${x.n}. ${x.summary ?? x.text}`)
145
+ .join("\n");
146
+ s.execution = null;
147
+ s.plan = null;
148
+ return { state: s, note: `全部步骤完成,计划已收尾。\n${done}` };
149
+ }
150
+
151
+ /** 唯一转移入口。 */
152
+ export function transition(prev: State, ev: Transition): TransitionResult {
153
+ const s = clone(prev);
154
+ switch (ev.t) {
155
+ case "mode.set": {
156
+ if (s.mode === ev.mode) return { state: prev };
157
+ s.mode = ev.mode;
158
+ return {
159
+ state: s,
160
+ note:
161
+ ev.mode === "plan"
162
+ ? "已切换到 Plan 模式(只读规划)"
163
+ : "已切换到 Build 模式",
164
+ };
165
+ }
166
+
167
+ case "plan.create": {
168
+ if (s.plan)
169
+ throw new TransitionError(
170
+ "已有未完成计划,须先完成或放弃(plan_complete / plan_task abandon)。",
171
+ );
172
+ if (!ev.title.trim()) throw new TransitionError("计划标题不能为空。");
173
+ if (!ev.scope.trim()) throw new TransitionError("计划范围不能为空。");
174
+ s.plan = {
175
+ seq: 1,
176
+ title: ev.title.trim(),
177
+ scope: ev.scope.trim(),
178
+ path: ev.path,
179
+ saved: false,
180
+ };
181
+ return { state: s, modelNote: `计划已创建:${s.plan.title}` };
182
+ }
183
+
184
+ case "plan.title": {
185
+ const p = requirePlan(s);
186
+ if (!ev.title.trim()) throw new TransitionError("标题不能为空。");
187
+ p.title = ev.title.trim();
188
+ return { state: s };
189
+ }
190
+
191
+ case "plan.scope.append": {
192
+ const p = requirePlan(s);
193
+ if (!ev.addition.trim()) throw new TransitionError("追加范围不能为空。");
194
+ p.scope = `${p.scope}\n\n## 追加范围${ev.note ? `(${ev.note})` : "(用户批准)"}\n${ev.addition.trim()}`;
195
+ if (p.outcome) p.outcome = undefined; // 范围变化使旧结局失效
196
+ return {
197
+ state: s,
198
+ modelNote: "范围已追加;请相应更新计划文件后重新 plan_exit。",
199
+ };
200
+ }
201
+
202
+ case "plan.exclude": {
203
+ requirePlan(s);
204
+ return { state: s, modelNote: `已记录排除话题:${ev.topic}` };
205
+ }
206
+
207
+ case "plan.saved": {
208
+ const p = requirePlan(s);
209
+ p.saved = true;
210
+ return { state: s };
211
+ }
212
+
213
+ case "plan.complete": {
214
+ const p = requirePlan(s);
215
+ p.outcome = undefined;
216
+ p.summary = ev.summary;
217
+ const hadExecution = s.execution !== null;
218
+ s.execution = null;
219
+ s.plan = null;
220
+ return {
221
+ state: s,
222
+ note: hadExecution ? "计划完成(分步执行已收尾)" : "计划完成",
223
+ };
224
+ }
225
+
226
+ case "plan.finish": {
227
+ const p = requirePlan(s);
228
+ p.outcome = ev.outcome;
229
+ return { state: s };
230
+ }
231
+
232
+ case "plan.abandon": {
233
+ requirePlan(s);
234
+ s.execution = null;
235
+ s.plan = null;
236
+ return { state: s, note: `计划已放弃(${ev.reason});文件保留在原处` };
237
+ }
238
+
239
+ case "exec.start": {
240
+ const p = requirePlan(s);
241
+ if (!p.saved)
242
+ throw new TransitionError("计划文件尚未写盘,无法分步执行。");
243
+ if (s.execution) throw new TransitionError("分步执行已在进行。");
244
+ const steps: Step[] = ev.steps.map((text, i) => ({
245
+ n: i + 1,
246
+ text,
247
+ status: i === 0 ? "ready" : "pending",
248
+ }));
249
+ if (steps.length === 0) throw new TransitionError("未解析出任何步骤。");
250
+ s.execution = { steps, paused: false };
251
+ return { state: s, note: `分步执行开始:共 ${steps.length} 步` };
252
+ }
253
+
254
+ case "exec.step.start": {
255
+ const ex = requireExecution(s);
256
+ if (ex.paused)
257
+ throw new TransitionError("执行已暂停,先 plan_step_control resume。");
258
+ const cur = ex.steps.find(
259
+ (x) => x.status === "ready" || x.status === "active",
260
+ );
261
+ if (!cur) throw new TransitionError("没有就绪的步骤。");
262
+ if (cur.status === "active") return { state: prev };
263
+ cur.status = "active";
264
+ return { state: s, note: `第 ${cur.n}/${ex.steps.length} 步开始` };
265
+ }
266
+
267
+ case "exec.step.complete": {
268
+ const ex = requireExecution(s);
269
+ const cur = ex.steps.find((x) => x.status === "active");
270
+ if (!cur)
271
+ throw new TransitionError(
272
+ "没有进行中的步骤。先 plan_step_control start。",
273
+ );
274
+ return finishStep(s, ex, cur, ev.summary);
275
+ }
276
+
277
+ case "exec.step.ack": {
278
+ // 指认用户声明的已完成步:当前步(ready/active)直接记录,不要求先 start
279
+ const ex = requireExecution(s);
280
+ if (ex.paused)
281
+ throw new TransitionError("执行已暂停,先 plan_step_control resume。");
282
+ const cur = ex.steps.find(
283
+ (x) => x.status === "ready" || x.status === "active",
284
+ );
285
+ if (!cur) throw new TransitionError("没有可指认的步骤。");
286
+ return finishStep(s, ex, cur, ev.summary);
287
+ }
288
+
289
+ case "exec.step.skip": {
290
+ const ex = requireExecution(s);
291
+ const cur = ex.steps.find(
292
+ (x) => x.status === "ready" || x.status === "active",
293
+ );
294
+ if (!cur) throw new TransitionError("没有可跳过的步骤。");
295
+ cur.status = "skipped";
296
+ const next = nextPending(ex.steps);
297
+ if (next) {
298
+ next.status = "ready";
299
+ return { state: s, note: `第 ${cur.n} 步已跳过;第 ${next.n} 步就绪` };
300
+ }
301
+ const done = ex.steps
302
+ .map(
303
+ (x) =>
304
+ ` ${x.n}. ${x.status === "skipped" ? "(跳过)" : (x.summary ?? x.text)}`,
305
+ )
306
+ .join("\n");
307
+ s.execution = null;
308
+ s.plan = null;
309
+ return { state: s, note: `全部步骤处理完毕,计划已收尾。\n${done}` };
310
+ }
311
+
312
+ case "exec.step.revise": {
313
+ const ex = requireExecution(s);
314
+ const st = ex.steps.find((x) => x.n === ev.n);
315
+ if (!st) throw new TransitionError(`不存在第 ${ev.n} 步。`);
316
+ if (st.status === "completed" || st.status === "active") {
317
+ throw new TransitionError(
318
+ `第 ${ev.n} 步已${st.status === "active" ? "在进行" : "完成"},不能修订。`,
319
+ );
320
+ }
321
+ st.text = ev.text;
322
+ return { state: s, note: `第 ${ev.n} 步已修订` };
323
+ }
324
+
325
+ case "exec.pause": {
326
+ const ex = requireExecution(s);
327
+ if (ex.paused) return { state: prev };
328
+ ex.paused = true;
329
+ return { state: s, note: "分步执行已暂停(保留进度,无实现授权)" };
330
+ }
331
+
332
+ case "exec.resume": {
333
+ const ex = requireExecution(s);
334
+ if (!ex.paused) return { state: prev };
335
+ ex.paused = false;
336
+ return { state: s, note: "分步执行已恢复" };
337
+ }
338
+
339
+ case "exec.cancel": {
340
+ requireExecution(s);
341
+ s.execution = null;
342
+ return { state: s, note: "分步执行已取消(计划保留,处于未完成)" };
343
+ }
344
+
345
+ default: {
346
+ // 编译期穷尽检查:新增转移未处理时在此报错
347
+ throw new TransitionError(
348
+ `未知转移 ${JSON.stringify(ev satisfies never)}`,
349
+ );
350
+ }
351
+ }
352
+ }
353
+
354
+ /** 工具守卫用的当前计划代号。 */
355
+ export function currentSeq(s: State): number | null {
356
+ return s.plan?.seq ?? null;
357
+ }
358
+
359
+ /** 人类可读的一行状态(状态栏用)。 */
360
+ export function statusLine(s: State): string {
361
+ const mode = s.mode === "plan" ? "📋 Plan" : "🔨 Build";
362
+ if (!s.plan) return mode;
363
+ if (s.execution) {
364
+ const done = s.execution.steps.filter(
365
+ (x) => x.status === "completed" || x.status === "skipped",
366
+ ).length;
367
+ const tag = s.execution.paused ? "⏸" : "▶";
368
+ return `${mode} ${tag} ${done}/${s.execution.steps.length} ${s.plan.title}`;
369
+ }
370
+ const suffix = s.plan.outcome
371
+ ? `(${outcomeLabel(s.plan.outcome)})`
372
+ : s.plan.saved
373
+ ? ""
374
+ : "(未写盘)";
375
+ return `${mode} ${s.plan.title}${suffix}`;
376
+ }
377
+
378
+ export function outcomeLabel(o: PlanOutcome): string {
379
+ switch (o.kind) {
380
+ case "awaiting_validation":
381
+ return "待验证";
382
+ case "blocked":
383
+ return "受阻";
384
+ case "waiting_for_input":
385
+ return "等输入";
386
+ case "still_working":
387
+ return "进行中";
388
+ }
389
+ }
390
+
391
+ /** 侧栏 widget 行(原生 setWidget)。 */
392
+ export function widgetLines(s: State): string[] | undefined {
393
+ if (!s.plan || !s.execution) return undefined;
394
+ const marks: Record<StepStatus, string> = {
395
+ pending: "○",
396
+ ready: "◉",
397
+ active: "◐",
398
+ completed: "●",
399
+ skipped: "↷",
400
+ };
401
+ const head = s.execution.paused ? "分步执行(暂停)" : "分步执行";
402
+ return [
403
+ `${head} · ${s.plan.title}`,
404
+ ...s.execution.steps.map(
405
+ (x) =>
406
+ `${marks[x.status]} ${x.n}. ${x.text}${x.status === "skipped" ? "(跳过)" : ""}`,
407
+ ),
408
+ ];
409
+ }
@@ -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
+ }