@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,4 +1,4 @@
1
- import { Option, Predicate, Result, Schema } from "effect";
1
+ import { Match, Option, Predicate, Result, Schema } from "effect";
2
2
  import type { SessionRuntime } from "../../runtime/session.ts";
3
3
  import { RunDoc, RunInputSchema, type RunInput } from "../run-records.ts";
4
4
  import { FanoutInputSchema, type FanoutInput } from "./fanout.ts";
@@ -239,13 +239,21 @@ export const decodeStoredInput = <A>(
239
239
  return decoded.value;
240
240
  };
241
241
 
242
+ /** The seven action literals, narrowed, so each branch receives only its own fields. */
243
+ type SteerRequest = Extract<ControlRequest, { readonly action: "steer" }>;
244
+ type StopRequest = Extract<ControlRequest, { readonly action: "stop" }>;
245
+ type GateRequest = Extract<ControlRequest, { readonly action: "approve" | "deny" }>;
246
+ type AnswerRequest = Extract<ControlRequest, { readonly action: "answer" }>;
247
+ type DeclineRequest = Extract<ControlRequest, { readonly action: "decline" }>;
248
+ type ResumeRequest = Extract<ControlRequest, { readonly action: "resume" }>;
249
+
242
250
  export const control = async (input: unknown, deps: ControlDeps): Promise<ControlResult> => {
243
- const request = decodeControl(input);
251
+ const decoded = decodeControl(input);
244
252
  const { runtime } = deps;
245
- const { doc, task } = await load(request, runtime);
253
+ const { doc, task } = await load(decoded, runtime);
246
254
  const status = statusOf(task);
247
255
 
248
- if (request.action === "steer") {
256
+ const steerBranch = async (request: SteerRequest): Promise<ControlResult> => {
249
257
  const missing = await missingFor(request.run, runtime);
250
258
  if (missing.missing.length > 0) {
251
259
  await recordMissing(request.run, doc, missing.missing, runtime);
@@ -276,9 +284,9 @@ export const control = async (input: unknown, deps: ControlDeps): Promise<Contro
276
284
  conversation.submit({ type: "input", content: request.message, whenBusy: "steer" }, context),
277
285
  );
278
286
  return resultOf(request.run, deps);
279
- }
287
+ };
280
288
 
281
- if (request.action === "stop") {
289
+ const stopBranch = async (request: StopRequest): Promise<ControlResult> => {
282
290
  if (doc.taskId !== null) {
283
291
  const ownTask = taskId(doc.taskId);
284
292
  await runtime.run((context) => runtime.harness.abortTask(ownTask, context));
@@ -288,9 +296,9 @@ export const control = async (input: unknown, deps: ControlDeps): Promise<Contro
288
296
  await cancelRequests(request.run, runtime);
289
297
  if (doc.taskId !== null) await awaitSettled(request.run, doc.taskId, deps);
290
298
  return resultOf(request.run, deps);
291
- }
299
+ };
292
300
 
293
- if (request.action === "approve" || request.action === "deny") {
301
+ const gateBranch = async (request: GateRequest): Promise<ControlResult> => {
294
302
  const decided = await decideGate(
295
303
  {
296
304
  run: request.run,
@@ -309,9 +317,9 @@ export const control = async (input: unknown, deps: ControlDeps): Promise<Contro
309
317
  deliveredTaskIds: decided.deliveredTaskIds,
310
318
  endedTaskIds: decided.endedTaskIds,
311
319
  });
312
- }
320
+ };
313
321
 
314
- if (request.action === "answer") {
322
+ const answerBranch = async (request: AnswerRequest): Promise<ControlResult> => {
315
323
  const decided = await answerRequest(
316
324
  {
317
325
  run: request.run,
@@ -341,96 +349,109 @@ export const control = async (input: unknown, deps: ControlDeps): Promise<Contro
341
349
  if (outcome !== "settled") runtime.log.write("info", `wait.${outcome}`, { runId: request.run });
342
350
  const view = await viewRun(request.run, runtime);
343
351
  return { view, text: answerText(request.run, view.status, view.requests) };
344
- }
352
+ };
345
353
 
346
- if (request.action === "decline") {
354
+ const declineBranch = async (request: DeclineRequest): Promise<ControlResult> => {
347
355
  await declineRequest(
348
356
  { run: request.run, request: request.request, sessionId: runtime.sessionId },
349
357
  runtime,
350
358
  );
351
359
  return { text: `decline ${request.run}: cancelled` };
352
- }
353
-
354
- if (doc.mode === "workflow") {
355
- throw RunNotResumable.make({
356
- message:
357
- `Run ${request.run} is a workflow; a script cannot resume. ` +
358
- `Launch a new workflow to run it again.`,
359
- });
360
- }
360
+ };
361
361
 
362
- if (status !== "failed" && status !== "stopped") {
363
- throw RunNotResumable.make({
364
- message: `Run ${request.run} is ${status}; only a failed or stopped run can resume.`,
365
- });
366
- }
362
+ const resumeBranch = async (request: ResumeRequest): Promise<ControlResult> => {
363
+ if (doc.mode === "workflow") {
364
+ throw RunNotResumable.make({
365
+ message:
366
+ `Run ${request.run} is a workflow; a script cannot resume. ` +
367
+ `Launch a new workflow to run it again.`,
368
+ });
369
+ }
367
370
 
368
- const missing = await missingFor(request.run, runtime);
369
- if (missing.missing.length > 0) {
370
- await recordMissing(request.run, doc, missing.missing, runtime);
371
- throw RunNotResumable.make({
372
- message: `Run ${request.run} is missing ${missing.missing.join(", ")}; ${missing.available}.`,
373
- });
374
- }
375
- const previousTask = task;
376
- if (previousTask === undefined) {
377
- throw RunNotResumable.make({
378
- message: `Run ${request.run} has no recorded input to resume.`,
379
- });
380
- }
381
- const previousTaskId = previousTask.id;
382
- const seed = { definition: doc.definition, lane: doc.lane };
383
- /** One commit creates the resumed task and points the run document at it. */
384
- const commitResumed = async (create: (tx: Tx) => Promise<TaskId>): Promise<number> =>
385
- runtime.run((context) =>
386
- runtime.harness.commit(async (tx) => {
387
- const created = await create(tx);
388
- const run = await tx.doc(RunDoc, request.run, seed);
389
- run.taskId = created;
390
- return created;
391
- }, context),
392
- );
393
- let resumedTaskId: number;
371
+ if (status !== "failed" && status !== "stopped") {
372
+ throw RunNotResumable.make({
373
+ message: `Run ${request.run} is ${status}; only a failed or stopped run can resume.`,
374
+ });
375
+ }
394
376
 
395
- if (previousTask.kind === "delegates.fanout") {
396
- const previous = decodeStoredInput(FanoutInputSchema, previousTask.input, request.run);
397
- const answeredChildren: { child: number; taskId: number }[] = [];
398
- for (const [child, childRunId] of doc.childRunIds.entries()) {
399
- const childDoc = await runtime.snapshot(RunDoc, childRunId);
400
- if (childDoc?.taskId === null || childDoc?.taskId === undefined) continue;
401
- const childTaskNumber = childDoc.taskId;
402
- const childTask = await runtime.run((context) =>
403
- runtime.harness.getTask(taskId(childTaskNumber), context),
377
+ const missing = await missingFor(request.run, runtime);
378
+ if (missing.missing.length > 0) {
379
+ await recordMissing(request.run, doc, missing.missing, runtime);
380
+ throw RunNotResumable.make({
381
+ message: `Run ${request.run} is missing ${missing.missing.join(", ")}; ${missing.available}.`,
382
+ });
383
+ }
384
+ const previousTask = task;
385
+ if (previousTask === undefined) {
386
+ throw RunNotResumable.make({
387
+ message: `Run ${request.run} has no recorded input to resume.`,
388
+ });
389
+ }
390
+ const previousTaskId = previousTask.id;
391
+ const seed = { definition: doc.definition, lane: doc.lane };
392
+ /** One commit creates the resumed task and points the run document at it. */
393
+ const commitResumed = async (create: (tx: Tx) => Promise<TaskId>): Promise<number> =>
394
+ runtime.run((context) =>
395
+ runtime.harness.commit(async (tx) => {
396
+ const created = await create(tx);
397
+ const run = await tx.doc(RunDoc, request.run, seed);
398
+ run.taskId = created;
399
+ return created;
400
+ }, context),
404
401
  );
405
- if (statusOf(childTask) === "answered") {
406
- answeredChildren.push({ child, taskId: childDoc.taskId });
402
+ let resumedTaskId: number;
403
+
404
+ if (previousTask.kind === "delegates.fanout") {
405
+ const previous = decodeStoredInput(FanoutInputSchema, previousTask.input, request.run);
406
+ const answeredChildren: { child: number; taskId: number }[] = [];
407
+ for (const [child, childRunId] of doc.childRunIds.entries()) {
408
+ const childDoc = await runtime.snapshot(RunDoc, childRunId);
409
+ if (childDoc?.taskId === null || childDoc?.taskId === undefined) continue;
410
+ const childTaskNumber = childDoc.taskId;
411
+ const childTask = await runtime.run((context) =>
412
+ runtime.harness.getTask(taskId(childTaskNumber), context),
413
+ );
414
+ if (statusOf(childTask) === "answered") {
415
+ answeredChildren.push({ child, taskId: childDoc.taskId });
416
+ }
407
417
  }
418
+ const resumed: FanoutInput = {
419
+ ...previous,
420
+ submissionKeyPrefix: `${request.run}:resume:${previousTaskId}`,
421
+ ...(answeredChildren.length === 0 ? {} : { answeredChildren }),
422
+ };
423
+ resumedTaskId = await commitResumed((tx) =>
424
+ tx.createTask(runtime.tasks.fanout, resumed, {
425
+ ownership: { kind: "conversation" },
426
+ conversationId: runtime.root.id,
427
+ }),
428
+ );
429
+ } else {
430
+ const previous = decodeStoredInput(RunInputSchema, previousTask.input, request.run);
431
+ const resumed: RunInput = {
432
+ ...previous,
433
+ submissionKey: `${request.run}:resume:${previousTaskId}`,
434
+ };
435
+ resumedTaskId = await commitResumed((tx) =>
436
+ tx.createTask(runtime.tasks.run, resumed, {
437
+ ownership: { kind: "conversation" },
438
+ conversationId: runtime.root.id,
439
+ }),
440
+ );
408
441
  }
409
- const resumed: FanoutInput = {
410
- ...previous,
411
- submissionKeyPrefix: `${request.run}:resume:${previousTaskId}`,
412
- ...(answeredChildren.length === 0 ? {} : { answeredChildren }),
413
- };
414
- resumedTaskId = await commitResumed((tx) =>
415
- tx.createTask(runtime.tasks.fanout, resumed, {
416
- ownership: { kind: "conversation" },
417
- conversationId: runtime.root.id,
418
- }),
419
- );
420
- } else {
421
- const previous = decodeStoredInput(RunInputSchema, previousTask.input, request.run);
422
- const resumed: RunInput = {
423
- ...previous,
424
- submissionKey: `${request.run}:resume:${previousTaskId}`,
425
- };
426
- resumedTaskId = await commitResumed((tx) =>
427
- tx.createTask(runtime.tasks.run, resumed, {
428
- ownership: { kind: "conversation" },
429
- conversationId: runtime.root.id,
430
- }),
431
- );
432
- }
433
442
 
434
- await awaitSettled(request.run, resumedTaskId, deps);
435
- return resultOf(request.run, deps);
443
+ await awaitSettled(request.run, resumedTaskId, deps);
444
+ return resultOf(request.run, deps);
445
+ };
446
+
447
+ // Every action literal has one branch; `Match.exhaustive` refuses a missing one.
448
+ return await Match.value(decoded).pipe(
449
+ Match.when({ action: "steer" }, steerBranch),
450
+ Match.when({ action: "stop" }, stopBranch),
451
+ Match.whenOr({ action: "approve" }, { action: "deny" }, gateBranch),
452
+ Match.when({ action: "answer" }, answerBranch),
453
+ Match.when({ action: "decline" }, declineBranch),
454
+ Match.when({ action: "resume" }, resumeBranch),
455
+ Match.exhaustive,
456
+ );
436
457
  };
@@ -6,23 +6,24 @@ import {
6
6
  type HarnessInspection,
7
7
  } from "@earendil-works/pi-durable";
8
8
  import { assert, it } from "@effect/vitest";
9
+ import { join, makeTempDir, writeText } from "../../../test-support/platform.ts";
9
10
  import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
10
11
  import { capArbitrary } from "../../../test-support/arbitraries.ts";
11
- import { mkdtemp, writeFile } from "node:fs/promises";
12
- import { tmpdir } from "node:os";
13
- import { join } from "node:path";
14
12
  import { stubHostSource } from "../../../test-support/stub-model-source.ts";
15
13
  import { createCatalogue, presets } from "../definitions.ts";
16
14
  import { DEFAULTS, type DelegatesConfig } from "../../runtime/config.ts";
17
15
  import { HostModelAdapter } from "../../runtime/models.ts";
18
- import { openSessionRuntime, type SessionIdentity } from "../../runtime/session.ts";
16
+ import { type SessionIdentity } from "../../runtime/session.ts";
17
+
19
18
  import { launch, type HostDefaults } from "./launch.ts";
20
19
  import { available, liveCounts, type AdmissionHost } from "./admission.ts";
21
20
  import { createDelegatesRegistry } from "../../runtime/extensions.ts";
22
- import { emptySkills } from "../skills.ts";
21
+ import { SkillsCatalogue } from "../skills.ts";
23
22
  import type { FanoutInput, FanoutState } from "./fanout.ts";
24
23
  import { RunDoc, RunIndexDoc } from "../run-records.ts";
25
24
  import { viewRun, viewSession } from "../view.ts";
25
+ import { waitFor } from "../../../test-support/wait.ts";
26
+ import { openTestSession } from "../../../test-support/seams.ts";
26
27
 
27
28
  const host: HostDefaults = {
28
29
  model: { provider: "stub", modelId: "stub-1" },
@@ -36,7 +37,7 @@ const config = (overrides: Partial<Omit<DelegatesConfig, "diagnostics">>): Deleg
36
37
  });
37
38
 
38
39
  const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
39
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-fanout-"));
40
+ const sessionDir = await makeTempDir("delegates-fanout-");
40
41
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
41
42
  };
42
43
 
@@ -57,7 +58,7 @@ const six = ["scout", "builder", "reviewer", "scout", "builder", "reviewer"].map
57
58
 
58
59
  it("a fanout of six runs at most four generations at once", async () => {
59
60
  const source = stubHostSource({ delayMs: 15 });
60
- const runtime = await openSessionRuntime({
61
+ const runtime = await openTestSession({
61
62
  identity: await identityFor("s-1"),
62
63
  models: new HostModelAdapter(source),
63
64
  });
@@ -80,7 +81,7 @@ it("a fanout of six runs at most four generations at once", async () => {
80
81
 
81
82
  it("the session ceiling throttles two concurrent fanouts", async () => {
82
83
  const source = stubHostSource({ delayMs: 15 });
83
- const runtime = await openSessionRuntime({
84
+ const runtime = await openTestSession({
84
85
  identity: await identityFor("s-1"),
85
86
  models: new HostModelAdapter(source),
86
87
  config: config({ laneCap: 10, sessionCeiling: 8 }),
@@ -101,7 +102,7 @@ it("the session ceiling throttles two concurrent fanouts", async () => {
101
102
 
102
103
  it("fail-fast aborts the other children and reports the failing child", async () => {
103
104
  const source = stubHostSource({ failAt: [2], delayAt: { 1: 0, 2: 0, 3: 2_000, 4: 2_000 } });
104
- const runtime = await openSessionRuntime({
105
+ const runtime = await openTestSession({
105
106
  identity: await identityFor("s-1"),
106
107
  models: new HostModelAdapter(source),
107
108
  });
@@ -124,12 +125,12 @@ it("fail-fast aborts the other children and reports the failing child", async ()
124
125
 
125
126
  it("caps come from delegates.json and survive a reopen", async () => {
126
127
  const identity = await identityFor("s-1");
127
- await writeFile(
128
+ await writeText(
128
129
  join(identity.agentDir, "delegates.json"),
129
130
  JSON.stringify({ caps: { laneCap: 2, sessionCeiling: 3 } }),
130
131
  );
131
132
  const source = stubHostSource({ delayMs: 15 });
132
- const first = await openSessionRuntime({
133
+ const first = await openTestSession({
133
134
  identity,
134
135
  models: new HostModelAdapter(source),
135
136
  });
@@ -143,7 +144,7 @@ it("caps come from delegates.json and survive a reopen", async () => {
143
144
  } finally {
144
145
  await first.close();
145
146
  }
146
- const second = await openSessionRuntime({ identity, models: new HostModelAdapter(source) });
147
+ const second = await openTestSession({ identity, models: new HostModelAdapter(source) });
147
148
  try {
148
149
  assert.strictEqual(second.config.laneCap, 2);
149
150
  await launch(
@@ -158,7 +159,7 @@ it("caps come from delegates.json and survive a reopen", async () => {
158
159
 
159
160
  it("fail-fast admits no child after the failing one", async () => {
160
161
  const source = stubHostSource({ failAt: [1] });
161
- const runtime = await openSessionRuntime({
162
+ const runtime = await openTestSession({
162
163
  identity: await identityFor("s-1"),
163
164
  models: new HostModelAdapter(source),
164
165
  config: config({ laneCap: 1, sessionCeiling: 8 }),
@@ -179,7 +180,7 @@ it("fail-fast admits no child after the failing one", async () => {
179
180
 
180
181
  it("the policy defaults to allSettled", async () => {
181
182
  const source = stubHostSource({ failAt: [2] });
182
- const runtime = await openSessionRuntime({
183
+ const runtime = await openTestSession({
183
184
  identity: await identityFor("s-1"),
184
185
  models: new HostModelAdapter(source),
185
186
  });
@@ -199,7 +200,7 @@ it("the policy defaults to allSettled", async () => {
199
200
  it("a single launch over the ceiling parks queued and is admitted later", async () => {
200
201
  const hold = deferred();
201
202
  const source = stubHostSource({ hold: () => hold.promise });
202
- const runtime = await openSessionRuntime({
203
+ const runtime = await openTestSession({
203
204
  identity: await identityFor("s-1"),
204
205
  models: new HostModelAdapter(source),
205
206
  config: config({ sessionCeiling: 1 }),
@@ -283,7 +284,7 @@ it("a fanout reserves another fanout's created-but-pending children", async () =
283
284
  };
284
285
  const { registry, tasks } = createDelegatesRegistry({
285
286
  admission,
286
- skills: emptySkills(),
287
+ skills: SkillsCatalogue.make(),
287
288
  });
288
289
  const harness = await Harness.open(
289
290
  new MemoryStorage(),
@@ -299,8 +300,8 @@ it("a fanout reserves another fanout's created-but-pending children", async () =
299
300
  runId: "run:probe#1",
300
301
  lane: "review",
301
302
  children: [
302
- { agent: "scout", task: "first", definition: presets[0]! },
303
- { agent: "scout", task: "second", definition: presets[0]! },
303
+ { agent: "scout", task: "first", definition: presets[0]!, maxTurns: 10 },
304
+ { agent: "scout", task: "second", definition: presets[0]!, maxTurns: 10 },
304
305
  ],
305
306
  host,
306
307
  maxTurns: 10,
@@ -373,7 +374,7 @@ it("admission arithmetic never exceeds either difference", () => {
373
374
  });
374
375
 
375
376
  it("status reports one row per child and lane counts", async () => {
376
- const runtime = await openSessionRuntime({
377
+ const runtime = await openTestSession({
377
378
  identity: await identityFor("s-1"),
378
379
  models: new HostModelAdapter(stubHostSource()),
379
380
  });
@@ -396,7 +397,7 @@ it("status reports one row per child and lane counts", async () => {
396
397
  });
397
398
 
398
399
  it("a run with a missing toolkit name reports the diagnostic", async () => {
399
- const runtime = await openSessionRuntime({
400
+ const runtime = await openTestSession({
400
401
  identity: await identityFor("s-1"),
401
402
  models: new HostModelAdapter(stubHostSource()),
402
403
  });
@@ -417,3 +418,107 @@ it("a run with a missing toolkit name reports the diagnostic", async () => {
417
418
  await runtime.close();
418
419
  }
419
420
  });
421
+
422
+ it("a detached fanout returns one entry per child with an empty answer", async () => {
423
+ const held = deferred();
424
+ const source = stubHostSource({ text: "done", hold: () => held.promise, holdAt: [1, 2] });
425
+ const runtime = await openTestSession({
426
+ identity: await identityFor("s-detached"),
427
+ models: new HostModelAdapter(source),
428
+ storage: new MemoryStorage(),
429
+ });
430
+ const settled: string[] = [];
431
+ runtime.settle.on((event) => settled.push(event.runId));
432
+ try {
433
+ const result = await launch(
434
+ {
435
+ kind: "fanout",
436
+ lane: "review",
437
+ agents: [
438
+ { agent: "scout", task: "first" },
439
+ { agent: "scout", task: "second" },
440
+ ],
441
+ execution: "detached",
442
+ },
443
+ { runtime, catalogue: createCatalogue(), host, waitMs: 5_000 },
444
+ );
445
+ assert.ok(
446
+ result.view.status === "queued" ||
447
+ result.view.status === "running" ||
448
+ result.view.status === "waiting",
449
+ result.view.status,
450
+ );
451
+ assert.strictEqual(result.view.children.length, 2);
452
+ // A detached group is at work, not blocked on a decision: the launch text says so.
453
+ assert.match(result.text, /^Run .* is (queued|running)\.$/, result.text);
454
+ for (const child of result.view.children) {
455
+ assert.strictEqual(child.answer, null);
456
+ assert.ok(child.status === "queued" || child.status === "running", child.status);
457
+ }
458
+ const parent = await runtime.snapshot(RunDoc, result.view.runId);
459
+ assert.strictEqual(parent?.execution, "detached");
460
+ assert.strictEqual(parent?.childRunIds.length, 2);
461
+ for (const runId of parent?.childRunIds ?? []) {
462
+ const child = await runtime.snapshot(RunDoc, runId);
463
+ assert.strictEqual(child?.execution, "detached");
464
+ // The notice marks a child with ` · parent <run id>`; the group is that parent.
465
+ assert.strictEqual(child?.parentRunId, result.view.runId);
466
+ }
467
+ held.release();
468
+ await waitFor(
469
+ async () => (await viewRun(result.view.runId, runtime)).status === "answered",
470
+ "the detached fanout settles",
471
+ 10_000,
472
+ );
473
+ // The group is a run of its own: its resolution admits it to the settle notice.
474
+ const group = await runtime.snapshot(RunDoc, result.view.runId);
475
+ assert.strictEqual(group?.resolution, "answered");
476
+ assert.strictEqual(group?.failure, null);
477
+ assert.ok(settled.includes(result.view.runId), settled.join(","));
478
+ } finally {
479
+ await runtime.close();
480
+ }
481
+ }, 20_000);
482
+
483
+ it("per-child budgets resolve per child inside one group", async () => {
484
+ const runtime = await openTestSession({
485
+ identity: await identityFor("s-budget"),
486
+ models: new HostModelAdapter(stubHostSource({ text: "ok" })),
487
+ storage: new MemoryStorage(),
488
+ config: config({ maxTurnsCeiling: 150 }),
489
+ });
490
+ try {
491
+ const result = await launch(
492
+ {
493
+ kind: "fanout",
494
+ lane: "review",
495
+ maxTurns: 200,
496
+ agents: [
497
+ { agent: "scout", task: "first", maxTurns: 60 },
498
+ { agent: "scout", task: "second" },
499
+ ],
500
+ },
501
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
502
+ );
503
+ const parent = await runtime.snapshot(RunDoc, result.view.runId);
504
+ const docs = [];
505
+ for (const runId of parent?.childRunIds ?? []) {
506
+ docs.push(await runtime.snapshot(RunDoc, runId));
507
+ }
508
+ assert.deepStrictEqual(
509
+ docs.map((doc) => doc?.maxTurns),
510
+ [60, 150],
511
+ );
512
+ for (const doc of docs) {
513
+ assert.ok(doc?.childConversationId !== null && doc?.childConversationId !== undefined);
514
+ const agent = await runtime.harness.snapshot(
515
+ AgentDoc,
516
+ doc.childConversationId as never,
517
+ BACKGROUND_CONTEXT,
518
+ );
519
+ assert.strictEqual(agent?.maxTurns, doc.maxTurns);
520
+ }
521
+ } finally {
522
+ await runtime.close();
523
+ }
524
+ }, 20_000);