@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
@@ -1,19 +1,14 @@
1
- import { readFileSync } from "node:fs";
2
- import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
6
2
  import { assert, afterEach, it } from "@effect/vitest";
3
+ import { join, makeDir, makeTempDir, readText, writeText } from "../../test-support/platform.ts";
4
+ import { Ref } from "effect";
7
5
  import { rejects, throws } from "../../test-support/assertions.ts";
8
6
  import { GateDoc, GateIndexDoc, gateKey } from "../domain/orchestration/gates.ts";
9
7
  import { RunIndexDoc } from "../domain/run-records.ts";
10
8
  import { HostModelAdapter } from "../runtime/models.ts";
11
9
  import { waitFor } from "../../test-support/wait.ts";
12
- import {
13
- openReadOnlyRuntime,
14
- openSessionRuntime,
15
- type SessionRuntime,
16
- } from "../runtime/session.ts";
10
+ import { openReadOnlyRuntime, type SessionRuntime } from "../runtime/session.ts";
11
+
17
12
  import type { LogLevel, LogSink } from "../runtime/log.ts";
18
13
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
19
14
  import { makeStubPi } from "../../test-support/stub-pi.ts";
@@ -26,12 +21,16 @@ import { ACTIVATION_ENTRY } from "./inspector-command.ts";
26
21
  import type { SessionView } from "../domain/view.ts";
27
22
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
28
23
  import { defineAgent } from "../domain/definitions.ts";
24
+ import { CODING_EXTENSION } from "../domain/names.ts";
25
+ import { openTestSession } from "../../test-support/seams.ts";
26
+ import type { SessionHandle } from "../runtime/handle.ts";
27
+ import { handleFor } from "../../test-support/session-handle.ts";
29
28
 
30
29
  /** A scratch agent directory, so a session start never scans the developer's `~/.pi/agent`. */
31
- const tempAgentDir = (): Promise<string> => mkdtemp(join(tmpdir(), "delegates-agent-"));
30
+ const tempAgentDir = (): Promise<string> => makeTempDir("delegates-agent-");
32
31
 
33
32
  it("a first-start conflict registers only the commands", async () => {
34
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
33
+ const sessionDir = await makeTempDir("delegates-entry-");
35
34
  const stub = makeStubPi({
36
35
  sessionId: "s-1",
37
36
  sessionDir,
@@ -67,7 +66,7 @@ it("a first-start conflict registers only the commands", async () => {
67
66
  });
68
67
 
69
68
  it("a conflict that registers after the start is refused before the first turn", async () => {
70
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
69
+ const sessionDir = await makeTempDir("delegates-entry-");
71
70
  const stub = makeStubPi({
72
71
  sessionId: "s-1",
73
72
  sessionDir,
@@ -89,7 +88,7 @@ it("a conflict that registers after the start is refused before the first turn",
89
88
  });
90
89
 
91
90
  it("a later start re-filters without a second notice", async () => {
92
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
91
+ const sessionDir = await makeTempDir("delegates-entry-");
93
92
  const stub = makeStubPi({
94
93
  sessionId: "s-1",
95
94
  sessionDir,
@@ -108,7 +107,7 @@ it("a later start re-filters without a second notice", async () => {
108
107
  });
109
108
 
110
109
  it("a clear verdict after a refusal changes nothing", async () => {
111
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
110
+ const sessionDir = await makeTempDir("delegates-entry-");
112
111
  const stub = makeStubPi({
113
112
  sessionId: "s-1",
114
113
  sessionDir,
@@ -132,7 +131,7 @@ it("a clear verdict after a refusal changes nothing", async () => {
132
131
  });
133
132
 
134
133
  it("a clear session registers and opens the runtime", async () => {
135
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
134
+ const sessionDir = await makeTempDir("delegates-entry-");
136
135
  const stub = makeStubPi({
137
136
  settings: { packages: [] },
138
137
  sessionId: "s-1",
@@ -162,7 +161,7 @@ it("a clear session registers and opens the runtime", async () => {
162
161
  });
163
162
 
164
163
  it("a clear start activates the tools it registers", async () => {
165
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
164
+ const sessionDir = await makeTempDir("delegates-entry-");
166
165
  const stub = makeStubPi({
167
166
  sessionId: "s-1",
168
167
  sessionDir,
@@ -187,7 +186,7 @@ it("a clear start activates the tools it registers", async () => {
187
186
  });
188
187
 
189
188
  it("print mode gets the message on stderr", async () => {
190
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
189
+ const sessionDir = await makeTempDir("delegates-entry-");
191
190
  const stub = makeStubPi({
192
191
  sessionId: "s-1",
193
192
  sessionDir,
@@ -214,7 +213,7 @@ it("print mode gets the message on stderr", async () => {
214
213
  });
215
214
 
216
215
  it("a refusal writes one log line", async () => {
217
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
216
+ const sessionDir = await makeTempDir("delegates-entry-");
218
217
  const stub = makeStubPi({
219
218
  sessionId: "s-1",
220
219
  sessionDir,
@@ -223,7 +222,7 @@ it("a refusal writes one log line", async () => {
223
222
  createDelegatesExtension({ agentDir: await tempAgentDir() })(stub.api);
224
223
  await stub.fire("session_start", { type: "session_start", reason: "startup" });
225
224
 
226
- const entries = readFileSync(join(sessionDir, "delegates.log"), "utf8")
225
+ const entries = (await readText(join(sessionDir, "delegates.log")))
227
226
  .trim()
228
227
  .split("\n")
229
228
  .map((line) => JSON.parse(line) as { code: string; conflict?: string; removed?: string });
@@ -234,7 +233,7 @@ it("a refusal writes one log line", async () => {
234
233
  });
235
234
 
236
235
  it("a reload reports again", async () => {
237
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
236
+ const sessionDir = await makeTempDir("delegates-entry-");
238
237
  const factory = createDelegatesExtension({ agentDir: await tempAgentDir() });
239
238
  const first = makeStubPi({
240
239
  sessionId: "s-1",
@@ -257,7 +256,7 @@ it("a reload reports again", async () => {
257
256
  });
258
257
 
259
258
  it("a model or thinking-level switch updates the host", async () => {
260
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
259
+ const sessionDir = await makeTempDir("delegates-entry-");
261
260
  const stub = makeStubPi({
262
261
  settings: { packages: [] },
263
262
  sessionId: "s-1",
@@ -298,7 +297,7 @@ it("a model or thinking-level switch updates the host", async () => {
298
297
  });
299
298
 
300
299
  it("an installed but disabled pi-subagents does not block", async () => {
301
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
300
+ const sessionDir = await makeTempDir("delegates-entry-");
302
301
  const stub = makeStubPi({
303
302
  settings: { packages: ["npm:pi-subagents"] },
304
303
  commands: [{ name: "skill:pi-subagents", source: "npm:pi-subagents", kind: "skill" }],
@@ -330,7 +329,7 @@ it("the factory reads no host action while the extension loads", () => {
330
329
  });
331
330
 
332
331
  it("the first session start registers the command when clear", async () => {
333
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
332
+ const sessionDir = await makeTempDir("delegates-entry-");
334
333
  const stub = makeStubPi({
335
334
  settings: { packages: [] },
336
335
  sessionId: "s-1",
@@ -350,7 +349,7 @@ it("the first session start registers the command when clear", async () => {
350
349
  });
351
350
 
352
351
  it("the delegates command lists each agent's tools and gates", async () => {
353
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
352
+ const sessionDir = await makeTempDir("delegates-entry-");
354
353
  const stub = makeStubPi({
355
354
  settings: { packages: [] },
356
355
  sessionId: "s-1",
@@ -382,7 +381,7 @@ it("the delegates command lists each agent's tools and gates", async () => {
382
381
  });
383
382
 
384
383
  it("a reload closes the previous runtime before opening the next", async () => {
385
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
384
+ const sessionDir = await makeTempDir("delegates-entry-");
386
385
  const stub = makeStubPi({
387
386
  settings: { packages: [] },
388
387
  sessionId: "s-1",
@@ -405,7 +404,7 @@ it("a reload closes the previous runtime before opening the next", async () => {
405
404
  });
406
405
 
407
406
  it("a session registers exactly the three delegation tools", async () => {
408
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
407
+ const sessionDir = await makeTempDir("delegates-entry-");
409
408
  const stub = makeStubPi({
410
409
  settings: { packages: [] },
411
410
  sessionId: "s-1",
@@ -423,7 +422,7 @@ it("a session registers exactly the three delegation tools", async () => {
423
422
  });
424
423
 
425
424
  it("an unverified version note is logged at session start", async () => {
426
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
425
+ const sessionDir = await makeTempDir("delegates-entry-");
427
426
  const stub = makeStubPi({
428
427
  settings: { packages: [] },
429
428
  sessionId: "s-1",
@@ -436,7 +435,7 @@ it("an unverified version note is logged at session start", async () => {
436
435
  })(stub.api);
437
436
  await stub.fire("session_start", { type: "session_start", reason: "startup" });
438
437
 
439
- const lines = readFileSync(join(sessionDir, "delegates.log"), "utf8").trim().split("\n");
438
+ const lines = (await readText(join(sessionDir, "delegates.log"))).trim().split("\n");
440
439
  const entries = lines.map((line) => JSON.parse(line) as { code: string; level: string });
441
440
  const notes = entries.filter((entry) => entry.code === "version.unverified");
442
441
  assert.strictEqual(notes.length, 1);
@@ -466,7 +465,7 @@ it("the delegates command logs a viewer failure and still prints the registry",
466
465
  approval: { gates: [{ name: "deploy", tools: ["bash"] }] },
467
466
  }),
468
467
  ],
469
- runtime: () => failing,
468
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(failing)),
470
469
  log: () => sink,
471
470
  });
472
471
  const handler = stub.registrations.commandHandlers.get("delegates");
@@ -481,7 +480,7 @@ it("the delegates command logs a viewer failure and still prints the registry",
481
480
  let cleanStub: StubPi | undefined;
482
481
 
483
482
  const stubForSession = async (mode: "tui" | "rpc" = "tui"): Promise<StubPi> => {
484
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
483
+ const sessionDir = await makeTempDir("delegates-entry-");
485
484
  const stub = makeStubPi({
486
485
  settings: { packages: [] },
487
486
  sessionId: "s-1",
@@ -527,12 +526,17 @@ const liveView = (): SessionView => ({
527
526
  status: "running",
528
527
  answer: null,
529
528
  durationMs: null,
529
+ maxTurns: null,
530
+ failure: null,
530
531
  },
531
532
  ],
532
533
  missing: [],
533
534
  gates: [],
534
535
  requests: [],
535
536
  diagnostic: null,
537
+ execution: "wait",
538
+ maxTurns: null,
539
+ failure: null,
536
540
  },
537
541
  ],
538
542
  lanes: [],
@@ -563,9 +567,43 @@ it("an rpc session start restores no surfaces", async () => {
563
567
 
564
568
  assert.strictEqual(stub.widgetCalls.length, 0);
565
569
  assert.strictEqual(stub.customCalls.length, 0);
570
+ assert.strictEqual(stub.statusCalls.length, 0);
566
571
  assert.strictEqual(fake.attaches.length, 0);
567
572
  });
568
573
 
574
+ it("a session that never opted in writes no footer line", async () => {
575
+ const stub = await stubForSession();
576
+ const fake = fakeObservations();
577
+ createDelegatesExtension({ inspector: inspectorOptions(fake) })(stub.api);
578
+ await stub.fire("session_start", { type: "session_start", reason: "new" });
579
+
580
+ assert.strictEqual(stub.statusCalls.length, 0);
581
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
582
+ });
583
+
584
+ it("a resume with the inspector off names the command in the footer", async () => {
585
+ const stub = await stubForSession();
586
+ stub.entries.push(marker(false));
587
+ const fake = fakeObservations();
588
+ createDelegatesExtension({ inspector: inspectorOptions(fake) })(stub.api);
589
+ await stub.fire("session_start", { type: "session_start", reason: "resume" });
590
+
591
+ assert.strictEqual(stub.statusCalls.at(-1)?.text, "delegates off · /delegates");
592
+ assert.strictEqual(stub.widgetCalls.length, 0);
593
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
594
+ });
595
+
596
+ it("an rpc resume with the inspector off writes no footer line", async () => {
597
+ const stub = await stubForSession("rpc");
598
+ stub.entries.push(marker(false));
599
+ const fake = fakeObservations();
600
+ createDelegatesExtension({ inspector: inspectorOptions(fake) })(stub.api);
601
+ await stub.fire("session_start", { type: "session_start", reason: "resume" });
602
+
603
+ assert.strictEqual(stub.statusCalls.length, 0);
604
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
605
+ });
606
+
569
607
  it("a reload restores the strip through the session_start handler", async () => {
570
608
  const stub = await stubForSession();
571
609
  stub.entries.push(marker(true));
@@ -580,6 +618,7 @@ it("a reload restores the strip through the session_start handler", async () =>
580
618
 
581
619
  await stub.fire("session_shutdown", { type: "session_shutdown" });
582
620
  assert.strictEqual(stub.widgetCalls.at(-1)?.content, undefined);
621
+ assert.strictEqual(stub.statusCalls.at(-1)?.text, undefined);
583
622
  assert.deepStrictEqual(fake.attached(), []);
584
623
  assert.strictEqual(new Set(fake.detaches).size, fake.detaches.length);
585
624
  assert.strictEqual(stub.notices.length, 0);
@@ -706,6 +745,22 @@ it("a fork starts with no surfaces and its reload stays empty", async () => {
706
745
  await stub.fire("session_shutdown", { type: "session_shutdown" });
707
746
  });
708
747
 
748
+ it("a fork outside tui still writes the off marker the resume reads", async () => {
749
+ const stub = await stubForSession("rpc");
750
+ stub.entries.push(marker(true));
751
+ const fake = fakeObservations();
752
+ createDelegatesExtension({ inspector: inspectorOptions(fake) })(stub.api);
753
+ await stub.fire("session_start", { type: "session_start", reason: "fork" });
754
+
755
+ assert.deepStrictEqual(
756
+ markerEntries(stub).map((entry) => (entry as { data?: { active?: boolean } }).data),
757
+ [{ active: true }, { active: false }],
758
+ );
759
+ assert.strictEqual(stub.widgetCalls.length, 0);
760
+ assert.strictEqual(stub.statusCalls.length, 0);
761
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
762
+ });
763
+
709
764
  it("a branch switch follows the marker through the session_tree handler", async () => {
710
765
  const stub = await stubForSession();
711
766
  const fake = fakeObservations();
@@ -803,13 +858,15 @@ it("the notice precedes the close", async () => {
803
858
  await stub.fire("session_start", { type: "session_start", reason: "startup" });
804
859
  assert.ok(runtime !== undefined);
805
860
 
806
- // A runtime double: the real close, preceded by the notice count it observes.
807
- const original = runtime.close.bind(runtime);
808
- const doubled = runtime as { close: () => Promise<void> };
861
+ // The harness close is the graph's finalizer, preceded by the notice count it observes.
862
+ const harness = runtime.harness as {
863
+ close: (context: typeof BACKGROUND_CONTEXT) => Promise<void>;
864
+ };
865
+ const original = harness.close.bind(runtime.harness);
809
866
  let noticesAtClose = -1;
810
- doubled.close = async () => {
867
+ harness.close = async (context) => {
811
868
  noticesAtClose = stub.notices.length;
812
- await original();
869
+ await original(context);
813
870
  };
814
871
 
815
872
  stub.addTool({ name: "delegate_launch", source: "npm:pi-subagents" });
@@ -839,7 +896,7 @@ it("the inspector and the gate alerts stop", async () => {
839
896
 
840
897
  // A gate appended after the refusal must not alert: the watcher stopped with the runtime.
841
898
  const sessionDir = sessionDirOf(stub);
842
- const second = await openSessionRuntime({
899
+ const second = await openTestSession({
843
900
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
844
901
  models: new HostModelAdapter(stubHostSource()),
845
902
  });
@@ -875,18 +932,24 @@ it("a close that never settles does not block the start", async () => {
875
932
  await stub.fire("session_start", { type: "session_start", reason: "startup" });
876
933
  assert.ok(runtime !== undefined);
877
934
 
878
- const original = runtime.close.bind(runtime);
879
- const doubled = runtime as { close: () => Promise<void> };
880
- doubled.close = () => new Promise<void>(() => {});
935
+ // A close that outlives the bound: the harness close settles only when the test releases it.
936
+ const harness = runtime.harness as {
937
+ close: (context: typeof BACKGROUND_CONTEXT) => Promise<void>;
938
+ };
939
+ let release: () => void = () => {};
940
+ const hanging = new Promise<void>((resolve) => {
941
+ release = resolve;
942
+ });
943
+ harness.close = () => hanging;
881
944
 
882
945
  stub.addTool({ name: "delegate_launch", source: "npm:pi-subagents" });
883
946
  await stub.fire("session_start", { type: "session_start", reason: "reload" });
884
947
 
885
- // The handle is owed to the shutdown; restore its close so the drain terminates.
886
- doubled.close = original;
948
+ // The start was not blocked; release the close so the shutdown drain terminates.
949
+ release();
887
950
  await stub.fire("session_shutdown", { type: "session_shutdown" });
888
951
 
889
- const entries = readFileSync(join(sessionDirOf(stub), "delegates.log"), "utf8")
952
+ const entries = (await readText(join(sessionDirOf(stub), "delegates.log")))
890
953
  .trim()
891
954
  .split("\n")
892
955
  .map((line) => JSON.parse(line) as { code: string });
@@ -1062,35 +1125,35 @@ it("a close that settles after the bound is retried at shutdown", async () => {
1062
1125
  await stub.fire("session_start", { type: "session_start", reason: "startup" });
1063
1126
  assert.ok(runtime !== undefined);
1064
1127
 
1065
- // A runtime double: the close resolves only after the bound, once for each caller.
1066
- const original = runtime.close.bind(runtime);
1128
+ // The harness close resolves only after the bound; one close is awaited, never started twice.
1129
+ const harness = runtime.harness as {
1130
+ close: (context: typeof BACKGROUND_CONTEXT) => Promise<void>;
1131
+ };
1132
+ const original = harness.close.bind(runtime.harness);
1067
1133
  let closeCalls = 0;
1068
1134
  let settled = false;
1069
- const work = (async () => {
1135
+ harness.close = async (context) => {
1136
+ closeCalls += 1;
1070
1137
  await new Promise((resolve) => setTimeout(resolve, 20));
1071
1138
  settled = true;
1072
- await original();
1073
- })();
1074
- const doubled = runtime as { close: () => Promise<void> };
1075
- doubled.close = () => {
1076
- closeCalls += 1;
1077
- return work;
1139
+ await original(context);
1078
1140
  };
1079
1141
 
1080
1142
  stub.addTool({ name: "delegate_launch", source: "npm:pi-subagents" });
1081
1143
  await stub.fire("session_start", { type: "session_start", reason: "reload" });
1082
1144
  await stub.fire("session_shutdown", { type: "session_shutdown" });
1083
1145
 
1084
- assert.strictEqual(closeCalls, 2);
1146
+ // The retry re-awaits the same dispose: the drain terminates and the close ran once.
1147
+ assert.strictEqual(closeCalls, 1);
1085
1148
  assert.strictEqual(settled, true);
1086
1149
  });
1087
1150
 
1088
1151
  it("the catalogue loads Pi's configured skill paths", async () => {
1089
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-entry-"));
1152
+ const sessionDir = await makeTempDir("delegates-entry-");
1090
1153
  const agentDir = await tempAgentDir();
1091
- const extraDir = await mkdtemp(join(tmpdir(), "delegates-skills-"));
1092
- await mkdir(join(extraDir, "gamma"), { recursive: true });
1093
- await writeFile(
1154
+ const extraDir = await makeTempDir("delegates-skills-");
1155
+ await makeDir(join(extraDir, "gamma"));
1156
+ await writeText(
1094
1157
  join(extraDir, "gamma", "SKILL.md"),
1095
1158
  "---\nname: gamma\ndescription: The gamma skill\n---\n\nGAMMA_BODY\n",
1096
1159
  );
@@ -1116,3 +1179,98 @@ it("the catalogue loads Pi's configured skill paths", async () => {
1116
1179
  await stub.fire("session_shutdown", { type: "session_shutdown" });
1117
1180
  }
1118
1181
  });
1182
+
1183
+ it("a close that outlives its bound still closes once when the shutdown drains it", async () => {
1184
+ const stub = await stubForSession();
1185
+ let runtime: SessionRuntime | undefined;
1186
+ createDelegatesExtension({
1187
+ agentDir: await tempAgentDir(),
1188
+ revocationCloseMs: 5,
1189
+ onRuntime: (current) => {
1190
+ if (current !== undefined) runtime = current;
1191
+ },
1192
+ })(stub.api);
1193
+ await stub.fire("session_start", { type: "session_start", reason: "startup" });
1194
+ assert.ok(runtime !== undefined);
1195
+
1196
+ // The harness close outlives the bound; the shutdown drain awaits it exactly once.
1197
+ const harness = runtime.harness as {
1198
+ close: (context: typeof BACKGROUND_CONTEXT) => Promise<void>;
1199
+ };
1200
+ const original = harness.close.bind(runtime.harness);
1201
+ let closes = 0;
1202
+ harness.close = async (context) => {
1203
+ closes += 1;
1204
+ await new Promise((resolve) => setTimeout(resolve, 20));
1205
+ await original(context);
1206
+ };
1207
+
1208
+ stub.addTool({ name: "delegate_launch", source: "npm:pi-subagents" });
1209
+ await stub.fire("session_start", { type: "session_start", reason: "reload" });
1210
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
1211
+
1212
+ assert.strictEqual(closes, 1);
1213
+ const entries = (await readText(join(sessionDirOf(stub), "delegates.log")))
1214
+ .trim()
1215
+ .split("\n")
1216
+ .map((line) => JSON.parse(line) as { code: string });
1217
+ assert.strictEqual(
1218
+ entries.filter((entry) => entry.code === "revocation.close_timeout").length,
1219
+ 1,
1220
+ JSON.stringify(entries),
1221
+ );
1222
+ });
1223
+
1224
+ it("a reload swap serves the new runtime when the next tool call runs", async () => {
1225
+ const sessionDir = await makeTempDir("delegates-entry-");
1226
+ const stub = makeStubPi({
1227
+ settings: { packages: [] },
1228
+ sessionId: "s-1",
1229
+ sessionDir,
1230
+ modelRegistry: stubHostSource({ text: "served" }),
1231
+ });
1232
+ const runtimes: SessionRuntime[] = [];
1233
+ createDelegatesExtension({
1234
+ agentDir: await tempAgentDir(),
1235
+ definitions: [
1236
+ defineAgent({
1237
+ name: "scout",
1238
+ role: "Scout",
1239
+ prompt: { role: "You look around." },
1240
+ tools: ["bash"],
1241
+ extensions: [CODING_EXTENSION],
1242
+ approval: { gates: [] },
1243
+ model: { provider: "stub", modelId: "stub-1" },
1244
+ }),
1245
+ ],
1246
+ onRuntime: (current) => {
1247
+ if (current !== undefined) runtimes.push(current);
1248
+ },
1249
+ })(stub.api);
1250
+ await stub.fire("session_start", { type: "session_start", reason: "startup" });
1251
+ await stub.fire("session_start", { type: "session_start", reason: "reload" });
1252
+ assert.strictEqual(runtimes.length, 2);
1253
+
1254
+ const tool = stub.registrations.toolDefinitions.get("delegate_launch") as {
1255
+ execute: (
1256
+ id: string,
1257
+ params: unknown,
1258
+ signal: undefined,
1259
+ onUpdate: undefined,
1260
+ ctx: unknown,
1261
+ ) => Promise<{ readonly content: readonly { readonly text: string }[] }>;
1262
+ };
1263
+ const result = await tool.execute(
1264
+ "",
1265
+ { request: { kind: "single", agent: "scout", task: "look" } },
1266
+ undefined,
1267
+ undefined,
1268
+ stub.context,
1269
+ );
1270
+
1271
+ assert.strictEqual(result.content[0]?.text, "served");
1272
+ assert.strictEqual(runtimes[0]?.state.kind, "closed");
1273
+ const index = await runtimes[1]?.snapshot(RunIndexDoc);
1274
+ assert.strictEqual(index?.runIds.length, 1, JSON.stringify(index));
1275
+ await stub.fire("session_shutdown", { type: "session_shutdown" });
1276
+ });