@andares/pi-toolkits 0.12.3 → 0.13.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.
Files changed (65) hide show
  1. package/README.md +100 -15
  2. package/README.zh-CN.md +94 -14
  3. package/package.json +19 -10
  4. package/src/features/ask/index.ts +6 -0
  5. package/src/features/init/apply.ts +32 -12
  6. package/src/features/init/audit-uat.test.ts +103 -0
  7. package/src/features/init/audit.ts +148 -0
  8. package/src/features/init/detect.ts +4 -0
  9. package/src/features/init/index.ts +47 -2
  10. package/src/features/init/plan.ts +11 -0
  11. package/src/features/init/refresh.test.ts +208 -0
  12. package/src/features/init/refresh.ts +255 -0
  13. package/src/features/init/spec.ts +20 -0
  14. package/src/features/init/templates/agents-skeleton.md +2 -0
  15. package/src/features/init/templates/uat-readme.md +53 -0
  16. package/src/features/init/templates/workflow-block.md +21 -0
  17. package/src/features/init/templates.test.ts +3 -1
  18. package/src/features/init/templates.ts +2 -0
  19. package/src/features/init/types.ts +12 -1
  20. package/src/features/permission/index.ts +32 -0
  21. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  22. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  23. package/src/features/plan/assets/index.html +14 -0
  24. package/src/features/plan/assets.test.ts +64 -0
  25. package/src/features/plan/blocks.test.ts +77 -0
  26. package/src/features/plan/blocks.ts +153 -0
  27. package/src/features/plan/diff.test.ts +144 -0
  28. package/src/features/plan/diff.ts +193 -0
  29. package/src/features/plan/feedback.test.ts +233 -0
  30. package/src/features/plan/feedback.ts +182 -0
  31. package/src/features/plan/index.test.ts +385 -0
  32. package/src/features/plan/index.ts +433 -0
  33. package/src/features/plan/prompt.test.ts +91 -0
  34. package/src/features/plan/prompt.ts +110 -0
  35. package/src/features/plan/render.test.ts +94 -0
  36. package/src/features/plan/render.ts +131 -0
  37. package/src/features/plan/server.test.ts +374 -0
  38. package/src/features/plan/server.ts +272 -0
  39. package/src/features/plan/store.test.ts +145 -0
  40. package/src/features/plan/store.ts +244 -0
  41. package/src/features/review/index.ts +54 -28
  42. package/src/features/review/review.test.ts +46 -1
  43. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  44. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  45. package/src/features/uat/assets/index.html +14 -0
  46. package/src/features/uat/constants.ts +23 -0
  47. package/src/features/uat/index.test.ts +404 -0
  48. package/src/features/uat/index.ts +329 -0
  49. package/src/features/uat/item-tool.ts +280 -0
  50. package/src/features/uat/ledger.test.ts +249 -0
  51. package/src/features/uat/ledger.ts +504 -0
  52. package/src/features/uat/prompt.ts +78 -0
  53. package/src/features/uat/record-tool.ts +167 -0
  54. package/src/features/uat/records.test.ts +145 -0
  55. package/src/features/uat/records.ts +268 -0
  56. package/src/features/uat/server.ts +181 -0
  57. package/src/features/uat/state.test.ts +41 -0
  58. package/src/features/uat/state.ts +67 -0
  59. package/src/index.ts +10 -1
  60. package/src/lib/ask-control.ts +25 -0
  61. package/src/lib/opener.test.ts +72 -0
  62. package/src/lib/opener.ts +121 -0
  63. package/src/lib/permission-control.ts +39 -0
  64. package/src/lib/startup.test.ts +1 -1
  65. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,272 @@
1
+ /**
2
+ * plan server — the review UI, served from inside the pi process.
3
+ *
4
+ * Shape of the contract:
5
+ * - one revision is reviewed at a time; the page pulls `/api/state` and then
6
+ * follows `/api/events` (SSE) for new revisions and annotations;
7
+ * - the browser posts annotations and the decision; both land in the store,
8
+ * and the decision resolves a promise the extension is awaiting — no IPC,
9
+ * no unix socket, no second process (the browser can only speak HTTP, and
10
+ * the server is already in the process that needs the answer);
11
+ * - on a decision the server broadcasts it, answers the request, and closes
12
+ * shortly after, so a finished review cannot keep a port open.
13
+ *
14
+ * The HTTP shell (token, Host allowlist, Origin refusal, port walk, static
15
+ * files, SSE) lives in `src/lib/web-review.ts`; this file is the plan-specific
16
+ * routes and payload.
17
+ */
18
+ import { fileURLToPath } from "node:url";
19
+ import { blockLabel, type Block } from "./blocks.js";
20
+ import type { BlockStatus, DiffEntry } from "./diff.js";
21
+ import type { Annotation, BlockAnnotations } from "./feedback.js";
22
+ import {
23
+ latestVersion,
24
+ recordPlanDecision,
25
+ setPlanAnnotations,
26
+ type PlanAnnotations,
27
+ type PlanSession,
28
+ } from "./store.js";
29
+ import { bindHost, isWsl, urlHost } from "../../lib/opener.js";
30
+ import { startWebServer, type WebServerHandle } from "../../lib/web-review.js";
31
+ import { renderBlockHtml } from "./render.js";
32
+
33
+ export interface PlanStateItem {
34
+ status: BlockStatus;
35
+ id: string;
36
+ prevId?: string;
37
+ /** Rendered HTML of the block (escaped markdown subset). */
38
+ html: string;
39
+ /** First line, for the feedback text and the collapsed rail. */
40
+ label: string;
41
+ }
42
+
43
+ export interface PlanStatePayload {
44
+ slug: string;
45
+ version: number;
46
+ totalVersions: number;
47
+ at: string;
48
+ source?: string;
49
+ items: PlanStateItem[];
50
+ annotations: PlanAnnotations;
51
+ decision?: { action: "approve" | "deny"; at: string };
52
+ decided: boolean;
53
+ /** Earlier revisions, newest first — the history drawer. */
54
+ history: Array<{ n: number; at: string; changed: number }>;
55
+ }
56
+
57
+ /** Compose what the page renders: blocks of one revision, tagged with their diff status. */
58
+ export function buildPlanState(session: PlanSession, versionNumber?: number): PlanStatePayload {
59
+ const version =
60
+ versionNumber === undefined
61
+ ? latestVersion(session)
62
+ : session.versions.find((candidate) => candidate.n === versionNumber);
63
+ if (!version) throw new Error(`no plan revision ${versionNumber} in ${session.dir}`);
64
+ const previous = session.versions.find((candidate) => candidate.n === version.n - 1);
65
+
66
+ const byId = new Map<string, Block>(version.blocks.map((block) => [block.id, block]));
67
+ const previousById = new Map<string, Block>(
68
+ (previous?.blocks ?? []).map((block) => [block.id, block]),
69
+ );
70
+ // A first revision has nothing to diff against: no badges, not "all added".
71
+ const entries: DiffEntry[] =
72
+ version.diff.length > 0
73
+ ? version.diff
74
+ : version.blocks.map((block) => ({ status: "unchanged" as const, id: block.id }));
75
+
76
+ const items: PlanStateItem[] = [];
77
+ for (const entry of entries) {
78
+ const current = byId.get(entry.id);
79
+ const source = current ?? previousById.get(entry.id);
80
+ if (!source) continue;
81
+ items.push({
82
+ status: entry.status,
83
+ id: entry.id,
84
+ prevId: entry.prevId,
85
+ html: "",
86
+ label: blockLabel(source),
87
+ });
88
+ }
89
+
90
+ return {
91
+ slug: session.slug,
92
+ version: version.n,
93
+ totalVersions: latestVersion(session).n,
94
+ at: version.at,
95
+ source: version.source,
96
+ items,
97
+ annotations: version.annotations,
98
+ decision: version.decision,
99
+ decided: version.decision !== undefined,
100
+ history: session.versions
101
+ .map((candidate) => ({
102
+ n: candidate.n,
103
+ at: candidate.at,
104
+ changed: candidate.diff.filter((entry) => entry.status !== "unchanged").length,
105
+ }))
106
+ .sort((a, b) => b.n - a.n),
107
+ };
108
+ }
109
+
110
+ export interface StartPlanServerOptions {
111
+ session: PlanSession;
112
+ /** Directory with the built UI. Defaults to `./assets/` next to this module. */
113
+ assetsDir?: string;
114
+ portStart?: number;
115
+ portAttempts?: number;
116
+ /** Milliseconds between "decision received" and the port closing. */
117
+ closeDelayMs?: number;
118
+ /** Render a block to HTML (injected so tests can skip the renderer). */
119
+ render?: (block: Pick<Block, "kind" | "text">) => string;
120
+ onDecision?: (decision: { action: "approve" | "deny"; version: number }) => void;
121
+ onAnnotations?: (annotations: PlanAnnotations, version: number) => void;
122
+ /** Overridable for tests: bind address and host used in the URL. */
123
+ bindHost?: string;
124
+ urlHost?: string;
125
+ }
126
+
127
+ export interface PlanServerHandle {
128
+ url: string;
129
+ port: number;
130
+ token: string;
131
+ close: () => Promise<void>;
132
+ broadcast: (event: string, data: unknown) => void;
133
+ }
134
+
135
+ function isVerdict(value: unknown): value is Annotation["verdict"] {
136
+ return value === "change" || value === "suggest" || value === "question";
137
+ }
138
+
139
+ /** Normalize whatever the page sent into the store's annotation shape. */
140
+ export function normalizeAnnotations(input: unknown): PlanAnnotations {
141
+ const raw = (input ?? {}) as { global?: unknown; blocks?: unknown };
142
+ const toAnnotation = (value: unknown): Annotation | undefined => {
143
+ const candidate = value as { verdict?: unknown; comment?: unknown };
144
+ const comment = typeof candidate?.comment === "string" ? candidate.comment : "";
145
+ const verdict = isVerdict(candidate?.verdict) ? candidate.verdict : undefined;
146
+ if (!verdict || comment.trim() === "") return undefined;
147
+ return { verdict, comment };
148
+ };
149
+ const global = Array.isArray(raw.global)
150
+ ? raw.global.map(toAnnotation).filter((value): value is Annotation => value !== undefined)
151
+ : [];
152
+ const blocks: BlockAnnotations[] = Array.isArray(raw.blocks)
153
+ ? raw.blocks
154
+ .map((value) => {
155
+ const group = value as { blockId?: unknown; annotations?: unknown };
156
+ const blockId = typeof group?.blockId === "string" ? group.blockId : "";
157
+ const annotations = Array.isArray(group?.annotations)
158
+ ? group.annotations
159
+ .map(toAnnotation)
160
+ .filter((item): item is Annotation => item !== undefined)
161
+ : [];
162
+ return { blockId, annotations };
163
+ })
164
+ .filter((group) => group.blockId !== "" && group.annotations.length > 0)
165
+ : [];
166
+ return { global, blocks };
167
+ }
168
+
169
+ export async function startPlanServer(options: StartPlanServerOptions): Promise<PlanServerHandle> {
170
+ const assetsDir = options.assetsDir ?? fileURLToPath(new URL("./assets/", import.meta.url));
171
+ const render = options.render ?? renderBlockHtml;
172
+ const closeDelayMs = options.closeDelayMs ?? 1500;
173
+ let closing = false;
174
+ let handle: WebServerHandle | undefined;
175
+
176
+ const server = await startWebServer({
177
+ assetsDir,
178
+ portStart: options.portStart,
179
+ portAttempts: options.portAttempts,
180
+ bindHost: options.bindHost ?? bindHost(isWsl()),
181
+ urlHost: options.urlHost ?? urlHost(isWsl()),
182
+ routes: async (ctx) => {
183
+ if (ctx.url.pathname === "/api/state" && ctx.req.method === "GET") {
184
+ const versionParam = ctx.url.searchParams.get("version");
185
+ const state = buildPlanState(
186
+ options.session,
187
+ versionParam ? Number(versionParam) : undefined,
188
+ );
189
+ const version = options.session.versions.find(
190
+ (candidate) => candidate.n === state.version,
191
+ );
192
+ const htmlById = new Map<string, string>();
193
+ for (const block of version?.blocks ?? []) htmlById.set(block.id, render(block));
194
+ const previous = options.session.versions.find(
195
+ (candidate) => candidate.n === state.version - 1,
196
+ );
197
+ for (const block of previous?.blocks ?? []) {
198
+ if (!htmlById.has(block.id)) htmlById.set(block.id, render(block));
199
+ }
200
+ ctx.json({
201
+ ...state,
202
+ items: state.items.map((item) => ({ ...item, html: htmlById.get(item.id) ?? "" })),
203
+ });
204
+ return true;
205
+ }
206
+
207
+ if (ctx.url.pathname === "/api/annotate" && ctx.req.method === "POST") {
208
+ const body = (await ctx.readBody()) as { version?: number; annotations?: unknown };
209
+ const annotations = normalizeAnnotations(body.annotations);
210
+ const version = body.version ?? latestVersion(options.session).n;
211
+ if (version !== latestVersion(options.session).n || closing) {
212
+ ctx.json({ error: "only the latest undecided revision can be annotated" }, 409);
213
+ return true;
214
+ }
215
+ setPlanAnnotations(options.session, version, annotations);
216
+ options.onAnnotations?.(annotations, version);
217
+ ctx.broadcast("annotations", { version, annotations });
218
+ ctx.json({ ok: true, version });
219
+ return true;
220
+ }
221
+
222
+ if (ctx.url.pathname === "/api/decide" && ctx.req.method === "POST") {
223
+ const body = (await ctx.readBody()) as { action?: unknown; version?: number };
224
+ const action =
225
+ body.action === "approve" || body.action === "deny" ? body.action : undefined;
226
+ if (!action) {
227
+ ctx.json({ error: "action must be approve or deny" }, 400);
228
+ return true;
229
+ }
230
+ const version = body.version ?? latestVersion(options.session).n;
231
+ const current = options.session.versions.find(
232
+ (candidate) => candidate.n === version,
233
+ );
234
+ if (
235
+ version !== latestVersion(options.session).n ||
236
+ closing ||
237
+ current?.decision !== undefined
238
+ ) {
239
+ // A second producer must not claim an outcome that will not be
240
+ // delivered (the first decision already owns the message).
241
+ ctx.json(
242
+ { error: "this revision has already been decided or is not latest" },
243
+ 409,
244
+ );
245
+ return true;
246
+ }
247
+ recordPlanDecision(options.session, version, action);
248
+ ctx.json({ ok: true, action, version });
249
+ ctx.broadcast("decided", { action, version });
250
+ if (!closing) {
251
+ closing = true;
252
+ setTimeout(() => {
253
+ options.onDecision?.({ action, version });
254
+ void handle?.close();
255
+ }, closeDelayMs).unref();
256
+ }
257
+ return true;
258
+ }
259
+
260
+ return false;
261
+ },
262
+ });
263
+ handle = server;
264
+
265
+ return {
266
+ url: server.url,
267
+ port: server.port,
268
+ token: server.token,
269
+ close: server.close,
270
+ broadcast: server.broadcast,
271
+ };
272
+ }
@@ -0,0 +1,145 @@
1
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
5
+ import {
6
+ appendPlanVersion,
7
+ createPlanSession,
8
+ latestVersion,
9
+ listPlanSessions,
10
+ loadPlanSession,
11
+ planSlug,
12
+ readVersionText,
13
+ recordPlanDecision,
14
+ setPlanAnnotations,
15
+ type PlanSession,
16
+ } from "./store.js";
17
+
18
+ let agentDir: string;
19
+
20
+ beforeAll(() => {
21
+ agentDir = mkdtempSync(join(tmpdir(), "pi-plan-store-"));
22
+ });
23
+
24
+ afterAll(() => {
25
+ rmSync(agentDir, { recursive: true, force: true });
26
+ });
27
+
28
+ const at = (seconds: number) => new Date(Date.UTC(2026, 10, 11, 0, 0, seconds));
29
+
30
+ function makeSession(text = "## Plan\n\nfirst step"): PlanSession {
31
+ return createPlanSession({
32
+ agentDir,
33
+ slug: `plan-${Math.random().toString(36).slice(2, 8)}`,
34
+ text,
35
+ source: "specs/x.md",
36
+ now: at(0),
37
+ });
38
+ }
39
+
40
+ describe("planSlug", () => {
41
+ it("lowercases, collapses separators and keeps CJK", () => {
42
+ expect(planSlug("Ask-Plan: Web UI!")).toBe("ask-plan-web-ui");
43
+ expect(planSlug("计划 评审")).toContain("计划");
44
+ expect(planSlug(" ")).toBe("plan");
45
+ });
46
+ });
47
+
48
+ describe("createPlanSession", () => {
49
+ it("writes the first revision and the state file", () => {
50
+ const session = makeSession();
51
+ expect(session.versions).toHaveLength(1);
52
+ expect(session.versions[0].n).toBe(1);
53
+ expect(session.versions[0].diff).toEqual([]);
54
+ expect(readVersionText(session, 1)).toBe("## Plan\n\nfirst step");
55
+ const onDisk = JSON.parse(readFileSync(join(session.dir, "state.json"), "utf8"));
56
+ expect(onDisk.versions).toHaveLength(1);
57
+ expect(onDisk.slug).toBe(session.slug);
58
+ });
59
+
60
+ it("allocates a second directory for a slug that already exists", () => {
61
+ const first = createPlanSession({ agentDir, slug: "same", text: "a" });
62
+ const second = createPlanSession({ agentDir, slug: "same", text: "b" });
63
+ expect(first.slug).toBe("same");
64
+ expect(second.slug).toBe("same-2");
65
+ expect(first.dir).not.toBe(second.dir);
66
+ });
67
+ });
68
+
69
+ describe("appendPlanVersion", () => {
70
+ it("numbers revisions and diffs against the previous one", () => {
71
+ const session = makeSession("## Plan\n\nfirst step\n\nsecond step");
72
+ const second = appendPlanVersion(session, {
73
+ text: "## Plan\n\nfirst step edited\n\nsecond step",
74
+ now: at(10),
75
+ });
76
+ expect(second.n).toBe(2);
77
+ expect(second.diff.map((entry) => entry.status).filter((status) => status !== "unchanged")).toEqual([
78
+ "modified",
79
+ ]);
80
+ expect(session.versions).toHaveLength(2);
81
+ expect(readVersionText(session, 2)).toContain("first step edited");
82
+ expect(latestVersion(session).n).toBe(2);
83
+ });
84
+
85
+ it("keeps at most 50 revisions and never drops a decided one", () => {
86
+ const session = makeSession("v1");
87
+ recordPlanDecision(session, 1, "approve", at(1));
88
+ for (let i = 2; i <= 53; i += 1) {
89
+ appendPlanVersion(session, { text: `v${i}`, now: at(i) });
90
+ }
91
+ expect(session.versions.length).toBeLessThanOrEqual(50);
92
+ expect(session.versions.some((version) => version.n === 1 && version.decision?.action === "approve")).toBe(true);
93
+ expect(latestVersion(session).n).toBe(53);
94
+ expect(existsSync(join(session.dir, "v001.md"))).toBe(true);
95
+
96
+ // The next identity follows the highest revision number, not the number
97
+ // of retained entries — otherwise pruning reuses 51 and overwrites it.
98
+ const next = appendPlanVersion(session, { text: "v54", now: at(54) });
99
+ expect(next.n).toBe(54);
100
+ expect(new Set(session.versions.map((version) => version.n)).size).toBe(session.versions.length);
101
+ expect(readVersionText(session, 54)).toBe("v54");
102
+ });
103
+ });
104
+
105
+ describe("annotations and decisions", () => {
106
+ it("persists annotations on the revision they belong to", () => {
107
+ const session = makeSession();
108
+ setPlanAnnotations(session, 1, {
109
+ global: [{ verdict: "change", comment: "rethink scope" }],
110
+ blocks: [{ blockId: session.versions[0].blocks[0].id, annotations: [{ verdict: "question", comment: "why?" }] }],
111
+ });
112
+ const reloaded = loadPlanSession(session.dir);
113
+ expect(reloaded.versions[0].annotations.global).toHaveLength(1);
114
+ expect(reloaded.versions[0].annotations.blocks[0].annotations[0].verdict).toBe("question");
115
+ });
116
+
117
+ it("records a decision with a timestamp", () => {
118
+ const session = makeSession();
119
+ recordPlanDecision(session, 1, "approve", at(5));
120
+ expect(loadPlanSession(session.dir).versions[0].decision).toEqual({
121
+ action: "approve",
122
+ at: at(5).toISOString(),
123
+ });
124
+ });
125
+
126
+ it("refuses a revision that does not exist", () => {
127
+ const session = makeSession();
128
+ expect(() => recordPlanDecision(session, 99, "approve")).toThrow(/no plan revision 99/);
129
+ expect(() => setPlanAnnotations(session, 99, { global: [], blocks: [] })).toThrow(/no plan revision 99/);
130
+ });
131
+ });
132
+
133
+ describe("loadPlanSession", () => {
134
+ it("reports a corrupt state file with its path", () => {
135
+ const session = makeSession();
136
+ writeFileSync(join(session.dir, "state.json"), "{not json");
137
+ expect(() => loadPlanSession(session.dir)).toThrow(/cannot read plan state at .*state\.json/);
138
+ });
139
+
140
+ it("lists sessions that have a state file", () => {
141
+ const session = makeSession();
142
+ const dirs = listPlanSessions(agentDir);
143
+ expect(dirs).toContain(session.dir);
144
+ });
145
+ });
@@ -0,0 +1,244 @@
1
+ /**
2
+ * plan store — every submitted revision, on disk.
3
+ *
4
+ * A plan review is a series of revisions, and the operator needs to look back
5
+ * at any of them ("what did v2 say before I asked for the split?"). So each
6
+ * submit snapshots the file into `<agent-dir>/ask-plan/<slug>/vNNN.md` and
7
+ * `state.json` keeps the metadata: blocks, the block-level diff against the
8
+ * previous revision, the annotations attached to it, and the decision.
9
+ *
10
+ * Deliberately outside the project tree: a review generates many revisions and
11
+ * polluting `git status` with them would be noise. The approved plan itself
12
+ * stays where the agent wrote it (`specs/<slug>.md`) — the store never rewrites
13
+ * that file, so "approved bytes == committed bytes" holds.
14
+ */
15
+ import {
16
+ existsSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ renameSync,
21
+ unlinkSync,
22
+ writeFileSync,
23
+ } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { parseBlocks, type Block } from "./blocks.js";
26
+ import { diffBlocks, type DiffEntry } from "./diff.js";
27
+ import type { Annotation, BlockAnnotations } from "./feedback.js";
28
+
29
+ export interface PlanAnnotations {
30
+ global: Annotation[];
31
+ blocks: BlockAnnotations[];
32
+ }
33
+
34
+ export interface PlanDecision {
35
+ action: "approve" | "deny";
36
+ at: string;
37
+ }
38
+
39
+ export interface PlanVersionMeta {
40
+ /** 1-based revision number. */
41
+ n: number;
42
+ at: string;
43
+ /** File the agent submitted from, when known. */
44
+ source?: string;
45
+ blocks: Block[];
46
+ /** Diff against revision n-1 ([] for the first). */
47
+ diff: DiffEntry[];
48
+ annotations: PlanAnnotations;
49
+ decision?: PlanDecision;
50
+ }
51
+
52
+ export interface PlanSession {
53
+ slug: string;
54
+ dir: string;
55
+ createdAt: string;
56
+ versions: PlanVersionMeta[];
57
+ }
58
+
59
+ /** Keep at most this many revisions; the oldest undecided ones go first. */
60
+ const MAX_VERSIONS = 50;
61
+
62
+ export function emptyAnnotations(): PlanAnnotations {
63
+ return { global: [], blocks: [] };
64
+ }
65
+
66
+ /** Slug for a directory name: ascii-ish, lowercase, bounded. */
67
+ export function planSlug(raw: string): string {
68
+ const slug = raw
69
+ .toLowerCase()
70
+ .replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-")
71
+ .replace(/^-+|-+$/g, "")
72
+ .slice(0, 40);
73
+ return slug || "plan";
74
+ }
75
+
76
+ function versionFile(dir: string, n: number): string {
77
+ return join(dir, `v${String(n).padStart(3, "0")}.md`);
78
+ }
79
+
80
+ function writeAtomic(path: string, content: string): void {
81
+ const tmp = `${path}.tmp-${process.pid}`;
82
+ writeFileSync(tmp, content, "utf8");
83
+ renameSync(tmp, path);
84
+ }
85
+
86
+ /** Pick a directory for the slug, appending -2, -3 … when one already exists. */
87
+ function allocateDir(root: string, slug: string): { dir: string; slug: string } {
88
+ mkdirSync(root, { recursive: true });
89
+ for (let attempt = 1; attempt < 100; attempt += 1) {
90
+ const candidate = attempt === 1 ? slug : `${slug}-${attempt}`;
91
+ const dir = join(root, candidate);
92
+ if (!existsSync(dir)) {
93
+ mkdirSync(dir, { recursive: true });
94
+ return { dir, slug: candidate };
95
+ }
96
+ }
97
+ throw new Error(`cannot allocate a directory for plan slug "${slug}" in ${root}`);
98
+ }
99
+
100
+ function saveState(session: PlanSession): void {
101
+ writeAtomic(join(session.dir, "state.json"), `${JSON.stringify(session, null, 2)}\n`);
102
+ }
103
+
104
+ /** Trim old revisions: never drop the latest, never drop a decided one. */
105
+ function pruneVersions(session: PlanSession): void {
106
+ if (session.versions.length <= MAX_VERSIONS) return;
107
+ const keep: PlanVersionMeta[] = [];
108
+ const latest = session.versions.at(-1);
109
+ // Iterate oldest → newest, dropping undecided revisions while over budget.
110
+ for (const version of session.versions) {
111
+ const overBudget = session.versions.length - keep.length > MAX_VERSIONS;
112
+ const protectedVersion = version.decision !== undefined || version === latest;
113
+ if (overBudget && !protectedVersion) {
114
+ const path = versionFile(session.dir, version.n);
115
+ if (existsSync(path)) unlinkSync(path);
116
+ continue;
117
+ }
118
+ keep.push(version);
119
+ }
120
+ session.versions = keep;
121
+ }
122
+
123
+ export interface CreatePlanSessionOptions {
124
+ /** `<agent-dir>` — the store lives at `<agentDir>/ask-plan/`. */
125
+ agentDir: string;
126
+ slug: string;
127
+ text: string;
128
+ source?: string;
129
+ now?: Date;
130
+ }
131
+
132
+ export function createPlanSession(options: CreatePlanSessionOptions): PlanSession {
133
+ const now = options.now ?? new Date();
134
+ const root = join(options.agentDir, "ask-plan");
135
+ const { dir, slug } = allocateDir(root, planSlug(options.slug));
136
+ const session: PlanSession = {
137
+ slug,
138
+ dir,
139
+ createdAt: now.toISOString(),
140
+ versions: [],
141
+ };
142
+ appendPlanVersion(session, {
143
+ text: options.text,
144
+ source: options.source,
145
+ now,
146
+ });
147
+ return session;
148
+ }
149
+
150
+ export interface AppendVersionOptions {
151
+ text: string;
152
+ source?: string;
153
+ now?: Date;
154
+ }
155
+
156
+ /** Snapshot a new revision, diffing it against the previous one. */
157
+ export function appendPlanVersion(
158
+ session: PlanSession,
159
+ options: AppendVersionOptions,
160
+ ): PlanVersionMeta {
161
+ const now = options.now ?? new Date();
162
+ const previous = session.versions.at(-1);
163
+ const blocks = parseBlocks(options.text);
164
+ // Revision numbers are identities, not positions. Pruning old revisions must
165
+ // never make the next submission reuse an existing number (and overwrite its
166
+ // snapshot or merge its annotations into the wrong review round).
167
+ const version: PlanVersionMeta = {
168
+ n: (previous?.n ?? 0) + 1,
169
+ at: now.toISOString(),
170
+ source: options.source,
171
+ blocks,
172
+ diff: previous ? diffBlocks(previous.blocks, blocks) : [],
173
+ annotations: emptyAnnotations(),
174
+ };
175
+ session.versions.push(version);
176
+ writeAtomic(versionFile(session.dir, version.n), options.text);
177
+ pruneVersions(session);
178
+ saveState(session);
179
+ return version;
180
+ }
181
+
182
+ export function setPlanAnnotations(
183
+ session: PlanSession,
184
+ n: number,
185
+ annotations: PlanAnnotations,
186
+ ): void {
187
+ const version = session.versions.find((candidate) => candidate.n === n);
188
+ if (!version) throw new Error(`no plan revision ${n} in ${session.dir}`);
189
+ version.annotations = annotations;
190
+ saveState(session);
191
+ }
192
+
193
+ export function recordPlanDecision(
194
+ session: PlanSession,
195
+ n: number,
196
+ action: "approve" | "deny",
197
+ now: Date = new Date(),
198
+ ): void {
199
+ const version = session.versions.find((candidate) => candidate.n === n);
200
+ if (!version) throw new Error(`no plan revision ${n} in ${session.dir}`);
201
+ version.decision = { action, at: now.toISOString() };
202
+ saveState(session);
203
+ }
204
+
205
+ export function latestVersion(session: PlanSession): PlanVersionMeta {
206
+ const version = session.versions.at(-1);
207
+ if (!version) throw new Error(`plan session ${session.dir} has no revisions`);
208
+ return version;
209
+ }
210
+
211
+ export function readVersionText(session: PlanSession, n: number): string {
212
+ return readFileSync(versionFile(session.dir, n), "utf8");
213
+ }
214
+
215
+ /**
216
+ * Load a session from disk (used by tests and by `/ask-plan open` after a reload).
217
+ * A corrupt state file is reported with the path — a raw SyntaxError from
218
+ * JSON.parse would leave the operator guessing which file is broken.
219
+ */
220
+ export function loadPlanSession(dir: string): PlanSession {
221
+ const path = join(dir, "state.json");
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(readFileSync(path, "utf8"));
225
+ } catch (error) {
226
+ const reason = error instanceof Error ? error.message : String(error);
227
+ throw new Error(`cannot read plan state at ${path}: ${reason}`);
228
+ }
229
+ if (!parsed || typeof parsed !== "object") {
230
+ throw new Error(`plan state at ${path} is not an object`);
231
+ }
232
+ return { ...(parsed as PlanSession), dir };
233
+ }
234
+
235
+ /** Directories under `<agentDir>/ask-plan/`, newest first. */
236
+ export function listPlanSessions(agentDir: string): string[] {
237
+ const root = join(agentDir, "ask-plan");
238
+ if (!existsSync(root)) return [];
239
+ return readdirSync(root, { withFileTypes: true })
240
+ .filter((entry) => entry.isDirectory())
241
+ .map((entry) => join(root, entry.name))
242
+ .filter((dir) => existsSync(join(dir, "state.json")))
243
+ .sort((a, b) => a.localeCompare(b));
244
+ }