@andares/pi-toolkits 0.12.4 → 0.14.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 (77) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +134 -17
  3. package/README.zh-CN.md +115 -16
  4. package/package.json +24 -11
  5. package/src/features/ask/index.ts +6 -0
  6. package/src/features/init/apply.ts +32 -12
  7. package/src/features/init/audit-uat.test.ts +103 -0
  8. package/src/features/init/audit.ts +148 -0
  9. package/src/features/init/detect.ts +4 -0
  10. package/src/features/init/index.ts +47 -2
  11. package/src/features/init/plan.ts +11 -0
  12. package/src/features/init/refresh.test.ts +208 -0
  13. package/src/features/init/refresh.ts +255 -0
  14. package/src/features/init/spec.ts +20 -0
  15. package/src/features/init/templates/agents-skeleton.md +2 -0
  16. package/src/features/init/templates/uat-readme.md +53 -0
  17. package/src/features/init/templates/workflow-block.md +21 -0
  18. package/src/features/init/templates.test.ts +3 -1
  19. package/src/features/init/templates.ts +2 -0
  20. package/src/features/init/types.ts +12 -1
  21. package/src/features/permission/index.ts +32 -0
  22. package/src/features/permission/policy.test.ts +10 -0
  23. package/src/features/permission/units.test.ts +157 -0
  24. package/src/features/permission/units.ts +317 -15
  25. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  26. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  27. package/src/features/plan/assets/index.html +14 -0
  28. package/src/features/plan/assets.test.ts +64 -0
  29. package/src/features/plan/blocks.test.ts +77 -0
  30. package/src/features/plan/blocks.ts +153 -0
  31. package/src/features/plan/diff.test.ts +144 -0
  32. package/src/features/plan/diff.ts +193 -0
  33. package/src/features/plan/feedback.test.ts +233 -0
  34. package/src/features/plan/feedback.ts +182 -0
  35. package/src/features/plan/index.test.ts +385 -0
  36. package/src/features/plan/index.ts +433 -0
  37. package/src/features/plan/prompt.test.ts +91 -0
  38. package/src/features/plan/prompt.ts +110 -0
  39. package/src/features/plan/render.test.ts +94 -0
  40. package/src/features/plan/render.ts +131 -0
  41. package/src/features/plan/server.test.ts +374 -0
  42. package/src/features/plan/server.ts +272 -0
  43. package/src/features/plan/store.test.ts +145 -0
  44. package/src/features/plan/store.ts +244 -0
  45. package/src/features/review/index.ts +54 -28
  46. package/src/features/review/review.test.ts +46 -1
  47. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  48. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  49. package/src/features/uat/assets/index.html +14 -0
  50. package/src/features/uat/constants.ts +23 -0
  51. package/src/features/uat/index.test.ts +404 -0
  52. package/src/features/uat/index.ts +329 -0
  53. package/src/features/uat/item-tool.ts +280 -0
  54. package/src/features/uat/ledger.test.ts +249 -0
  55. package/src/features/uat/ledger.ts +504 -0
  56. package/src/features/uat/prompt.ts +78 -0
  57. package/src/features/uat/record-tool.ts +167 -0
  58. package/src/features/uat/records.test.ts +145 -0
  59. package/src/features/uat/records.ts +268 -0
  60. package/src/features/uat/server.ts +181 -0
  61. package/src/features/uat/state.test.ts +41 -0
  62. package/src/features/uat/state.ts +67 -0
  63. package/src/features/whats-new/changelog.ts +104 -0
  64. package/src/features/whats-new/constants.ts +35 -0
  65. package/src/features/whats-new/index.ts +146 -0
  66. package/src/features/whats-new/notice.ts +68 -0
  67. package/src/features/whats-new/paths.ts +29 -0
  68. package/src/features/whats-new/store.ts +114 -0
  69. package/src/features/whats-new/version.ts +43 -0
  70. package/src/features/whats-new/whats-new.test.ts +460 -0
  71. package/src/index.ts +13 -1
  72. package/src/lib/ask-control.ts +25 -0
  73. package/src/lib/opener.test.ts +72 -0
  74. package/src/lib/opener.ts +121 -0
  75. package/src/lib/permission-control.ts +39 -0
  76. package/src/lib/startup.test.ts +1 -1
  77. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,404 @@
1
+ /**
2
+ * ask-uat wiring: command, clustering tool, page server, toggle round-trip.
3
+ *
4
+ * The server is real (a checkbox write is only proven by an HTTP round-trip),
5
+ * the browser opener is a fake, and the project root is injected so the test
6
+ * never shells out to git.
7
+ */
8
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
+ import { request } from "node:http";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import { setAskControl } from "../../lib/ask-control.js";
15
+ import { registerUat, uatSummary } from "./index.js";
16
+ import { RECORD_CHANGE_TOOL, UAT_COMMAND, UAT_ITEM_TOOL } from "./constants.js";
17
+ import { createRecord, isoMinute } from "./records.js";
18
+
19
+ /**
20
+ * Every timestamp in this file is derived from this one date. Headers carry the
21
+ * machine's UTC offset, so writing the offset out by hand makes the assertion
22
+ * pass only in the author's timezone (CI is UTC and caught exactly that).
23
+ */
24
+ const fixedNow = new Date(2026, 10, 13, 21, 7);
25
+
26
+ let root: string;
27
+ let sessionId = "s-1";
28
+
29
+ beforeEach(() => {
30
+ root = mkdtempSync(join(tmpdir(), "uat-index-"));
31
+ sessionId = `s-${Math.random().toString(36).slice(2, 8)}`;
32
+ mkdirSync(join(root, ".agents/framework"), { recursive: true });
33
+ writeFileSync(join(root, ".agents/framework/state.toml"), 'version = 1\ntool = "test"\n', "utf8");
34
+ });
35
+
36
+ afterEach(() => {
37
+ setAskControl(undefined);
38
+ rmSync(root, { recursive: true, force: true });
39
+ });
40
+
41
+ interface Harness {
42
+ pi: ExtensionAPI;
43
+ commands: Map<string, { handler: (args: string, ctx: ExtensionContext) => Promise<void> }>;
44
+ tools: Map<
45
+ string,
46
+ { execute: (id: string, params: Record<string, unknown>, a?: unknown, b?: unknown, ctx?: ExtensionContext) => Promise<{ content: Array<{ text: string }>; details: unknown; isError?: boolean }> }
47
+ >;
48
+ handlers: Record<string, Array<(event: { systemPrompt: string }, ctx?: ExtensionContext) => unknown>>;
49
+ sendUserMessage: ReturnType<typeof vi.fn>;
50
+ notify: ReturnType<typeof vi.fn>;
51
+ openBrowser: ReturnType<typeof vi.fn>;
52
+ activeTools: () => string[];
53
+ ctx: ExtensionContext;
54
+ shutdown: () => void;
55
+ }
56
+
57
+ function harness(): Harness {
58
+ const commands = new Map<string, { handler: (args: string, ctx: ExtensionContext) => Promise<void> }>();
59
+ const tools = new Map<string, never>();
60
+ const handlers: Harness["handlers"] = {};
61
+ let activeTools = ["read", "grep", "bash", "write", "edit"];
62
+ const sendUserMessage = vi.fn();
63
+ const pi = {
64
+ registerCommand: (name: string, def: never) => commands.set(name, def),
65
+ registerTool: (def: { name: string }) => tools.set(def.name, def as never),
66
+ on: (type: string, handler: never) => {
67
+ handlers[type] = [...(handlers[type] ?? []), handler];
68
+ },
69
+ getActiveTools: () => activeTools,
70
+ setActiveTools: (names: string[]) => {
71
+ activeTools = names;
72
+ },
73
+ sendUserMessage,
74
+ } as unknown as ExtensionAPI;
75
+ const notify = vi.fn();
76
+ const ctx = {
77
+ cwd: root,
78
+ hasUI: true,
79
+ isIdle: () => true,
80
+ ui: { notify },
81
+ sessionManager: { getSessionId: () => sessionId },
82
+ } as unknown as ExtensionContext;
83
+ const openBrowser = vi.fn();
84
+ registerUat(pi, {
85
+ openBrowser,
86
+ root: (cwd) => cwd,
87
+ now: () => fixedNow,
88
+ portStart: 47_000 + Math.floor(Math.random() * 800),
89
+ idleCloseMs: 0,
90
+ });
91
+ return {
92
+ pi,
93
+ commands,
94
+ tools: tools as unknown as Harness["tools"],
95
+ handlers,
96
+ sendUserMessage,
97
+ notify,
98
+ openBrowser,
99
+ activeTools: () => activeTools,
100
+ ctx,
101
+ shutdown: () => {
102
+ for (const handler of handlers.session_shutdown ?? []) handler({ systemPrompt: "" });
103
+ },
104
+ };
105
+ }
106
+
107
+ /** POST JSON the way the page does. */
108
+ async function post(url: string, path: string, body: unknown): Promise<{ status: number; body: any }> {
109
+ const parsed = new URL(url);
110
+ const token = parsed.searchParams.get("t") ?? "";
111
+ return new Promise((resolve, reject) => {
112
+ const req = request(
113
+ {
114
+ host: "127.0.0.1",
115
+ port: Number(parsed.port),
116
+ path,
117
+ method: "POST",
118
+ headers: { "content-type": "application/json", "x-plan-token": token },
119
+ },
120
+ (res) => {
121
+ const chunks: Buffer[] = [];
122
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
123
+ res.on("end", () =>
124
+ resolve({
125
+ status: res.statusCode ?? 0,
126
+ body: JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"),
127
+ }),
128
+ );
129
+ },
130
+ );
131
+ req.on("error", reject);
132
+ req.write(JSON.stringify(body));
133
+ req.end();
134
+ });
135
+ }
136
+
137
+ async function get(url: string, path: string): Promise<any> {
138
+ const parsed = new URL(url);
139
+ const token = parsed.searchParams.get("t") ?? "";
140
+ return new Promise((resolve, reject) => {
141
+ const req = request(
142
+ {
143
+ host: "127.0.0.1",
144
+ port: Number(parsed.port),
145
+ path,
146
+ method: "GET",
147
+ headers: { "x-plan-token": token },
148
+ },
149
+ (res) => {
150
+ const chunks: Buffer[] = [];
151
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
152
+ res.on("end", () =>
153
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}")),
154
+ );
155
+ },
156
+ );
157
+ req.on("error", reject);
158
+ req.end();
159
+ });
160
+ }
161
+
162
+ describe("ask-uat command", () => {
163
+ it("refuses a project without the framework", async () => {
164
+ rmSync(join(root, ".agents/framework"), { recursive: true, force: true });
165
+ const h = harness();
166
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
167
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("run /ask-init first"), "error");
168
+ expect(h.openBrowser).not.toHaveBeenCalled();
169
+ });
170
+
171
+ it("opens the page and dispatches clustering only when records are pending", async () => {
172
+ createRecord(root, { title: "alpha change", body: "body", now: new Date(2026, 10, 12, 9, 0) });
173
+ const h = harness();
174
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
175
+
176
+ expect(h.openBrowser).toHaveBeenCalledTimes(1);
177
+ expect(h.activeTools()).toContain(UAT_ITEM_TOOL);
178
+ expect(h.activeTools()).toContain(RECORD_CHANGE_TOOL);
179
+ expect(h.sendUserMessage).toHaveBeenCalledTimes(1);
180
+ expect(h.sendUserMessage.mock.calls[0][0]).toContain("alpha change");
181
+
182
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
183
+ expect(h.activeTools()).not.toContain(UAT_ITEM_TOOL);
184
+ h.shutdown();
185
+ });
186
+
187
+ it("does not dispatch a turn when nothing is pending", async () => {
188
+ const h = harness();
189
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
190
+ expect(h.openBrowser).toHaveBeenCalledTimes(1);
191
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
192
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("0 pending"), "info");
193
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
194
+ h.shutdown();
195
+ });
196
+
197
+ it("reopens the existing page instead of starting twice", async () => {
198
+ const h = harness();
199
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
200
+ await h.commands.get(UAT_COMMAND)!.handler("open", h.ctx);
201
+ expect(h.openBrowser).toHaveBeenCalledTimes(2);
202
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
203
+ h.shutdown();
204
+ });
205
+
206
+ it("clusters newly pending records when the page is already open", async () => {
207
+ const h = harness();
208
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
209
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
210
+ createRecord(root, { title: "later change", body: "body", now: new Date(2026, 10, 13, 20, 0) });
211
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
212
+ expect(h.sendUserMessage).toHaveBeenCalledWith(expect.stringContaining("later change"));
213
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
214
+ h.shutdown();
215
+ });
216
+
217
+ it("removes phase tools on a session switch", async () => {
218
+ const h = harness();
219
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
220
+ expect(h.activeTools()).toContain(UAT_ITEM_TOOL);
221
+ sessionId = "another-session";
222
+ for (const handler of h.handlers.session_start ?? []) handler({ systemPrompt: "" }, h.ctx);
223
+ expect(h.activeTools()).not.toContain(UAT_ITEM_TOOL);
224
+ expect(h.activeTools()).toContain(RECORD_CHANGE_TOOL);
225
+ h.shutdown();
226
+ });
227
+
228
+ it("exits consult mode deliberately and refuses to start during planning", async () => {
229
+ let consulting = true;
230
+ setAskControl({ isActive: () => consulting, exit: () => { consulting = false; } });
231
+ const h = harness();
232
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
233
+ expect(consulting).toBe(false);
234
+ expect(h.openBrowser).toHaveBeenCalledTimes(1);
235
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
236
+
237
+ h.pi.setActiveTools([...h.activeTools(), "plan_submit"]);
238
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
239
+ expect(h.notify).toHaveBeenLastCalledWith(expect.stringContaining("finish or approve the plan"), "warning");
240
+ expect(h.openBrowser).toHaveBeenCalledTimes(1);
241
+ h.shutdown();
242
+ });
243
+
244
+ it("keeps record_change out of read-only consult and planning phases", async () => {
245
+ setAskControl({ isActive: () => true, exit: () => {} });
246
+ const h = harness();
247
+ for (const handler of h.handlers.before_agent_start ?? []) handler({ systemPrompt: "base" }, h.ctx);
248
+ expect(h.activeTools()).not.toContain(RECORD_CHANGE_TOOL);
249
+ const result = await h.tools.get(RECORD_CHANGE_TOOL)!.execute(
250
+ "t",
251
+ { title: "forbidden", body: "body", behavior: "must not write" },
252
+ undefined,
253
+ undefined,
254
+ h.ctx,
255
+ );
256
+ expect(result.isError).toBe(true);
257
+ expect(existsSync(join(root, ".agents/implementations/2026-11-13_2107_forbidden.md"))).toBe(false);
258
+
259
+ setAskControl(undefined);
260
+ h.pi.setActiveTools([...h.activeTools(), "plan_submit"]);
261
+ for (const handler of h.handlers.before_agent_start ?? []) handler({ systemPrompt: "base" }, h.ctx);
262
+ expect(h.activeTools()).not.toContain(RECORD_CHANGE_TOOL);
263
+ h.shutdown();
264
+ });
265
+ });
266
+
267
+ describe("record_change", () => {
268
+ it("writes the canonical record and the candidate event", async () => {
269
+ const h = harness();
270
+ const result = await h.tools.get(RECORD_CHANGE_TOOL)!.execute(
271
+ "t",
272
+ {
273
+ title: "Ask UAT lands",
274
+ body: "## What\n\nDone.",
275
+ behavior: "The operator opens /ask-uat and sees pending items.",
276
+ hint: "run /ask-uat, tick one item",
277
+ },
278
+ undefined,
279
+ undefined,
280
+ h.ctx,
281
+ );
282
+ const text = result.content[0].text;
283
+ expect(text).toContain("registered it for acceptance");
284
+ const file = join(root, ".agents/implementations/2026-11-13_2107_ask-uat-lands.md");
285
+ expect(existsSync(file)).toBe(true);
286
+ const content = readFileSync(file, "utf8");
287
+ expect(content.split("\n")[0]).toBe(`# ${isoMinute(fixedNow)} — Ask UAT lands`);
288
+ expect(readFileSync(join(root, ".agents/uat/ledger.jsonl"), "utf8")).toContain("candidate");
289
+ h.shutdown();
290
+ });
291
+
292
+ it("refuses outside a framework project", async () => {
293
+ rmSync(join(root, ".agents/framework"), { recursive: true, force: true });
294
+ const h = harness();
295
+ const result = await h.tools.get(RECORD_CHANGE_TOOL)!.execute(
296
+ "t",
297
+ { title: "x", body: "y", behavior: "z" },
298
+ undefined,
299
+ undefined,
300
+ h.ctx,
301
+ );
302
+ expect(result.isError).toBe(true);
303
+ expect(result.content[0].text).toContain("/ask-init");
304
+ h.shutdown();
305
+ });
306
+ });
307
+
308
+ describe("page round-trip", () => {
309
+ it("clusters an item, then accepts it through the API", async () => {
310
+ const first = createRecord(root, {
311
+ title: "alpha change",
312
+ body: "body",
313
+ now: new Date(2026, 10, 12, 9, 0),
314
+ });
315
+ const second = createRecord(root, {
316
+ title: "beta change",
317
+ body: "body",
318
+ now: new Date(2026, 10, 12, 10, 0),
319
+ });
320
+ const h = harness();
321
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
322
+ const url = h.openBrowser.mock.calls[0][0] as string;
323
+
324
+ const created = await h.tools.get(UAT_ITEM_TOOL)!.execute(
325
+ "t",
326
+ {
327
+ op: "create",
328
+ title: "One behaviour",
329
+ summary: "The operator can do the thing.",
330
+ steps: ["open it", "see it"],
331
+ reports: [first.entry.id, second.entry.id],
332
+ },
333
+ undefined,
334
+ undefined,
335
+ h.ctx,
336
+ );
337
+ expect(created.content[0].text).toContain("Created U-");
338
+
339
+ let state = await get(url, "/api/state");
340
+ expect(state.items).toHaveLength(1);
341
+ expect(state.pending).toHaveLength(0);
342
+ expect(state.counts.open).toBe(1);
343
+
344
+ const itemId = state.items[0].id;
345
+ const toggled = await post(url, "/api/toggle", { item: itemId, checked: true });
346
+ expect(toggled.status).toBe(200);
347
+ expect(toggled.body.state.checked).toHaveLength(1);
348
+
349
+ state = await get(url, "/api/state");
350
+ expect(state.checked[0].id).toBe(itemId);
351
+ expect(uatSummary(root).counts.checked).toBe(1);
352
+
353
+ // Evidence is reachable from the page.
354
+ const report = await get(url, `/api/report?id=${encodeURIComponent(first.entry.id)}`);
355
+ expect(report.text).toContain("alpha change");
356
+
357
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
358
+ h.shutdown();
359
+ });
360
+
361
+ it("rejects a toggle for an unknown item", async () => {
362
+ const h = harness();
363
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
364
+ const url = h.openBrowser.mock.calls[0][0] as string;
365
+ const response = await post(url, "/api/toggle", { item: "U-nope", checked: true });
366
+ expect(response.status).toBe(404);
367
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
368
+ h.shutdown();
369
+ });
370
+
371
+ it("rejects a malformed toggle instead of treating it as an uncheck", async () => {
372
+ const first = createRecord(root, { title: "alpha", body: "body", now: new Date(2026, 10, 12, 9, 0) });
373
+ const h = harness();
374
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
375
+ const url = h.openBrowser.mock.calls[0][0] as string;
376
+ const created = await h.tools.get(UAT_ITEM_TOOL)!.execute(
377
+ "t",
378
+ { op: "create", title: "One", summary: "Summary", reports: [first.entry.id] },
379
+ undefined,
380
+ undefined,
381
+ h.ctx,
382
+ );
383
+ const itemId = (created.details as { item: string }).item;
384
+ const response = await post(url, "/api/toggle", { item: itemId, checked: "yes" });
385
+ expect(response.status).toBe(400);
386
+ expect(uatSummary(root).items[0]?.checkedAt).toBeUndefined();
387
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
388
+ h.shutdown();
389
+ });
390
+
391
+ it("gives same-minute same-title items distinct identities", async () => {
392
+ const first = createRecord(root, { title: "alpha", body: "body", now: new Date(2026, 10, 12, 9, 0) });
393
+ const second = createRecord(root, { title: "beta", body: "body", now: new Date(2026, 10, 12, 10, 0) });
394
+ const h = harness();
395
+ await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
396
+ const params = (report: string) => ({ op: "create", title: "Same", summary: "Summary", reports: [report] });
397
+ const one = await h.tools.get(UAT_ITEM_TOOL)!.execute("t", params(first.entry.id), undefined, undefined, h.ctx);
398
+ const two = await h.tools.get(UAT_ITEM_TOOL)!.execute("t", params(second.entry.id), undefined, undefined, h.ctx);
399
+ expect((one.details as { item: string }).item).not.toBe((two.details as { item: string }).item);
400
+ expect(uatSummary(root).items).toHaveLength(2);
401
+ await h.commands.get(UAT_COMMAND)!.handler("off", h.ctx);
402
+ h.shutdown();
403
+ });
404
+ });