@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,1343 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { Theme } from "@earendil-works/pi-coding-agent";
4
+ import { MemoryStorage } from "@earendil-works/pi-durable";
5
+ import { Effect, Ref } from "effect";
6
+ import { assert, beforeEach, it } from "@effect/vitest";
7
+ import { makeTempDir } from "../../test-support/platform.ts";
8
+ import { fakeObservations } from "../../test-support/fake-observations.ts";
9
+ import { inspectorClock } from "../../test-support/inspector-clock.ts";
10
+ import { makeStubPi, type StubPi } from "../../test-support/stub-pi.ts";
11
+ import { makeStubTui } from "../../test-support/stub-tui.ts";
12
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
13
+ import { waitFor } from "../../test-support/wait.ts";
14
+ import { registerDelegatesCommand } from "./commands.ts";
15
+ import { createCatalogue, defineAgent } from "../domain/definitions.ts";
16
+ import { CODING_EXTENSION } from "../domain/names.ts";
17
+ import { launch, type HostDefaults } from "../domain/orchestration/launch.ts";
18
+ import { GateDoc, GateIndexDoc, type GateRecord } from "../domain/orchestration/gates.ts";
19
+ import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
20
+ import type { ChildView, RunStatus, RunView, SessionView } from "../domain/view.ts";
21
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
22
+ import type { ActionResult } from "../presentation/actions.ts";
23
+ import {
24
+ isLiveStatus,
25
+ liveAddress,
26
+ RUN_INDEX_ADDRESS,
27
+ runAddress,
28
+ TASK_GRAPH_ADDRESS,
29
+ } from "../presentation/inspector.ts";
30
+ import { STRIP_KEY, STRIP_PLACEMENT } from "../presentation/strip.ts";
31
+ import { HostModelAdapter } from "../runtime/models.ts";
32
+ import { type SessionRuntime } from "../runtime/session.ts";
33
+
34
+ import {
35
+ ACTIVATION_ENTRY,
36
+ ensureInspector,
37
+ hostFor,
38
+ readActivation,
39
+ registerInspectorOverlay,
40
+ runDelegatesCommand,
41
+ teardownInspector,
42
+ type InspectorCommandDeps,
43
+ } from "./inspector-command.ts";
44
+ import { OVERLAY_OPTIONS } from "../presentation/overlay.ts";
45
+ import type { RequestNotice } from "../presentation/wording.ts";
46
+ import { DEFAULT_INSPECT_SHORTCUT } from "../presentation/shortcut.ts";
47
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
48
+ import type { SessionHandle } from "../runtime/handle.ts";
49
+
50
+ const plainTheme = {
51
+ fg: (_color: string, text: string): string => text,
52
+ bg: (_color: string, text: string): string => text,
53
+ bold: (text: string): string => text,
54
+ style: (text: string): string => text,
55
+ } as unknown as Theme;
56
+
57
+ const host: HostDefaults = {
58
+ model: { provider: "stub", modelId: "stub-1" },
59
+ thinkingLevel: "low",
60
+ };
61
+
62
+ const deployer = defineAgent({
63
+ name: "deployer",
64
+ role: "Deploy agent",
65
+ prompt: { role: "You deploy things." },
66
+ tools: ["bash"],
67
+ extensions: [CODING_EXTENSION],
68
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
69
+ });
70
+
71
+ const gatedCatalogue = createCatalogue([deployer]);
72
+
73
+ const openRuntime = async (log?: LogSink): Promise<TestSession> => {
74
+ const sessionDir = await makeTempDir("delegates-inspector-command-");
75
+ return openTestSession({
76
+ identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
77
+ models: new HostModelAdapter(stubHostSource()),
78
+ storage: new MemoryStorage(),
79
+ ...(log === undefined ? {} : { log }),
80
+ });
81
+ };
82
+
83
+ const recordingLog = (): {
84
+ readonly sink: LogSink;
85
+ readonly entries: { level: LogLevel; code: string; fields: LogFields }[];
86
+ } => {
87
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
88
+ return {
89
+ entries,
90
+ sink: {
91
+ write: (level, code, fields = {}) => {
92
+ entries.push({ level, code, fields });
93
+ },
94
+ },
95
+ };
96
+ };
97
+
98
+ const runView = (
99
+ input: Partial<RunView> & { readonly runId: string; readonly status: RunStatus },
100
+ ): RunView => ({
101
+ definition: "scout",
102
+ mode: "single",
103
+ lane: "default",
104
+ conversationId: null,
105
+ taskId: null,
106
+ answer: null,
107
+ durationMs: null,
108
+ children: [],
109
+ missing: [],
110
+ gates: [],
111
+ requests: [],
112
+ diagnostic: null,
113
+ execution: "wait",
114
+ maxTurns: null,
115
+ failure: null,
116
+ ...input,
117
+ });
118
+
119
+ const childView = (
120
+ input: Partial<ChildView> & { readonly child: number; readonly runId: string },
121
+ ): ChildView => ({
122
+ conversationId: null,
123
+ taskId: null,
124
+ agent: "scout",
125
+ status: "running",
126
+ answer: null,
127
+ durationMs: null,
128
+ maxTurns: null,
129
+ failure: null,
130
+ ...input,
131
+ });
132
+
133
+ const view = (runs: readonly RunView[], gates: SessionView["gates"] = []): SessionView => ({
134
+ runs,
135
+ lanes: [],
136
+ gates,
137
+ reviews: [],
138
+ requests: [],
139
+ });
140
+
141
+ const gateOf = (input: Partial<GateRecord> & { readonly gate: string }): GateRecord => ({
142
+ runId: "run:r1",
143
+ status: "pending",
144
+ tool: "bash",
145
+ taskId: null,
146
+ taskIds: [],
147
+ childRunIds: [],
148
+ requestedAt: 1_000,
149
+ deadline: 0,
150
+ decision: null,
151
+ decidedBy: null,
152
+ reason: null,
153
+ ...input,
154
+ });
155
+
156
+ const liveView = (label = "deployer", status: RunStatus = "running"): SessionView =>
157
+ view([
158
+ runView({
159
+ runId: "run:a",
160
+ status,
161
+ conversationId: 10,
162
+ definition: "fanout",
163
+ children: [
164
+ childView({ child: 0, runId: "run:a:child:0", conversationId: 10, agent: label, status }),
165
+ ],
166
+ }),
167
+ ]);
168
+
169
+ const answeredView = (): SessionView =>
170
+ view([
171
+ runView({
172
+ runId: "run:done",
173
+ status: "answered",
174
+ children: [childView({ child: 0, runId: "run:done", status: "answered" })],
175
+ }),
176
+ ]);
177
+
178
+ const sequence = (
179
+ items: readonly SessionView[],
180
+ ): { readonly read: () => Promise<SessionView>; readonly reads: () => number } => {
181
+ let reads = 0;
182
+ return {
183
+ read: () => {
184
+ const index = Math.min(reads, items.length - 1);
185
+ reads += 1;
186
+ return Promise.resolve(items[index] as SessionView);
187
+ },
188
+ reads: () => reads,
189
+ };
190
+ };
191
+
192
+ const ctxOf = (stub: StubPi): ExtensionContext => stub.context as ExtensionContext;
193
+
194
+ const depsOf = (
195
+ stub: StubPi,
196
+ runtime: TestSession,
197
+ options: {
198
+ readonly observe?: ReturnType<typeof fakeObservations>;
199
+ readonly view?: () => Promise<SessionView>;
200
+ readonly shortcut?: string;
201
+ readonly onEndFiber?: () => void;
202
+ } = {},
203
+ ): InspectorCommandDeps => ({
204
+ session: Ref.makeUnsafe<SessionHandle | undefined>(runtime.handle),
205
+ host: (ctx) => hostFor(stub.api, ctx),
206
+ ...(options.shortcut === undefined ? {} : { shortcut: options.shortcut }),
207
+ inspector: {
208
+ ...(options.observe === undefined ? {} : { observe: options.observe }),
209
+ ...(options.view === undefined ? {} : { view: options.view }),
210
+ ...(options.onEndFiber === undefined ? {} : { onEndFiber: () => options.onEndFiber?.() }),
211
+ now: () => 4_000,
212
+ timers: inspectorClock(),
213
+ },
214
+ });
215
+
216
+ const widgetFactory = (
217
+ stub: StubPi,
218
+ index = stub.widgetCalls.length - 1,
219
+ ): ((tui: unknown, theme: Theme) => { render: (width: number) => string[] }) => {
220
+ const call = stub.widgetCalls[index];
221
+ assert.ok(call !== undefined, "a widget registration exists");
222
+ return call.content as (tui: unknown, theme: Theme) => { render: (width: number) => string[] };
223
+ };
224
+
225
+ const markerEntries = (stub: StubPi): SessionEntry[] =>
226
+ stub.entries.filter((entry) => entry.type === "custom" && entry.customType === ACTIVATION_ENTRY);
227
+
228
+ const activationMarker = (active: boolean): SessionEntry =>
229
+ ({ type: "custom", customType: ACTIVATION_ENTRY, data: { active } }) as SessionEntry;
230
+
231
+ const seedListing = async (runtime: SessionRuntime): Promise<void> => {
232
+ await runtime.harness.commit(async (tx) => {
233
+ const index = await tx.doc(RunIndexDoc);
234
+ const doc = await tx.doc(RunDoc, "run:seed", { definition: "scout", lane: "coding" });
235
+ doc.requestedAgent = "scout";
236
+ index.runIds.push("run:seed");
237
+ const gates = await tx.doc(GateIndexDoc);
238
+ const gate = await tx.doc(GateDoc, "run:seed:deploy", { runId: "run:seed", gate: "deploy" });
239
+ gate.status = "pending";
240
+ gate.requestedAt = 1_000;
241
+ gates.keys.push("run:seed:deploy");
242
+ }, BACKGROUND_CONTEXT);
243
+ };
244
+
245
+ const reset = async (): Promise<void> => {
246
+ await teardownInspector({ markOff: false });
247
+ };
248
+
249
+ // A test cut short by the runner must not leave an activation for the next file.
250
+ beforeEach(async () => {
251
+ await reset();
252
+ });
253
+
254
+ it("activation resolves one inspector, writes one marker and registers one widget", async () => {
255
+ const stub = makeStubPi({ mode: "tui" });
256
+ const runtime = await openRuntime();
257
+ const fake = fakeObservations();
258
+ const views = sequence([liveView()]);
259
+ try {
260
+ await runDelegatesCommand(
261
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
262
+ ctxOf(stub),
263
+ );
264
+
265
+ assert.deepStrictEqual(stub.entries, [activationMarker(true)]);
266
+ assert.strictEqual(stub.widgetCalls.length, 1);
267
+ assert.deepStrictEqual(stub.widgetCalls[0]?.options, { placement: STRIP_PLACEMENT });
268
+ assert.strictEqual(stub.customCalls.length, 0);
269
+ assert.ok(fake.attaches.includes(RUN_INDEX_ADDRESS));
270
+ assert.ok(fake.attaches.includes(TASK_GRAPH_ADDRESS));
271
+ assert.ok(fake.attaches.includes(runAddress("run:a")));
272
+ assert.ok(fake.attaches.includes(liveAddress(10)));
273
+ assert.strictEqual(views.reads(), 1);
274
+
275
+ const component = widgetFactory(stub)(makeStubTui(), plainTheme);
276
+ const lines = component.render(80);
277
+ assert.ok(lines[1]?.includes("running 1"), String(lines[1]));
278
+ assert.ok(lines[2]?.includes("deployer"), String(lines[2]));
279
+ } finally {
280
+ await reset();
281
+ await runtime.close();
282
+ }
283
+ });
284
+
285
+ it("a failed activation provisions nothing and writes one ending line", async () => {
286
+ const stub = makeStubPi({ mode: "tui" });
287
+ const runtime = await openRuntime();
288
+ const fake = fakeObservations();
289
+ let fail = true;
290
+ const views = {
291
+ read: () => (fail ? Promise.reject(new Error("boom")) : Promise.resolve(liveView())),
292
+ };
293
+ try {
294
+ await runDelegatesCommand(
295
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
296
+ ctxOf(stub),
297
+ );
298
+
299
+ assert.deepStrictEqual(stub.entries, []);
300
+ assert.strictEqual(stub.widgetCalls.length, 0);
301
+ assert.strictEqual(stub.customCalls.length, 0);
302
+ assert.strictEqual(stub.notices.length, 1);
303
+ assert.strictEqual(stub.notices[0]?.severity, "warning");
304
+ assert.ok(stub.notices[0]?.message.includes("failed to start: boom"));
305
+
306
+ // A second press retries and succeeds.
307
+ fail = false;
308
+ await runDelegatesCommand(
309
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
310
+ ctxOf(stub),
311
+ );
312
+ assert.strictEqual(markerEntries(stub).length, 1);
313
+ assert.strictEqual(stub.widgetCalls.length, 1);
314
+ } finally {
315
+ await reset();
316
+ await runtime.close();
317
+ }
318
+ });
319
+
320
+ it("the mount requests one render per published revision and drops the replay", async () => {
321
+ const stub = makeStubPi({ mode: "tui" });
322
+ const runtime = await openRuntime();
323
+ const fake = fakeObservations();
324
+ const views = sequence([
325
+ liveView("first"),
326
+ liveView("second"),
327
+ liveView("third"),
328
+ liveView("fourth"),
329
+ ]);
330
+ try {
331
+ await runDelegatesCommand(
332
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
333
+ ctxOf(stub),
334
+ );
335
+ const tui = makeStubTui();
336
+ widgetFactory(stub)(tui, plainTheme).render(80);
337
+ assert.strictEqual(tui.renders, 0);
338
+
339
+ fake.push(RUN_INDEX_ADDRESS);
340
+ await waitFor(() => tui.renders === 1, "one render for the second revision");
341
+ fake.push(RUN_INDEX_ADDRESS);
342
+ await waitFor(() => tui.renders === 2, "one render for the third revision");
343
+ fake.push(RUN_INDEX_ADDRESS);
344
+ await waitFor(() => tui.renders === 3, "one render for the fourth revision");
345
+
346
+ const component = widgetFactory(stub)(makeStubTui(), plainTheme);
347
+ assert.ok(component.render(80)[2]?.includes("fourth"));
348
+ } finally {
349
+ await reset();
350
+ await runtime.close();
351
+ }
352
+ });
353
+
354
+ it("a second press deactivates everything once", async () => {
355
+ const stub = makeStubPi({ mode: "tui" });
356
+ const runtime = await openRuntime();
357
+ const fake = fakeObservations();
358
+ const views = sequence([liveView()]);
359
+ try {
360
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
361
+ await runDelegatesCommand(deps, ctxOf(stub));
362
+ const reads = views.reads();
363
+ await runDelegatesCommand(deps, ctxOf(stub));
364
+
365
+ assert.strictEqual(stub.widgetCalls.at(-1)?.content, undefined);
366
+ assert.deepStrictEqual(
367
+ markerEntries(stub).map((entry) => (entry as { data?: { active?: boolean } }).data),
368
+ [{ active: true }, { active: false }],
369
+ );
370
+ assert.strictEqual(new Set(fake.detaches).size, fake.detaches.length);
371
+ assert.deepStrictEqual(fake.attached(), []);
372
+
373
+ fake.push(RUN_INDEX_ADDRESS);
374
+ await new Promise((resolve) => setTimeout(resolve, 20));
375
+ assert.strictEqual(views.reads(), reads);
376
+ } finally {
377
+ await reset();
378
+ await runtime.close();
379
+ }
380
+ });
381
+
382
+ it("two presses before the first activation settles resolve one inspector and end off", async () => {
383
+ const stub = makeStubPi({ mode: "tui" });
384
+ const runtime = await openRuntime();
385
+ const fake = fakeObservations();
386
+ const views = sequence([liveView()]);
387
+ try {
388
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
389
+ await Promise.all([
390
+ runDelegatesCommand(deps, ctxOf(stub)),
391
+ runDelegatesCommand(deps, ctxOf(stub)),
392
+ ]);
393
+
394
+ assert.ok(fake.attaches.length > 0);
395
+ assert.strictEqual(fake.detaches.length, fake.attaches.length);
396
+ assert.deepStrictEqual(fake.attached(), []);
397
+ assert.strictEqual(stub.widgetCalls.filter((call) => call.content !== undefined).length, 1);
398
+ assert.deepStrictEqual(
399
+ markerEntries(stub).map((entry) => (entry as { data?: { active?: boolean } }).data),
400
+ [{ active: true }, { active: false }],
401
+ );
402
+ } finally {
403
+ await reset();
404
+ await runtime.close();
405
+ }
406
+ });
407
+
408
+ it("a teardown waits for an activation that is still building", async () => {
409
+ const stub = makeStubPi({ mode: "tui" });
410
+ const runtime = await openRuntime();
411
+ const fake = fakeObservations();
412
+ const views = sequence([liveView()]);
413
+ try {
414
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
415
+ const starting = runDelegatesCommand(deps, ctxOf(stub));
416
+ await teardownInspector({ markOff: false });
417
+ await starting;
418
+
419
+ assert.ok(fake.attaches.length > 0);
420
+ assert.strictEqual(fake.detaches.length, fake.attaches.length);
421
+ assert.deepStrictEqual(fake.attached(), []);
422
+ assert.strictEqual(stub.widgetCalls.at(-1)?.content, undefined);
423
+ } finally {
424
+ await reset();
425
+ await runtime.close();
426
+ }
427
+ });
428
+
429
+ it("a third press reactivates at revision 1", async () => {
430
+ const stub = makeStubPi({ mode: "tui" });
431
+ const runtime = await openRuntime();
432
+ const fake = fakeObservations();
433
+ const views = sequence([liveView("first"), liveView("second")]);
434
+ try {
435
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
436
+ await runDelegatesCommand(deps, ctxOf(stub));
437
+ const firstAttaches = fake.attaches.length;
438
+ await runDelegatesCommand(deps, ctxOf(stub));
439
+ const detachesAfterOff = fake.detaches.length;
440
+
441
+ await runDelegatesCommand(deps, ctxOf(stub));
442
+ assert.strictEqual(fake.attaches.length, firstAttaches * 2);
443
+ assert.strictEqual(fake.detaches.length, detachesAfterOff);
444
+ assert.strictEqual(stub.widgetCalls.filter((call) => call.content !== undefined).length, 2);
445
+
446
+ const component = widgetFactory(stub)(makeStubTui(), plainTheme);
447
+ const lines = component.render(80);
448
+ assert.ok(lines[2]?.includes("second"), String(lines[2]));
449
+ } finally {
450
+ await reset();
451
+ await runtime.close();
452
+ }
453
+ });
454
+
455
+ it("an activation whose last marker is already true appends nothing", async () => {
456
+ const stub = makeStubPi({ mode: "tui" });
457
+ stub.entries.push({
458
+ type: "custom",
459
+ customType: ACTIVATION_ENTRY,
460
+ data: { active: true },
461
+ } as SessionEntry);
462
+ const runtime = await openRuntime();
463
+ const fake = fakeObservations();
464
+ try {
465
+ await runDelegatesCommand(
466
+ depsOf(stub, runtime, { observe: fake, view: async () => liveView() }),
467
+ ctxOf(stub),
468
+ );
469
+ assert.strictEqual(markerEntries(stub).length, 1);
470
+ assert.strictEqual(stub.widgetCalls.length, 1);
471
+ assert.ok(fake.attaches.length > 0);
472
+ } finally {
473
+ await reset();
474
+ await runtime.close();
475
+ }
476
+ });
477
+
478
+ it("the strip mounts once at activation and follows a live push", async () => {
479
+ const stub = makeStubPi({ mode: "tui" });
480
+ const runtime = await openRuntime();
481
+ const fake = fakeObservations();
482
+ const views = sequence([answeredView(), liveView()]);
483
+ try {
484
+ await runDelegatesCommand(
485
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
486
+ ctxOf(stub),
487
+ );
488
+ assert.strictEqual(stub.widgetCalls.length, 1);
489
+ assert.strictEqual(typeof stub.widgetCalls[0]?.content, "function");
490
+ assert.strictEqual(stub.statusCalls[0]?.text, "delegates idle · ctrl+space");
491
+
492
+ fake.push(RUN_INDEX_ADDRESS);
493
+ await waitFor(() => stub.statusCalls.length === 2, "the live push published");
494
+ assert.strictEqual(stub.widgetCalls.length, 1);
495
+ assert.strictEqual(stub.statusCalls[1]?.text, "delegates running 1 · ctrl+space");
496
+
497
+ // Same snapshot again: the footer already reads this, so nothing is written.
498
+ fake.push(RUN_INDEX_ADDRESS);
499
+ await new Promise((resolve) => setTimeout(resolve, 60));
500
+ assert.strictEqual(stub.statusCalls.length, 2, "an unchanged publication writes no line");
501
+ } finally {
502
+ await reset();
503
+ await runtime.close();
504
+ }
505
+ });
506
+
507
+ it("the command prints today's listing outside tui mode and touches nothing", async () => {
508
+ const stub = makeStubPi({ mode: "rpc" });
509
+ const runtime = await openRuntime();
510
+ let inspectorCalls = 0;
511
+ try {
512
+ await seedListing(runtime);
513
+ registerDelegatesCommand(stub.api, {
514
+ definitions: createCatalogue().all,
515
+ session: Ref.makeUnsafe<SessionHandle | undefined>(runtime.handle),
516
+ log: () => runtime.log,
517
+ inspector: async () => {
518
+ inspectorCalls += 1;
519
+ },
520
+ });
521
+ const handler = stub.registrations.commandHandlers.get("delegates");
522
+ assert.ok(handler !== undefined);
523
+ await handler("", ctxOf(stub));
524
+
525
+ assert.strictEqual(inspectorCalls, 0);
526
+ assert.strictEqual(stub.widgetCalls.length, 0);
527
+ assert.strictEqual(stub.customCalls.length, 0);
528
+ assert.strictEqual(stub.entries.length, 0);
529
+ assert.strictEqual(stub.notices.length, 1);
530
+ assert.strictEqual(stub.notices[0]?.severity, "info");
531
+ const text = stub.notices[0]?.message ?? "";
532
+ assert.ok(text.includes("scout"), text);
533
+ assert.ok(text.includes("run:seed"), text);
534
+ assert.ok(text.includes("coding: running"), text);
535
+ assert.ok(text.includes("gate deploy pending for run:seed"), text);
536
+ } finally {
537
+ await runtime.close();
538
+ }
539
+ });
540
+
541
+ it("readActivation takes the last entry, and a false marker turns it off", () => {
542
+ const marker = (active: boolean): SessionEntry =>
543
+ ({ type: "custom", customType: ACTIVATION_ENTRY, data: { active } }) as SessionEntry;
544
+ assert.strictEqual(readActivation([]), false);
545
+ assert.strictEqual(readActivation([marker(true)]), true);
546
+ assert.strictEqual(readActivation([marker(true), marker(false)]), false);
547
+ assert.strictEqual(readActivation([marker(false), marker(true)]), true);
548
+ assert.strictEqual(readActivation([{ type: "label" } as SessionEntry]), false);
549
+ });
550
+
551
+ it("ensureInspector activates a session with no marker, once", async () => {
552
+ const stub = makeStubPi({ mode: "tui" });
553
+ const runtime = await openRuntime();
554
+ const fake = fakeObservations();
555
+ const views = sequence([liveView()]);
556
+ try {
557
+ await ensureInspector(depsOf(stub, runtime, { observe: fake, view: views.read }), ctxOf(stub));
558
+ assert.deepStrictEqual(
559
+ markerEntries(stub).map((entry) => (entry as { data?: { active?: boolean } }).data),
560
+ [{ active: true }],
561
+ );
562
+ assert.strictEqual(stub.widgetCalls.length, 1);
563
+
564
+ await ensureInspector(depsOf(stub, runtime, { observe: fake, view: views.read }), ctxOf(stub));
565
+ assert.strictEqual(markerEntries(stub).length, 1);
566
+ assert.strictEqual(stub.widgetCalls.length, 1);
567
+ } finally {
568
+ await reset();
569
+ await runtime.close();
570
+ }
571
+ });
572
+
573
+ it("ensureInspector leaves an explicit off marker alone", async () => {
574
+ const stub = makeStubPi({ mode: "tui" });
575
+ stub.entries.push(activationMarker(false));
576
+ const runtime = await openRuntime();
577
+ try {
578
+ await ensureInspector(depsOf(stub, runtime), ctxOf(stub));
579
+ assert.deepStrictEqual(stub.widgetCalls, []);
580
+ assert.strictEqual(markerEntries(stub).length, 1);
581
+ } finally {
582
+ await reset();
583
+ await runtime.close();
584
+ }
585
+ });
586
+
587
+ it("ensureInspector activates an active marker without appending", async () => {
588
+ const stub = makeStubPi({ mode: "tui" });
589
+ stub.entries.push(activationMarker(true));
590
+ const runtime = await openRuntime();
591
+ const fake = fakeObservations();
592
+ const views = sequence([liveView()]);
593
+ try {
594
+ await ensureInspector(depsOf(stub, runtime, { observe: fake, view: views.read }), ctxOf(stub));
595
+ assert.strictEqual(markerEntries(stub).length, 1);
596
+ assert.strictEqual(stub.widgetCalls.length, 1);
597
+ } finally {
598
+ await reset();
599
+ await runtime.close();
600
+ }
601
+ });
602
+
603
+ it("ensureInspector does nothing outside tui", async () => {
604
+ const stub = makeStubPi({ mode: "rpc" });
605
+ const runtime = await openRuntime();
606
+ try {
607
+ await ensureInspector(depsOf(stub, runtime), ctxOf(stub));
608
+ assert.deepStrictEqual(stub.entries, []);
609
+ assert.deepStrictEqual(stub.widgetCalls, []);
610
+ } finally {
611
+ await reset();
612
+ await runtime.close();
613
+ }
614
+ });
615
+
616
+ it("a live row is one that can still change", () => {
617
+ for (const status of ["queued", "running", "waiting"] as const) {
618
+ assert.strictEqual(isLiveStatus(status), true);
619
+ }
620
+ for (const status of ["answered", "failed", "stopped", "denied"] as const) {
621
+ assert.strictEqual(isLiveStatus(status), false);
622
+ }
623
+ });
624
+
625
+ it("the strip key is one widget", () => {
626
+ assert.strictEqual(STRIP_KEY, "delegates-inspector");
627
+ });
628
+
629
+ interface MountedOverlay {
630
+ readonly call: NonNullable<ReturnType<typeof mountCall>>;
631
+ readonly tui: ReturnType<typeof makeStubTui>;
632
+ readonly component: { render: (width: number) => string[]; handleInput: (data: string) => void };
633
+ }
634
+
635
+ const mountCall = (stub: StubPi, index = stub.customCalls.length - 1) => stub.customCalls[index];
636
+
637
+ const mountOverlay = (stub: StubPi): MountedOverlay => {
638
+ const call = mountCall(stub);
639
+ assert.ok(call !== undefined, "an overlay was mounted");
640
+ assert.ok(call.done !== undefined, "the overlay can be closed");
641
+ const tui = makeStubTui();
642
+ const component = (
643
+ call.factory as (
644
+ tui: unknown,
645
+ theme: Theme,
646
+ keybindings: unknown,
647
+ done: (value?: unknown) => void,
648
+ ) => { render: (width: number) => string[]; handleInput: (data: string) => void }
649
+ )(tui, plainTheme, undefined, call.done);
650
+ return { call, tui, component };
651
+ };
652
+
653
+ const registerOverlay = (stub: StubPi, deps: InspectorCommandDeps): void => {
654
+ registerInspectorOverlay(stub.api, deps);
655
+ };
656
+
657
+ const fireShortcut = (stub: StubPi, shortcut = DEFAULT_INSPECT_SHORTCUT): void => {
658
+ const registered = stub.registrations.shortcuts.get(shortcut);
659
+ assert.ok(registered !== undefined);
660
+ void registered.handler(ctxOf(stub));
661
+ };
662
+
663
+ const fireOverlayCommand = (stub: StubPi): void => {
664
+ const handler = stub.registrations.commandHandlers.get("delegates:overlay");
665
+ assert.ok(handler !== undefined);
666
+ void handler("", ctxOf(stub));
667
+ };
668
+
669
+ it("the shortcut refuses before activation", async () => {
670
+ const stub = makeStubPi({ mode: "tui" });
671
+ const runtime = await openRuntime();
672
+ const fake = fakeObservations();
673
+ const views = sequence([liveView()]);
674
+ try {
675
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
676
+ fireShortcut(stub);
677
+ await new Promise((resolve) => setTimeout(resolve, 20));
678
+ assert.strictEqual(stub.customCalls.length, 0);
679
+ assert.strictEqual(stub.widgetCalls.length, 0);
680
+ assert.strictEqual(stub.entries.length, 0);
681
+ assert.strictEqual(views.reads(), 0);
682
+ assert.deepStrictEqual(stub.notices, [
683
+ { message: "inspector is off — run /delegates to turn it on", severity: "warning" },
684
+ ]);
685
+ } finally {
686
+ await reset();
687
+ await runtime.close();
688
+ }
689
+ });
690
+
691
+ it("the shortcut mounts one overlay per press", async () => {
692
+ const stub = makeStubPi({ mode: "tui" });
693
+ const runtime = await openRuntime();
694
+ const fake = fakeObservations();
695
+ const views = sequence([liveView()]);
696
+ try {
697
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
698
+ await runDelegatesCommand(
699
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
700
+ ctxOf(stub),
701
+ );
702
+ fireShortcut(stub);
703
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
704
+
705
+ const call = mountCall(stub);
706
+ assert.ok(call !== undefined);
707
+ assert.strictEqual((call.options as { overlay?: boolean }).overlay, true);
708
+ const overlayOptions = (call.options as { overlayOptions?: () => unknown }).overlayOptions;
709
+ assert.strictEqual(typeof overlayOptions, "function");
710
+ assert.deepStrictEqual(overlayOptions?.(), OVERLAY_OPTIONS);
711
+ const mounted = mountOverlay(stub);
712
+ assert.ok(mounted.component.render(80)[0]?.includes("Delegates"));
713
+ } finally {
714
+ await reset();
715
+ await runtime.close();
716
+ }
717
+ });
718
+
719
+ it("a configured shortcut registers that key and the strip names it", async () => {
720
+ const stub = makeStubPi({ mode: "tui" });
721
+ const runtime = await openRuntime();
722
+ const fake = fakeObservations();
723
+ const views = sequence([liveView()]);
724
+ try {
725
+ const deps = depsOf(stub, runtime, {
726
+ observe: fake,
727
+ view: views.read,
728
+ shortcut: "ctrl+alt+i",
729
+ });
730
+ registerOverlay(stub, deps);
731
+ await runDelegatesCommand(deps, ctxOf(stub));
732
+
733
+ assert.ok(stub.registrations.shortcuts.has("ctrl+alt+i"));
734
+ assert.strictEqual(stub.registrations.shortcuts.has(DEFAULT_INSPECT_SHORTCUT), false);
735
+ const lines = widgetFactory(stub)(makeStubTui(), plainTheme).render(80);
736
+ assert.ok(lines[1]?.includes("ctrl+alt+i"), lines.join("\n"));
737
+
738
+ fireShortcut(stub, "ctrl+alt+i");
739
+ await waitFor(() => stub.customCalls.length === 1, "the configured shortcut mounted");
740
+ } finally {
741
+ await reset();
742
+ await runtime.close();
743
+ }
744
+ });
745
+
746
+ it("the overlay command refuses when the inspector is off", async () => {
747
+ const stub = makeStubPi({ mode: "tui" });
748
+ const runtime = await openRuntime();
749
+ const fake = fakeObservations();
750
+ try {
751
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: async () => liveView() }));
752
+ fireOverlayCommand(stub);
753
+ await new Promise((resolve) => setTimeout(resolve, 20));
754
+ assert.strictEqual(stub.customCalls.length, 0);
755
+ assert.strictEqual(stub.entries.length, 0);
756
+ assert.strictEqual(stub.widgetCalls.length, 0);
757
+ assert.deepStrictEqual(
758
+ stub.notices.map((notice) => [notice.message, notice.severity]),
759
+ [["inspector is off — run /delegates to turn it on", "warning"]],
760
+ );
761
+ } finally {
762
+ await reset();
763
+ await runtime.close();
764
+ }
765
+ });
766
+
767
+ it("the overlay command opens the overlay when activated", async () => {
768
+ const stub = makeStubPi({ mode: "tui" });
769
+ const runtime = await openRuntime();
770
+ const fake = fakeObservations();
771
+ const views = sequence([liveView()]);
772
+ try {
773
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
774
+ await runDelegatesCommand(
775
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
776
+ ctxOf(stub),
777
+ );
778
+ const before = stub.entries.length;
779
+ fireOverlayCommand(stub);
780
+ await waitFor(() => stub.customCalls.length === 1, "the overlay command mounted");
781
+ assert.strictEqual(stub.entries.length, before);
782
+ assert.ok(stub.notices.length === 0);
783
+ } finally {
784
+ await reset();
785
+ await runtime.close();
786
+ }
787
+ });
788
+
789
+ it("the mount registers its close handle with the activation", async () => {
790
+ const stub = makeStubPi({ mode: "tui" });
791
+ const runtime = await openRuntime();
792
+ const fake = fakeObservations();
793
+ const views = sequence([liveView()]);
794
+ try {
795
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
796
+ await runDelegatesCommand(
797
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
798
+ ctxOf(stub),
799
+ );
800
+ fireShortcut(stub);
801
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
802
+ const { call } = mountOverlay(stub);
803
+
804
+ await teardownInspector();
805
+ assert.strictEqual(call.doneCalls, 1);
806
+ assert.strictEqual(stub.widgetCalls.at(-1)?.content, undefined);
807
+
808
+ await teardownInspector();
809
+ assert.strictEqual(call.doneCalls, 1);
810
+ } finally {
811
+ await reset();
812
+ await runtime.close();
813
+ }
814
+ });
815
+
816
+ it("closing the overlay keeps the strip and writes no notice", async () => {
817
+ const stub = makeStubPi({ mode: "tui" });
818
+ const runtime = await openRuntime();
819
+ const fake = fakeObservations();
820
+ const views = sequence([liveView()]);
821
+ try {
822
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
823
+ await runDelegatesCommand(
824
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
825
+ ctxOf(stub),
826
+ );
827
+ const widgetCalls = stub.widgetCalls.length;
828
+ fireShortcut(stub);
829
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
830
+ const { call, component } = mountOverlay(stub);
831
+
832
+ component.handleInput("\x1b");
833
+ assert.strictEqual(call.doneCalls, 1);
834
+ assert.strictEqual(stub.widgetCalls.length, widgetCalls);
835
+ assert.strictEqual(stub.notices.length, 0);
836
+ } finally {
837
+ await reset();
838
+ await runtime.close();
839
+ }
840
+ });
841
+
842
+ it("a publication repaints the open overlay", async () => {
843
+ const stub = makeStubPi({ mode: "tui" });
844
+ const runtime = await openRuntime();
845
+ const fake = fakeObservations();
846
+ const views = sequence([liveView("first"), liveView("second")]);
847
+ try {
848
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
849
+ await runDelegatesCommand(
850
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
851
+ ctxOf(stub),
852
+ );
853
+ fireShortcut(stub);
854
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
855
+ const { tui, component } = mountOverlay(stub);
856
+ component.render(80);
857
+ assert.strictEqual(tui.renders, 0);
858
+ component.handleInput("\r");
859
+
860
+ const rendersBeforePush = tui.renders;
861
+ fake.push(RUN_INDEX_ADDRESS);
862
+ await waitFor(
863
+ () => tui.renders === rendersBeforePush + 1,
864
+ "the publication repainted the overlay",
865
+ 2_000,
866
+ );
867
+ assert.ok(component.render(80).some((line) => line.includes("second")));
868
+ } finally {
869
+ await reset();
870
+ await runtime.close();
871
+ }
872
+ });
873
+
874
+ it("the action status line survives the push that settles the row", async () => {
875
+ const stub = makeStubPi({ mode: "tui" });
876
+ const runtime = await openRuntime();
877
+ const run = await launch(
878
+ { kind: "single", agent: "deployer", task: "deploy it" },
879
+ { runtime, catalogue: gatedCatalogue, host, waitMs: 10_000 },
880
+ );
881
+ const runId = run.view.runId;
882
+ const waiting = view([
883
+ runView({
884
+ runId,
885
+ status: "waiting",
886
+ definition: "deployer",
887
+ children: [childView({ child: 0, runId, agent: "deployer", status: "waiting" })],
888
+ }),
889
+ ]);
890
+ const stopped = view([
891
+ runView({
892
+ runId,
893
+ status: "stopped",
894
+ definition: "deployer",
895
+ children: [childView({ child: 0, runId, agent: "deployer", status: "stopped" })],
896
+ }),
897
+ ]);
898
+ const views = sequence([waiting, stopped]);
899
+ const fake = fakeObservations();
900
+ try {
901
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
902
+ await runDelegatesCommand(
903
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
904
+ ctxOf(stub),
905
+ );
906
+ fireShortcut(stub);
907
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
908
+ const { component } = mountOverlay(stub);
909
+
910
+ component.handleInput("s");
911
+ await waitFor(
912
+ () => component.render(80).some((line) => line.includes(`stopped run ${runId}`)),
913
+ "the action line landed",
914
+ 2_000,
915
+ );
916
+
917
+ fake.push(RUN_INDEX_ADDRESS);
918
+ await waitFor(
919
+ () =>
920
+ component
921
+ .render(80)
922
+ .some((line) => line.includes(`${runId} ·`) || line.includes("· stopped")),
923
+ "the settling push landed",
924
+ 2_000,
925
+ );
926
+ assert.ok(component.render(80).some((line) => line.includes(`stopped run ${runId}`)));
927
+ } finally {
928
+ await reset();
929
+ await runtime.close();
930
+ }
931
+ });
932
+
933
+ it("a gate on a waiting child is approved through the parent run", async () => {
934
+ const stub = makeStubPi({ mode: "tui" });
935
+ const runtime = await openRuntime();
936
+ const childRun = "run:fan:child:0";
937
+ const current = view(
938
+ [
939
+ runView({
940
+ runId: "run:fan",
941
+ definition: "fanout",
942
+ status: "waiting",
943
+ gates: ["deploy"],
944
+ children: [childView({ child: 0, runId: childRun, agent: "deployer", status: "waiting" })],
945
+ }),
946
+ ],
947
+ [gateOf({ runId: "run:fan", gate: "deploy", childRunIds: [childRun] })],
948
+ );
949
+ const targets: unknown[] = [];
950
+ try {
951
+ const deps: InspectorCommandDeps = {
952
+ ...depsOf(stub, runtime, { view: async () => current }),
953
+ action: (input) => {
954
+ targets.push(input.target);
955
+ return Promise.resolve({ ok: true, message: "approved gate deploy" });
956
+ },
957
+ };
958
+ registerOverlay(stub, deps);
959
+ await runDelegatesCommand(deps, ctxOf(stub));
960
+ fireShortcut(stub);
961
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
962
+ const { component } = mountOverlay(stub);
963
+
964
+ component.handleInput("\r");
965
+ component.handleInput("\x1b[B");
966
+ assert.strictEqual(
967
+ component.render(80).some((line) => line.includes("deployer")),
968
+ true,
969
+ );
970
+ component.handleInput("a");
971
+
972
+ assert.deepStrictEqual(targets, [
973
+ { rowId: `child:${childRun}`, runId: "run:fan", gate: "deploy" },
974
+ ]);
975
+ } finally {
976
+ await reset();
977
+ await runtime.close();
978
+ }
979
+ });
980
+
981
+ it("a late action result writes no status line after the overlay closes", async () => {
982
+ const stub = makeStubPi({ mode: "tui" });
983
+ const runtime = await openRuntime();
984
+ const fake = fakeObservations();
985
+ const views = sequence([liveView()]);
986
+ let settle: ((result: ActionResult) => void) | undefined;
987
+ try {
988
+ const deps: InspectorCommandDeps = {
989
+ ...depsOf(stub, runtime, { observe: fake, view: views.read }),
990
+ action: () =>
991
+ new Promise<ActionResult>((resolve) => {
992
+ settle = resolve;
993
+ }),
994
+ };
995
+ registerOverlay(stub, deps);
996
+ await runDelegatesCommand(deps, ctxOf(stub));
997
+ fireShortcut(stub);
998
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
999
+ const first = mountOverlay(stub);
1000
+ first.component.handleInput("s");
1001
+ first.component.handleInput("\x1b");
1002
+ assert.strictEqual(first.call.doneCalls, 1);
1003
+
1004
+ settle?.({ ok: true, message: "stopped run run:a" });
1005
+ await Promise.resolve();
1006
+ await Promise.resolve();
1007
+
1008
+ fireShortcut(stub);
1009
+ await waitFor(() => stub.customCalls.length === 2, "the overlay reopened");
1010
+ const lines = mountOverlay(stub).component.render(80);
1011
+ assert.ok(!lines.some((line) => line.includes("stopped run run:a")), lines.join("\n"));
1012
+ } finally {
1013
+ await reset();
1014
+ await runtime.close();
1015
+ }
1016
+ });
1017
+
1018
+ it("a rejected action is logged and leaves no status line", async () => {
1019
+ const stub = makeStubPi({ mode: "tui" });
1020
+ const log = recordingLog();
1021
+ const runtime = await openRuntime(log.sink);
1022
+ const fake = fakeObservations();
1023
+ const views = sequence([liveView()]);
1024
+ try {
1025
+ const deps: InspectorCommandDeps = {
1026
+ ...depsOf(stub, runtime, { observe: fake, view: views.read }),
1027
+ action: () => Promise.reject(new Error("boom")),
1028
+ };
1029
+ registerOverlay(stub, deps);
1030
+ await runDelegatesCommand(deps, ctxOf(stub));
1031
+ fireShortcut(stub);
1032
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
1033
+ const { component } = mountOverlay(stub);
1034
+ component.handleInput("s");
1035
+
1036
+ await waitFor(
1037
+ () => log.entries.filter((entry) => entry.code === "inspector.action_failed").length > 0,
1038
+ "the rejected action was logged",
1039
+ );
1040
+ const failures = log.entries.filter((entry) => entry.code === "inspector.action_failed");
1041
+ assert.strictEqual(failures.length, 1);
1042
+ assert.ok(String(failures[0]?.fields.detail).includes("boom"), JSON.stringify(failures));
1043
+ assert.ok(!component.render(80).some((line) => line.includes("stopped run")));
1044
+ } finally {
1045
+ await reset();
1046
+ await runtime.close();
1047
+ }
1048
+ });
1049
+
1050
+ it("a second verb while one is in flight is dispatched and the last result wins", async () => {
1051
+ const stub = makeStubPi({ mode: "tui" });
1052
+ const runtime = await openRuntime();
1053
+ const fake = fakeObservations();
1054
+ const gated = view(
1055
+ [],
1056
+ [gateOf({ gate: "deploy", requestedAt: 1_000 }), gateOf({ gate: "smoke", requestedAt: 2_000 })],
1057
+ );
1058
+ const views = sequence([gated]);
1059
+ const pending: ((result: ActionResult) => void)[] = [];
1060
+ const targets: string[] = [];
1061
+ try {
1062
+ const deps: InspectorCommandDeps = {
1063
+ ...depsOf(stub, runtime, { observe: fake, view: views.read }),
1064
+ action: (input) => {
1065
+ targets.push(input.target.gate ?? input.target.runId);
1066
+ return new Promise<ActionResult>((resolve) => {
1067
+ pending.push(resolve);
1068
+ });
1069
+ },
1070
+ };
1071
+ registerOverlay(stub, deps);
1072
+ await runDelegatesCommand(deps, ctxOf(stub));
1073
+ fireShortcut(stub);
1074
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
1075
+ const { component } = mountOverlay(stub);
1076
+
1077
+ component.handleInput("a");
1078
+ component.handleInput("\x1b[B");
1079
+ component.handleInput("a");
1080
+ assert.deepStrictEqual(targets, ["deploy", "smoke"]);
1081
+ assert.strictEqual(pending.length, 2);
1082
+
1083
+ // The second gate resolves first; the first must not overwrite it.
1084
+ pending[1]?.({ ok: true, message: "approved gate smoke on run run:r1" });
1085
+ await Promise.resolve();
1086
+ await Promise.resolve();
1087
+ pending[0]?.({ ok: true, message: "approved gate deploy on run run:r1" });
1088
+ await Promise.resolve();
1089
+ await Promise.resolve();
1090
+
1091
+ const lines = component.render(80);
1092
+ assert.ok(
1093
+ lines.some((line) => line.includes("approved gate smoke")),
1094
+ lines.join("\n"),
1095
+ );
1096
+ assert.ok(!lines.some((line) => line.includes("approved gate deploy")), lines.join("\n"));
1097
+ } finally {
1098
+ await reset();
1099
+ await runtime.close();
1100
+ }
1101
+ });
1102
+
1103
+ it("three toggles append three markers", async () => {
1104
+ const stub = makeStubPi({ mode: "tui" });
1105
+ const runtime = await openRuntime();
1106
+ const fake = fakeObservations();
1107
+ const views = sequence([liveView("one"), liveView("two"), liveView("three")]);
1108
+ try {
1109
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
1110
+ await runDelegatesCommand(deps, ctxOf(stub));
1111
+ await runDelegatesCommand(deps, ctxOf(stub));
1112
+ await runDelegatesCommand(deps, ctxOf(stub));
1113
+ assert.deepStrictEqual(
1114
+ markerEntries(stub).map((entry) => (entry as { data?: { active?: boolean } }).data),
1115
+ [{ active: true }, { active: false }, { active: true }],
1116
+ );
1117
+ } finally {
1118
+ await reset();
1119
+ await runtime.close();
1120
+ }
1121
+ });
1122
+
1123
+ it("the footer line follows the toggle", async () => {
1124
+ const stub = makeStubPi({ mode: "tui" });
1125
+ const runtime = await openRuntime();
1126
+ const fake = fakeObservations();
1127
+ const views = sequence([liveView("one"), liveView("one")]);
1128
+ try {
1129
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
1130
+ await runDelegatesCommand(deps, ctxOf(stub));
1131
+ const on = stub.statusCalls.at(-1);
1132
+ assert.ok(on?.text?.startsWith("delegates ") === true);
1133
+ assert.ok(on?.text?.includes(DEFAULT_INSPECT_SHORTCUT) === true);
1134
+ await runDelegatesCommand(deps, ctxOf(stub));
1135
+ assert.strictEqual(stub.statusCalls.at(-1)?.text, "delegates off · /delegates");
1136
+ assert.deepStrictEqual(
1137
+ stub.statusCalls.map((call) => call.key),
1138
+ ["delegates", "delegates"],
1139
+ );
1140
+ } finally {
1141
+ await reset();
1142
+ await runtime.close();
1143
+ }
1144
+ });
1145
+
1146
+ it("a forced close writes exactly one notice", async () => {
1147
+ const stub = makeStubPi({ mode: "tui" });
1148
+ const runtime = await openRuntime();
1149
+ const fake = fakeObservations();
1150
+ const views = sequence([liveView()]);
1151
+ try {
1152
+ registerOverlay(stub, depsOf(stub, runtime, { observe: fake, view: views.read }));
1153
+ await runDelegatesCommand(
1154
+ depsOf(stub, runtime, { observe: fake, view: views.read }),
1155
+ ctxOf(stub),
1156
+ );
1157
+ fireShortcut(stub);
1158
+ await waitFor(() => stub.customCalls.length === 1, "the overlay mounted");
1159
+ const { call } = mountOverlay(stub);
1160
+ await Effect.runPromise(Effect.promise(() => runtime.close()));
1161
+
1162
+ await waitFor(() => stub.notices.length === 1, "the forced-close notice", 3_000);
1163
+ assert.strictEqual(stub.notices[0]?.severity, "warning");
1164
+ assert.ok(stub.notices[0]?.message.includes("the session closed"));
1165
+ assert.strictEqual(call.doneCalls, 1);
1166
+ assert.strictEqual(stub.widgetCalls.at(-1)?.content, undefined);
1167
+ assert.deepStrictEqual(fake.attached(), []);
1168
+ await new Promise((resolve) => setTimeout(resolve, 20));
1169
+ assert.strictEqual(stub.notices.length, 1);
1170
+ } finally {
1171
+ await reset();
1172
+ await runtime.close();
1173
+ }
1174
+ });
1175
+
1176
+ const requestNotice = (): RequestNotice => ({
1177
+ id: "request:run:1:12:c1",
1178
+ runId: "run:1",
1179
+ childRunId: "run:1",
1180
+ requestId: "12:c1",
1181
+ prompt: "x".repeat(400),
1182
+ options: [
1183
+ { label: "staging", description: null, recommended: false },
1184
+ { label: "production", description: null, recommended: false },
1185
+ ],
1186
+ allowOther: true,
1187
+ deadline: 1_000,
1188
+ });
1189
+
1190
+ it("the Pi surface posts one bounded toast and one follow-up message", () => {
1191
+ const stub = makeStubPi();
1192
+ stub.activate();
1193
+ const host = hostFor(stub.api, ctxOf(stub));
1194
+ host.notifyRequest(requestNotice());
1195
+
1196
+ assert.strictEqual(stub.notices.length, 1);
1197
+ assert.deepStrictEqual(stub.notices[0], {
1198
+ message: `request 12:c1 asks: ${"x".repeat(120)}`,
1199
+ severity: "warning",
1200
+ });
1201
+
1202
+ assert.strictEqual(stub.messages.length, 1);
1203
+ const sent = stub.messages[0]?.message as {
1204
+ readonly customType: string;
1205
+ readonly content: string;
1206
+ readonly details: unknown;
1207
+ };
1208
+ assert.strictEqual(sent.customType, "delegates.request");
1209
+ assert.deepStrictEqual(sent.details, { runId: "run:1", requestId: "12:c1" });
1210
+ assert.ok(sent.content.includes('"prompt":"'), sent.content);
1211
+ assert.ok(sent.content.includes('"questions"'), sent.content);
1212
+ assert.ok(sent.content.includes("question tool when it exists"), sent.content);
1213
+ assert.ok(sent.content.includes("Do not answer for them"), sent.content);
1214
+ assert.ok(sent.content.includes('"action":"decline"'), sent.content);
1215
+ assert.ok(!sent.content.includes('"label":"staging"' + "x"), sent.content);
1216
+ assert.deepStrictEqual(stub.messages[0]?.options, {
1217
+ deliverAs: "followUp",
1218
+ triggerTurn: true,
1219
+ });
1220
+ });
1221
+
1222
+ it("a request alert entry is read back on a reload", () => {
1223
+ const stub = makeStubPi();
1224
+ stub.activate();
1225
+ const host = hostFor(stub.api, ctxOf(stub));
1226
+ host.appendRequestAlert("request:run:1:12:c1");
1227
+
1228
+ assert.deepStrictEqual([...host.readRequestAlerts()], ["request:run:1:12:c1"]);
1229
+ });
1230
+
1231
+ it("an activation reports the read failure type when the layer fails to build", async () => {
1232
+ const stub = makeStubPi({ mode: "tui" });
1233
+ const log = recordingLog();
1234
+ const runtime = await openRuntime(log.sink);
1235
+ const fake = fakeObservations();
1236
+ const deps = depsOf(stub, runtime, {
1237
+ observe: fake,
1238
+ view: () => Promise.reject(new Error("boom")),
1239
+ });
1240
+ try {
1241
+ await runDelegatesCommand(deps, ctxOf(stub));
1242
+
1243
+ assert.deepStrictEqual(stub.entries, []);
1244
+ assert.strictEqual(stub.widgetCalls.length, 0);
1245
+ const recorded = log.entries.find((entry) => entry.code === "inspector.read_failed");
1246
+ assert.ok(recorded !== undefined, "the read failure is recorded");
1247
+ assert.strictEqual(recorded.level, "error");
1248
+ assert.strictEqual(stub.notices.length, 1);
1249
+ assert.ok(stub.notices[0]?.message.includes("failed to start: boom"));
1250
+ } finally {
1251
+ await reset();
1252
+ await runtime.close();
1253
+ }
1254
+ });
1255
+
1256
+ it("teardown detaches a sink before it interrupts the subscription when the overlay closes", async () => {
1257
+ const stub = makeStubPi({ mode: "tui" });
1258
+ const runtime = await openRuntime();
1259
+ const events: string[] = [];
1260
+ const fake = fakeObservations({ onDetach: () => events.push("scope-closed") });
1261
+ const views = sequence([liveView("first"), liveView("second")]);
1262
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
1263
+ try {
1264
+ await runDelegatesCommand(deps, ctxOf(stub));
1265
+ const repainting = { requestRender: () => events.push("detach") };
1266
+ widgetFactory(stub)(repainting, plainTheme).render(80);
1267
+ fake.push(RUN_INDEX_ADDRESS);
1268
+ await waitFor(() => views.reads() === 2, "the push published");
1269
+
1270
+ await runDelegatesCommand(deps, ctxOf(stub));
1271
+
1272
+ // Every sink detaches before the activation's scope closes its observations.
1273
+ const firstDetach = events.indexOf("detach");
1274
+ const firstClosed = events.indexOf("scope-closed");
1275
+ assert.ok(firstDetach >= 0, `the sink detached: ${JSON.stringify(events)}`);
1276
+ assert.ok(firstClosed > firstDetach, `the scope closed after: ${JSON.stringify(events)}`);
1277
+ assert.ok(events.slice(firstClosed).every((event) => event === "scope-closed"));
1278
+ const after = events.length;
1279
+ fake.push(RUN_INDEX_ADDRESS);
1280
+ await new Promise((resolve) => setTimeout(resolve, 20));
1281
+ assert.strictEqual(events.length, after, "the interrupted subscription repaints nothing");
1282
+ } finally {
1283
+ await reset();
1284
+ await runtime.close();
1285
+ }
1286
+ });
1287
+
1288
+ it("one inspector is constructed per activation when two activations run", async () => {
1289
+ const stub = makeStubPi({ mode: "tui" });
1290
+ const runtime = await openRuntime();
1291
+ const fake = fakeObservations();
1292
+ const views = sequence([liveView()]);
1293
+ let builds = 0;
1294
+ const deps = depsOf(stub, runtime, {
1295
+ observe: fake,
1296
+ view: views.read,
1297
+ onEndFiber: () => {
1298
+ builds += 1;
1299
+ },
1300
+ });
1301
+ try {
1302
+ await runDelegatesCommand(deps, ctxOf(stub));
1303
+ assert.strictEqual(builds, 1);
1304
+ await runDelegatesCommand(deps, ctxOf(stub));
1305
+ await runDelegatesCommand(deps, ctxOf(stub));
1306
+ assert.strictEqual(builds, 2, "the second activation builds its own inspector");
1307
+
1308
+ await Promise.all([
1309
+ runDelegatesCommand(deps, ctxOf(stub)),
1310
+ runDelegatesCommand(deps, ctxOf(stub)),
1311
+ ]);
1312
+ assert.strictEqual(builds, 3, "a de-duplicated double press adds no second inspector");
1313
+ } finally {
1314
+ await reset();
1315
+ await runtime.close();
1316
+ }
1317
+ });
1318
+
1319
+ it("a second activation reads the store again instead of reusing the first snapshot", async () => {
1320
+ const stub = makeStubPi({ mode: "tui" });
1321
+ const runtime = await openRuntime();
1322
+ const fake = fakeObservations();
1323
+ const views = sequence([view([]), liveView()]);
1324
+ const deps = depsOf(stub, runtime, { observe: fake, view: views.read });
1325
+ try {
1326
+ await runDelegatesCommand(deps, ctxOf(stub));
1327
+ assert.strictEqual(views.reads(), 1);
1328
+ assert.ok(
1329
+ !widgetFactory(stub)(makeStubTui(), plainTheme).render(80).join("\n").includes("deployer"),
1330
+ );
1331
+
1332
+ await runDelegatesCommand(deps, ctxOf(stub));
1333
+ await runDelegatesCommand(deps, ctxOf(stub));
1334
+
1335
+ assert.strictEqual(views.reads(), 2, "the new activation read the store again");
1336
+ assert.ok(
1337
+ widgetFactory(stub)(makeStubTui(), plainTheme).render(80).join("\n").includes("deployer"),
1338
+ );
1339
+ } finally {
1340
+ await reset();
1341
+ await runtime.close();
1342
+ }
1343
+ });