@ftrdotdev/pi-delegates 0.1.0 → 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 (94) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/OPERATIONS.md +79 -6
  3. package/README.md +25 -17
  4. package/ROADMAP.md +21 -0
  5. package/TESTING.md +153 -318
  6. package/package.json +4 -3
  7. package/skills/pi-delegates/SKILL.md +29 -0
  8. package/skills/pi-delegates/references/launch.md +28 -0
  9. package/src/docs-contract.test.ts +106 -0
  10. package/src/domain/definitions.ts +3 -1
  11. package/src/domain/failure.ts +33 -0
  12. package/src/domain/model-source.ts +30 -0
  13. package/src/domain/orchestration/control.test.ts +69 -35
  14. package/src/domain/orchestration/control.ts +110 -89
  15. package/src/domain/orchestration/fanout.test.ts +125 -20
  16. package/src/domain/orchestration/fanout.ts +60 -22
  17. package/src/domain/orchestration/gates.test.ts +14 -15
  18. package/src/domain/orchestration/launch.test.ts +210 -11
  19. package/src/domain/orchestration/launch.ts +142 -32
  20. package/src/domain/orchestration/requests.test.ts +11 -16
  21. package/src/domain/orchestration/requests.ts +14 -1
  22. package/src/domain/orchestration/review.test.ts +89 -11
  23. package/src/domain/orchestration/run-wait.test.ts +4 -1
  24. package/src/domain/orchestration/run-wait.ts +1 -1
  25. package/src/domain/orchestration/workflow.test.ts +157 -16
  26. package/src/domain/orchestration/workflow.ts +269 -196
  27. package/src/domain/run-records.ts +214 -52
  28. package/src/domain/settlement.test.ts +186 -0
  29. package/src/domain/settlement.ts +137 -0
  30. package/src/domain/shapes.test.ts +20 -0
  31. package/src/domain/skills.test.ts +31 -20
  32. package/src/domain/skills.ts +36 -19
  33. package/src/domain/toolkit.test.ts +15 -1
  34. package/src/domain/toolkit.ts +8 -13
  35. package/src/domain/turn-budget.test.ts +37 -0
  36. package/src/domain/turn-budget.ts +23 -0
  37. package/src/domain/view.test.ts +78 -14
  38. package/src/domain/view.ts +67 -35
  39. package/src/extension/commands.test.ts +27 -23
  40. package/src/extension/commands.ts +10 -7
  41. package/src/extension/entry.test.ts +214 -56
  42. package/src/extension/entry.ts +78 -40
  43. package/src/extension/gate-alerts.test.ts +10 -8
  44. package/src/extension/inspector-command.test.ts +173 -21
  45. package/src/extension/inspector-command.ts +100 -53
  46. package/src/extension/prompt.test.ts +2 -4
  47. package/src/extension/retry-observer.test.ts +292 -0
  48. package/src/extension/retry-observer.ts +150 -0
  49. package/src/extension/settle-alerts.test.ts +579 -0
  50. package/src/extension/settle-alerts.ts +175 -0
  51. package/src/extension/shortcut.test.ts +6 -8
  52. package/src/extension/tools.test.ts +325 -24
  53. package/src/extension/tools.ts +61 -13
  54. package/src/extension/version.test.ts +21 -29
  55. package/src/goldens.test.ts +294 -0
  56. package/src/harness-policy.test.ts +13 -11
  57. package/src/layers.test.ts +309 -0
  58. package/src/layers.ts +405 -0
  59. package/src/package-manifest.test.ts +32 -19
  60. package/src/presentation/actions.test.ts +8 -8
  61. package/src/presentation/activity.test.ts +7 -8
  62. package/src/presentation/close.test.ts +14 -16
  63. package/src/presentation/inspector.test.ts +14 -11
  64. package/src/presentation/inspector.ts +27 -25
  65. package/src/presentation/overlay.test.ts +1 -3
  66. package/src/presentation/repaint.test.ts +226 -190
  67. package/src/presentation/snapshot.test.ts +5 -0
  68. package/src/presentation/status.test.ts +43 -0
  69. package/src/presentation/status.ts +30 -0
  70. package/src/presentation/strip.test.ts +13 -6
  71. package/src/presentation/strip.ts +7 -14
  72. package/src/presentation/wording.test.ts +153 -3
  73. package/src/presentation/wording.ts +78 -6
  74. package/src/runtime/bridge.ts +38 -44
  75. package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
  76. package/src/runtime/clock.ts +31 -0
  77. package/src/runtime/config.test.ts +26 -7
  78. package/src/runtime/config.ts +6 -1
  79. package/src/runtime/execution-env.test.ts +6 -8
  80. package/src/runtime/extensions.test.ts +4 -4
  81. package/src/runtime/extensions.ts +23 -11
  82. package/src/runtime/handle.ts +54 -0
  83. package/src/runtime/log.test.ts +19 -7
  84. package/src/runtime/log.ts +23 -0
  85. package/src/runtime/mcp.test.ts +29 -32
  86. package/src/runtime/mcp.ts +70 -3
  87. package/src/runtime/runtime-state.test.ts +25 -0
  88. package/src/runtime/runtime-state.ts +36 -0
  89. package/src/runtime/session-tag.ts +11 -0
  90. package/src/runtime/session.test.ts +24 -31
  91. package/src/runtime/session.ts +99 -261
  92. package/src/runtime/storage.ts +29 -0
  93. package/src/test-hygiene.test.ts +97 -0
  94. package/src/runtime/timers.ts +0 -10
@@ -3,20 +3,21 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
3
  import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { createCatalogue, type AgentDefinition } from "../domain/definitions.ts";
6
+ import { Ref } from "effect";
6
7
  import { viewSession, type SessionView } from "../domain/view.ts";
7
8
  import { fileLogSink, errorFields, nullLogSink, type LogSink } from "../runtime/log.ts";
8
9
  import { HostModelAdapter } from "../runtime/models.ts";
9
- import {
10
- openReadOnlyRuntime,
11
- openSessionRuntime,
12
- storePathFor,
13
- type SessionRuntime,
14
- } from "../runtime/session.ts";
10
+ import { openReadOnlyRuntime, storePathFor, type SessionRuntime } from "../runtime/session.ts";
11
+ import { makeSessionSeams, openSessionRuntime, type SessionConfig } from "../layers.ts";
12
+ import type { SessionHandle } from "../runtime/handle.ts";
15
13
  import { DEFAULTS } from "../runtime/config.ts";
16
14
  import { registerDelegatesCommand } from "./commands.ts";
17
15
  import { coexistenceVerdict } from "./guard.ts";
18
16
  import { startGateAlerts, type GateAlertWatch } from "./gate-alerts.ts";
19
17
  import { requestHostFor, startRequestAlerts, type RequestAlertWatch } from "./request-alerts.ts";
18
+ import { startRetryObserver, type RetryObserverWatch } from "./retry-observer.ts";
19
+ import { settleHostFor, startSettleAlerts, type SettleAlertWatch } from "./settle-alerts.ts";
20
+ import { recordAnnouncement } from "../domain/run-records.ts";
20
21
  import {
21
22
  ensureInspector,
22
23
  hostFor,
@@ -98,17 +99,21 @@ export const createDelegatesExtension =
98
99
  };
99
100
  let currentHost: HostDefaults = fallbackHost;
100
101
  const inspectorShortcut = resolveInspectShortcut(options.inspectorShortcut);
101
- let runtime: SessionRuntime | undefined;
102
+ let handle: SessionHandle | undefined;
103
+ /** One source for the current handle: the entry fills it as a session opens. */
104
+ const current = Ref.makeUnsafe<SessionHandle | undefined>(undefined);
102
105
  let gateAlerts: GateAlertWatch | undefined;
103
106
  let requestAlerts: RequestAlertWatch | undefined;
107
+ let retryObserver: RetryObserverWatch | undefined;
108
+ let settleAlerts: SettleAlertWatch | undefined;
104
109
  const state: RevocationState = {};
105
110
  let surface: "none" | "commands" | "full" = "none";
106
111
  /** Runtimes whose close outlived the bound; `session_shutdown` drains them. */
107
- const closing: SessionRuntime[] = [];
112
+ const closing: SessionHandle[] = [];
108
113
 
109
114
  const inspectorDeps = (): InspectorCommandDeps => ({
110
- runtime: () => runtime,
111
- host: (ctx) => hostFor(pi, ctx, () => runtime?.log ?? nullLogSink),
115
+ session: current,
116
+ host: (ctx) => hostFor(pi, ctx, () => handle?.runtime.log ?? nullLogSink),
112
117
  shortcut: inspectorShortcut,
113
118
  ...(options.inspector === undefined ? {} : { inspector: options.inspector }),
114
119
  });
@@ -125,6 +130,18 @@ export const createDelegatesExtension =
125
130
  await current?.close();
126
131
  };
127
132
 
133
+ const stopRetryObserver = async (): Promise<void> => {
134
+ const current = retryObserver;
135
+ retryObserver = undefined;
136
+ await current?.close();
137
+ };
138
+
139
+ const stopSettleAlerts = async (): Promise<void> => {
140
+ const current = settleAlerts;
141
+ settleAlerts = undefined;
142
+ await current?.close();
143
+ };
144
+
128
145
  const logFor = (ctx: ExtensionContext): LogSink =>
129
146
  fileLogSink(join(ctx.sessionManager.getSessionDir(), "delegates.log"));
130
147
 
@@ -165,8 +182,8 @@ export const createDelegatesExtension =
165
182
 
166
183
  registerDelegatesCommand(pi, {
167
184
  definitions: catalogue.all,
168
- runtime: () => runtime,
169
- log: () => runtime?.log ?? nullLogSink,
185
+ session: current,
186
+ log: () => handle?.runtime.log ?? nullLogSink,
170
187
  inspector: (ctx) => runDelegatesCommand(inspectorDeps(), ctx),
171
188
  revoked: () => state.verdict,
172
189
  reader: readStore,
@@ -178,16 +195,12 @@ export const createDelegatesExtension =
178
195
  });
179
196
 
180
197
  registerDelegateTools(pi, {
181
- runtime: () => {
182
- if (runtime === undefined) {
183
- throw new Error("The delegation runtime is not ready; start a session first.");
184
- }
185
- return runtime;
186
- },
198
+ session: current,
187
199
  catalogue,
188
200
  host: { model: { provider: "", modelId: "" }, thinkingLevel: "low" },
189
- launchWaitMs: () => runtime?.config.launchWaitMs ?? DEFAULTS.launchWaitMs,
190
- log: () => runtime?.log ?? nullLogSink,
201
+ launchWaitMs: () =>
202
+ Ref.getUnsafe(current)?.runtime.config.launchWaitMs ?? DEFAULTS.launchWaitMs,
203
+ log: () => Ref.getUnsafe(current)?.runtime.log ?? nullLogSink,
191
204
  onRunCreated: (ctx) => ensureInspector(inspectorDeps(), ctx),
192
205
  });
193
206
  };
@@ -210,9 +223,11 @@ export const createDelegatesExtension =
210
223
  }
211
224
  await stopGateAlerts();
212
225
  await stopRequestAlerts();
226
+ await stopRetryObserver();
227
+ await stopSettleAlerts();
213
228
  await teardownInspector({ markOff: false });
214
- const previous = runtime;
215
- runtime = undefined;
229
+ const previous = handle;
230
+ handle = undefined;
216
231
  if (previous === undefined) return;
217
232
  options.onRuntime?.(undefined);
218
233
  await closeWithin(
@@ -249,11 +264,13 @@ export const createDelegatesExtension =
249
264
  // must tear the previous activation down before its runtime closes.
250
265
  await stopGateAlerts();
251
266
  await stopRequestAlerts();
267
+ await stopRetryObserver();
268
+ await stopSettleAlerts();
252
269
  await teardownInspector({ markOff: false });
253
270
  currentHost = hostFrom(ctx, fallbackHost);
254
- const previous = runtime;
271
+ const previous = handle;
255
272
  if (previous !== undefined) {
256
- runtime = undefined;
273
+ handle = undefined;
257
274
  options.onRuntime?.(undefined);
258
275
  await previous.close();
259
276
  }
@@ -263,7 +280,7 @@ export const createDelegatesExtension =
263
280
  detail: "The pi-ai version could not be read; the identity check did not run.",
264
281
  });
265
282
  }
266
- runtime = await openSessionRuntime({
283
+ const config: SessionConfig = {
267
284
  identity: {
268
285
  sessionId: ctx.sessionManager.getSessionId(),
269
286
  sessionDir: ctx.sessionManager.getSessionDir(),
@@ -273,17 +290,13 @@ export const createDelegatesExtension =
273
290
  models: new HostModelAdapter(ctx.modelRegistry),
274
291
  catalogue,
275
292
  host: () => currentHost,
276
- log,
277
293
  projectTrusted: ctx.isProjectTrusted(),
278
294
  notify: (message) => ctx.ui.notify(message, "warning"),
279
- skills: {
280
- cwd: ctx.cwd,
281
- agentDir: options.agentDir ?? getAgentDir(),
282
- skillPaths: pi.getSettings().skills ?? [],
283
- },
284
- });
285
- options.onRuntime?.(runtime);
286
- const failures = runtime.mcp.failures;
295
+ skillsRoots: pi.getSettings().skills ?? [],
296
+ };
297
+ handle = await openSessionRuntime(config, current, makeSessionSeams(config, { log }));
298
+ options.onRuntime?.(handle.runtime);
299
+ const failures = handle.runtime.mcp.failures;
287
300
  if (failures.length > 0) {
288
301
  ctx.ui.notify(
289
302
  `MCP servers are not connected: ${failures.map((failure) => failure.server).join(", ")}. ` +
@@ -293,22 +306,45 @@ export const createDelegatesExtension =
293
306
  }
294
307
  try {
295
308
  gateAlerts = startGateAlerts({
296
- runtime,
309
+ runtime: handle.runtime,
297
310
  host: inspectorDeps().host(ctx),
298
311
  shortcut: inspectorShortcut,
299
312
  });
300
313
  } catch (error) {
301
- runtime.log.write("warn", "inspector.gate_alert_failed", {
314
+ handle.runtime.log.write("warn", "inspector.gate_alert_failed", {
302
315
  detail: error instanceof Error ? error.message : String(error),
303
316
  });
304
317
  }
305
318
  try {
306
319
  requestAlerts = startRequestAlerts({
320
+ runtime: handle.runtime,
321
+ host: requestHostFor(ctx.mode, inspectorDeps().host(ctx), handle.runtime.log),
322
+ });
323
+ } catch (error) {
324
+ handle.runtime.log.write("warn", "inspector.request_alert_failed", {
325
+ detail: error instanceof Error ? error.message : String(error),
326
+ });
327
+ }
328
+ try {
329
+ retryObserver = startRetryObserver({
330
+ runtime: handle.runtime,
331
+ log: handle.runtime.log,
332
+ });
333
+ } catch (error) {
334
+ handle.runtime.log.write("warn", "retry.observer_failed", {
335
+ detail: error instanceof Error ? error.message : String(error),
336
+ });
337
+ }
338
+ const runtime = handle.runtime;
339
+ try {
340
+ settleAlerts = startSettleAlerts({
307
341
  runtime,
308
- host: requestHostFor(ctx.mode, inspectorDeps().host(ctx), runtime.log),
342
+ host: settleHostFor(ctx.mode, inspectorDeps().host(ctx), runtime.log),
343
+ announce: (runId, taskId) => recordAnnouncement(runtime, runId, taskId),
344
+ log: runtime.log,
309
345
  });
310
346
  } catch (error) {
311
- runtime.log.write("warn", "inspector.request_alert_failed", {
347
+ runtime.log.write("warn", "inspector.settle_alert_failed", {
312
348
  detail: error instanceof Error ? error.message : String(error),
313
349
  });
314
350
  }
@@ -332,9 +368,11 @@ export const createDelegatesExtension =
332
368
  pi.on("session_shutdown", async () => {
333
369
  await stopGateAlerts();
334
370
  await stopRequestAlerts();
371
+ await stopRetryObserver();
372
+ await stopSettleAlerts();
335
373
  await teardownInspector({ markOff: false });
336
- await runtime?.close();
337
- runtime = undefined;
374
+ await handle?.close();
375
+ handle = undefined;
338
376
  options.onRuntime?.(undefined);
339
377
  // A close that settled after the bound was never retried by `closeWithin`.
340
378
  for (const overdue of closing.splice(0)) await overdue.close();
@@ -1,13 +1,13 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
3
3
  import { MemoryStorage } from "@earendil-works/pi-durable";
4
- import { mkdtemp } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
4
  import { assert, it } from "@effect/vitest";
5
+ import { makeTempDir } from "../../test-support/platform.ts";
6
+ import { Ref } from "effect";
8
7
  import { GateDoc, GateIndexDoc, gateKey } from "../domain/orchestration/gates.ts";
9
8
  import { HostModelAdapter } from "../runtime/models.ts";
10
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
9
+ import { type SessionRuntime } from "../runtime/session.ts";
10
+
11
11
  import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
12
12
  import { makeStubPi, type StubPi } from "../../test-support/stub-pi.ts";
13
13
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
@@ -23,10 +23,12 @@ import type { InspectorCommandDeps } from "./inspector-command.ts";
23
23
  import { startGateAlerts } from "./gate-alerts.ts";
24
24
  import { fakeObservations } from "../../test-support/fake-observations.ts";
25
25
  import { inspectorClock } from "../../test-support/inspector-clock.ts";
26
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
27
+ import type { SessionHandle } from "../runtime/handle.ts";
26
28
 
27
- const openRuntime = async (log?: LogSink): Promise<SessionRuntime> => {
28
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-gate-alerts-"));
29
- return openSessionRuntime({
29
+ const openRuntime = async (log?: LogSink): Promise<TestSession> => {
30
+ const sessionDir = await makeTempDir("delegates-gate-alerts-");
31
+ return openTestSession({
30
32
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
31
33
  models: new HostModelAdapter(stubHostSource()),
32
34
  storage: new MemoryStorage(),
@@ -167,7 +169,7 @@ it("the active inspector does not duplicate the watcher's alert", async () => {
167
169
  await seedEmptyIndex(runtime);
168
170
  const fake = fakeObservations();
169
171
  const deps: InspectorCommandDeps = {
170
- runtime: () => runtime,
172
+ session: Ref.makeUnsafe<SessionHandle | undefined>(runtime.handle),
171
173
  host: (ctx) => hostFor(stub.api, ctx, () => runtime.log),
172
174
  shortcut: "ctrl+space",
173
175
  inspector: {
@@ -2,11 +2,9 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
3
3
  import type { Theme } from "@earendil-works/pi-coding-agent";
4
4
  import { MemoryStorage } from "@earendil-works/pi-durable";
5
- import { Effect } from "effect";
6
- import { mkdtemp } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
5
+ import { Effect, Ref } from "effect";
9
6
  import { assert, beforeEach, it } from "@effect/vitest";
7
+ import { makeTempDir } from "../../test-support/platform.ts";
10
8
  import { fakeObservations } from "../../test-support/fake-observations.ts";
11
9
  import { inspectorClock } from "../../test-support/inspector-clock.ts";
12
10
  import { makeStubPi, type StubPi } from "../../test-support/stub-pi.ts";
@@ -31,7 +29,8 @@ import {
31
29
  } from "../presentation/inspector.ts";
32
30
  import { STRIP_KEY, STRIP_PLACEMENT } from "../presentation/strip.ts";
33
31
  import { HostModelAdapter } from "../runtime/models.ts";
34
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
32
+ import { type SessionRuntime } from "../runtime/session.ts";
33
+
35
34
  import {
36
35
  ACTIVATION_ENTRY,
37
36
  ensureInspector,
@@ -45,6 +44,8 @@ import {
45
44
  import { OVERLAY_OPTIONS } from "../presentation/overlay.ts";
46
45
  import type { RequestNotice } from "../presentation/wording.ts";
47
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";
48
49
 
49
50
  const plainTheme = {
50
51
  fg: (_color: string, text: string): string => text,
@@ -69,9 +70,9 @@ const deployer = defineAgent({
69
70
 
70
71
  const gatedCatalogue = createCatalogue([deployer]);
71
72
 
72
- const openRuntime = async (log?: LogSink): Promise<SessionRuntime> => {
73
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-inspector-command-"));
74
- return openSessionRuntime({
73
+ const openRuntime = async (log?: LogSink): Promise<TestSession> => {
74
+ const sessionDir = await makeTempDir("delegates-inspector-command-");
75
+ return openTestSession({
75
76
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
76
77
  models: new HostModelAdapter(stubHostSource()),
77
78
  storage: new MemoryStorage(),
@@ -109,6 +110,9 @@ const runView = (
109
110
  gates: [],
110
111
  requests: [],
111
112
  diagnostic: null,
113
+ execution: "wait",
114
+ maxTurns: null,
115
+ failure: null,
112
116
  ...input,
113
117
  });
114
118
 
@@ -121,6 +125,8 @@ const childView = (
121
125
  status: "running",
122
126
  answer: null,
123
127
  durationMs: null,
128
+ maxTurns: null,
129
+ failure: null,
124
130
  ...input,
125
131
  });
126
132
 
@@ -187,19 +193,21 @@ const ctxOf = (stub: StubPi): ExtensionContext => stub.context as ExtensionConte
187
193
 
188
194
  const depsOf = (
189
195
  stub: StubPi,
190
- runtime: SessionRuntime,
196
+ runtime: TestSession,
191
197
  options: {
192
198
  readonly observe?: ReturnType<typeof fakeObservations>;
193
199
  readonly view?: () => Promise<SessionView>;
194
200
  readonly shortcut?: string;
201
+ readonly onEndFiber?: () => void;
195
202
  } = {},
196
203
  ): InspectorCommandDeps => ({
197
- runtime: () => runtime,
204
+ session: Ref.makeUnsafe<SessionHandle | undefined>(runtime.handle),
198
205
  host: (ctx) => hostFor(stub.api, ctx),
199
206
  ...(options.shortcut === undefined ? {} : { shortcut: options.shortcut }),
200
207
  inspector: {
201
208
  ...(options.observe === undefined ? {} : { observe: options.observe }),
202
209
  ...(options.view === undefined ? {} : { view: options.view }),
210
+ ...(options.onEndFiber === undefined ? {} : { onEndFiber: () => options.onEndFiber?.() }),
203
211
  now: () => 4_000,
204
212
  timers: inspectorClock(),
205
213
  },
@@ -243,7 +251,7 @@ beforeEach(async () => {
243
251
  await reset();
244
252
  });
245
253
 
246
- it("activation builds one layer, writes one marker and registers one widget", async () => {
254
+ it("activation resolves one inspector, writes one marker and registers one widget", async () => {
247
255
  const stub = makeStubPi({ mode: "tui" });
248
256
  const runtime = await openRuntime();
249
257
  const fake = fakeObservations();
@@ -371,7 +379,7 @@ it("a second press deactivates everything once", async () => {
371
379
  }
372
380
  });
373
381
 
374
- it("two presses before the first activation settles build one layer and end off", async () => {
382
+ it("two presses before the first activation settles resolve one inspector and end off", async () => {
375
383
  const stub = makeStubPi({ mode: "tui" });
376
384
  const runtime = await openRuntime();
377
385
  const fake = fakeObservations();
@@ -467,25 +475,29 @@ it("an activation whose last marker is already true appends nothing", async () =
467
475
  }
468
476
  });
469
477
 
470
- it("a strip that hides comes back on the next live push", async () => {
478
+ it("the strip mounts once at activation and follows a live push", async () => {
471
479
  const stub = makeStubPi({ mode: "tui" });
472
480
  const runtime = await openRuntime();
473
481
  const fake = fakeObservations();
474
- const views = sequence([answeredView(), liveView(), answeredView()]);
482
+ const views = sequence([answeredView(), liveView()]);
475
483
  try {
476
484
  await runDelegatesCommand(
477
485
  depsOf(stub, runtime, { observe: fake, view: views.read }),
478
486
  ctxOf(stub),
479
487
  );
480
- assert.strictEqual(stub.widgetCalls.length, 0);
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");
481
491
 
482
492
  fake.push(RUN_INDEX_ADDRESS);
483
- await waitFor(() => stub.widgetCalls.length === 1, "the live push registered the strip");
484
- assert.strictEqual(typeof stub.widgetCalls[0]?.content, "function");
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");
485
496
 
497
+ // Same snapshot again: the footer already reads this, so nothing is written.
486
498
  fake.push(RUN_INDEX_ADDRESS);
487
- await waitFor(() => stub.widgetCalls.length === 2, "the terminal push hid the strip");
488
- assert.strictEqual(stub.widgetCalls[1]?.content, undefined);
499
+ await new Promise((resolve) => setTimeout(resolve, 60));
500
+ assert.strictEqual(stub.statusCalls.length, 2, "an unchanged publication writes no line");
489
501
  } finally {
490
502
  await reset();
491
503
  await runtime.close();
@@ -500,7 +512,7 @@ it("the command prints today's listing outside tui mode and touches nothing", as
500
512
  await seedListing(runtime);
501
513
  registerDelegatesCommand(stub.api, {
502
514
  definitions: createCatalogue().all,
503
- runtime: () => runtime,
515
+ session: Ref.makeUnsafe<SessionHandle | undefined>(runtime.handle),
504
516
  log: () => runtime.log,
505
517
  inspector: async () => {
506
518
  inspectorCalls += 1;
@@ -654,7 +666,7 @@ const fireOverlayCommand = (stub: StubPi): void => {
654
666
  void handler("", ctxOf(stub));
655
667
  };
656
668
 
657
- it("the shortcut is inert before activation", async () => {
669
+ it("the shortcut refuses before activation", async () => {
658
670
  const stub = makeStubPi({ mode: "tui" });
659
671
  const runtime = await openRuntime();
660
672
  const fake = fakeObservations();
@@ -667,6 +679,9 @@ it("the shortcut is inert before activation", async () => {
667
679
  assert.strictEqual(stub.widgetCalls.length, 0);
668
680
  assert.strictEqual(stub.entries.length, 0);
669
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
+ ]);
670
685
  } finally {
671
686
  await reset();
672
687
  await runtime.close();
@@ -1105,6 +1120,29 @@ it("three toggles append three markers", async () => {
1105
1120
  }
1106
1121
  });
1107
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
+
1108
1146
  it("a forced close writes exactly one notice", async () => {
1109
1147
  const stub = makeStubPi({ mode: "tui" });
1110
1148
  const runtime = await openRuntime();
@@ -1189,3 +1227,117 @@ it("a request alert entry is read back on a reload", () => {
1189
1227
 
1190
1228
  assert.deepStrictEqual([...host.readRequestAlerts()], ["request:run:1:12:c1"]);
1191
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
+ });