@ftrdotdev/pi-delegates 0.0.0-stage → 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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,131 @@
1
+ // Each test builds its own harness double, so the bridge layer is provided at
2
+ // the test boundary; there is no shared layer to hoist.
3
+ // oxlint-disable effecttsgo/strict-effect-provide
4
+ import type { Context } from "@earendil-works/chord/context";
5
+ import { assert, it } from "@effect/vitest";
6
+ import { SessionFailed } from "@earendil-works/pi-durable";
7
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
8
+ import { Deferred, Effect, Fiber } from "effect";
9
+ import { sessionIdArbitrary, singleRequestArbitrary } from "../../test-support/arbitraries.ts";
10
+ import {
11
+ DurableBridge,
12
+ HarnessClosed,
13
+ HarnessFailure,
14
+ requestId,
15
+ type HarnessCalls,
16
+ } from "./bridge.ts";
17
+ import { operationContext } from "./context.ts";
18
+
19
+ it.effect("a bridged call returns the harness value inside the effect", () => {
20
+ let recorded: Context | undefined;
21
+ let abortedDuringCall: boolean | undefined;
22
+ const calls: HarnessCalls = {
23
+ call: async (operation, signal) => {
24
+ recorded = operationContext(signal);
25
+ abortedDuringCall = recorded.abortSignal?.aborted;
26
+ return operation(recorded);
27
+ },
28
+ };
29
+ return Effect.gen(function* () {
30
+ const bridge = yield* DurableBridge;
31
+ const value = yield* bridge.call(async () => 42);
32
+ assert.strictEqual(value, 42);
33
+ assert.ok(recorded?.abortSignal instanceof AbortSignal);
34
+ assert.strictEqual(abortedDuringCall, false);
35
+ }).pipe(Effect.provide(DurableBridge.layer(calls)));
36
+ });
37
+
38
+ it.effect("interrupting the effect aborts the operation's signal once", () => {
39
+ let aborts = 0;
40
+ const entered = Deferred.makeUnsafe<void>();
41
+ const calls: HarnessCalls = {
42
+ call: <A>(_operation: (context: Context) => Promise<A>, signal?: AbortSignal) =>
43
+ new Promise<A>((resolve) => {
44
+ signal?.addEventListener("abort", () => {
45
+ aborts += 1;
46
+ resolve("aborted" as A);
47
+ });
48
+ Deferred.doneUnsafe(entered, Effect.void);
49
+ }),
50
+ };
51
+ return Effect.gen(function* () {
52
+ const bridge = yield* DurableBridge;
53
+ const fiber = yield* bridge.call(() => Promise.resolve("")).pipe(Effect.forkChild);
54
+ yield* Deferred.await(entered);
55
+ yield* Fiber.interrupt(fiber);
56
+ assert.strictEqual(aborts, 1);
57
+ }).pipe(Effect.provide(DurableBridge.layer(calls)));
58
+ });
59
+
60
+ it.effect("a storage failure reports one closed state and short-circuits", () => {
61
+ let callCalls = 0;
62
+ const reported: unknown[] = [];
63
+ const calls: HarnessCalls = {
64
+ call: async () => {
65
+ callCalls += 1;
66
+ throw new SessionFailed(new Error("disk gone"));
67
+ },
68
+ report: (error) => reported.push(error),
69
+ };
70
+ return Effect.gen(function* () {
71
+ const bridge = yield* DurableBridge;
72
+ const first = yield* bridge.call(async () => 1).pipe(Effect.flip);
73
+ assert.ok(first instanceof HarnessClosed);
74
+ assert.strictEqual(first.reason, "disk gone");
75
+ const closed = yield* bridge.closed;
76
+ assert.strictEqual(closed?.reason, "disk gone");
77
+ const second = yield* bridge.call(async () => 2).pipe(Effect.flip);
78
+ assert.strictEqual(second.reason, "disk gone");
79
+ assert.strictEqual(callCalls, 1);
80
+ assert.strictEqual(reported.length, 1);
81
+ }).pipe(Effect.provide(DurableBridge.layer(calls)));
82
+ });
83
+
84
+ it.effect("a non-fatal rejection fails once and leaves the bridge open", () => {
85
+ let callCalls = 0;
86
+ const reported: unknown[] = [];
87
+ const calls: HarnessCalls = {
88
+ call: async () => {
89
+ callCalls += 1;
90
+ if (callCalls === 1) throw new Error("malformed operation");
91
+ return 2 as never;
92
+ },
93
+ report: (error) => reported.push(error),
94
+ };
95
+ return Effect.gen(function* () {
96
+ const bridge = yield* DurableBridge;
97
+ const first = yield* bridge.call(async () => 1).pipe(Effect.flip);
98
+ assert.ok(first instanceof HarnessFailure);
99
+ assert.strictEqual(first.reason, "malformed operation");
100
+ assert.ok(first.cause instanceof Error);
101
+ const closed = yield* bridge.closed;
102
+ assert.strictEqual(closed, undefined);
103
+ const second = yield* bridge.call(async () => 2);
104
+ assert.strictEqual(second, 2);
105
+ assert.strictEqual(callCalls, 2);
106
+ assert.strictEqual(reported.length, 0);
107
+ }).pipe(Effect.provide(DurableBridge.layer(calls)));
108
+ });
109
+
110
+ it("the same launch identity produces the same request id", () => {
111
+ const request = { kind: "single", agent: "scout", task: "look around" };
112
+ assert.strictEqual(requestId("s-1", request), requestId("s-1", request));
113
+ assert.notStrictEqual(
114
+ requestId("s-1", request),
115
+ requestId("s-1", { ...request, agent: "builder" }),
116
+ );
117
+ assert.notStrictEqual(requestId("s-1", request), requestId("s-2", request));
118
+ assert.match(requestId("s-1", request), /^run:s-1:[0-9a-f]{16}$/);
119
+ });
120
+
121
+ it.prop(
122
+ "an identity is deterministic and session-scoped",
123
+ { sessionId: sessionIdArbitrary, request: singleRequestArbitrary },
124
+ ({ sessionId, request }) => {
125
+ const first = requestId(sessionId, request);
126
+ assert.strictEqual(first, requestId(sessionId, { ...request }));
127
+ assert.notStrictEqual(first, requestId(`${sessionId}x`, request));
128
+ if (request.task.length >= 4) assert.ok(!first.includes(request.task), first);
129
+ },
130
+ { arbitrary: { runs: PROPERTY_RUNS } },
131
+ );
@@ -0,0 +1,128 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import { ReadOnlySession, SessionFailed } from "@earendil-works/pi-durable";
3
+ import { createHash } from "node:crypto";
4
+ import { Context as EffectContext, Effect, Layer, Predicate, Ref, Schema } from "effect";
5
+
6
+ export type HarnessCalls = {
7
+ readonly call: <A>(
8
+ operation: (context: Context) => Promise<A>,
9
+ signal?: AbortSignal,
10
+ ) => Promise<A>;
11
+ /** A host hook for the one failure that closes the bridge; never throws. */
12
+ readonly report?: (error: unknown) => void;
13
+ };
14
+
15
+ export class HarnessClosed extends Schema.TaggedError<
16
+ HarnessClosed,
17
+ { readonly brand: unique symbol }
18
+ >()("HarnessClosed", {
19
+ reason: Schema.String,
20
+ }) {}
21
+
22
+ /** A rejection that leaves the harness usable: the call failed, the bridge did not close. */
23
+ export class HarnessFailure extends Schema.TaggedError<
24
+ HarnessFailure,
25
+ { readonly brand: unique symbol }
26
+ >()("HarnessFailure", {
27
+ reason: Schema.String,
28
+ cause: Schema.Unknown,
29
+ }) {}
30
+
31
+ /**
32
+ * The two fatal durable errors: `SessionFailed` ends the session and `ReadOnlySession` refuses
33
+ * writes. Every other rejection, `StorageRequestError` included, fails only that call.
34
+ */
35
+ const isFatal = (error: unknown): boolean =>
36
+ error instanceof SessionFailed || error instanceof ReadOnlySession;
37
+
38
+ const fatalReason = (error: unknown): string => {
39
+ if (error instanceof SessionFailed && error.cause !== undefined) return fatalReason(error.cause);
40
+ if (error instanceof Error) return error.message;
41
+ if (Predicate.isObject(error)) {
42
+ const message = error.message;
43
+ if (typeof message === "string") return message;
44
+ }
45
+ return String(error);
46
+ };
47
+
48
+ /**
49
+ * The single asynchronous seam between the Effect domain and the durable
50
+ * harness. Nothing else calls the harness directly.
51
+ */
52
+ export class DurableBridge extends EffectContext.Service<
53
+ DurableBridge,
54
+ {
55
+ readonly call: <A>(
56
+ operation: (context: Context) => Promise<A>,
57
+ ) => Effect.Effect<A, HarnessClosed | HarnessFailure>;
58
+ readonly closed: Effect.Effect<HarnessClosed | undefined>;
59
+ }
60
+ >()("@ftrdotdev/pi-delegates/runtime/bridge/DurableBridge") {
61
+ static readonly layer = (calls: HarnessCalls): Layer.Layer<DurableBridge> =>
62
+ Layer.effect(DurableBridge, makeBridge(calls));
63
+ }
64
+
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);
69
+
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;
77
+
78
+ // The enclosing scope owns the controller: it aborts when the call settles or interrupts.
79
+ const signal = yield* Effect.abortSignal;
80
+
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
+ );
101
+
102
+ const closed: Effect.Effect<HarnessClosed | undefined> = Ref.get(closedRef);
103
+
104
+ return DurableBridge.of({ call, closed });
105
+ });
106
+ /** Canonical JSON: object keys sorted, arrays in order. */
107
+ export const stableJson = (value: unknown): string => {
108
+ const canonical = (input: unknown): unknown => {
109
+ if (Array.isArray(input)) return input.map(canonical);
110
+ if (Predicate.isObject(input)) {
111
+ return Object.fromEntries(
112
+ Object.keys(input)
113
+ .sort()
114
+ .map((key) => [key, canonical(input[key])]),
115
+ );
116
+ }
117
+ return input;
118
+ };
119
+ return JSON.stringify(canonical(value));
120
+ };
121
+
122
+ /**
123
+ * Content-addressed: the same request in the same session maps to one
124
+ * identity. The attempt number is added by `claimLaunch`, which reuses an
125
+ * unfinished run and starts a new attempt once the run is terminal.
126
+ */
127
+ export const requestId = (sessionId: string, request: object): string =>
128
+ `run:${sessionId}:${createHash("sha256").update(stableJson(request)).digest("hex").slice(0, 16)}`;
@@ -0,0 +1,31 @@
1
+ import { afterEach, assert, beforeEach, it, vi } from "@effect/vitest";
2
+ import { systemTimers } from "./clock.ts";
3
+
4
+ beforeEach(() => {
5
+ vi.useFakeTimers();
6
+ });
7
+
8
+ afterEach(() => {
9
+ vi.useRealTimers();
10
+ });
11
+
12
+ it("systemTimers runs the callback at the delay, not before", () => {
13
+ let fired = 0;
14
+ systemTimers.setTimeout(() => {
15
+ fired += 1;
16
+ }, 100);
17
+ vi.advanceTimersByTime(99);
18
+ assert.strictEqual(fired, 0);
19
+ vi.advanceTimersByTime(1);
20
+ assert.strictEqual(fired, 1);
21
+ });
22
+
23
+ it("clearTimeout cancels the armed callback", () => {
24
+ let fired = 0;
25
+ const handle = systemTimers.setTimeout(() => {
26
+ fired += 1;
27
+ }, 50);
28
+ systemTimers.clearTimeout(handle);
29
+ vi.advanceTimersByTime(1_000);
30
+ assert.strictEqual(fired, 0);
31
+ });
@@ -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
+ }
@@ -0,0 +1,63 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { join, makeTempDir, writeText } from "../../test-support/platform.ts";
3
+ import { DEFAULTS, readDelegatesConfig } from "./config.ts";
4
+
5
+ it("delegates.json overrides the caps and default turn limit", async () => {
6
+ const agentDir = await makeTempDir("delegates-config-");
7
+ await writeText(
8
+ join(agentDir, "delegates.json"),
9
+ JSON.stringify({
10
+ caps: { laneCap: 2, sessionCeiling: 3 },
11
+ defaults: { maxTurns: 7, launchWaitMs: 1000 },
12
+ }),
13
+ );
14
+ assert.deepStrictEqual(readDelegatesConfig(agentDir), {
15
+ laneCap: 2,
16
+ sessionCeiling: 3,
17
+ maxTurns: 7,
18
+ maxTurnsCeiling: 400,
19
+ launchWaitMs: 1000,
20
+ diagnostics: [],
21
+ });
22
+ });
23
+
24
+ it("an absent file yields the defaults", () => {
25
+ assert.deepStrictEqual(readDelegatesConfig("/does/not/exist"), {
26
+ ...DEFAULTS,
27
+ diagnostics: [],
28
+ });
29
+ });
30
+
31
+ it("a malformed file yields the defaults plus one diagnostic naming the path", async () => {
32
+ const agentDir = await makeTempDir("delegates-config-");
33
+ const path = join(agentDir, "delegates.json");
34
+ await writeText(path, "{ not json");
35
+ const config = readDelegatesConfig(agentDir);
36
+ assert.strictEqual(config.laneCap, DEFAULTS.laneCap);
37
+ assert.strictEqual(config.sessionCeiling, DEFAULTS.sessionCeiling);
38
+ assert.strictEqual(config.maxTurns, DEFAULTS.maxTurns);
39
+ assert.strictEqual(config.launchWaitMs, DEFAULTS.launchWaitMs);
40
+ assert.strictEqual(config.diagnostics.length, 1);
41
+ assert.strictEqual(config.diagnostics[0]?.code, "config.invalid_json");
42
+ assert.ok(config.diagnostics[0]?.detail.includes(path), String(config.diagnostics[0]?.detail));
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
+ });
@@ -0,0 +1,92 @@
1
+ import { Predicate } from "effect";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ export interface ConfigDiagnostic {
6
+ /** A stable identifier: `config.<problem>`. */
7
+ readonly code: string;
8
+ /** Display-only text that names the file and the problem. */
9
+ readonly detail: string;
10
+ }
11
+
12
+ export interface DelegatesConfig {
13
+ readonly laneCap: number;
14
+ readonly sessionCeiling: number;
15
+ /** The budget a child gets when no level declares one. */
16
+ readonly maxTurns: number;
17
+ /** The one ceiling every resolved budget is clamped to. */
18
+ readonly maxTurnsCeiling: number;
19
+ readonly launchWaitMs: number;
20
+ readonly diagnostics: readonly ConfigDiagnostic[];
21
+ }
22
+
23
+ export const DEFAULTS: Omit<DelegatesConfig, "diagnostics"> = {
24
+ laneCap: 4,
25
+ sessionCeiling: 8,
26
+ maxTurns: 120,
27
+ maxTurnsCeiling: 400,
28
+ launchWaitMs: 600_000,
29
+ };
30
+
31
+ const isPositiveInteger = (value: unknown): value is number =>
32
+ typeof value === "number" && Number.isInteger(value) && value > 0;
33
+
34
+ /**
35
+ * Reads `<agentDir>/delegates.json`; never throws, reports problems as
36
+ * diagnostics. `read` is injectable so tests need no file system.
37
+ */
38
+ export const readDelegatesConfig = (
39
+ agentDir: string,
40
+ read: (path: string) => string | undefined = (path) => {
41
+ try {
42
+ return readFileSync(path, "utf8");
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ },
47
+ ): DelegatesConfig => {
48
+ const path = join(agentDir, "delegates.json");
49
+ const text = read(path);
50
+ if (text === undefined) return { ...DEFAULTS, diagnostics: [] };
51
+
52
+ let parsed: unknown;
53
+ try {
54
+ parsed = JSON.parse(text);
55
+ } catch (error) {
56
+ return {
57
+ ...DEFAULTS,
58
+ diagnostics: [
59
+ { code: "config.invalid_json", detail: `${path} is not valid JSON: ${String(error)}` },
60
+ ],
61
+ };
62
+ }
63
+
64
+ if (!Predicate.isObject(parsed)) {
65
+ return {
66
+ ...DEFAULTS,
67
+ diagnostics: [{ code: "config.not_object", detail: `${path} must hold a JSON object.` }],
68
+ };
69
+ }
70
+
71
+ const caps = Predicate.isObject(parsed.caps) ? parsed.caps : {};
72
+ const defaults = Predicate.isObject(parsed.defaults) ? parsed.defaults : {};
73
+ const diagnostics: ConfigDiagnostic[] = [];
74
+ const pick = (value: unknown, fallback: number, name: string): number => {
75
+ if (value === undefined) return fallback;
76
+ if (isPositiveInteger(value)) return value;
77
+ diagnostics.push({
78
+ code: "config.invalid_value",
79
+ detail: `${path}: ${name} must be a positive integer; using ${fallback}.`,
80
+ });
81
+ return fallback;
82
+ };
83
+
84
+ return {
85
+ laneCap: pick(caps.laneCap, DEFAULTS.laneCap, "caps.laneCap"),
86
+ sessionCeiling: pick(caps.sessionCeiling, DEFAULTS.sessionCeiling, "caps.sessionCeiling"),
87
+ maxTurns: pick(defaults.maxTurns, DEFAULTS.maxTurns, "defaults.maxTurns"),
88
+ maxTurnsCeiling: pick(caps.maxTurns, DEFAULTS.maxTurnsCeiling, "caps.maxTurns"),
89
+ launchWaitMs: pick(defaults.launchWaitMs, DEFAULTS.launchWaitMs, "defaults.launchWaitMs"),
90
+ diagnostics,
91
+ };
92
+ };
@@ -0,0 +1,19 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
+ import { operationContext } from "./context.ts";
4
+
5
+ it("a call with no signal uses the background context itself", () => {
6
+ assert.strictEqual(operationContext(), BACKGROUND_CONTEXT);
7
+ assert.strictEqual(operationContext(undefined), BACKGROUND_CONTEXT);
8
+ });
9
+
10
+ it("a call with a signal carries the caller's cancellation", () => {
11
+ const controller = new AbortController();
12
+ const context = operationContext(controller.signal);
13
+
14
+ assert.notStrictEqual(context, BACKGROUND_CONTEXT);
15
+ assert.strictEqual(context.abortSignal?.aborted, false);
16
+ controller.abort();
17
+ assert.strictEqual(context.abortSignal?.aborted, true);
18
+ assert.strictEqual(BACKGROUND_CONTEXT.abortSignal, undefined);
19
+ });
@@ -0,0 +1,9 @@
1
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
+ import type { Context } from "@earendil-works/chord/context";
3
+
4
+ /**
5
+ * One place for the direction rule: outbound work uses the caller's signal.
6
+ * Cleanup that must finish runs with an unbounded context, built at the call site.
7
+ */
8
+ export const operationContext = (signal?: AbortSignal): Context =>
9
+ signal === undefined ? BACKGROUND_CONTEXT : withAbortSignal(signal, BACKGROUND_CONTEXT);
@@ -0,0 +1,33 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { join, makeTempDir, writeText } from "../../test-support/platform.ts";
3
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
4
+ import { getOrThrow } from "@earendil-works/pi-durable/env";
5
+ import { conversationEnv } from "./execution-env.ts";
6
+
7
+ it("a conversation reads the file its cwd names", async () => {
8
+ const dir = await makeTempDir("delegates-env-");
9
+ await writeText(join(dir, "note.txt"), "hello\n");
10
+ const env = conversationEnv("/elsewhere")({ cwd: dir });
11
+ const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
12
+ assert.strictEqual(text, "hello\n");
13
+ });
14
+
15
+ it("a conversation without a cwd falls back to the session cwd", async () => {
16
+ const dir = await makeTempDir("delegates-env-");
17
+ await writeText(join(dir, "note.txt"), "fallback\n");
18
+ const env = conversationEnv(dir)({});
19
+ const text = getOrThrow(await env.readTextFile(join(dir, "note.txt"), BACKGROUND_CONTEXT));
20
+ assert.strictEqual(text, "fallback\n");
21
+ });
22
+
23
+ it("a conversation runs a shell command in its cwd", async () => {
24
+ const dir = await makeTempDir("delegates-env-");
25
+ const env = conversationEnv("/elsewhere")({ cwd: dir });
26
+ assert.strictEqual(env.cwd, dir);
27
+ const chunks: string[] = [];
28
+ const result = getOrThrow(
29
+ await env.exec("echo hello", { onOutput: (text) => chunks.push(text) }, BACKGROUND_CONTEXT),
30
+ );
31
+ assert.strictEqual(result.exitCode, 0);
32
+ assert.match(chunks.join(""), /hello/);
33
+ });
@@ -0,0 +1,15 @@
1
+ import type { EnvTarget } from "@earendil-works/pi-durable";
2
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
3
+
4
+ /**
5
+ * Builds the file and shell environment of one delegate conversation.
6
+ *
7
+ * pi-durable leaves `api.env` undefined when `Harness.open` gets no `env`
8
+ * option, and then every read, write and bash tool inside a delegate fails with
9
+ * "No execution environment is configured". The conversation's own `cwd` wins;
10
+ * the session cwd is the fallback shown to every local environment.
11
+ */
12
+ export const conversationEnv =
13
+ (fallbackCwd: string) =>
14
+ (target: Pick<EnvTarget, "cwd">): NodeExecutionEnv =>
15
+ new NodeExecutionEnv({ cwd: target.cwd ?? fallbackCwd });
@@ -0,0 +1,86 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import { throws } from "../../test-support/assertions.ts";
4
+ import type { AdmissionHost } from "../domain/orchestration/admission.ts";
5
+ import type { SkillsCatalogue } from "../domain/skills.ts";
6
+ import { WORKFLOW_SECTION_KEY, refusingSandbox } from "../domain/orchestration/workflow-section.ts";
7
+ import {
8
+ CODING_EXTENSION,
9
+ CODEMODE_EXTENSION,
10
+ GATE_GUARD_EXTENSION,
11
+ RUN_TASK_EXTENSION,
12
+ RUNS_EXTENSION,
13
+ SKILLS_EXTENSION,
14
+ QUESTIONS_EXTENSION,
15
+ } from "../domain/names.ts";
16
+ import { createDelegatesRegistry } from "./extensions.ts";
17
+
18
+ const skills: SkillsCatalogue["Service"] = {
19
+ all: () => [],
20
+ find: () => undefined,
21
+ resolve: () => [],
22
+ render: () => "",
23
+ diagnostics: Effect.succeed([]),
24
+ reload: Effect.succeed([]),
25
+ };
26
+
27
+ const admission: AdmissionHost = {
28
+ inspect: () => Promise.reject(new Error("the install must not inspect the harness")),
29
+ caps: () => ({ laneCap: 1, sessionCeiling: 1 }),
30
+ pollMs: 10,
31
+ };
32
+
33
+ /** One installation over the refusing sandbox, so no worker starts. */
34
+ const install = () => createDelegatesRegistry({ admission, skills, sandbox: refusingSandbox() });
35
+
36
+ it("the registry installs the eight extensions in contract order", () => {
37
+ const installed = install()
38
+ .registry.snapshot()
39
+ .installed()
40
+ .map((extension) => extension.name);
41
+
42
+ assert.deepStrictEqual(installed, [
43
+ CODING_EXTENSION,
44
+ SKILLS_EXTENSION,
45
+ "tool-search",
46
+ GATE_GUARD_EXTENSION,
47
+ CODEMODE_EXTENSION,
48
+ RUNS_EXTENSION,
49
+ RUN_TASK_EXTENSION,
50
+ QUESTIONS_EXTENSION,
51
+ ]);
52
+ });
53
+
54
+ it("code mode is installed before the run tools that script it", () => {
55
+ const installed = install()
56
+ .registry.snapshot()
57
+ .installed()
58
+ .map((extension) => extension.name);
59
+
60
+ assert.ok(installed.indexOf(CODEMODE_EXTENSION) < installed.indexOf(RUNS_EXTENSION));
61
+ });
62
+
63
+ it("the registry registers the run and fanout tasks themselves", () => {
64
+ const { registry, tasks } = install();
65
+ const registered = registry.snapshot().tasks();
66
+
67
+ assert.ok(registered.includes(tasks.run));
68
+ assert.ok(registered.includes(tasks.fanout));
69
+ });
70
+
71
+ it("the registry carries the skills and workflow sections", () => {
72
+ const keys = install()
73
+ .registry.snapshot()
74
+ .sections()
75
+ .map((entry) => entry.section.key);
76
+
77
+ assert.ok(keys.includes(SKILLS_EXTENSION));
78
+ assert.ok(keys.includes(WORKFLOW_SECTION_KEY));
79
+ });
80
+
81
+ it("the installation's sandbox names a failed start", () => {
82
+ throws(
83
+ () => install().sandbox.start("1", {} as never),
84
+ /workflow sandbox: this runtime runs no script/,
85
+ );
86
+ });