@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,329 @@
1
+ /**
2
+ * ask-uat — the acceptance phase.
3
+ *
4
+ * `/ask-uat` opens a page that answers one question: *"what did I ship that I
5
+ * have not verified yet?"* The flow is deliberately shallow:
6
+ *
7
+ * pending change records ──cluster──▶ acceptance items ──check──▶ accepted
8
+ *
9
+ * - the page opens first, then the clustering work order is dispatched, so
10
+ * items stream into the page while the agent works;
11
+ * - `uat_item` is the only writer of item identity, and it is active only in
12
+ * this phase; `record_change` is active in framework projects outside the
13
+ * read-only consult and planning phases;
14
+ * - nothing here edits code, and there is no submit: a checkbox appends one
15
+ * event to `.agents/uat/ledger.jsonl` and that is the whole decision.
16
+ *
17
+ * The phase ends on `/ask-uat off`, on a session switch, or after the configured
18
+ * idle timeout.
19
+ */
20
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
21
+ import { getAskControl } from "../../lib/ask-control.js";
22
+ import { openInBrowser } from "../../lib/opener.js";
23
+ import {
24
+ MAX_CANDIDATES_PER_RUN,
25
+ MAX_ITEMS_PER_RUN,
26
+ RECORD_CHANGE_TOOL,
27
+ UAT_COMMAND,
28
+ UAT_IDLE_CLOSE_MS,
29
+ } from "./constants.js";
30
+ import { registerUatItemTool } from "./item-tool.js";
31
+ import { deriveState, ledgerPath, readEvents, appendEvent, newEventId } from "./ledger.js";
32
+ import { listRecords } from "./records.js";
33
+ import { buildUatKickoff, describeCounts, UAT_MODE_BANNER } from "./prompt.js";
34
+ import { registerRecordTool } from "./record-tool.js";
35
+ import { startUatServer, type UatServerHandle } from "./server.js";
36
+ import { frameworkInstalled, loadSnapshot, resolveProjectRoot } from "./state.js";
37
+
38
+ export interface UatOptions {
39
+ /** Opening the browser is injectable so tests never spawn one. */
40
+ openBrowser?: (url: string) => unknown;
41
+ portStart?: number;
42
+ portAttempts?: number;
43
+ idleCloseMs?: number;
44
+ now?: () => Date;
45
+ root?: (cwd: string) => string;
46
+ maxCandidates?: number;
47
+ maxItems?: number;
48
+ }
49
+
50
+ function sessionIdOf(ctx: ExtensionContext): string {
51
+ try {
52
+ return ctx.sessionManager.getSessionId();
53
+ } catch {
54
+ return `pid-${process.pid}`;
55
+ }
56
+ }
57
+
58
+ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
59
+ const open = options.openBrowser ?? openInBrowser;
60
+ const now = options.now ?? (() => new Date());
61
+ const rootOf = options.root ?? resolveProjectRoot;
62
+ const idleCloseMs = options.idleCloseMs ?? UAT_IDLE_CLOSE_MS;
63
+ const maxCandidates = options.maxCandidates ?? MAX_CANDIDATES_PER_RUN;
64
+ const maxItems = options.maxItems ?? MAX_ITEMS_PER_RUN;
65
+
66
+ let active = false;
67
+ let server: UatServerHandle | undefined;
68
+ let batch: string | undefined;
69
+ let root: string | undefined;
70
+ let ctxRef: ExtensionContext | undefined;
71
+ let uatSessionId: string | undefined;
72
+ let lastActivity = Date.now();
73
+ let idleTimer: NodeJS.Timeout | undefined;
74
+
75
+ // `plan_submit` is the owning feature's phase marker. Detecting the active
76
+ // tool avoids a second global control registry while still keeping the two
77
+ // phases' write surfaces disjoint.
78
+ const planningTool = "plan_submit";
79
+
80
+ function recordChangeAllowed(tools: readonly string[] = pi.getActiveTools()): boolean {
81
+ return !getAskControl()?.isActive() && !tools.includes(planningTool);
82
+ }
83
+
84
+ function syncRecordTool(installed: boolean): void {
85
+ const current = pi.getActiveTools();
86
+ const present = current.includes(RECORD_CHANGE_TOOL);
87
+ const wanted = installed && recordChangeAllowed(current);
88
+ if (present === wanted) return;
89
+ pi.setActiveTools(
90
+ wanted
91
+ ? [...current, RECORD_CHANGE_TOOL]
92
+ : current.filter((name) => name !== RECORD_CHANGE_TOOL),
93
+ );
94
+ }
95
+
96
+ registerRecordTool(pi, { now, root: rootOf, canRecord: () => recordChangeAllowed() });
97
+ registerUatItemTool(pi, {
98
+ isActive: () => active,
99
+ currentBatch: () => batch,
100
+ now,
101
+ root: rootOf,
102
+ });
103
+
104
+ function toolsWith(names: readonly string[], remove: readonly string[] = []): string[] {
105
+ const current = pi.getActiveTools().filter((name) => !remove.includes(name));
106
+ for (const name of names) if (!current.includes(name)) current.push(name);
107
+ return current;
108
+ }
109
+
110
+ function closeServer(): void {
111
+ if (!server) return;
112
+ const handle = server;
113
+ server = undefined;
114
+ void handle.close();
115
+ }
116
+
117
+ function clearIdle(): void {
118
+ if (idleTimer) clearInterval(idleTimer);
119
+ idleTimer = undefined;
120
+ }
121
+
122
+ function touch(): void {
123
+ lastActivity = Date.now();
124
+ }
125
+
126
+ function leave(ctx: ExtensionContext, reason: string): void {
127
+ if (!active && !server) return;
128
+ active = false;
129
+ batch = undefined;
130
+ clearIdle();
131
+ closeServer();
132
+ pi.setActiveTools(toolsWith([], ["uat_item"]));
133
+ ctx.ui.notify(`ask-uat: ${reason}`, "info");
134
+ }
135
+
136
+ function startIdleTimer(): void {
137
+ clearIdle();
138
+ if (idleCloseMs <= 0) return;
139
+ idleTimer = setInterval(() => {
140
+ if (!active || !server) return;
141
+ if (Date.now() - lastActivity < idleCloseMs) return;
142
+ const ctx = ctxRef;
143
+ if (ctx) leave(ctx, "page closed after inactivity.");
144
+ }, Math.min(60_000, Math.max(1_000, Math.floor(idleCloseMs / 4))));
145
+ idleTimer.unref();
146
+ }
147
+
148
+ /** One `batch` event per clustering run (only when there is something to cluster). */
149
+ function openBatch(candidates: number): string | undefined {
150
+ if (candidates === 0) return undefined;
151
+ const at = now();
152
+ const eventId = newEventId(at);
153
+ const id = `B-${at.getFullYear()}${String(at.getMonth() + 1).padStart(2, "0")}${String(
154
+ at.getDate(),
155
+ ).padStart(2, "0")}-${String(at.getHours()).padStart(2, "0")}${String(
156
+ at.getMinutes(),
157
+ ).padStart(2, "0")}-${eventId.slice(-6)}`;
158
+ appendEvent(ledgerPath(root ?? process.cwd()), {
159
+ v: 1,
160
+ id: eventId,
161
+ ts: at.toISOString(),
162
+ type: "batch",
163
+ batch: id,
164
+ candidates,
165
+ });
166
+ return id;
167
+ }
168
+
169
+ /** Dispatch one clustering turn; the open page streams the resulting items. */
170
+ function dispatchClustering(): void {
171
+ if (!root) return;
172
+ const state = loadSnapshot(root).state;
173
+ if (state.pending.length === 0) return;
174
+ batch = openBatch(state.pending.length);
175
+ const fresh = loadSnapshot(root).state;
176
+ pi.sendUserMessage(
177
+ buildUatKickoff({
178
+ pending: fresh.pending,
179
+ openItems: fresh.open,
180
+ maxCandidates,
181
+ maxItems,
182
+ }),
183
+ );
184
+ }
185
+
186
+ async function start(ctx: ExtensionContext): Promise<void> {
187
+ const projectRoot = rootOf(ctx.cwd || process.cwd());
188
+ if (!frameworkInstalled(projectRoot)) {
189
+ ctx.ui.notify(
190
+ "ask-uat: this project has no agent framework (.agents/framework/state.toml) — run /ask-init first.",
191
+ "error",
192
+ );
193
+ return;
194
+ }
195
+ root = projectRoot;
196
+ ctxRef = ctx;
197
+
198
+ if (pi.getActiveTools().includes(planningTool)) {
199
+ ctx.ui.notify("ask-uat: finish or approve the plan before acceptance.", "warning");
200
+ return;
201
+ }
202
+
203
+ if (active && server) {
204
+ open(server.url);
205
+ const state = loadSnapshot(projectRoot).state;
206
+ ctx.ui.notify(`ask-uat: page reopened — ${describeCounts(state)}.`, "info");
207
+ // A second /ask-uat is the explicit "cluster what arrived since then"
208
+ // action; merely reopening must not leave new records stuck forever.
209
+ if (state.pending.length > 0 && ctx.isIdle()) dispatchClustering();
210
+ return;
211
+ }
212
+
213
+ if (!ctx.isIdle()) {
214
+ ctx.ui.notify("ask-uat: the agent is still running — finish or abort first.", "warning");
215
+ return;
216
+ }
217
+
218
+ // UAT legitimately writes ledger events, so it cannot run inside the
219
+ // read-only consult phase. Match /ask-plan: the explicit phase command
220
+ // exits consult mode through its owner, preserving its tool snapshot.
221
+ const ask = getAskControl();
222
+ if (ask?.isActive()) ask.exit(ctx);
223
+
224
+ const snapshot = loadSnapshot(projectRoot);
225
+ server = await startUatServer({
226
+ root: projectRoot,
227
+ portStart: options.portStart,
228
+ portAttempts: options.portAttempts,
229
+ now,
230
+ onActivity: touch,
231
+ });
232
+ active = true;
233
+ touch();
234
+ startIdleTimer();
235
+ // The framework is installed here, so both tools belong in the request:
236
+ // clustering writes items, and the same turn may need to record a change.
237
+ pi.setActiveTools(toolsWith(["record_change", "uat_item"]));
238
+ open(server.url);
239
+
240
+ const pending = snapshot.state.pending;
241
+ const state = snapshot.state;
242
+ ctx.ui.notify(
243
+ `ask-uat: ${server.url} — ${describeCounts(state)}.`,
244
+ "info",
245
+ );
246
+ if (snapshot.skipped > 0) {
247
+ ctx.ui.notify(
248
+ `ask-uat: ${snapshot.skipped} malformed ledger line(s) were skipped — check .agents/uat/ledger.jsonl.`,
249
+ "warning",
250
+ );
251
+ }
252
+
253
+ if (pending.length === 0) return;
254
+ dispatchClustering();
255
+ }
256
+
257
+ pi.registerCommand(UAT_COMMAND, {
258
+ description:
259
+ "Acceptance: cluster unaccepted change records into user-facing items, then open the page. `open` reopens it, `off` closes it.",
260
+ handler: async (args: string, ctx: ExtensionContext) => {
261
+ const arg = args.trim();
262
+ ctxRef = ctx;
263
+ if (arg === "off") {
264
+ if (!active && !server) {
265
+ ctx.ui.notify("ask-uat: not open.", "info");
266
+ return;
267
+ }
268
+ leave(ctx, "closed.");
269
+ return;
270
+ }
271
+ if (arg === "open") {
272
+ if (!server) {
273
+ ctx.ui.notify("ask-uat: no page is open — run /ask-uat first.", "warning");
274
+ return;
275
+ }
276
+ open(server.url);
277
+ ctx.ui.notify(`ask-uat: ${server.url}`, "info");
278
+ return;
279
+ }
280
+ if (arg !== "") {
281
+ ctx.ui.notify("ask-uat: usage — /ask-uat | /ask-uat open | /ask-uat off", "warning");
282
+ return;
283
+ }
284
+ await start(ctx);
285
+ },
286
+ });
287
+
288
+ // Re-assert the tool surface every turn: the host rebuilds the loadout at the
289
+ // start of a run, so a `setActiveTools` done in `session_start` alone loses.
290
+ pi.on("before_agent_start", (event, ctx) => {
291
+ const projectRoot = root ?? rootOf(ctx.cwd || process.cwd());
292
+ syncRecordTool(frameworkInstalled(projectRoot));
293
+ if (active) {
294
+ const current = pi.getActiveTools();
295
+ if (!current.includes("uat_item")) pi.setActiveTools([...current, "uat_item"]);
296
+ }
297
+ if (!active) return undefined;
298
+ return { systemPrompt: `${event.systemPrompt}\n\n${UAT_MODE_BANNER}` };
299
+ });
300
+
301
+ pi.on("session_start", (_event, ctx) => {
302
+ const next = sessionIdOf(ctx);
303
+ ctxRef = ctx;
304
+ if (next === uatSessionId) return;
305
+ // A different session must not inherit the previous page or phase.
306
+ uatSessionId = next;
307
+ active = false;
308
+ batch = undefined;
309
+ clearIdle();
310
+ closeServer();
311
+ // Session state never leaks: remove the phase tool unconditionally, then
312
+ // recompute the record tool from the new project's framework and phase.
313
+ pi.setActiveTools(toolsWith([], ["uat_item"]));
314
+ root = rootOf(ctx.cwd || process.cwd());
315
+ syncRecordTool(frameworkInstalled(root));
316
+ });
317
+
318
+ pi.on("session_shutdown", () => {
319
+ clearIdle();
320
+ closeServer();
321
+ active = false;
322
+ });
323
+ }
324
+
325
+ /** Exported for tests: what the page would show right now, without a server. */
326
+ export function uatSummary(root: string): ReturnType<typeof deriveState> {
327
+ const records = listRecords(root);
328
+ return deriveState(records, readEvents(ledgerPath(root)).events);
329
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * UAT feature — the `uat_item` tool (clustering writes).
3
+ *
4
+ * Only active while `/ask-uat` is open. It is the single writer of acceptance
5
+ * item identity: implementation sessions append *candidates* and never create
6
+ * items, because ten parallel sessions cannot see each other and would each
7
+ * invent a near-duplicate. Clustering happens here, once, with the full set in
8
+ * view.
9
+ *
10
+ * Every operation appends to the ledger; nothing is rewritten. `merge` and
11
+ * `drop` exist because acceptance debt must be reducible: duplicates happen and
12
+ * abandoned work must be retirable without deleting history.
13
+ */
14
+ import { Type } from "typebox";
15
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
16
+ import { UAT_ITEM_TOOL } from "./constants.js";
17
+ import {
18
+ appendEvent,
19
+ deriveState,
20
+ ledgerPath,
21
+ newEventId,
22
+ readEvents,
23
+ type UatItemView,
24
+ } from "./ledger.js";
25
+ import { isoMinute, listRecords, slugify } from "./records.js";
26
+ import { resolveProjectRoot } from "./state.js";
27
+
28
+ const PARAMS = Type.Object({
29
+ op: Type.Union(
30
+ [
31
+ Type.Literal("create"),
32
+ Type.Literal("link"),
33
+ Type.Literal("amend"),
34
+ Type.Literal("merge"),
35
+ Type.Literal("drop"),
36
+ ],
37
+ {
38
+ description:
39
+ "create = new acceptance item from one or more change records; link = attach new records to an existing item; amend = revise an item's text; merge = fold duplicate items into one; drop = retire abandoned work.",
40
+ },
41
+ ),
42
+ item: Type.Optional(
43
+ Type.String({
44
+ description: "Target item id (link/amend/merge/drop). Omit for create — the id is generated.",
45
+ }),
46
+ ),
47
+ title: Type.Optional(Type.String({ description: "Short user-facing title (create/amend)." })),
48
+ summary: Type.Optional(
49
+ Type.String({
50
+ description: "2-3 user-facing sentences: what the operator can now do or see (create/amend).",
51
+ }),
52
+ ),
53
+ steps: Type.Optional(
54
+ Type.Array(Type.String({ description: "One test step and its expected result." }), {
55
+ description: "How to verify by hand, 3-6 entries (create/amend).",
56
+ }),
57
+ ),
58
+ edge: Type.Optional(
59
+ Type.Array(Type.String({ description: "One corner case worth a quick try." }), {
60
+ description: "Optional edge cases (create/amend).",
61
+ }),
62
+ ),
63
+ skip: Type.Optional(
64
+ Type.String({
65
+ description: 'What NOT to test this round, e.g. "internal refactor, no user-visible change".',
66
+ }),
67
+ ),
68
+ spec: Type.Optional(Type.String({ description: "Spec this item implements, e.g. specs/ask-uat.md." })),
69
+ area: Type.Optional(Type.String({ description: "Short area label used for grouping." })),
70
+ reports: Type.Optional(
71
+ Type.Array(Type.String({ description: "Change-record id, e.g. 2026-11-13_2107_ask-uat." }), {
72
+ description: "Change records that are evidence for this item (create/link).",
73
+ }),
74
+ ),
75
+ sources: Type.Optional(
76
+ Type.Array(Type.String({ description: "Item id to fold into `item`." }), {
77
+ description: "Items absorbed into the target on merge.",
78
+ }),
79
+ ),
80
+ reason: Type.Optional(Type.String({ description: "Why the item is dropped (drop)." })),
81
+ });
82
+
83
+ const DESCRIPTION = `Create or maintain acceptance items for the UAT page.
84
+
85
+ An acceptance item is one user-visible behaviour the operator verifies by hand; a change
86
+ record is evidence, not an item. Prefer linking new records to an existing open item over
87
+ creating a near-duplicate. Every call appends to .agents/uat/ledger.jsonl; nothing is
88
+ rewritten, and no call edits code.`;
89
+
90
+ const GUIDELINES = [
91
+ "Cluster change records into acceptance items: one item per behaviour a person can verify by hand, not one item per record.",
92
+ "Write `summary` in 2-3 sentences from the operator's point of view; never mention file names or functions there.",
93
+ "Use op=\"link\" when the new evidence belongs to an already-open item; create a new item only for a distinct behaviour.",
94
+ "Use op=\"drop\" with a reason for work that shipped but never became user-visible, or that was abandoned.",
95
+ ];
96
+
97
+ function errorResult(text: string) {
98
+ return { content: [{ type: "text" as const, text }], details: {}, isError: true };
99
+ }
100
+
101
+ function summarize(item: UatItemView): string {
102
+ return `${item.id} — ${item.title} (${item.reports.length} record${item.reports.length === 1 ? "" : "s"})`;
103
+ }
104
+
105
+ export interface UatItemToolOptions {
106
+ /** Whether `/ask-uat` currently holds the phase open. */
107
+ isActive: () => boolean;
108
+ /** Batch id assigned to items created in this run. */
109
+ currentBatch: () => string | undefined;
110
+ now?: () => Date;
111
+ root?: (cwd: string) => string;
112
+ }
113
+
114
+ export function registerUatItemTool(pi: ExtensionAPI, options: UatItemToolOptions): void {
115
+ const now = options.now ?? (() => new Date());
116
+ const rootOf = options.root ?? resolveProjectRoot;
117
+
118
+ pi.registerTool<typeof PARAMS, { item?: string }>({
119
+ name: UAT_ITEM_TOOL,
120
+ label: "Acceptance item",
121
+ description: DESCRIPTION,
122
+ promptSnippet: "Create or maintain acceptance items (ask-uat only)",
123
+ promptGuidelines: GUIDELINES,
124
+ parameters: PARAMS,
125
+ defaultActive: false,
126
+ async execute(
127
+ _toolCallId,
128
+ params,
129
+ _signal,
130
+ _onUpdate,
131
+ ctx: ExtensionContext,
132
+ ) {
133
+ if (!options.isActive()) {
134
+ return errorResult("uat_item: no UAT run is open — use /ask-uat first.");
135
+ }
136
+ const root = rootOf(ctx.cwd || process.cwd());
137
+ const records = listRecords(root);
138
+ const recordIds = new Set(records.map((record) => record.id));
139
+ const events = readEvents(ledgerPath(root)).events;
140
+ const state = deriveState(records, events);
141
+ const findItem = (id: string): UatItemView | undefined =>
142
+ state.items.find((item) => item.id === id);
143
+ const at = now();
144
+ const itemStamp = isoMinute(at);
145
+ const ts = at.toISOString();
146
+ const append = (event: Parameters<typeof appendEvent>[1]): void =>
147
+ appendEvent(ledgerPath(root), event);
148
+ const base = { v: 1, id: newEventId(at), ts } as const;
149
+
150
+ const checkReports = (reports: string[] | undefined): string[] | string => {
151
+ const list = [...new Set((reports ?? []).map((value) => value.trim()).filter(Boolean))];
152
+ if (list.length === 0) return "`reports` is required: at least one change-record id.";
153
+ const unknown = list.filter((report) => !recordIds.has(report));
154
+ if (unknown.length > 0) {
155
+ return `Unknown change record(s): ${unknown.join(", ")}. Pass ids exactly as listed by /ask-uat.`;
156
+ }
157
+ return list;
158
+ };
159
+
160
+ switch (params.op) {
161
+ case "create": {
162
+ const title = (params.title ?? "").trim();
163
+ const summary = (params.summary ?? "").trim();
164
+ if (title === "") return errorResult("uat_item: `title` is required for create.");
165
+ if (summary === "") return errorResult("uat_item: `summary` is required for create.");
166
+ const reports = checkReports(params.reports);
167
+ if (typeof reports === "string") return errorResult(`uat_item: ${reports}`);
168
+ const suffix = base.id.slice(-6);
169
+ const id = `U-${itemStamp.slice(0, 10).replace(/-/g, "")}-${itemStamp.slice(11, 13)}${itemStamp.slice(14, 16)}-${slugify(title)}-${suffix}`;
170
+ append({
171
+ ...base,
172
+ type: "item",
173
+ item: id,
174
+ batch: options.currentBatch(),
175
+ title,
176
+ summary,
177
+ steps: (params.steps ?? []).map((step) => step.trim()).filter(Boolean),
178
+ edge: (params.edge ?? []).map((edge) => edge.trim()).filter(Boolean),
179
+ skip: params.skip?.trim() || undefined,
180
+ reports,
181
+ spec: params.spec?.trim() || undefined,
182
+ area: params.area?.trim() || undefined,
183
+ });
184
+ return {
185
+ content: [
186
+ {
187
+ type: "text" as const,
188
+ text: `Created ${id} — ${title} (${reports.length} record${reports.length === 1 ? "" : "s"}). The page updates immediately.`,
189
+ },
190
+ ],
191
+ details: { item: id },
192
+ };
193
+ }
194
+ case "link": {
195
+ const item = findItem((params.item ?? "").trim());
196
+ if (!item) return errorResult("uat_item: `item` must be an existing open item id.");
197
+ const reports = checkReports(params.reports);
198
+ if (typeof reports === "string") return errorResult(`uat_item: ${reports}`);
199
+ const fresh = reports.filter((report) => !item.reports.includes(report));
200
+ if (fresh.length === 0) {
201
+ return {
202
+ content: [
203
+ { type: "text" as const, text: `${item.id} already carries every listed record; nothing appended.` },
204
+ ],
205
+ details: { item: item.id },
206
+ };
207
+ }
208
+ append({ ...base, type: "link", item: item.id, reports: fresh });
209
+ return {
210
+ content: [
211
+ {
212
+ type: "text" as const,
213
+ text: `Linked ${fresh.length} record${fresh.length === 1 ? "" : "s"} to ${summarize(item)}. If it was accepted, the page now shows it as reopened.`,
214
+ },
215
+ ],
216
+ details: { item: item.id },
217
+ };
218
+ }
219
+ case "amend": {
220
+ const item = findItem((params.item ?? "").trim());
221
+ if (!item) return errorResult("uat_item: `item` must be an existing open item id.");
222
+ const patch = {
223
+ title: params.title?.trim() || undefined,
224
+ summary: params.summary?.trim() || undefined,
225
+ steps: params.steps?.map((step) => step.trim()).filter(Boolean),
226
+ edge: params.edge?.map((edge) => edge.trim()).filter(Boolean),
227
+ skip: params.skip?.trim() || undefined,
228
+ spec: params.spec?.trim() || undefined,
229
+ };
230
+ if (Object.values(patch).every((value) => value === undefined)) {
231
+ return errorResult("uat_item: amend needs at least one of title/summary/steps/edge/skip/spec.");
232
+ }
233
+ append({ ...base, type: "amend", item: item.id, ...patch });
234
+ return {
235
+ content: [{ type: "text" as const, text: `Amended ${item.id}.` }],
236
+ details: { item: item.id },
237
+ };
238
+ }
239
+ case "merge": {
240
+ const item = findItem((params.item ?? "").trim());
241
+ if (!item) return errorResult("uat_item: `item` must be the surviving item id.");
242
+ const sources = [...new Set((params.sources ?? []).map((value) => value.trim()).filter(Boolean))];
243
+ if (sources.length === 0) return errorResult("uat_item: `sources` is required for merge.");
244
+ const unknown = sources.filter((source) => source !== item.id && !findItem(source));
245
+ if (unknown.length > 0) {
246
+ return errorResult(`uat_item: unknown source item(s): ${unknown.join(", ")}.`);
247
+ }
248
+ const real = sources.filter((source) => source !== item.id);
249
+ if (real.length === 0) return errorResult("uat_item: merge needs at least one source besides the target.");
250
+ append({ ...base, type: "merge", item: item.id, sources: real });
251
+ return {
252
+ content: [
253
+ {
254
+ type: "text" as const,
255
+ text: `Merged ${real.length} item${real.length === 1 ? "" : "s"} into ${item.id}; their records now count as evidence for it.`,
256
+ },
257
+ ],
258
+ details: { item: item.id },
259
+ };
260
+ }
261
+ case "drop": {
262
+ const item = findItem((params.item ?? "").trim());
263
+ if (!item) return errorResult("uat_item: `item` must be an existing open item id.");
264
+ append({
265
+ ...base,
266
+ type: "drop",
267
+ item: item.id,
268
+ reason: params.reason?.trim() || undefined,
269
+ });
270
+ return {
271
+ content: [{ type: "text" as const, text: `Dropped ${item.id}.` }],
272
+ details: { item: item.id },
273
+ };
274
+ }
275
+ default:
276
+ return errorResult("uat_item: unknown op.");
277
+ }
278
+ },
279
+ });
280
+ }