@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
@@ -13,28 +13,21 @@ export const STRIP_CHILD_LINES = 2;
13
13
  /** The strip sits above the editor, where the tracker widget sits. */
14
14
  export const STRIP_PLACEMENT = "aboveEditor" as const;
15
15
 
16
- /** Visible only while live work or a pending gate exists: terminal rows do not keep it alive. */
17
- export const stripVisible = (snapshot: InspectorSnapshot): boolean =>
18
- snapshot.counts.running +
19
- snapshot.counts.queued +
20
- snapshot.counts.waiting +
21
- snapshot.counts.gates >
22
- 0;
23
-
24
16
  /** Oldest first, running before waiting; queued children last. */
25
17
  const childOrder = (row: InspectorRow): number =>
26
18
  row.status === "running" ? 0 : row.status === "waiting" ? 1 : 2;
27
19
 
28
20
  /**
29
- * One to three content lines, never more and never blank. The candidates are
30
- * the live rows in reverse projection order (the projection is newest first),
31
- * so a newly launched child never evicts the oldest.
21
+ * One to three content lines, never blank: the counters line, then at most two
22
+ * live child lines. `countersLine` renders `idle — ctrl+space` rather than an
23
+ * empty string, so the box stays on screen from activation to teardown. The
24
+ * candidates are the live rows in reverse projection order (the projection is
25
+ * newest first), so a newly launched child never evicts the oldest.
32
26
  */
33
27
  export const stripLines = (
34
28
  snapshot: InspectorSnapshot,
35
29
  shortcut = DEFAULT_INSPECT_SHORTCUT,
36
30
  ): string[] => {
37
- if (!stripVisible(snapshot)) return [];
38
31
  const live = snapshot.rows
39
32
  .filter((row) => row.childCount === 0 && isLiveStatus(row.status))
40
33
  .reverse()
@@ -47,7 +40,7 @@ export const stripLines = (
47
40
  countersLine(snapshot.counts, shortcut),
48
41
  ...named.map((row, index) => childLine(row, index === named.length - 1 ? overflow : 0)),
49
42
  ];
50
- return lines.filter((line) => line.length > 0).slice(0, STRIP_MAX_CONTENT_LINES);
43
+ return lines.slice(0, STRIP_MAX_CONTENT_LINES);
51
44
  };
52
45
 
53
46
  /**
@@ -68,7 +61,7 @@ export const makeDelegatesStrip = (options: {
68
61
  { label: "Delegates", color: "border", cache: false },
69
62
  );
70
63
  return defineComponent({
71
- render: (width: number) => (stripVisible(options.getSnapshot()) ? box.render(width) : []),
64
+ render: (width: number) => box.render(width),
72
65
  invalidate: () => box.invalidate(),
73
66
  });
74
67
  };
@@ -1,5 +1,6 @@
1
1
  import { assert, it } from "@effect/vitest";
2
- import type { LaneView } from "../domain/view.ts";
2
+ import type { LaneView, RunView } from "../domain/view.ts";
3
+ import { renderStatusText } from "../extension/tools.ts";
3
4
  import type { GateRow, InspectorRow, RequestRow } from "./snapshot.ts";
4
5
  import {
5
6
  GATES_HEADER,
@@ -8,6 +9,7 @@ import {
8
9
  RUNS_HEADER,
9
10
  childLine,
10
11
  countersLine,
12
+ detachedPart,
11
13
  formatElapsed,
12
14
  gateAgentMessage,
13
15
  gateDetailLine,
@@ -21,6 +23,7 @@ import {
21
23
  requestToastLine,
22
24
  rowLine,
23
25
  runStatusLine,
26
+ settleAgentMessage,
24
27
  type RequestNotice,
25
28
  } from "./wording.ts";
26
29
 
@@ -77,6 +80,12 @@ it("countersLine shows queued only when non-zero and names the shortcut", () =>
77
80
  );
78
81
  });
79
82
 
83
+ it("countersLine prints no zero counter and says idle when nothing is live", () => {
84
+ const empty = { running: 0, queued: 0, waiting: 0, gates: 0, requests: 0 };
85
+ assert.strictEqual(countersLine({ ...empty, gates: 1 }), "gates 1 — ctrl+space");
86
+ assert.strictEqual(countersLine(empty), "idle — ctrl+space");
87
+ });
88
+
80
89
  it("childLine names the duration, the status, the tool or the age", () => {
81
90
  assert.strictEqual(childLine(row({ durationMs: 12_000 }), 0), "deployer · took 12s");
82
91
  assert.strictEqual(childLine(row({ status: "failed" }), 0), "deployer · failed");
@@ -105,17 +114,136 @@ it("rowLine joins the status with children, activity and gates", () => {
105
114
  );
106
115
  });
107
116
 
117
+ const statusRow = (overrides: Partial<RunView> = {}): RunView => ({
118
+ runId: "r1",
119
+ definition: "scout",
120
+ mode: "single",
121
+ lane: "default",
122
+ conversationId: null,
123
+ taskId: null,
124
+ status: "stopped",
125
+ answer: null,
126
+ durationMs: null,
127
+ children: [],
128
+ missing: [],
129
+ gates: [],
130
+ requests: [],
131
+ diagnostic: null,
132
+ execution: "wait",
133
+ maxTurns: null,
134
+ failure: null,
135
+ ...overrides,
136
+ });
137
+
108
138
  it("runStatusLine drops the mode for a single run", () => {
109
139
  assert.strictEqual(
110
- runStatusLine({ definition: "fanout", mode: "single", status: "running" }),
140
+ runStatusLine({
141
+ definition: "fanout",
142
+ mode: "single",
143
+ status: "running",
144
+ }),
111
145
  "fanout · running",
112
146
  );
113
147
  assert.strictEqual(
114
- runStatusLine({ definition: "fanout", mode: "workflow", status: "waiting" }),
148
+ runStatusLine({
149
+ definition: "fanout",
150
+ mode: "workflow",
151
+ status: "waiting",
152
+ }),
115
153
  "fanout · workflow · waiting",
116
154
  );
117
155
  });
118
156
 
157
+ it("a failed detached row keeps the marker after the failure and before the budget", () => {
158
+ const view = renderStatusText({
159
+ runs: [
160
+ statusRow({
161
+ runId: "r1",
162
+ status: "failed",
163
+ execution: "detached",
164
+ maxTurns: 1,
165
+ failure: { reason: "turn_limit", detail: "1 turn" },
166
+ }),
167
+ ],
168
+ lanes: [],
169
+ gates: [],
170
+ requests: [],
171
+ reviews: [],
172
+ });
173
+ assert.strictEqual(view, "r1 scout · failed (turn_limit): 1 turn · detached · turns 1");
174
+ });
175
+
176
+ it("the run line marks a detached run and child lines do not", () => {
177
+ assert.strictEqual(detachedPart("detached"), " · detached");
178
+ assert.strictEqual(detachedPart("wait"), "");
179
+ assert.strictEqual(
180
+ `${runStatusLine({
181
+ definition: "scout",
182
+ mode: "single",
183
+ status: "running",
184
+ })}${detachedPart("detached")}`,
185
+ "scout · running · detached",
186
+ );
187
+ assert.strictEqual(
188
+ runStatusLine({
189
+ definition: "scout",
190
+ mode: "single",
191
+ status: "running",
192
+ }),
193
+ "scout · running",
194
+ );
195
+
196
+ const children = [0, 1].map((child) => ({
197
+ child,
198
+ runId: `r1:child:${child}`,
199
+ conversationId: null,
200
+ taskId: null,
201
+ agent: "scout",
202
+ status: "running" as const,
203
+ answer: null,
204
+ durationMs: null,
205
+ maxTurns: null,
206
+ failure: null,
207
+ }));
208
+ const view = renderStatusText({
209
+ runs: [
210
+ statusRow({
211
+ runId: "r1",
212
+ definition: "fanout",
213
+ mode: "fanout",
214
+ status: "running",
215
+ execution: "detached",
216
+ children,
217
+ }),
218
+ ],
219
+ lanes: [],
220
+ gates: [],
221
+ requests: [],
222
+ reviews: [],
223
+ });
224
+ const lines = view.split("\n");
225
+ assert.ok(lines[0]?.includes(" · detached"), view);
226
+ assert.strictEqual(view.split("detached").length - 1, 1, view);
227
+ for (const line of lines.slice(1)) assert.ok(!line.includes("detached"), line);
228
+ });
229
+
230
+ it("a stopped or denied run records no failure fact and renders as today", () => {
231
+ const denied = statusRow({
232
+ runId: "r1",
233
+ status: "denied",
234
+ diagnostic: "request 12:c1 was declined",
235
+ });
236
+ const stopped = statusRow({ runId: "r2", status: "stopped" });
237
+ const view = renderStatusText({
238
+ runs: [denied, stopped],
239
+ lanes: [],
240
+ gates: [],
241
+ requests: [],
242
+ reviews: [],
243
+ });
244
+ assert.strictEqual(view, "r2 scout · stopped\nr1 scout · denied (request 12:c1 was declined)");
245
+ });
246
+
119
247
  it("the lane, omitted and header lines are exact", () => {
120
248
  assert.strictEqual(laneLine(lane), "coding: running 1, queued 0, answered 2");
121
249
  assert.strictEqual(omittedLine(5), "5 older runs not shown.");
@@ -236,3 +364,25 @@ it("requestDetailLines wraps the prompt, labels and deadline to the box", () =>
236
364
  assert.ok(text.includes(`deadline ${new Date(1_000).toISOString()}`), text);
237
365
  assert.ok(lines.length > 2, lines.join("\n"));
238
366
  });
367
+
368
+ it("the notice text is status only and names each run", () => {
369
+ const message = settleAgentMessage({
370
+ rows: [
371
+ { runId: "r#1", definition: "scout", outcome: "answered", failure: null, parentRunId: null },
372
+ {
373
+ runId: "r#2",
374
+ definition: "builder",
375
+ outcome: "failed",
376
+ failure: { reason: "turn_limit", detail: "120 turns" },
377
+ parentRunId: "r#0",
378
+ },
379
+ ],
380
+ });
381
+ assert.strictEqual(
382
+ message,
383
+ "2 runs settled.\nrun r#1 scout answered\n" +
384
+ "run r#2 builder failed (turn_limit): 120 turns · parent r#0\n" +
385
+ "These are status notices; nothing is required.",
386
+ );
387
+ for (const word of ["Resume", "Relaunch", "Poll"]) assert.ok(!message.includes(word), message);
388
+ });
@@ -1,5 +1,8 @@
1
1
  import { isTerminalStatus, type LaneView, type RunStatus } from "../domain/view.ts";
2
2
  import type { RunMode } from "../domain/run-records.ts";
3
+ import type { FailureFact } from "../domain/failure.ts";
4
+ import type { Execution } from "../domain/failure.ts";
5
+ import type { Resolution } from "../domain/failure.ts";
3
6
  import { truncate } from "../runtime/log.ts";
4
7
  import { DEFAULT_INSPECT_SHORTCUT } from "./shortcut.ts";
5
8
  import type { GateRow, InspectorRow, InspectorSnapshot, RequestRow } from "./snapshot.ts";
@@ -25,16 +28,32 @@ export const formatElapsed = (ms: number): string => {
25
28
  return `${hours}h ${String(minutes).padStart(2, "0")}m`;
26
29
  };
27
30
 
28
- /** `running 2 · queued 1 · waiting 1 · gates 1 — ctrl+space`; `queued` appears only when non-zero. */
31
+ /**
32
+ * The non-zero counters in a fixed order: `running 2 · waiting 1 · gates 1`.
33
+ * The strip and the footer both build their line from this, so the two surfaces
34
+ * cannot drift apart.
35
+ */
36
+ export const counterParts = (counts: InspectorSnapshot["counts"]): string[] => {
37
+ const parts: string[] = [];
38
+ if (counts.running > 0) parts.push(`running ${counts.running}`);
39
+ if (counts.queued > 0) parts.push(`queued ${counts.queued}`);
40
+ if (counts.waiting > 0) parts.push(`waiting ${counts.waiting}`);
41
+ if (counts.gates > 0) parts.push(`gates ${counts.gates}`);
42
+ if (counts.requests > 0) parts.push(`requests ${counts.requests}`);
43
+ return parts;
44
+ };
45
+
46
+ /**
47
+ * `idle — ctrl+space` when nothing is live, otherwise the counters and the
48
+ * shortcut. A zero counter never prints: `running 0` only crowds out the one
49
+ * counter that matters.
50
+ */
29
51
  export const countersLine = (
30
52
  counts: InspectorSnapshot["counts"],
31
53
  shortcut = DEFAULT_INSPECT_SHORTCUT,
32
54
  ): string => {
33
- const parts = [`running ${counts.running}`];
34
- if (counts.queued > 0) parts.push(`queued ${counts.queued}`);
35
- parts.push(`waiting ${counts.waiting}`, `gates ${counts.gates}`);
36
- if (counts.requests > 0) parts.push(`requests ${counts.requests}`);
37
- return `${parts.join(" · ")} — ${shortcut}`;
55
+ const parts = counterParts(counts);
56
+ return parts.length === 0 ? `idle — ${shortcut}` : `${parts.join(" · ")} — ${shortcut}`;
38
57
  };
39
58
 
40
59
  const activityDetail = (row: InspectorRow): string => {
@@ -79,10 +98,63 @@ export const runStatusLine = (run: {
79
98
  }): string =>
80
99
  [run.definition, ...(run.mode === "single" ? [] : [run.mode]), run.status].join(" · ");
81
100
 
101
+ /** ` · detached` — after the status and its failure part, before the budget. */
102
+ export const detachedPart = (execution: Execution): string =>
103
+ execution === "detached" ? " · detached" : "";
104
+
82
105
  /** `coding: running 1, queued 0, answered 2` — the same function `tools.ts` renders. */
83
106
  export const laneLine = (lane: LaneView): string =>
84
107
  `${lane.name}: running ${lane.running}, queued ${lane.queued}, answered ${lane.answered}`;
85
108
 
109
+ /** ` (model_error): 429: rate limit exceeded` — reason, then the canonical detail. */
110
+ export const failurePart = (failure: FailureFact | null): string =>
111
+ failure === null
112
+ ? ""
113
+ : ` (${failure.reason})${failure.detail === null ? "" : `: ${failure.detail}`}`;
114
+
115
+ /** One settle notice lists at most this many rows; the rest wait for the next window. */
116
+ export const SETTLE_MAX_ROWS = 20;
117
+
118
+ /** `· turns 120` — the resolved budget a child ran with; empty when unrecorded. */
119
+ export const turnsPart = (maxTurns: number | null): string =>
120
+ maxTurns === null ? "" : ` · turns ${maxTurns}`;
121
+
122
+ /** One settle row: a run that settled, its outcome and its failure fact. */
123
+ export interface SettleRow {
124
+ readonly runId: string;
125
+ readonly definition: string;
126
+ readonly outcome: Resolution;
127
+ readonly failure: FailureFact | null;
128
+ readonly parentRunId: string | null;
129
+ }
130
+
131
+ /** One coalesced batch of settled detached runs. */
132
+ export interface SettleNotice {
133
+ readonly rows: readonly SettleRow[];
134
+ }
135
+
136
+ /** The one sentence that keeps a status notice from reading as an instruction. */
137
+ export const STATUS_ONLY_NOTE = "These are status notices; nothing is required.";
138
+
139
+ export const settleHeadline = (count: number): string =>
140
+ `${count} ${count === 1 ? "run" : "runs"} settled.`;
141
+
142
+ /** `run r#2 builder failed (turn_limit): 120 turns · parent r#0` — one settled run. */
143
+ export const settleRunLine = (row: SettleRow): string =>
144
+ `run ${row.runId} ${row.definition} ${row.outcome}${failurePart(row.failure)}` +
145
+ (row.parentRunId === null ? "" : ` · parent ${row.parentRunId}`);
146
+
147
+ export const settleTailLine = (omitted: number): string => `${omitted} more settled, not listed.`;
148
+
149
+ /** The injected agent message: status only, never a command. */
150
+ export const settleAgentMessage = (notice: SettleNotice, omitted = 0): string =>
151
+ [
152
+ settleHeadline(notice.rows.length),
153
+ ...notice.rows.map(settleRunLine),
154
+ ...(omitted === 0 ? [] : [settleTailLine(omitted)]),
155
+ STATUS_ONLY_NOTE,
156
+ ].join("\n");
157
+
86
158
  /** `5 older runs not shown.` — the sentence the status tool already prints. */
87
159
  export const omittedLine = (omitted: number): string => `${omitted} older runs not shown.`;
88
160
 
@@ -56,59 +56,53 @@ export class DurableBridge extends EffectContext.Service<
56
56
  operation: (context: Context) => Promise<A>,
57
57
  ) => Effect.Effect<A, HarnessClosed | HarnessFailure>;
58
58
  readonly closed: Effect.Effect<HarnessClosed | undefined>;
59
- readonly report: (error: unknown) => Effect.Effect<void>;
60
59
  }
61
60
  >()("@ftrdotdev/pi-delegates/runtime/bridge/DurableBridge") {
62
61
  static readonly layer = (calls: HarnessCalls): Layer.Layer<DurableBridge> =>
63
- Layer.effect(
64
- DurableBridge,
65
- Effect.gen(function* () {
66
- const closedRef = yield* Ref.make<HarnessClosed | undefined>(undefined);
67
-
68
- const call = <A>(
69
- operation: (context: Context) => Promise<A>,
70
- ): Effect.Effect<A, HarnessClosed | HarnessFailure> =>
71
- Effect.scoped(
72
- Effect.gen(function* () {
73
- const alreadyClosed = yield* Ref.get(closedRef);
74
- if (alreadyClosed !== undefined) return yield* alreadyClosed;
62
+ Layer.effect(DurableBridge, makeBridge(calls));
63
+ }
75
64
 
76
- // The enclosing scope owns the controller: it aborts when the call settles or interrupts.
77
- const signal = yield* Effect.abortSignal;
65
+ /** The bridge's program; `layer` is the only public way to build it. */
66
+ const makeBridge = (calls: HarnessCalls): Effect.Effect<DurableBridge["Service"]> =>
67
+ Effect.gen(function* () {
68
+ const closedRef = yield* Ref.make<HarnessClosed | undefined>(undefined);
78
69
 
79
- const attempt: Effect.Effect<A, HarnessClosed | HarnessFailure> = Effect.tryPromise({
80
- try: () => calls.call(operation, signal),
81
- catch: (error): HarnessClosed | HarnessFailure =>
82
- isFatal(error)
83
- ? HarnessClosed.make({ reason: fatalReason(error) })
84
- : HarnessFailure.make({ reason: fatalReason(error), cause: error }),
85
- }).pipe(
86
- Effect.catchTag("HarnessClosed", (failure) =>
87
- Effect.gen(function* () {
88
- const current = yield* Ref.modify(closedRef, (value) =>
89
- value === undefined ? [failure, failure] : [value, value],
90
- );
91
- if (current === failure) calls.report?.(failure);
92
- return yield* current;
93
- }),
94
- ),
95
- );
96
- return yield* attempt;
97
- }),
98
- );
70
+ const call = <A>(
71
+ operation: (context: Context) => Promise<A>,
72
+ ): Effect.Effect<A, HarnessClosed | HarnessFailure> =>
73
+ Effect.scoped(
74
+ Effect.gen(function* () {
75
+ const alreadyClosed = yield* Ref.get(closedRef);
76
+ if (alreadyClosed !== undefined) return yield* alreadyClosed;
99
77
 
100
- const closed: Effect.Effect<HarnessClosed | undefined> = Ref.get(closedRef);
78
+ // The enclosing scope owns the controller: it aborts when the call settles or interrupts.
79
+ const signal = yield* Effect.abortSignal;
101
80
 
102
- const report = (error: unknown): Effect.Effect<void> =>
103
- Effect.sync(() => {
104
- calls.report?.(error);
105
- });
81
+ const attempt: Effect.Effect<A, HarnessClosed | HarnessFailure> = Effect.tryPromise({
82
+ try: () => calls.call(operation, signal),
83
+ catch: (error): HarnessClosed | HarnessFailure =>
84
+ isFatal(error)
85
+ ? HarnessClosed.make({ reason: fatalReason(error) })
86
+ : HarnessFailure.make({ reason: fatalReason(error), cause: error }),
87
+ }).pipe(
88
+ Effect.catchTag("HarnessClosed", (failure) =>
89
+ Effect.gen(function* () {
90
+ const current = yield* Ref.modify(closedRef, (value) =>
91
+ value === undefined ? [failure, failure] : [value, value],
92
+ );
93
+ if (current === failure) calls.report?.(failure);
94
+ return yield* current;
95
+ }),
96
+ ),
97
+ );
98
+ return yield* attempt;
99
+ }),
100
+ );
106
101
 
107
- return DurableBridge.of({ call, closed, report });
108
- }),
109
- );
110
- }
102
+ const closed: Effect.Effect<HarnessClosed | undefined> = Ref.get(closedRef);
111
103
 
104
+ return DurableBridge.of({ call, closed });
105
+ });
112
106
  /** Canonical JSON: object keys sorted, arrays in order. */
113
107
  export const stableJson = (value: unknown): string => {
114
108
  const canonical = (input: unknown): unknown => {
@@ -1,5 +1,5 @@
1
1
  import { afterEach, assert, beforeEach, it, vi } from "@effect/vitest";
2
- import { systemTimers } from "./timers.ts";
2
+ import { systemTimers } from "./clock.ts";
3
3
 
4
4
  beforeEach(() => {
5
5
  vi.useFakeTimers();
@@ -0,0 +1,31 @@
1
+ import { Context, Layer } from "effect";
2
+
3
+ /** Injectable timers, so orchestration tests never sleep on wall-clock time. */
4
+ export interface Timers {
5
+ setTimeout(callback: () => void, ms: number): unknown;
6
+ clearTimeout(handle: unknown): void;
7
+ }
8
+
9
+ export const systemTimers: Timers = {
10
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
11
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
12
+ };
13
+
14
+ /** The session's clock: the host's `now`, shared by the domain and the harness. */
15
+ export class ClockService extends Context.Service<ClockService, () => number>()(
16
+ "@ftrdotdev/pi-delegates/runtime/clock/ClockService",
17
+ ) {
18
+ /** The host's `now`, as the one clock every seam reads. */
19
+ static layer(now: () => number): Layer.Layer<ClockService> {
20
+ return Layer.succeed(ClockService, now);
21
+ }
22
+ }
23
+
24
+ /** The session's one timer source, shared by the harness and every wait. */
25
+ export class TimersService extends Context.Service<TimersService, Timers>()(
26
+ "@ftrdotdev/pi-delegates/runtime/clock/TimersService",
27
+ ) {
28
+ static layer(timers: Timers): Layer.Layer<TimersService> {
29
+ return Layer.succeed(TimersService, timers);
30
+ }
31
+ }
@@ -1,12 +1,10 @@
1
- import { mkdtemp, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
1
  import { assert, it } from "@effect/vitest";
2
+ import { join, makeTempDir, writeText } from "../../test-support/platform.ts";
5
3
  import { DEFAULTS, readDelegatesConfig } from "./config.ts";
6
4
 
7
5
  it("delegates.json overrides the caps and default turn limit", async () => {
8
- const agentDir = await mkdtemp(join(tmpdir(), "delegates-config-"));
9
- await writeFile(
6
+ const agentDir = await makeTempDir("delegates-config-");
7
+ await writeText(
10
8
  join(agentDir, "delegates.json"),
11
9
  JSON.stringify({
12
10
  caps: { laneCap: 2, sessionCeiling: 3 },
@@ -17,6 +15,7 @@ it("delegates.json overrides the caps and default turn limit", async () => {
17
15
  laneCap: 2,
18
16
  sessionCeiling: 3,
19
17
  maxTurns: 7,
18
+ maxTurnsCeiling: 400,
20
19
  launchWaitMs: 1000,
21
20
  diagnostics: [],
22
21
  });
@@ -30,9 +29,9 @@ it("an absent file yields the defaults", () => {
30
29
  });
31
30
 
32
31
  it("a malformed file yields the defaults plus one diagnostic naming the path", async () => {
33
- const agentDir = await mkdtemp(join(tmpdir(), "delegates-config-"));
32
+ const agentDir = await makeTempDir("delegates-config-");
34
33
  const path = join(agentDir, "delegates.json");
35
- await writeFile(path, "{ not json");
34
+ await writeText(path, "{ not json");
36
35
  const config = readDelegatesConfig(agentDir);
37
36
  assert.strictEqual(config.laneCap, DEFAULTS.laneCap);
38
37
  assert.strictEqual(config.sessionCeiling, DEFAULTS.sessionCeiling);
@@ -42,3 +41,23 @@ it("a malformed file yields the defaults plus one diagnostic naming the path", a
42
41
  assert.strictEqual(config.diagnostics[0]?.code, "config.invalid_json");
43
42
  assert.ok(config.diagnostics[0]?.detail.includes(path), String(config.diagnostics[0]?.detail));
44
43
  });
44
+
45
+ it("the default budget is 120 and the ceiling 400", () => {
46
+ const config = readDelegatesConfig("/does/not/exist");
47
+ assert.strictEqual(config.maxTurns, 120);
48
+ assert.strictEqual(config.maxTurnsCeiling, 400);
49
+ assert.deepStrictEqual(config.diagnostics, []);
50
+ });
51
+
52
+ it("an unusable caps value falls back with one diagnostic", () => {
53
+ const config = readDelegatesConfig("/agent", () =>
54
+ JSON.stringify({ caps: { maxTurns: 0 }, defaults: { maxTurns: "many" } }),
55
+ );
56
+ assert.strictEqual(config.maxTurnsCeiling, DEFAULTS.maxTurnsCeiling);
57
+ assert.strictEqual(config.maxTurns, DEFAULTS.maxTurns);
58
+ const invalid = config.diagnostics.filter((entry) => entry.code === "config.invalid_value");
59
+ assert.strictEqual(invalid.length, 2);
60
+ const details = invalid.map((entry) => entry.detail).join("\n");
61
+ assert.ok(details.includes("caps.maxTurns"), details);
62
+ assert.ok(details.includes("defaults.maxTurns"), details);
63
+ });
@@ -12,7 +12,10 @@ export interface ConfigDiagnostic {
12
12
  export interface DelegatesConfig {
13
13
  readonly laneCap: number;
14
14
  readonly sessionCeiling: number;
15
+ /** The budget a child gets when no level declares one. */
15
16
  readonly maxTurns: number;
17
+ /** The one ceiling every resolved budget is clamped to. */
18
+ readonly maxTurnsCeiling: number;
16
19
  readonly launchWaitMs: number;
17
20
  readonly diagnostics: readonly ConfigDiagnostic[];
18
21
  }
@@ -20,7 +23,8 @@ export interface DelegatesConfig {
20
23
  export const DEFAULTS: Omit<DelegatesConfig, "diagnostics"> = {
21
24
  laneCap: 4,
22
25
  sessionCeiling: 8,
23
- maxTurns: 40,
26
+ maxTurns: 120,
27
+ maxTurnsCeiling: 400,
24
28
  launchWaitMs: 600_000,
25
29
  };
26
30
 
@@ -81,6 +85,7 @@ export const readDelegatesConfig = (
81
85
  laneCap: pick(caps.laneCap, DEFAULTS.laneCap, "caps.laneCap"),
82
86
  sessionCeiling: pick(caps.sessionCeiling, DEFAULTS.sessionCeiling, "caps.sessionCeiling"),
83
87
  maxTurns: pick(defaults.maxTurns, DEFAULTS.maxTurns, "defaults.maxTurns"),
88
+ maxTurnsCeiling: pick(caps.maxTurns, DEFAULTS.maxTurnsCeiling, "caps.maxTurns"),
84
89
  launchWaitMs: pick(defaults.launchWaitMs, DEFAULTS.launchWaitMs, "defaults.launchWaitMs"),
85
90
  diagnostics,
86
91
  };
@@ -1,29 +1,27 @@
1
- import { mkdtemp, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
1
  import { assert, it } from "@effect/vitest";
2
+ import { join, makeTempDir, writeText } from "../../test-support/platform.ts";
5
3
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
6
4
  import { getOrThrow } from "@earendil-works/pi-durable/env";
7
5
  import { conversationEnv } from "./execution-env.ts";
8
6
 
9
7
  it("a conversation reads the file its cwd names", async () => {
10
- const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
11
- await writeFile(join(dir, "note.txt"), "hello\n", "utf8");
8
+ const dir = await makeTempDir("delegates-env-");
9
+ await writeText(join(dir, "note.txt"), "hello\n");
12
10
  const env = conversationEnv("/elsewhere")({ cwd: dir });
13
11
  const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
14
12
  assert.strictEqual(text, "hello\n");
15
13
  });
16
14
 
17
15
  it("a conversation without a cwd falls back to the session cwd", async () => {
18
- const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
19
- await writeFile(join(dir, "note.txt"), "fallback\n", "utf8");
16
+ const dir = await makeTempDir("delegates-env-");
17
+ await writeText(join(dir, "note.txt"), "fallback\n");
20
18
  const env = conversationEnv(dir)({});
21
19
  const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
22
20
  assert.strictEqual(text, "fallback\n");
23
21
  });
24
22
 
25
23
  it("a conversation runs a shell command in its cwd", async () => {
26
- const dir = await mkdtemp(join(tmpdir(), "delegates-env-"));
24
+ const dir = await makeTempDir("delegates-env-");
27
25
  const env = conversationEnv("/elsewhere")({ cwd: dir });
28
26
  assert.strictEqual(env.cwd, dir);
29
27
  const chunks: string[] = [];
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
2
2
  import { Effect } from "effect";
3
3
  import { throws } from "../../test-support/assertions.ts";
4
4
  import type { AdmissionHost } from "../domain/orchestration/admission.ts";
5
+ import type { SkillsCatalogue } from "../domain/skills.ts";
5
6
  import { WORKFLOW_SECTION_KEY, refusingSandbox } from "../domain/orchestration/workflow-section.ts";
6
7
  import {
7
8
  CODING_EXTENSION,
@@ -12,16 +13,15 @@ import {
12
13
  SKILLS_EXTENSION,
13
14
  QUESTIONS_EXTENSION,
14
15
  } from "../domain/names.ts";
15
- import type { SkillsService } from "../domain/skills.ts";
16
16
  import { createDelegatesRegistry } from "./extensions.ts";
17
17
 
18
- const skills: SkillsService = {
18
+ const skills: SkillsCatalogue["Service"] = {
19
19
  all: () => [],
20
20
  find: () => undefined,
21
21
  resolve: () => [],
22
22
  render: () => "",
23
- diagnostics: () => [],
24
- reload: Effect.void,
23
+ diagnostics: Effect.succeed([]),
24
+ reload: Effect.succeed([]),
25
25
  };
26
26
 
27
27
  const admission: AdmissionHost = {