@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
@@ -15,6 +15,7 @@ import {
15
15
  import { Effect, Option, Schema } from "effect";
16
16
  import type { DelegatesConfig } from "../runtime/config.ts";
17
17
  import { AgentDefinition } from "./definitions.ts";
18
+ import type { SkillsCatalogue } from "./skills.ts";
18
19
  import { available, liveCounts, type AdmissionHost } from "./orchestration/admission.ts";
19
20
  import {
20
21
  bindToolkit,
@@ -25,11 +26,20 @@ import {
25
26
  } from "./toolkit.ts";
26
27
  import type { Context } from "@earendil-works/chord/context";
27
28
  import { conversationId, taskId } from "./ids.ts";
28
- import { reasonOf } from "../runtime/log.ts";
29
- import type { SkillsService } from "./skills.ts";
29
+ import { nullLogSink, reasonOf, type LogSink } from "../runtime/log.ts";
30
+ import {
31
+ logRunFailed,
32
+ nullSettleSignal,
33
+ reasonFor,
34
+ recordSettlement,
35
+ type SettleSignal,
36
+ } from "./settlement.ts";
37
+ import type { FailureReason } from "./failure.ts";
30
38
  import type { McpPresence } from "../runtime/mcp.ts";
39
+ import type { SessionRuntime } from "../runtime/session.ts";
31
40
  import { GateDoc, GateIndexDoc, type GateRecord } from "./orchestration/gates.ts";
32
41
  import { RequestDoc, RequestIndexDoc, type RequestRecord } from "./orchestration/requests.ts";
42
+ import { Execution, FailureFact, Resolution } from "./failure.ts";
33
43
 
34
44
  export const RunMode = Schema.Literals(["single", "fanout", "review", "workflow"]);
35
45
  export type RunMode = typeof RunMode.Type;
@@ -49,6 +59,18 @@ export const RunMetadata = Schema.Struct({
49
59
  parentRunId: Schema.NullOr(Schema.String),
50
60
  childRunIds: Schema.Array(Schema.String),
51
61
  diagnostics: Schema.Array(Schema.String),
62
+ /** The launch kind; `wait` for a document written before version 3. */
63
+ execution: Execution,
64
+ /** The budget the child ran with; `null` while no claim resolved one. */
65
+ maxTurns: Schema.NullOr(Schema.Finite),
66
+ /** The settle outcome, one per task; `null` until the task ends. */
67
+ resolution: Schema.NullOr(Resolution),
68
+ /** `null` unless the run failed. */
69
+ failure: Schema.NullOr(FailureFact),
70
+ /** The task whose settlement was announced; `null` until a notice is delivered. */
71
+ settledTaskId: Schema.NullOr(Schema.Finite),
72
+ /** Durable retries observed on the child conversation. */
73
+ retryCount: Schema.Finite,
52
74
  });
53
75
  export type RunMetadata = typeof RunMetadata.Type;
54
76
 
@@ -59,22 +81,38 @@ export interface RunDocSeed {
59
81
  readonly lane: string;
60
82
  /** Absent: a root run. */
61
83
  readonly parentRunId?: string;
84
+ /** Absent: `wait`. */
85
+ readonly execution?: Execution;
62
86
  }
63
87
 
64
88
  const VERSION_WITH_MODE = 2;
89
+ const VERSION_WITH_TERMINAL_FACTS = 3;
65
90
 
66
- /** One migration: version 1 may predate the run mode and the parent run id, or already carry them. */
91
+ /**
92
+ * Two migrations: version 1 may predate the run mode and the parent run id, or
93
+ * already carry them; a version 2 document predates every terminal fact.
94
+ */
67
95
  export const migrateRun = (value: JsonObject, fromVersion: number): RunMetadata & JsonObject =>
68
96
  ({
69
97
  ...value,
70
98
  ...(fromVersion < VERSION_WITH_MODE
71
99
  ? { mode: value.mode ?? "single", parentRunId: value.parentRunId ?? null }
72
100
  : {}),
101
+ ...(fromVersion < VERSION_WITH_TERMINAL_FACTS
102
+ ? {
103
+ execution: value.execution ?? "wait",
104
+ maxTurns: value.maxTurns ?? null,
105
+ resolution: value.resolution ?? null,
106
+ failure: value.failure ?? null,
107
+ settledTaskId: value.settledTaskId ?? null,
108
+ retryCount: value.retryCount ?? 0,
109
+ }
110
+ : {}),
73
111
  }) as unknown as RunMetadata & JsonObject;
74
112
 
75
113
  export const RunDoc = defineDocFamily<RunMetadata & JsonObject, RunDocSeed & JsonObject>({
76
114
  kind: "delegates.run",
77
- version: VERSION_WITH_MODE,
115
+ version: VERSION_WITH_TERMINAL_FACTS,
78
116
  scope: "session",
79
117
  family: true,
80
118
  initial: (seed) => ({
@@ -91,6 +129,12 @@ export const RunDoc = defineDocFamily<RunMetadata & JsonObject, RunDocSeed & Jso
91
129
  parentRunId: seed.parentRunId ?? null,
92
130
  childRunIds: [],
93
131
  diagnostics: [],
132
+ execution: seed.execution ?? "wait",
133
+ maxTurns: null,
134
+ resolution: null,
135
+ failure: null,
136
+ settledTaskId: null,
137
+ retryCount: 0,
94
138
  }),
95
139
  migrate: migrateRun,
96
140
  checkpointWhen: () => true,
@@ -169,7 +213,7 @@ export const answerText = (messages: readonly Message[]): string => {
169
213
  /** Resolves toolkit names against the phase's registry snapshot and the runtime's catalogue. */
170
214
  export const resolverFor = (deps: {
171
215
  readonly registry: RegistrySnapshot;
172
- readonly skills: SkillsService;
216
+ readonly skills: SkillsCatalogue["Service"];
173
217
  /** The runtime's MCP presence; absent in a read-only viewer, which connects to nothing. */
174
218
  readonly presence?: McpPresence;
175
219
  }): ToolkitResolver => {
@@ -216,13 +260,50 @@ export const resolverFor = (deps: {
216
260
 
217
261
  const failed = (diagnostic: string): RunResult => ({ status: "failed", diagnostic });
218
262
 
263
+ /** A package-native failure: one terminal commit, one fact and one log line. */
264
+ const internalFailure = async (
265
+ task: { readonly input: RunInput },
266
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
267
+ context: Context,
268
+ diagnostic: string,
269
+ log: LogSink,
270
+ settleSignal: SettleSignal,
271
+ ): Promise<void> => {
272
+ let recorded: Awaited<ReturnType<typeof recordSettlement>>;
273
+ await runtime.commit(async (tx) => {
274
+ const doc = await tx.doc(RunDoc, task.input.runId, {
275
+ definition: task.input.definition.name,
276
+ lane: task.input.lane,
277
+ });
278
+ recorded = await recordSettlement(doc, {
279
+ resolution: "failed",
280
+ reason: "internal",
281
+ rawDetail: diagnostic,
282
+ });
283
+ return {
284
+ status: "terminal",
285
+ outcome: {
286
+ status: "failed",
287
+ error: { message: diagnostic },
288
+ result: failed(diagnostic),
289
+ },
290
+ };
291
+ }, context);
292
+ if (recorded !== undefined) {
293
+ logRunFailed(log, task.input.runId, recorded.failure, recorded.retryable);
294
+ }
295
+ settleSignal.emit({ runId: task.input.runId });
296
+ };
297
+
219
298
  const bind = async (
220
299
  task: RunningTask<RunInput, Extract<RunState, { phase: "bind" }>, RunResult>,
221
300
  runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
222
301
  context: Context,
223
302
  admission: AdmissionHost,
224
- skills: SkillsService,
303
+ skills: SkillsCatalogue["Service"],
225
304
  mcpPresence: () => McpPresence | undefined,
305
+ log: LogSink,
306
+ settleSignal: SettleSignal,
226
307
  ): Promise<void> => {
227
308
  const inspection = await admission.inspect();
228
309
  const ownedTasks = await runtime.ownedTasks(context);
@@ -255,18 +336,7 @@ const bind = async (
255
336
  try {
256
337
  bound = await Effect.runPromise(bindToolkit(task.input.definition, resolver));
257
338
  } catch (error) {
258
- const diagnostic = reasonOf(error);
259
- await runtime.commit(
260
- () => ({
261
- status: "terminal",
262
- outcome: {
263
- status: "failed",
264
- error: { message: diagnostic },
265
- result: failed(diagnostic),
266
- },
267
- }),
268
- context,
269
- );
339
+ await internalFailure(task, runtime, context, reasonOf(error), log, settleSignal);
270
340
  return;
271
341
  }
272
342
 
@@ -300,23 +370,21 @@ const submit = async (
300
370
  task: RunningTask<RunInput, Extract<RunState, { phase: "submit" }>, RunResult>,
301
371
  runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
302
372
  context: Context,
373
+ log: LogSink,
374
+ settleSignal: SettleSignal,
303
375
  ): Promise<void> => {
304
376
  const conversation = await runtime.conversation(
305
377
  conversationId(task.state.checkpoint.childId),
306
378
  context,
307
379
  );
308
380
  if (conversation === undefined) {
309
- const diagnostic = "child conversation is missing";
310
- await runtime.commit(
311
- () => ({
312
- status: "terminal",
313
- outcome: {
314
- status: "failed",
315
- error: { message: diagnostic },
316
- result: failed(diagnostic),
317
- },
318
- }),
381
+ await internalFailure(
382
+ task,
383
+ runtime,
319
384
  context,
385
+ "child conversation is missing",
386
+ log,
387
+ settleSignal,
320
388
  );
321
389
  return;
322
390
  }
@@ -375,9 +443,13 @@ const settle = async (
375
443
  task: RunningTask<RunInput, Extract<RunState, { phase: "settle" }>, RunResult>,
376
444
  runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
377
445
  context: Context,
446
+ log: LogSink,
447
+ settleSignal: SettleSignal,
378
448
  ): Promise<void> => {
379
449
  const signal = await runtime.readSignal(SubmissionSettled, task.input.submissionKey, context);
380
450
  let result: RunResult;
451
+ let failureReason: FailureReason | undefined;
452
+ let rawDetail: string | undefined;
381
453
  if (signal === undefined || "expired" in signal) {
382
454
  result = failed("missing_settlement");
383
455
  } else {
@@ -415,29 +487,50 @@ const settle = async (
415
487
  );
416
488
  result =
417
489
  last?.status === "denied" ? { status: "denied" } : failed(record.reason ?? "unanswered");
490
+ if (result.status === "failed") {
491
+ failureReason = reasonFor(record.reason);
492
+ rawDetail = typeof record.detail === "string" ? record.detail : undefined;
493
+ }
418
494
  }
419
495
  }
420
- await runtime.commit(
421
- () =>
422
- result.status === "failed"
423
- ? {
424
- status: "terminal",
425
- outcome: {
426
- status: "failed",
427
- error: { message: result.diagnostic },
428
- result,
429
- },
430
- }
431
- : { status: "terminal", outcome: { status: "completed", result } },
432
- context,
433
- );
496
+ let recorded: Awaited<ReturnType<typeof recordSettlement>>;
497
+ await runtime.commit(async (tx) => {
498
+ const doc = await tx.doc(RunDoc, task.input.runId, {
499
+ definition: task.input.definition.name,
500
+ lane: task.input.lane,
501
+ });
502
+ recorded = await recordSettlement(doc, {
503
+ resolution: result.status,
504
+ ...(failureReason === undefined ? {} : { reason: failureReason }),
505
+ ...(rawDetail === undefined ? {} : { rawDetail }),
506
+ });
507
+ return result.status === "failed"
508
+ ? {
509
+ status: "terminal",
510
+ outcome: {
511
+ status: "failed",
512
+ error: { message: result.diagnostic },
513
+ result,
514
+ },
515
+ }
516
+ : { status: "terminal", outcome: { status: "completed", result } };
517
+ }, context);
518
+ // After the commit resolves: one line per failed run, then the settle event.
519
+ if (recorded !== undefined) {
520
+ logRunFailed(log, task.input.runId, recorded.failure, recorded.retryable);
521
+ }
522
+ settleSignal.emit({ runId: task.input.runId });
434
523
  };
435
524
 
436
525
  export const createRunTask = (
437
526
  admission: AdmissionHost,
438
- skills: SkillsService,
527
+ skills: SkillsCatalogue["Service"],
439
528
  /** The runtime's MCP presence, read at each bind; absent in a read-only runtime. */
440
529
  mcpPresence: () => McpPresence | undefined = () => undefined,
530
+ /** The session sink: one `run.failed` line per failed run. */
531
+ log: LogSink = nullLogSink,
532
+ /** The in-process settle signal: every terminal commit emits once. */
533
+ settleSignal: SettleSignal = nullSettleSignal,
441
534
  ) =>
442
535
  defineTask<RunInput, RunState, RunResult, RunHooks>({
443
536
  name: "delegates.run",
@@ -445,18 +538,24 @@ export const createRunTask = (
445
538
  initial: (input) => ({ phase: "bind", input }),
446
539
  phases: {
447
540
  bind: (task, runtime, context) =>
448
- bind(task, runtime, context, admission, skills, mcpPresence),
449
- submit,
450
- settle,
541
+ bind(task, runtime, context, admission, skills, mcpPresence, log, settleSignal),
542
+ submit: (task, runtime, context) => submit(task, runtime, context, log, settleSignal),
543
+ settle: (task, runtime, context) => settle(task, runtime, context, log, settleSignal),
451
544
  },
452
- abort: async (_task, runtime, context) =>
453
- runtime.commit(
454
- () => ({
545
+ abort: async (task, runtime, context) => {
546
+ await runtime.commit(async (tx) => {
547
+ const doc = await tx.doc(RunDoc, task.input.runId, {
548
+ definition: task.input.definition.name,
549
+ lane: task.input.lane,
550
+ });
551
+ await recordSettlement(doc, { resolution: "stopped" });
552
+ return {
455
553
  status: "terminal",
456
554
  outcome: { status: "aborted", reason: "stopped", result: { status: "stopped" } },
457
- }),
458
- context,
459
- ),
555
+ };
556
+ }, context);
557
+ settleSignal.emit({ runId: task.input.runId });
558
+ },
460
559
  });
461
560
 
462
561
  export interface LaunchIndexAttempt {
@@ -525,3 +624,66 @@ export const claimLaunch = async (
525
624
  export type RunConfig = Pick<DelegatesConfig, "maxTurns"> & { readonly cwd?: string };
526
625
 
527
626
  export type { TaskRecord };
627
+
628
+ export interface ListedRuns {
629
+ readonly runIds: readonly string[];
630
+ /** Indexed runs older than the window; zero when every indexed run is listed. */
631
+ readonly omitted: number;
632
+ /**
633
+ * The documents read while listing, keyed by the indexed run they belong to.
634
+ * A child reached through its parent's `childRunIds` has no entry: a caller
635
+ * that needs it reads it once.
636
+ */
637
+ readonly docs: ReadonlyMap<string, RunMetadata & JsonObject>;
638
+ }
639
+
640
+ /**
641
+ * The runs a session-scoped reader enumerates: the newest `limit` indexed run
642
+ * ids, each followed by its group's children. A fanout or review child is never
643
+ * indexed, so its parent document is the only way to reach it.
644
+ *
645
+ * Every windowed run is read, watched or not: a workflow commits its children to
646
+ * `childRunIds` only after it starts, so skipping a watched parent would hide
647
+ * every child that appears later. The read documents are returned, letting a
648
+ * caller that also needs them pay one snapshot instead of two.
649
+ */
650
+ export const listedRuns = async (
651
+ runtime: SessionRuntime,
652
+ options: { readonly limit?: number } = {},
653
+ ): Promise<ListedRuns> => {
654
+ const index = await runtime.snapshot(RunIndexDoc);
655
+ const indexed = index?.runIds ?? [];
656
+ // The index is in creation order, so the tail is the newest.
657
+ const window = options.limit === undefined ? indexed : indexed.slice(-options.limit);
658
+ const runIds: string[] = [];
659
+ const docs = new Map<string, RunMetadata & JsonObject>();
660
+ const add = (runId: string): void => {
661
+ if (!runIds.includes(runId)) runIds.push(runId);
662
+ };
663
+ for (const runId of window) {
664
+ add(runId);
665
+ const doc = await runtime.snapshot(RunDoc, runId);
666
+ if (doc === undefined) continue;
667
+ docs.set(runId, doc);
668
+ for (const childRunId of doc.childRunIds) add(childRunId);
669
+ }
670
+ return { runIds, omitted: indexed.length - window.length, docs };
671
+ };
672
+
673
+ /**
674
+ * The only committer of the announced marker: the recorder's announcement path.
675
+ * The snapshot guard keeps a vanished run from being re-created from a seed.
676
+ */
677
+ export const recordAnnouncement = async (
678
+ runtime: SessionRuntime,
679
+ runId: string,
680
+ taskId: number,
681
+ ): Promise<void> => {
682
+ if ((await runtime.snapshot(RunDoc, runId)) === undefined) return;
683
+ await runtime.run((context) =>
684
+ runtime.harness.commit(async (tx) => {
685
+ const doc = await tx.doc(RunDoc, runId, { definition: "", lane: "default" });
686
+ doc.settledTaskId = taskId;
687
+ }, context),
688
+ );
689
+ };
@@ -0,0 +1,186 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
+ import { makeTempDir } from "../../test-support/platform.ts";
4
+ import { stubHostSource, type StubHostOptions } from "../../test-support/stub-model-source.ts";
5
+ import { HostModelAdapter } from "../runtime/models.ts";
6
+ import { DEFAULTS, type DelegatesConfig } from "../runtime/config.ts";
7
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
8
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
9
+ import { createCatalogue } from "./definitions.ts";
10
+ import { launch, type HostDefaults } from "./orchestration/launch.ts";
11
+ import { RunDoc } from "./run-records.ts";
12
+ import { FAILURE_REASONS, remedyOf } from "./settlement.ts";
13
+ import { startRetryObserver } from "../extension/retry-observer.ts";
14
+
15
+ const host: HostDefaults = {
16
+ model: { provider: "stub", modelId: "stub-1" },
17
+ thinkingLevel: "low",
18
+ };
19
+
20
+ const recordingSink = () => {
21
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
22
+ const sink: LogSink = {
23
+ write: (level, code, fields = {}) => {
24
+ entries.push({ level, code, fields });
25
+ },
26
+ };
27
+ return { sink, entries };
28
+ };
29
+
30
+ const open = async (
31
+ source: StubHostOptions,
32
+ options: {
33
+ readonly log?: LogSink;
34
+ readonly config?: DelegatesConfig;
35
+ } = {},
36
+ ): Promise<TestSession> => {
37
+ const sessionDir = await makeTempDir("delegates-settlement-");
38
+ return openTestSession({
39
+ identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
40
+ models: new HostModelAdapter(stubHostSource(source)),
41
+ ...(options.log === undefined ? {} : { log: options.log }),
42
+ ...(options.config === undefined ? {} : { config: options.config }),
43
+ });
44
+ };
45
+
46
+ const launchScout = (runtime: TestSession, waitMs = 10_000) =>
47
+ launch(
48
+ { kind: "single", agent: "scout", task: "look" },
49
+ { runtime, catalogue: createCatalogue(), host, waitMs },
50
+ );
51
+
52
+ it("every failure reason has a remedy and the set is closed", () => {
53
+ assert.strictEqual(FAILURE_REASONS.length, 11);
54
+ const remedies = FAILURE_REASONS.map(remedyOf);
55
+ assert.ok(
56
+ remedies.every((remedy) => remedy !== undefined),
57
+ JSON.stringify(remedies),
58
+ );
59
+ assert.deepStrictEqual(remedies, [
60
+ "relaunch",
61
+ "fix_config",
62
+ "relaunch",
63
+ "relaunch",
64
+ "relaunch",
65
+ "relaunch",
66
+ "relaunch",
67
+ "relaunch",
68
+ "narrow",
69
+ "narrow",
70
+ "relaunch",
71
+ ]);
72
+ });
73
+
74
+ it("a provider failure persists its reason and canonical detail", async () => {
75
+ const runtime = await open({ failAt: [1], failMessage: "invalid request: no such model field" });
76
+ try {
77
+ const result = await launchScout(runtime);
78
+ assert.strictEqual(result.view.status, "failed");
79
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
80
+ assert.strictEqual(doc?.resolution, "failed");
81
+ assert.deepStrictEqual(doc?.failure, {
82
+ reason: "model_error",
83
+ detail: "invalid request: no such model field",
84
+ });
85
+ assert.strictEqual(doc?.settledTaskId, null);
86
+ assert.strictEqual(doc?.retryCount, 0);
87
+ } finally {
88
+ await runtime.close();
89
+ }
90
+ });
91
+
92
+ it("retryable comes from the observed count, not from the text", async () => {
93
+ const recorder = recordingSink();
94
+ const runtime = await open(
95
+ { failAt: [1, 2, 3, 4], failMessage: "429: rate limit exceeded" },
96
+ { log: recorder.sink },
97
+ );
98
+ // The count is the retry observer's evidence, started as the entry starts it.
99
+ const observer = startRetryObserver({ runtime, log: recorder.sink });
100
+ try {
101
+ const result = await launchScout(runtime, 20_000);
102
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
103
+ assert.ok((doc?.retryCount ?? 0) >= 1, String(doc?.retryCount));
104
+ const failures = recorder.entries.filter((entry) => entry.code === "run.failed");
105
+ assert.strictEqual(failures.length, 1);
106
+ const failure = failures[0];
107
+ assert.strictEqual(failure?.level, "error");
108
+ assert.strictEqual(failure?.fields.reason, "model_error");
109
+ assert.strictEqual(failure?.fields.retryable, true);
110
+ assert.strictEqual(failure?.fields.remedy, "relaunch");
111
+ assert.strictEqual(failure?.fields.detail, "429: rate limit exceeded");
112
+ } finally {
113
+ await observer.close();
114
+ await runtime.close();
115
+ }
116
+ }, 30_000);
117
+
118
+ it("a turn-limit run records the budget text as its detail", async () => {
119
+ const recorder = recordingSink();
120
+ const runtime = await open(
121
+ { toolCall: { name: "read", arguments: { path: "x" } } },
122
+ { log: recorder.sink, config: { ...DEFAULTS, maxTurns: 1, diagnostics: [] } },
123
+ );
124
+ try {
125
+ const result = await launchScout(runtime);
126
+ const doc = await runtime.snapshot(RunDoc, result.view.runId);
127
+ assert.strictEqual(doc?.failure?.reason, "turn_limit");
128
+ assert.strictEqual(doc?.failure?.detail, "1 turn");
129
+ const failures = recorder.entries.filter((entry) => entry.code === "run.failed");
130
+ assert.strictEqual(failures.length, 1);
131
+ assert.strictEqual(failures[0]?.fields.retryable, false);
132
+ assert.strictEqual(failures[0]?.fields.remedy, "narrow");
133
+ } finally {
134
+ await runtime.close();
135
+ }
136
+ });
137
+
138
+ it("a package-native failure keeps its diagnostic text under reason internal", async () => {
139
+ let release = (): void => {};
140
+ const held = new Promise<void>((resolve) => {
141
+ release = resolve;
142
+ });
143
+ const runtime = await open({ text: "slow", hold: () => held });
144
+ try {
145
+ const result = await launchScout(runtime, 0);
146
+ const runId = result.view.runId;
147
+ const { control } = await import("./orchestration/control.ts");
148
+ await control(
149
+ { action: "stop", run: runId },
150
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
151
+ );
152
+ // The child conversation is gone before the settle phase reads it.
153
+ await runtime.harness.commit(async (tx) => {
154
+ const doc = await tx.doc(RunDoc, runId, { definition: "scout", lane: "default" });
155
+ doc.childConversationId = 9_999;
156
+ }, BACKGROUND_CONTEXT);
157
+ release();
158
+ await control(
159
+ { action: "resume", run: runId },
160
+ { runtime, wait: { policy: "settle", waitMs: 10_000 } },
161
+ );
162
+ const doc = await runtime.snapshot(RunDoc, runId);
163
+ assert.strictEqual(doc?.failure?.reason, "internal");
164
+ assert.strictEqual(doc?.failure?.detail, "child conversation is missing");
165
+ } finally {
166
+ await runtime.close();
167
+ }
168
+ });
169
+
170
+ it("the recorder signals a settlement only after its commit landed", async () => {
171
+ const runtime = await open({ text: "ok" });
172
+ const events: string[] = [];
173
+ const seen: Promise<string | null | undefined>[] = [];
174
+ const detach = runtime.settle.on((event) => {
175
+ events.push(event.runId);
176
+ seen.push(runtime.snapshot(RunDoc, event.runId).then((doc) => doc?.resolution));
177
+ });
178
+ try {
179
+ const result = await launchScout(runtime);
180
+ assert.deepStrictEqual(events, [result.view.runId]);
181
+ assert.deepStrictEqual(await Promise.all(seen), ["answered"]);
182
+ } finally {
183
+ detach();
184
+ await runtime.close();
185
+ }
186
+ });