@andares/pi-toolkits 1.2.4 → 1.3.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.
@@ -11,11 +11,11 @@ import { request } from "node:http";
11
11
  import { tmpdir } from "node:os";
12
12
  import { dirname, join } from "node:path";
13
13
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
- import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
14
+ import type { ExtensionAPI, ExtensionContext, InputEvent, InputEventResult, ToolCallEvent } from "@earendil-works/pi-coding-agent";
15
15
  import type { GateHub, GateVerdict } from "../../lib/gates.js";
16
16
  import { setPermissionControl, type PermissionControl } from "../../lib/permission-control.js";
17
17
  import { setAskControl } from "../../lib/ask-control.js";
18
- import { LEGACY_SPEC_PHASE_TOOL } from "../../lib/phases.js";
18
+ import { LEGACY_SPEC_PHASE_TOOL, UAT_PHASE_TOOL } from "../../lib/phases.js";
19
19
  import { registerSpec, SPEC_COMMAND, SPEC_SUBMIT_TOOL } from "./index.js";
20
20
 
21
21
  /**
@@ -55,11 +55,17 @@ function writeSpec(relativePath: string, text: string): void {
55
55
  writeFileSync(path, text);
56
56
  }
57
57
 
58
+ /** An input event, the way the host hands a typed message to extensions. */
59
+ function briefEvent(text: string, source: "interactive" | "rpc" | "extension" = "interactive"): InputEvent {
60
+ return { type: "input", text, source };
61
+ }
62
+
58
63
  interface Harness {
59
64
  pi: ExtensionAPI;
60
65
  commands: Map<string, { description: string; handler: (args: string, ctx: ExtensionContext) => Promise<void> }>;
61
66
  tools: Map<string, { name: string; execute: (id: string, params: { path?: string }) => Promise<{ content: Array<{ text: string }>; details: unknown }> }>;
62
67
  handlers: Record<string, Array<(event: { systemPrompt: string }, ctx?: ExtensionContext) => { systemPrompt?: string } | undefined>>;
68
+ inputs: Array<(event: InputEvent, ctx: ExtensionContext) => InputEventResult | undefined>;
63
69
  gates: Array<{ name: string; order?: number; evaluate: (event: ToolCallEvent) => GateVerdict | undefined }>;
64
70
  sendUserMessage: ReturnType<typeof vi.fn>;
65
71
  activeTools: () => string[];
@@ -74,6 +80,7 @@ function harness(): Harness {
74
80
  const tools = new Map<string, { name: string; execute: (id: string, params: { path?: string }) => Promise<{ content: Array<{ text: string }>; details: unknown }> }>();
75
81
  const gates: Harness["gates"] = [];
76
82
  const handlers: Harness["handlers"] = {};
83
+ const inputs: Harness["inputs"] = [];
77
84
  let activeTools = ["read", "grep", "bash", "write", "edit"];
78
85
  const sendUserMessage = vi.fn();
79
86
  const pi = {
@@ -82,9 +89,17 @@ function harness(): Harness {
82
89
  tools.set(def.name, def as never);
83
90
  },
84
91
  on: (type: string, handler: (event: { systemPrompt: string }, ctx?: ExtensionContext) => { systemPrompt?: string } | undefined) => {
92
+ if (type === "input") {
93
+ inputs.push(handler as unknown as Harness["inputs"][number]);
94
+ return;
95
+ }
85
96
  handlers[type] = [...(handlers[type] ?? []), handler];
86
97
  },
87
98
  getActiveTools: () => activeTools,
99
+ getCommands: () => [
100
+ { name: "ask-spec", source: "extension" },
101
+ { name: "ask-perm", source: "extension" },
102
+ ],
88
103
  getAllTools: () => [
89
104
  { name: "read" },
90
105
  { name: "bash" },
@@ -121,7 +136,7 @@ function harness(): Harness {
121
136
  portStart: takePort(),
122
137
  closeDelayMs: 25,
123
138
  });
124
- return { pi, commands, tools, gates, handlers, sendUserMessage, activeTools: () => activeTools, openBrowser, notify, ctx, control };
139
+ return { pi, commands, tools, gates, handlers, inputs, sendUserMessage, activeTools: () => activeTools, openBrowser, notify, ctx, control };
125
140
  }
126
141
 
127
142
  /** Talk to the review server the way the page does. */
@@ -218,10 +233,12 @@ describe("ask-spec command", () => {
218
233
  expect(h.commands.has("ask-plan")).toBe(false);
219
234
  });
220
235
 
221
- it("defaults the spec file to specs/spec.md without a topic", async () => {
236
+ it("arms the phase instead of starting it without a topic", async () => {
222
237
  const h = harness();
223
238
  await h.commands.get(SPEC_COMMAND)!.handler("", h.ctx);
224
- expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("specs/spec.md"), "info");
239
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("armed"), "info");
240
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
241
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
225
242
  });
226
243
 
227
244
  it("leaves spec mode when the bare command is run again", async () => {
@@ -236,11 +253,14 @@ describe("ask-spec command", () => {
236
253
  expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("spec mode off"), "info");
237
254
  expect(h.sendUserMessage).toHaveBeenCalledTimes(1);
238
255
 
239
- // The next bare invocation starts a fresh default-topic review.
256
+ // The next bare invocation arms a new review; its brief arrives as a message.
240
257
  await handler("", h.ctx);
258
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
259
+ const submitted = h.inputs[0]!(briefEvent("write the spec"), h.ctx);
260
+ expect(submitted).toMatchObject({ action: "transform" });
241
261
  expect(h.activeTools()).toContain(SPEC_SUBMIT_TOOL);
242
- expect(h.notify).toHaveBeenLastCalledWith(expect.stringContaining("specs/spec.md"), "info");
243
- expect(h.sendUserMessage).toHaveBeenCalledTimes(2);
262
+ expect(h.notify).toHaveBeenLastCalledWith(expect.stringContaining("specs/write-the-spec.md"), "info");
263
+ expect(h.sendUserMessage).toHaveBeenCalledTimes(1);
244
264
  });
245
265
 
246
266
  it("opens a new window and server for the revision after feedback, keeping history", async () => {
@@ -451,6 +471,162 @@ describe("phase integration", () => {
451
471
  });
452
472
  });
453
473
 
474
+ describe("armed bare command", () => {
475
+ const arm = (h: Harness) => h.commands.get(SPEC_COMMAND)!.handler("", h.ctx);
476
+ const send = (h: Harness, event: InputEvent) => h.inputs[0]!(event, h.ctx);
477
+
478
+ it("nothing happens until the brief arrives", async () => {
479
+ const h = harness();
480
+ await arm(h);
481
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
482
+ expect(h.control.enableDefaults).not.toHaveBeenCalled();
483
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
484
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("armed"), "info");
485
+ });
486
+
487
+ it("turns the next message into the kickoff, verbatim, and starts the phase", async () => {
488
+ const h = harness();
489
+ await arm(h);
490
+ h.notify.mockClear();
491
+ const brief = [
492
+ "Add an armed entry for ask-spec",
493
+ "",
494
+ "Second paragraph, kept word for word, with `code` and a list:",
495
+ "- one",
496
+ "- two",
497
+ ].join("\n");
498
+
499
+ const result = send(h, briefEvent(brief));
500
+ expect(result).toMatchObject({ action: "transform" });
501
+ const transformed = result?.action === "transform" ? result.text : "";
502
+ expect(transformed).toContain(brief);
503
+ expect(transformed).toContain("Target file: `specs/add-an-armed-entry-for-ask-spec.md`");
504
+ expect(transformed).toContain("Start spec review.");
505
+
506
+ expect(h.activeTools()).toContain(SPEC_SUBMIT_TOOL);
507
+ expect(h.control.enableDefaults).toHaveBeenCalledWith(h.ctx);
508
+ expect(h.notify).toHaveBeenCalledWith(
509
+ expect.stringContaining("specs/add-an-armed-entry-for-ask-spec.md"),
510
+ "info",
511
+ );
512
+ // The transformed input is the message; nothing is sent a second time.
513
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
514
+ });
515
+
516
+ it("has the banner and the submit tool already on for that turn", async () => {
517
+ const h = harness();
518
+ await arm(h);
519
+ send(h, briefEvent("armed banner"));
520
+ const injected = h.handlers.before_agent_start![0]!({ systemPrompt: "base" });
521
+ expect(injected?.systemPrompt).toContain("[ASK-SPEC — SPEC REVIEW]");
522
+ expect(h.activeTools()).toContain(SPEC_SUBMIT_TOOL);
523
+ });
524
+
525
+ it("stops arming once the brief is used", async () => {
526
+ const h = harness();
527
+ await arm(h);
528
+ send(h, briefEvent("first brief"));
529
+ expect(send(h, briefEvent("a second, unrelated message"))).toBeUndefined();
530
+ });
531
+
532
+ it("keeps arming past commands and extension-sent messages", async () => {
533
+ const h = harness();
534
+ await arm(h);
535
+ expect(send(h, briefEvent("/ask-perm allow"))).toBeUndefined();
536
+ expect(send(h, briefEvent("dispatched by autostart", "extension"))).toBeUndefined();
537
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
538
+ // Still armed: the operator's own message is the brief.
539
+ expect(send(h, briefEvent("the real brief"))).toMatchObject({ action: "transform" });
540
+ });
541
+
542
+ it("cancels with the bare command again, and with `off`", async () => {
543
+ const h = harness();
544
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
545
+
546
+ await arm(h);
547
+ await handler("", h.ctx);
548
+ expect(h.notify).toHaveBeenLastCalledWith(
549
+ expect.stringContaining("pending requirement cancelled"),
550
+ "info",
551
+ );
552
+ expect(send(h, briefEvent("too late"))).toBeUndefined();
553
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
554
+
555
+ await arm(h);
556
+ await handler("off", h.ctx);
557
+ expect(h.notify).toHaveBeenLastCalledWith(
558
+ expect.stringContaining("pending requirement cancelled"),
559
+ "info",
560
+ );
561
+ expect(send(h, briefEvent("also too late"))).toBeUndefined();
562
+ });
563
+
564
+ it("accepts a brief that starts with a path rather than a real command", async () => {
565
+ const h = harness();
566
+ await arm(h);
567
+ const result = send(h, briefEvent("/tmp contains the fixtures\n\nKeep the exporter unchanged."));
568
+ expect(result).toMatchObject({ action: "transform" });
569
+ expect(result?.action === "transform" ? result.text : "").toContain("/tmp contains the fixtures");
570
+ });
571
+
572
+ it("replaces the armed brief when a topic is given instead", async () => {
573
+ const h = harness();
574
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
575
+ await arm(h);
576
+ await handler("topic", h.ctx);
577
+
578
+ // `off` must leave the active phase, not merely cancel the old wait.
579
+ await handler("off", h.ctx);
580
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
581
+ expect(h.notify).toHaveBeenLastCalledWith(expect.stringContaining("spec mode off"), "info");
582
+ expect(send(h, briefEvent("an unrelated later message"))).toBeUndefined();
583
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
584
+ });
585
+
586
+ it("does not enter over UAT if it opened while the brief was pending", async () => {
587
+ const h = harness();
588
+ await arm(h);
589
+ h.pi.setActiveTools([...h.activeTools(), UAT_PHASE_TOOL]);
590
+ h.notify.mockClear();
591
+
592
+ expect(send(h, briefEvent("must not start spec over UAT"))).toBeUndefined();
593
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
594
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("ask-uat is open"), "warning");
595
+
596
+ // The blocked attempt cancels the wait instead of arming a later surprise.
597
+ h.pi.setActiveTools(h.activeTools().filter((name) => name !== UAT_PHASE_TOOL));
598
+ expect(send(h, briefEvent("a later ordinary message"))).toBeUndefined();
599
+ });
600
+
601
+ it("does not enter during streaming if the agent started while armed", async () => {
602
+ const h = harness();
603
+ await arm(h);
604
+ h.notify.mockClear();
605
+
606
+ const queued = { ...briefEvent("queued while streaming"), streamingBehavior: "followUp" } as const;
607
+ expect(send(h, queued)).toBeUndefined();
608
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
609
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("still running"), "warning");
610
+ expect(send(h, briefEvent("after the run"))).toBeUndefined();
611
+ });
612
+
613
+ it("drops the armed state when the session changes", async () => {
614
+ const h = harness();
615
+ await arm(h);
616
+ const nextCtx = {
617
+ ...h.ctx,
618
+ sessionManager: { getSessionId: () => "next-session" },
619
+ } as unknown as ExtensionContext;
620
+ h.handlers.session_start![0]!({ systemPrompt: "" }, nextCtx);
621
+ expect(h.inputs[0]!(briefEvent("from the old session"), h.ctx)).toBeUndefined();
622
+ });
623
+
624
+ it("does nothing at all when not armed", async () => {
625
+ const h = harness();
626
+ expect(h.inputs[0]!(briefEvent("just a normal message"), h.ctx)).toBeUndefined();
627
+ });
628
+ });
629
+
454
630
  describe("spec gate", () => {
455
631
  const gate = (h: Harness) => h.gates.find((entry) => entry.name === "spec");
456
632
 
@@ -22,7 +22,13 @@ import { readFileSync } from "node:fs";
22
22
  import { isAbsolute, relative, resolve } from "node:path";
23
23
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
24
  import { Type } from "typebox";
25
- import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
25
+ import type {
26
+ ExtensionAPI,
27
+ ExtensionContext,
28
+ InputEvent,
29
+ InputEventResult,
30
+ ToolCallEvent,
31
+ } from "@earendil-works/pi-coding-agent";
26
32
  import type { GateHub } from "../../lib/gates.js";
27
33
  import { getPermissionControl, type PermissionSnapshot } from "../../lib/permission-control.js";
28
34
  import { getAskControl } from "../../lib/ask-control.js";
@@ -33,7 +39,12 @@ import { canonicalize, isWithin } from "../permission/paths.js";
33
39
  import { parseCommandUnits } from "../permission/units.js";
34
40
  import { buildFeedbackMarkdown } from "./feedback.js";
35
41
  import { openInBrowser } from "../../lib/opener.js";
36
- import { buildSpecKickoff, buildSpecSystemPrompt } from "./prompt.js";
42
+ import {
43
+ buildSpecKickoff,
44
+ buildSpecKickoffFromBrief,
45
+ buildSpecSystemPrompt,
46
+ specTitleFromBrief,
47
+ } from "./prompt.js";
37
48
  import { renderBlockHtml } from "../review-page/render.js";
38
49
  import { buildSpecState, startSpecServer, type SpecServerHandle } from "./server.js";
39
50
  import {
@@ -114,6 +125,12 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
114
125
  let cwd = process.cwd();
115
126
  let ctxRef: ExtensionContext | undefined;
116
127
  let specSessionId: string | undefined;
128
+ /**
129
+ * The bare command arms the phase instead of starting it: the requirement is
130
+ * a message the operator has not typed yet. Until it arrives the phase is off
131
+ * (no gates, no tools, no permission change) — only this flag is set.
132
+ */
133
+ let armedForBrief = false;
117
134
 
118
135
  function closeServer(): void {
119
136
  if (!server) return;
@@ -160,6 +177,54 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
160
177
  return { handle, started: true };
161
178
  }
162
179
 
180
+ /** Target file and kickoff for a brief that arrives as a message. */
181
+ function briefPlan(brief: string): { path: string; kickoff: string } {
182
+ const path = `specs/${specSlug(specTitleFromBrief(brief))}.md`;
183
+ return { path, kickoff: buildSpecKickoffFromBrief(brief, path) };
184
+ }
185
+
186
+ /**
187
+ * Turn spec review on. Shared by both entries: `/ask-spec <topic>` and the
188
+ * armed bare command whose brief arrives as the next message. Sending the
189
+ * kickoff stays with the caller — the two paths deliver it differently (a new
190
+ * message vs. the transformed input that is already on its way).
191
+ */
192
+ function enterPhase(target: ExtensionContext, plan: { path: string; kickoff: string }): void {
193
+ // Entering through a topic replaces a pending bare-command brief. Leaving
194
+ // the flag set would make `off` cancel the wait instead of the active
195
+ // phase, and would consume a later, unrelated message as another brief.
196
+ armedForBrief = false;
197
+ const readiness = frameworkReadiness(resolveProjectRoot(cwd));
198
+ if (!readiness.ready) {
199
+ target.ui.notify(
200
+ `ask-spec: no complete agent framework (missing: ${readiness.missing.join(", ")}). The spec still works, but record_change and /ask-uat stay unavailable until /ask-init.`,
201
+ "info",
202
+ );
203
+ }
204
+ specPath = plan.path;
205
+ session = undefined;
206
+ specSessionId = sessionIdOf(target);
207
+ const permission = getPermissionControl();
208
+ permissionBefore = permission?.snapshot();
209
+ permission?.enableDefaults(target);
210
+ permissionDuring = permission?.snapshot();
211
+ // Spec mode is intentionally less restrictive than ask mode. Let ask
212
+ // restore its own tool snapshot before we add spec_submit.
213
+ if (getAskControl()?.isActive()) getAskControl()?.exit(target);
214
+ active = true;
215
+ pi.setActiveTools(toolSetWithSubmit());
216
+ target.ui.notify(
217
+ `ask-spec: reviewing. Write the spec to ${plan.path}, then call ${SPEC_SUBMIT_TOOL}.`,
218
+ "info",
219
+ );
220
+ }
221
+
222
+ /** True only for a command the host actually knows, not any `/path`-like text. */
223
+ function isRegisteredCommand(text: string): boolean {
224
+ const name = /^\/([^\s]+)/.exec(text)?.[1];
225
+ return name !== undefined && pi.getCommands().some((command) => command.name === name);
226
+ }
227
+
163
228
  function toolSetWithSubmit(): string[] {
164
229
  const tools = pi
165
230
  .getActiveTools()
@@ -258,13 +323,18 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
258
323
 
259
324
  const specCommand = {
260
325
  description:
261
- "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. Run without arguments again, or use `off`, to leave the phase; `open` re-opens the review.",
326
+ "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. Without arguments it arms the phase and your next message (multi-line paste included) becomes the brief; run the bare command again or use `off` to leave or cancel, and `open` re-opens the review.",
262
327
  handler: async (args: string, ctx: ExtensionContext) => {
263
328
  const arg = args.trim();
264
329
  ctxRef = ctx;
265
330
  cwd = canonicalize(ctx.cwd || process.cwd());
266
331
 
267
332
  if (arg === "off") {
333
+ if (armedForBrief) {
334
+ armedForBrief = false;
335
+ ctx.ui.notify("ask-spec: pending requirement cancelled.", "info");
336
+ return;
337
+ }
268
338
  if (!active) {
269
339
  ctx.ui.notify("ask-spec: not in spec mode.", "info");
270
340
  return;
@@ -312,35 +382,75 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
312
382
  return;
313
383
  }
314
384
 
315
- const readiness = frameworkReadiness(resolveProjectRoot(cwd));
316
- if (!readiness.ready) {
385
+ // Bare command: arm and wait for the brief instead of starting from a
386
+ // topic that has to be squeezed onto the command line. A pasted
387
+ // multi-paragraph requirement is the whole point of this entry.
388
+ if (arg === "") {
389
+ if (armedForBrief) {
390
+ armedForBrief = false;
391
+ ctx.ui.notify("ask-spec: pending requirement cancelled.", "info");
392
+ return;
393
+ }
394
+ armedForBrief = true;
317
395
  ctx.ui.notify(
318
- `ask-spec: no complete agent framework (missing: ${readiness.missing.join(", ")}). The spec still works, but record_change and /ask-uat stay unavailable until /ask-init.`,
396
+ "ask-spec: armed — send the requirement as your next message (multi-line and pasted text are fine); spec review starts from it. /ask-spec again cancels.",
319
397
  "info",
320
398
  );
399
+ return;
321
400
  }
322
401
 
323
- const slug = specSlug(arg || "spec");
324
- specPath = `specs/${slug}.md`;
325
- session = undefined;
326
- specSessionId = sessionIdOf(ctx);
327
- const permission = getPermissionControl();
328
- permissionBefore = permission?.snapshot();
329
- permission?.enableDefaults(ctx);
330
- permissionDuring = permission?.snapshot();
331
- // Spec mode is intentionally less restrictive than ask mode. Let ask
332
- // restore its own tool snapshot before we add spec_submit.
333
- if (getAskControl()?.isActive()) getAskControl()?.exit(ctx);
334
- active = true;
335
- pi.setActiveTools(toolSetWithSubmit());
336
- ctx.ui.notify(
337
- `ask-spec: reviewing. Write the spec to ${specPath}, then call ${SPEC_SUBMIT_TOOL}.`,
338
- "info",
339
- );
340
- pi.sendUserMessage(buildSpecKickoff(arg || undefined));
402
+ const plan = { path: `specs/${specSlug(arg)}.md`, kickoff: buildSpecKickoff(arg) };
403
+ enterPhase(ctx, plan);
404
+ pi.sendUserMessage(plan.kickoff);
341
405
  },
342
406
  };
343
407
 
408
+ /**
409
+ * The armed bare command: the next message is the brief.
410
+ *
411
+ * The input runs before the model sees anything, so the phase is turned on
412
+ * here — `before_agent_start` then injects the spec banner and re-asserts the
413
+ * tool set for this very turn — and the message is transformed into the
414
+ * kickoff with the requirement embedded verbatim. Nothing is dropped or sent
415
+ * twice: it is still the operator's one message.
416
+ *
417
+ * Commands and extension-dispatched messages are not the brief: built-in
418
+ * slash commands never reach here, but a registered `/cmd` can, and
419
+ * autostart sends its whole list through `sendUserMessage` with source
420
+ * `extension` — neither should be eaten as a requirement.
421
+ */
422
+ pi.on("input", (event: InputEvent, ctx: ExtensionContext): InputEventResult | undefined => {
423
+ if (!armedForBrief || active) return undefined;
424
+ if (event.source === "extension") return undefined;
425
+ const brief = event.text.trim();
426
+ if (brief === "" || isRegisteredCommand(brief)) return undefined;
427
+ // The command enforces these before arming, but either state can change
428
+ // while the operator is composing the brief. Re-check at the moment the
429
+ // phase would really start: entering during a stream would mutate the
430
+ // current run's tools, and entering over UAT would stack the two phases.
431
+ if (event.streamingBehavior !== undefined || !ctx.isIdle()) {
432
+ armedForBrief = false;
433
+ ctx.ui.notify(
434
+ "ask-spec: the agent is still running — pending requirement cancelled; finish or abort first.",
435
+ "warning",
436
+ );
437
+ return undefined;
438
+ }
439
+ if (pi.getActiveTools().includes(UAT_PHASE_TOOL)) {
440
+ armedForBrief = false;
441
+ ctx.ui.notify(
442
+ "ask-spec: ask-uat is open — pending requirement cancelled; /ask-uat off first.",
443
+ "warning",
444
+ );
445
+ return undefined;
446
+ }
447
+ ctxRef = ctx;
448
+ cwd = canonicalize(ctx.cwd || process.cwd());
449
+ const plan = briefPlan(brief);
450
+ enterPhase(ctx, plan);
451
+ return { action: "transform", text: plan.kickoff };
452
+ });
453
+
344
454
  // One name only. The pre-rename `/ask-plan` alias was removed 2026-11-27
345
455
  // (it had been undocumented since the rename; autostart entries still
346
456
  // spelled that way are skipped by the pre-flight and reported, so they are
@@ -500,6 +610,7 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
500
610
  });
501
611
 
502
612
  pi.on("session_shutdown", () => {
613
+ armedForBrief = false;
503
614
  closeServer();
504
615
  });
505
616
 
@@ -510,6 +621,7 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
510
621
  // or permission snapshot. Permission's own session_start has already reset
511
622
  // its state, so do not restore the old snapshot here.
512
623
  active = false;
624
+ armedForBrief = false;
513
625
  session = undefined;
514
626
  permissionBefore = undefined;
515
627
  permissionDuring = undefined;
@@ -1,10 +1,12 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
3
  buildSpecKickoff,
4
+ buildSpecKickoffFromBrief,
4
5
  buildSpecSystemPrompt,
5
6
  INTERVIEW_GUIDE,
6
7
  SPEC_MODE_BANNER,
7
8
  SPEC_FRAMEWORK_GUIDE,
9
+ specTitleFromBrief,
8
10
  } from "./prompt.js";
9
11
 
10
12
  describe("spec review prompt", () => {
@@ -89,3 +91,21 @@ describe("buildSpecKickoff", () => {
89
91
  expect(buildSpecKickoff(" ")).toContain("the work we have been discussing in this session");
90
92
  });
91
93
  });
94
+
95
+ describe("brief-shaped kickoff", () => {
96
+ it("keeps the requirement byte for byte, blank lines and lists included", () => {
97
+ const brief = "Renew the watcher\n\nWhy: the current one drops events.\n\n- keep the API\n- add a test";
98
+ const kickoff = buildSpecKickoffFromBrief(brief, "specs/renew-the-watcher.md");
99
+ expect(kickoff).toContain(brief);
100
+ expect(kickoff).toContain("Target file: `specs/renew-the-watcher.md`");
101
+ expect(kickoff).toContain("Do not implement anything yet.");
102
+ });
103
+
104
+ it("takes the file title from the first real line", () => {
105
+ expect(specTitleFromBrief("## Add a queue\n\ndetail")).toBe("Add a queue");
106
+ expect(specTitleFromBrief("\n\n 1. Fix the export\nmore")).toBe("Fix the export");
107
+ expect(specTitleFromBrief("```ts\nconst a = 1;\n```\nTop level ask")).toBe("Top level ask");
108
+ expect(specTitleFromBrief("### ")).toBe("spec");
109
+ expect(specTitleFromBrief(" ")).toBe("spec");
110
+ });
111
+ });
@@ -108,3 +108,49 @@ export function buildSpecKickoff(topic: string | undefined): string {
108
108
  "submit it with spec_submit. Do not implement anything yet.",
109
109
  ].join("\n");
110
110
  }
111
+
112
+ /**
113
+ * First line of a message-shaped brief, stripped of markdown markers, for the
114
+ * default file name. A requirement usually opens with the line that names the
115
+ * work; the rest is detail that makes a poor file name and would be truncated
116
+ * anyway.
117
+ */
118
+ export function specTitleFromBrief(brief: string): string {
119
+ let inFence = false;
120
+ for (const raw of brief.split(/\r?\n/)) {
121
+ const line = raw.trim();
122
+ if (line.startsWith("```") || line.startsWith("~~~")) {
123
+ inFence = !inFence;
124
+ continue;
125
+ }
126
+ if (inFence || line === "") continue;
127
+ const stripped = line
128
+ .replace(/^#{1,6}\s*/, "")
129
+ .replace(/^([-*+>]|\d+[.)])\s+/, "")
130
+ .trim();
131
+ // A line that is nothing but list/quote markers names nothing.
132
+ if (stripped === "" || /^[-*+>#]+$/.test(stripped)) continue;
133
+ return stripped;
134
+ }
135
+ return "spec";
136
+ }
137
+
138
+ /**
139
+ * Kickoff for the armed bare command. Here the requirement is the operator's
140
+ * whole message, so it is embedded verbatim instead of being compressed into a
141
+ * one-line topic: the point of that entry is that a long, pasted, multi-paragraph
142
+ * brief arrives intact.
143
+ */
144
+ export function buildSpecKickoffFromBrief(brief: string, specPath: string): string {
145
+ return [
146
+ "Start spec review.",
147
+ `Target file: \`${specPath}\`.`,
148
+ "",
149
+ "## Operator's requirement",
150
+ "",
151
+ brief.trim(),
152
+ "",
153
+ "Explore the code before writing, ask me what you cannot infer, then write the spec file and",
154
+ "submit it with spec_submit. Do not implement anything yet.",
155
+ ].join("\n");
156
+ }
@@ -21,8 +21,8 @@ import type { KeyId } from "@earendil-works/pi-tui";
21
21
  /**
22
22
  * Stash hotkey.
23
23
  *
24
- * Compatibility rationale (verified against pi 0.99.0–1.5.1 keybindings, live
25
- * matchesKey probes and terminal/OS behavior):
24
+ * Compatibility rationale (keybinding tables audited across pi 1.0.0–1.7.0;
25
+ * matchesKey probes and terminal/OS behavior verified separately):
26
26
  * - pi: no default binding for ctrl+alt+<letter> (only ctrl+alt+] is taken);
27
27
  * extension shortcuts dispatch first while the editor is focused
28
28
  * - terminals: alt encodes as ESC-prefix, so ctrl+alt+y arrives as "\x1b\x19"
@@ -0,0 +1 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return t(this.context.count)},getNextContextId(){return t(this.context.count++)}};function t(t){let n=String(t),r=n.length-1;return e.context.id+(r?String.fromCharCode(96+r):``)+n}function n(t){e.context=t}var r=(e,t)=>e===t,i=Symbol(`solid-track`),a={equals:r},o=null,s=ae,c=1,l=2,u={owned:null,cleanups:null,context:null,owner:null},d=null,f=null,p=null,m=null,h=null,g=0;function _(e,t){let n=p,r=d,i=e.length===0,a=t===void 0?r:t,o=i?u:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(v(o));d=o,p=null;try{return M(s,!0)}finally{p=n,d=r}}function v(e){return()=>S(()=>F(e))}function y(e,t){t=t?Object.assign({},a,t):a;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[D.bind(n),e=>(typeof e==`function`&&(e=f&&f.running&&f.sources.has(n)?e(n.tValue):e(n.value)),re(n,e))]}function b(e,t,n){O(A(e,t,!1,c))}function ee(e,t,n){s=oe;let r=A(e,t,!1,c),i=E&&ne(E);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),h?h.push(r):O(r)}function x(e,t,n){n=n?Object.assign({},a,n):a;let r=A(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,O(r),D.bind(r)}function S(e){if(p===null)return e();let t=p;p=null;try{return e()}finally{p=t}}function te(e){ee(()=>S(e))}function C(e){return d===null||(d.cleanups===null?d.cleanups=[e]:d.cleanups.push(e)),e}var[w,T]=y(!1);function ne(e){let t;return d&&d.context&&(t=d.context[e.id])!==void 0?t:e.defaultValue}var E;function D(){let e=f&&f.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===c)O(this);else{let e=m;m=null,M(()=>N(this),!1),m=e}}if(p){let e=this.observers;if(!e||e[e.length-1]!==p){let t=e?e.length:0;p.sources?(p.sources.push(this),p.sourceSlots.push(t)):(p.sources=[this],p.sourceSlots=[t]),e?(e.push(p),this.observerSlots.push(p.sources.length-1)):(this.observers=[p],this.observerSlots=[p.sources.length-1])}}return e&&f.sources.has(this)?this.tValue:this.value}function re(e,t,n){let r=f&&f.running&&f.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(f){let r=f.running;(r||!n&&f.sources.has(e))&&(f.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&M(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=f&&f.running;r&&f.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?m.push(n):h.push(n),n.observers&&P(n)),r?n.tState=c:n.state=c)}if(m.length>1e6)throw m=[],Error()},!1)}return t}function O(e){if(!e.fn)return;F(e);let t=g;k(e,f&&f.running&&f.sources.has(e)?e.tValue:e.value,t),f&&!f.running&&f.sources.has(e)&&queueMicrotask(()=>{M(()=>{f&&(f.running=!0),p=d=e,k(e,e.tValue,t),p=d=null},!1)})}function k(e,t,n){let r,i=d,a=p;p=d=e;try{r=e.fn(t)}catch(t){return e.pure&&(f&&f.running?(e.tState=c,e.tOwned&&e.tOwned.forEach(F),e.tOwned=void 0):(e.state=c,e.owned&&e.owned.forEach(F),e.owned=null)),e.updatedAt=n+1,R(t)}finally{p=a,d=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?re(e,r,!0):f&&f.running&&e.pure?(f.sources.has(e)||(e.value=r),f.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function A(e,t,n,r=c,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:d,context:d?d.context:null,pure:n};return f&&f.running&&(a.state=0,a.tState=r),d===null||d!==u&&(f&&f.running&&d.pure?d.tOwned?d.tOwned.push(a):d.tOwned=[a]:d.owned?d.owned.push(a):d.owned=[a]),a}function j(e){let t=f&&f.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===l)return N(e);if(e.suspense&&S(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<g);){if(t&&f.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(f.disposed.has(t))return}if((t?e.tState:e.state)===c)O(e);else if((t?e.tState:e.state)===l){let t=m;m=null,M(()=>N(e,n[0]),!1),m=t}}}function M(e,t){if(m)return e();let n=!1;t||(m=[]),h?n=!0:h=[],g++;try{let t=e();return ie(n),t}catch(e){n||(h=null),m=null,R(e)}}function ie(e){if(m&&=(ae(m),null),e)return;let t;if(f){if(!f.promises.size&&!f.queue.size){let e=f.sources,n=f.disposed;h.push.apply(h,f.effects),t=f.resolve;for(let e of h)`tState`in e&&(e.state=e.tState),delete e.tState;f=null,M(()=>{for(let e of n)F(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)F(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}T(!1)},!1)}else if(f.running){f.running=!1,f.effects.push.apply(f.effects,h),h=null,T(!0);return}}let n=h;h=null,n.length&&M(()=>s(n),!1),t&&t()}function ae(e){for(let t=0;t<e.length;t++)j(e[t])}function oe(t){let r,i=0;for(r=0;r<t.length;r++){let e=t[r];e.user?t[i++]=e:j(e)}if(e.context){if(e.count){e.effects||=[],e.effects.push(...t.slice(0,i));return}n()}for(e.effects&&(e.done||!e.count)&&(t=[...e.effects,...t],i+=e.effects.length,delete e.effects),r=0;r<i;r++)j(t[r])}function N(e,t){let n=f&&f.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===c?i!==t&&(!i.updatedAt||i.updatedAt<g)&&j(i):e===l&&N(i,t)}}}function P(e){let t=f&&f.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=l:r.state=l,r.pure?m.push(r):h.push(r),r.observers&&P(r))}}function F(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)F(e.tOwned[t]);delete e.tOwned}if(f&&f.running&&e.pure)I(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)F(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}f&&f.running?e.tState=0:e.state=0}function I(e,t){if(t||(e.tState=0,f.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)I(e.owned[t])}function se(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function L(e,t,n){try{for(let n of t)n(e)}catch(e){R(e,n&&n.owner||null)}}function R(e,t=d){let n=o&&t&&t.context&&t.context[o],r=se(e);if(!n)throw r;h?h.push({fn(){L(r,n,t)},state:c}):L(r,n,t)}var ce=Symbol(`fallback`);function le(e){for(let t=0;t<e.length;t++)e[t]()}function z(e,t,n={}){let r=[],a=[],o=[],s=0,c=t.length>1?[]:null;return C(()=>le(o)),()=>{let l=e()||[],u=l.length,d,f;return l[i],S(()=>{let e,t,i,m,h,g,v,y,b;if(u===0)s!==0&&(le(o),o=[],r=[],a=[],s=0,c&&=[]),n.fallback&&(r=[ce],a[0]=_(e=>(o[0]=e,n.fallback())),s=1);else if(s===0){for(a=Array(u),f=0;f<u;f++)r[f]=l[f],a[f]=_(p);s=u}else{for(i=Array(u),m=Array(u),c&&(h=Array(u)),g=0,v=Math.min(s,u);g<v&&r[g]===l[g];g++);for(v=s-1,y=u-1;v>=g&&y>=g&&r[v]===l[y];v--,y--)i[y]=a[v],m[y]=o[v],c&&(h[y]=c[v]);for(e=new Map,t=Array(y+1),f=y;f>=g;f--)b=l[f],d=e.get(b),t[f]=d===void 0?-1:d,e.set(b,f);for(d=g;d<=v;d++)b=r[d],f=e.get(b),f!==void 0&&f!==-1?(i[f]=a[d],m[f]=o[d],c&&(h[f]=c[d]),f=t[f],e.set(b,f)):o[d]();for(f=g;f<u;f++)f in i?(a[f]=i[f],o[f]=m[f],c&&(c[f]=h[f],c[f](f))):a[f]=_(p);a=a.slice(0,s=u),r=l.slice(0)}return a});function p(e){if(o[f]=e,c){let[e,n]=y(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function B(e,t){return S(()=>e(t||{}))}var ue=e=>`Stale read from <${e}>.`;function V(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return x(z(()=>e.each,e.children,t||void 0))}function H(e){let t=e.keyed,n=x(()=>e.when,void 0,void 0),r=t?n:x(n,void 0,{equals:(e,t)=>!e==!t});return x(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?S(()=>a(t?i:()=>{if(!S(r))throw ue(`Show`);return n()})):a}return e.fallback},void 0,void 0)}var U=e=>x(()=>e());function W(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;){if(t[o]===n[s]){o++,s++;continue}for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var de=`_$DX_DELEGATE`;function fe(e,t,n,r={}){let i;return _(r=>{i=r,t===document?e():K(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function G(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>S(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function pe(e,t=window.document){let n=t[de]||(t[de]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,ve))}}function me(e,t,n){_e(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function he(e,t){_e(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function ge(e,t,n){if(!t)return n?me(e,`style`):t;let r=e.style;if(typeof t==`string`)return r.cssText=t;typeof n==`string`&&(r.cssText=n=void 0),n||={},t||={};let i,a;for(a in n)t[a]??r.removeProperty(a),delete n[a];for(a in t)i=t[a],i!==n[a]&&(r.setProperty(a,i),n[a]=i);return n}function K(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return q(e,t,r,n);b(r=>q(e,t(),r,n),r)}function _e(t){return!!e.context&&!e.done&&(!t||t.isConnected)}function ve(t){if(e.registry&&e.events&&e.events.find(([e,n])=>n===t))return;let n=t.target,r=`$$${t.type}`,i=t.target,a=t.currentTarget,o=e=>Object.defineProperty(t,"target",{configurable:!0,value:e}),s=()=>{let e=n[r];if(e&&!n.disabled){let i=n[`${r}Data`];if(i===void 0?e.call(n,t):e.call(n,i,t),t.cancelBubble)return}return n.host&&typeof n.host!=`string`&&!n.host._$host&&n.contains(t.target)&&o(n.host),!0},c=()=>{for(;s()&&(n=n._$host||n.parentNode||n.host););};Object.defineProperty(t,"currentTarget",{configurable:!0,get(){return n||document}}),e.registry&&!e.done&&(e.done=_$HY.done=!0);try{if(t.composedPath){let e=t.composedPath();o(e[0]);for(let t=0;t<e.length-2&&(n=e[t],s());t++){if(n._$host){n=n._$host,c();break}if(n.parentNode===a)break}}else c();o(i)}finally{t=n=null}}function q(e,t,n,r,i){let a=_e(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=X(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=X(e,n,r)}else if(o===`function`)return b(()=>{let i=t();for(;typeof i==`function`;)i=i();n=q(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(J(o,t,n,i))return b(()=>n=q(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=X(e,n,r),s)return n}else c?n.length===0?Y(e,o,r):W(e,n,o):(n&&X(e),Y(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=X(e,n,r,t);X(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function J(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=J(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=J(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function Y(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function X(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var ye=new URLSearchParams(window.location.search).get(`t`)??``;async function Z(e,t={}){let n=await fetch(e,{...t,headers:{...t.body?{"content-type":`application/json`}:{},"x-plan-token":ye,...t.headers??{}}});if(!n.ok)throw Error(`${t.method??`GET`} ${e} → HTTP ${n.status}`);return await n.json()}function be(){return Z(`/api/state`)}async function Q(e,t){return(await Z(`/api/toggle`,{method:`POST`,body:JSON.stringify({item:e,checked:t})})).state}function $(e){return Z(`/api/report?id=${encodeURIComponent(e)}`)}function xe(e,t,n){let r=new EventSource(`/api/events?t=${encodeURIComponent(ye)}`);return r.addEventListener(`state`,()=>e()),r.onopen=()=>n?.(!0),r.onerror=()=>{n?.(!1),t(`connection lost — the page stops updating; reopen it from the extension`)},()=>r.close()}var Se=G(`<p class="banner error">`),Ce=G(`<p><strong></strong> new change record<!> waiting to be clustered — run <code>/ask-uat</code>.`),we=G(`<p><strong></strong> record<!> no behaviour line; clustering them means reading the files — <code>/ask-uat legacy</code> includes them.`),Te=G(`<div class="banner pending">`),Ee=G(`<p class=empty>Nothing to verify. Run <code>/ask-uat</code> after the next round of changes lands.`),De=G(`<button class=accepted><span class=accepted-left><svg viewBox="0 0 24 24"aria-hidden=true class="icon ok"><circle cx=12 cy=12 r=9></circle><path d="M8 12.5 11 15.5 16.5 9"></path></svg><strong> accepted</strong><span class=muted>— expand to undo a tick</span></span><svg viewBox="0 0 24 24"aria-hidden=true class=icon><path>`),Oe=G(`<ul class="items accepted-list">`),ke=G(`<p class=note>Nothing waiting — the queue is caught up.`),Ae=G(`<p class=note> new · <!> unlabeled. The next run clusters up to 12 items from 40 records.`),je=G(`<code>/ask-uat legacy`),Me=G(`<section class=card><span class=kicker>Recently accepted</span><ul class=recents>`),Ne=G(`<ul class=retired>`),Pe=G(`<section class=card><button class=card-toggle><span class=kicker>Retired · </span><svg viewBox="0 0 24 24"aria-hidden=true class=icon><path></path></svg></button><p class=note>No user-visible behaviour (<code>none:</code>) or retired by the agent. They stay on disk and never come back as pending.`),Fe=G(`<div class=page><div class="glow glow-a"></div><div class="glow glow-b"></div><div class="glow glow-c"></div><div class=shell><header class=head><div class=brand><div class=mark><svg viewBox="0 0 24 24"aria-hidden=true><path d="M5 12.5 10 17.5 19 7.5"></path></svg></div><span class=brand-label>Acceptance · UAT</span></div><div class=head-row><div><h1>Acceptance</h1><p class=meta><span class=mono></span><span class=dot></span><span> open</span><span class=dot></span><span class=meta-strong> accepted</span><span class=dot></span><span> waiting</span></p></div><button class=ghost><svg viewBox="0 0 24 24"aria-hidden=true class=icon><path d="M21 12a9 9 0 1 1-2.6-6.4M21 4v5h-5"></path></svg>refresh</button></div></header><section class=progress aria-label="Acceptance progress"><div class=score><span class=score-num></span><span class=score-label>of <!> verified</span></div><div class=track-wrap><div class=track><div class=track-fill></div></div><div class=legend><span class=legend-item><i class=legend-dot></i> still open</span><span class="legend-item legend-ok"><i class="legend-dot leaf"></i> accepted</span><span class=legend-item><i class="legend-dot amber"></i> not clustered</span></div></div><div class=live><span class=live-label>SSE</span><span><i></i></span></div></section><div class=layout><main class=board><div class=list-head><span class=kicker>Needs verification</span><span class=list-count> item</span></div><ul class=items></ul></main><aside class=rail><section class=card><span class=kicker>How this works</span><ul class=bullets><li>A tick writes the ledger immediately — there is no submit step.</li><li>Closing the page keeps every decision.</li><li>A ticked item can be unticked; the ledger just gets another event.</li></ul></section><section class="card wash"><span class=kicker>Queue</span><div class=commands><code>/ask-uat</code></div></section><p class="root mono">`),Ie=G(`<p class="banner error"> malformed ledger line(s) were skipped — check .agents/uat/ledger.jsonl.`),Le=G(`<span class="badge reopened">reopened`),Re=G(`<span class="badge area">`),ze=G(`<span class=kicker>Test plan`),Be=G(`<ol class=steps>`),Ve=G(`<span class=kicker>Edge cases`),He=G(`<ul class=edge>`),Ue=G(`<div class=skip><span class=kicker>Not under test</span><p>`),We=G(`<div class=skip><span class=kicker>Spec</span><p class=mono>`),Ge=G(`<button class="chip chip-more">`),Ke=G(`<div class=details><p class=kicker>Evidence</p><div class=chips>`),qe=G(`<li class=item><label class=check><input type=checkbox><span class=check-box></span></label><div class=body><div class=row><h2></h2><span class=badges><span class=badge> record</span><span class=badge></span></span></div><p class=summary></p><button class=more>`),Je=G(`<li>`),Ye=G(`<button class=chip>`),Xe=G(`<li class="item done"><label class=check><input type=checkbox><span class="check-box checked"><svg viewBox="0 0 24 24"aria-hidden=true><path d="M5 12.5 10 17.5 19 7.5"></path></svg></span></label><div class=body><h2></h2><p class=summary></p><p class=stamp>accepted `),Ze=G(`<section class=card><span class=kicker>This batch</span><span class="mono batch-id"></span><div class=rule></div><div class=kv><span>Items</span><strong></strong></div><div class=kv><span>Records linked</span><strong></strong></div><div class=kv><span>Clustered in</span><strong></strong></div><p class=note>Items stream in while the agent clusters; this page never needs a reload.`),Qe=G(`<li><svg viewBox="0 0 24 24"aria-hidden=true class="icon ok"><circle cx=12 cy=12 r=9></circle><path d="M8 12.5 11 15.5 16.5 9"></path></svg><span>`),$e=G(`<li><span class=mono></span><span class=retired-reason></span><span>`),et=G(`<div class=drawer><div class=drawer-inner><div class=drawer-head><span class="drawer-title mono"><svg viewBox="0 0 24 24"aria-hidden=true class=icon><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"></path><path d="M14 3v5h5"></path></svg>.md</span><button class=link>close</button></div><pre></pre><p class=drawer-note>Read-only evidence — ticking happens on the item above.`);function tt(){let[e,t]=y(),[n,r]=y(),[i,a]=y(!0),[o,s]=y(new Set),[c,l]=y(new Set),[u,d]=y(),[f,p]=y(),[m,h]=y(!1),[g,_]=y(!1);async function v(){try{t(await be()),r(void 0)}catch(e){r(e instanceof Error?e.message:String(e))}}te(()=>{v(),C(xe(()=>void v(),e=>r(e),e=>a(e)))});let ee=x(()=>e()?.open??[]),S=x(()=>e()?.checked??[]),w=x(()=>e()?.counts??{items:0,open:0,checked:0,pending:0,pendingNew:0,pendingLegacy:0,retired:0,totalRecords:0}),T=x(()=>w().open+w().checked),ne=x(()=>{let e=T();return e===0?0:Math.round(w().checked/e*100)}),E=x(()=>e()?.batches?.[0]),D=x(()=>{let t=E()?.id;return t?(e()?.items??[]).filter(e=>e.batch===t):[]}),re=x(()=>D().reduce((e,t)=>e+t.reports.length,0)),O=x(()=>{let e=E()?.at;if(!e)return;let t=D().map(e=>Date.parse(e.createdAt)).filter(e=>Number.isFinite(e)).reduce((e,t)=>Math.max(e,t),Date.parse(e)),n=Math.round((t-Date.parse(e))/6e4);return Number.isFinite(n)?Math.max(0,n):void 0}),k=x(()=>w().pendingNew+w().pendingLegacy),A=x(()=>{let t=e()?.root??``;return t.split(/[\\/]/).filter(Boolean).pop()??t});function j(e){let t=new Set(o());t.has(e)?t.delete(e):t.add(e),s(t)}function M(e){let t=new Set(c());t.has(e)?t.delete(e):t.add(e),l(t)}async function ie(e,n){p(e);try{let i=await Q(e,n);t(i),r(void 0)}catch(e){r(e instanceof Error?e.message:String(e))}finally{p(void 0)}}async function ae(e){try{d(await $(e))}catch(e){r(e instanceof Error?e.message:String(e))}}return(()=>{var t=Fe(),r=t.firstChild.nextSibling.nextSibling.nextSibling,a=r.firstChild,s=a.firstChild.nextSibling.firstChild,l=s.firstChild.nextSibling.firstChild,p=l.nextSibling.nextSibling,y=p.firstChild,x=p.nextSibling.nextSibling,te=x.firstChild,C=x.nextSibling.nextSibling,oe=C.firstChild,N=s.nextSibling,P=a.nextSibling,F=P.firstChild,I=F.firstChild,se=I.nextSibling,L=se.firstChild.nextSibling;L.nextSibling;var R=F.nextSibling,ce=R.firstChild,le=ce.firstChild,z=ce.nextSibling.firstChild,ue=z.firstChild.nextSibling,W=z.nextSibling,de=W.firstChild.nextSibling,fe=W.nextSibling,G=fe.firstChild.nextSibling,pe=R.nextSibling.firstChild.nextSibling,_e=pe.firstChild,ve=P.nextSibling,q=ve.firstChild,J=q.firstChild,Y=J.firstChild.nextSibling,X=Y.firstChild,ye=J.nextSibling,Z=q.nextSibling,be=Z.firstChild,Q=be.nextSibling,$=Q.firstChild.nextSibling;$.firstChild;var xe=Q.nextSibling;return K(l,A),K(p,()=>w().open,y),K(x,()=>w().checked,te),K(C,k,oe),N.$$click=()=>void v(),K(r,B(H,{get when(){return n()},get children(){var e=Se();return K(e,n),e}}),P),K(r,B(H,{get when(){return e()?.skipped},children:e=>(()=>{var t=Ie(),n=t.firstChild;return K(t,e,n),t})()}),P),K(I,()=>w().checked),K(se,T,L),K(z,()=>w().open,ue),K(W,()=>w().checked,de),K(fe,k,G),K(pe,()=>i()?`live`:`offline`,null),K(r,B(H,{get when(){return k()>0},get children(){var e=Te();return K(e,B(H,{get when(){return w().pendingNew>0},get children(){var e=Ce(),t=e.firstChild,n=t.nextSibling.nextSibling;return n.nextSibling,K(t,()=>w().pendingNew),K(e,()=>w().pendingNew===1?``:`s`,n),e}}),null),K(e,B(H,{get when(){return w().pendingLegacy>0},get children(){var e=we(),t=e.firstChild,n=t.nextSibling.nextSibling;return n.nextSibling,K(t,()=>w().pendingLegacy),K(e,()=>w().pendingLegacy===1?` has`:`s have`,n),e}}),null),e}}),ve),K(Y,()=>w().open,X),K(Y,()=>w().open===1?``:`s`,null),K(q,B(H,{get when(){return U(()=>!!e())()&&ee().length===0},get children(){return Ee()}}),ye),K(ye,B(V,{get each(){return ee()},children:e=>(()=>{var t=qe(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.firstChild,s=a.firstChild,l=s.nextSibling,u=l.firstChild,d=u.firstChild,p=u.nextSibling,m=a.nextSibling,h=m.nextSibling;return r.addEventListener(`change`,()=>void ie(e.id,!0)),r.checked=!1,K(s,()=>e.title),K(l,B(H,{get when(){return e.reopened},get children(){return Le()}}),u),K(u,()=>e.reports.length,d),K(u,()=>e.reports.length===1?``:`s`,null),K(l,B(H,{get when(){return e.area},get children(){var t=Re();return K(t,()=>e.area),t}}),p),K(p,()=>nt(e.createdAt)),K(m,()=>e.summary),h.$$click=()=>j(e.id),K(h,()=>o().has(e.id)?`hide test plan`:`show test plan`,null),K(h,(()=>{var t=U(()=>!!o().has(e.id));return()=>t()?``:` · ${e.steps.length} steps`})(),null),K(i,B(H,{get when(){return o().has(e.id)},get children(){var t=Ke(),n=t.firstChild,r=n.nextSibling;return K(t,B(H,{get when(){return e.steps.length>0},get children(){return[ze(),(()=>{var t=Be();return K(t,B(V,{get each(){return e.steps},children:e=>(()=>{var t=Je();return K(t,e),t})()})),t})()]}}),n),K(t,B(H,{get when(){return e.edge.length>0},get children(){return[Ve(),(()=>{var t=He();return K(t,B(V,{get each(){return e.edge},children:e=>(()=>{var t=Je();return K(t,e),t})()})),t})()]}}),n),K(t,B(H,{get when(){return e.skip},get children(){var t=Ue(),n=t.firstChild.nextSibling;return K(n,()=>e.skip),t}}),n),K(t,B(H,{get when(){return e.spec},get children(){var t=We(),n=t.firstChild.nextSibling;return K(n,()=>e.spec),t}}),n),K(r,B(V,{get each(){return U(()=>!!c().has(e.id))()?e.reports:e.reports.slice(0,6)},children:e=>(()=>{var t=Ye();return t.$$click=()=>void ae(e),K(t,()=>it(e)),t})()}),null),K(r,B(H,{get when(){return e.reports.length>6},get children(){var t=Ge();return t.$$click=()=>M(e.id),K(t,(()=>{var t=U(()=>!!c().has(e.id));return()=>t()?`less`:`+${e.reports.length-6}`})()),t}}),null),t}}),null),b(()=>r.disabled=f()===e.id),t})()})),K(q,B(H,{get when(){return w().checked>0},get children(){return[(()=>{var e=De(),t=e.firstChild,n=t.firstChild.nextSibling,r=n.firstChild,i=t.nextSibling.firstChild;return e.$$click=()=>h(!m()),K(n,()=>w().checked,r),b(()=>me(i,`d`,m()?`M6 15l6-6 6 6`:`M6 9l6 6 6-6`)),e})(),B(H,{get when(){return m()},get children(){var e=Oe();return K(e,B(V,{get each(){return S()},children:e=>(()=>{var t=Xe(),n=t.firstChild,r=n.firstChild,i=n.nextSibling.firstChild,a=i.nextSibling,o=a.nextSibling;return o.firstChild,r.addEventListener(`change`,()=>void ie(e.id,!1)),r.checked=!0,K(i,()=>e.title),K(a,()=>e.summary),K(o,()=>rt(e.checkedAt??e.createdAt),null),b(()=>r.disabled=f()===e.id),t})()})),e}})]}}),null),K(Z,B(H,{get when(){return E()},children:e=>(()=>{var t=Ze(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling.firstChild.nextSibling;return K(n,()=>e().id),K(i,()=>D().length),K(o,re),K(s,(()=>{var e=U(()=>O()===void 0);return()=>e()?`—`:`${O()} min`})()),t})()}),be),K(Q,B(H,{get when(){return k()===0},get children(){return ke()}}),$),K(Q,B(H,{get when(){return k()>0},get children(){var e=Ae(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,K(e,()=>w().pendingNew,t),K(e,()=>w().pendingLegacy,n),e}}),$),K($,B(H,{get when(){return w().pendingLegacy>0},get children(){return je()}}),null),K(Z,B(H,{get when(){return w().checked>0},get children(){var e=Me(),t=e.firstChild.nextSibling;return K(t,B(V,{get each(){return S().slice(0,3)},children:e=>(()=>{var t=Qe(),n=t.firstChild.nextSibling;return K(n,()=>e.title),t})()})),e}}),xe),K(Z,B(H,{get when(){return w().retired>0},get children(){var t=Pe(),n=t.firstChild,r=n.firstChild;r.firstChild;var i=r.nextSibling.firstChild;return n.nextSibling,n.$$click=()=>_(!g()),K(r,()=>w().retired,null),K(t,B(H,{get when(){return g()},get children(){var t=Ne();return K(t,B(V,{get each(){return(e()?.retired??[]).slice(0,40)},children:e=>(()=>{var t=$e(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return K(n,()=>it(e.id)),K(r,()=>e.reason===`none`?`none:`:`dropped`),K(i,()=>e.title),t})()})),t}}),null),b(()=>me(i,`d`,g()?`M6 15l6-6 6 6`:`M6 9l6 6 6-6`)),t}}),xe),K(xe,()=>e()?.root),K(t,B(H,{get when(){return u()},children:e=>(()=>{var t=et(),n=t.firstChild.firstChild,r=n.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=n.nextSibling;return K(r,()=>e().id,i),a.$$click=()=>d(void 0),K(o,()=>e().text),t})()}),null),b(e=>{var t=`width:${ne()}%`,n=i()?`live-state`:`live-state down`,r=i()?`legend-dot leaf`:`legend-dot amber`;return e.e=ge(le,t,e.e),n!==e.t&&he(pe,e.t=n),r!==e.a&&he(_e,e.a=r),e},{e:void 0,t:void 0,a:void 0}),t})()}function nt(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleDateString(void 0,{month:`2-digit`,day:`2-digit`})}function rt(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function it(e){let t=/^(\d{4})-(\d{2})-(\d{2})_(\d{4})/.exec(e);return t?`${t[2]}-${t[3]}_${t[4]}`:e.length>22?`${e.slice(0,20)}…`:e}pe([`click`]);var at=document.getElementById(`root`);at&&fe(()=>B(tt,{}),at);