@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
package/src/layers.ts ADDED
@@ -0,0 +1,405 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import type { JsonValue } from "@earendil-works/chord/json";
3
+ import type { Models } from "@earendil-works/pi-ai/models";
4
+ import type { CodemodeSandboxBase } from "@earendil-works/pi-codemode/portable";
5
+ import type {
6
+ JsonObject,
7
+ SessionDocFamilyToken,
8
+ SessionDocToken,
9
+ Storage,
10
+ } from "@earendil-works/pi-durable";
11
+ import { Harness, SessionFailed } from "@earendil-works/pi-durable";
12
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
13
+ import { Context, Effect, Exit, Fiber, Layer, ManagedRuntime, Ref, Scope } from "effect";
14
+ import { createCatalogue, type DefinitionCatalogue } from "./domain/definitions.ts";
15
+ import { ModelSourceService } from "./domain/model-source.ts";
16
+ import type { HostDefaults } from "./domain/orchestration/launch.ts";
17
+ import { SkillsCatalogue, type SkillRoots } from "./domain/skills.ts";
18
+ import type { DelegatesConfig } from "./runtime/config.ts";
19
+ import { ClockService, systemTimers, TimersService, type Timers } from "./runtime/clock.ts";
20
+ import { LogSinkService, nullLogSink, type LogSink } from "./runtime/log.ts";
21
+ import { McpHostService, type McpClientFactory, type McpHost } from "./runtime/mcp.ts";
22
+ import { DurableBridge, type HarnessCalls } from "./runtime/bridge.ts";
23
+ import { makeRuntimeState } from "./runtime/runtime-state.ts";
24
+ import { operationContext } from "./runtime/context.ts";
25
+ import { reasonOf } from "./runtime/log.ts";
26
+ import type { AdmissionHost } from "./domain/orchestration/admission.ts";
27
+ import { readDelegatesConfig } from "./runtime/config.ts";
28
+ import { conversationEnv } from "./runtime/execution-env.ts";
29
+ import { logReport } from "./runtime/log.ts";
30
+ import { makeSettleSignal } from "./domain/settlement.ts";
31
+ import { WorkflowService } from "./domain/orchestration/workflow.ts";
32
+ import { createDelegatesRegistry } from "./runtime/extensions.ts";
33
+ import {
34
+ buildSessionRuntime,
35
+ isFamilyToken,
36
+ SessionRuntimeTag,
37
+ setTimerFrom,
38
+ storePathFor,
39
+ type HarnessParts,
40
+ type RuntimeHolder,
41
+ type SessionIdentity,
42
+ } from "./runtime/session.ts";
43
+ import type {
44
+ SessionGraph,
45
+ SessionGraphLayer,
46
+ SessionHandle,
47
+ SessionSeams,
48
+ } from "./runtime/handle.ts";
49
+ import { SessionCore } from "./runtime/handle.ts";
50
+ import { StorageError, StorageService } from "./runtime/storage.ts";
51
+ import {
52
+ Inspector,
53
+ type InspectorDeps,
54
+ type InspectorReadFailed,
55
+ } from "./presentation/inspector.ts";
56
+
57
+ /**
58
+ * The production inputs the session graph needs. Not an alias for the old
59
+ * override bag: no seam field (`storage`, `now`, `timers`, `log`, `skills`,
60
+ * `mcp`) lives here, so a test double has exactly one way in, and it is a
61
+ * layer.
62
+ */
63
+ export interface SessionConfig {
64
+ readonly identity: SessionIdentity;
65
+ readonly models: Models;
66
+ readonly config?: DelegatesConfig;
67
+ readonly catalogue?: DefinitionCatalogue;
68
+ /** Read at each launch, as today. */
69
+ readonly host?: () => HostDefaults;
70
+ /** Extra skill paths; the seam layer builds the roots from the identity. */
71
+ readonly skillsRoots?: readonly string[];
72
+ readonly sandbox?: CodemodeSandboxBase;
73
+ /** The runtime reads `.pi/mcp.json` only when the project is trusted. */
74
+ readonly projectTrusted?: boolean;
75
+ readonly mcpFactory?: McpClientFactory;
76
+ readonly notify?: (message: string) => void;
77
+ }
78
+
79
+ /** The roots Pi scans for skills, from the identity and the config's extra paths. */
80
+ const rootsFor = (config: SessionConfig): SkillRoots => ({
81
+ cwd: config.identity.cwd,
82
+ agentDir: config.identity.agentDir,
83
+ skillPaths: config.skillsRoots ?? [],
84
+ });
85
+
86
+ /** The named doubles a seam layer may replace: one field per seam, and nothing else. */
87
+ export interface SeamDoubles {
88
+ /** A storage instance instead of the session's sqlite file. */
89
+ readonly storage?: Storage | undefined;
90
+ readonly now?: (() => number) | undefined;
91
+ readonly timers?: Timers | undefined;
92
+ readonly log?: LogSink | undefined;
93
+ /** The full roots, when a test scans a directory that is not the identity's. */
94
+ readonly skills?: SkillRoots | undefined;
95
+ /** A connected host instead of the `mcp.json` scan. */
96
+ readonly mcp?: McpHost | undefined;
97
+ }
98
+
99
+ /**
100
+ * Every ambient seam the session reads; nothing that needs the opened harness.
101
+ * A doubled seam replaces the production default in place, so a test builds the
102
+ * same graph the entry does and every other seam stays production.
103
+ */
104
+ export const makeSessionSeams = (
105
+ config: SessionConfig,
106
+ doubles: SeamDoubles = {},
107
+ ): Layer.Layer<SessionSeams, StorageError> => {
108
+ const storage = doubles.storage;
109
+ const base = Layer.mergeAll(
110
+ StorageService.layer(
111
+ storage === undefined
112
+ ? () => openNodeSqliteStorage(storePathFor(config.identity))
113
+ : () => Promise.resolve(storage),
114
+ ),
115
+ ClockService.layer(doubles.now ?? Date.now),
116
+ TimersService.layer(doubles.timers ?? systemTimers),
117
+ LogSinkService.layer(doubles.log ?? nullLogSink),
118
+ ModelSourceService.layer(config.models, config.host),
119
+ SkillsCatalogue.layer(doubles.skills ?? rootsFor(config)),
120
+ );
121
+ const mcp =
122
+ doubles.mcp === undefined
123
+ ? McpHostService.layer({
124
+ agentDir: config.identity.agentDir,
125
+ cwd: config.identity.cwd,
126
+ sessionDir: config.identity.sessionDir,
127
+ projectTrusted: config.projectTrusted ?? false,
128
+ catalogue: config.catalogue ?? createCatalogue([]),
129
+ mcpFactory: config.mcpFactory,
130
+ notify: config.notify,
131
+ })
132
+ : McpHostService.adopt(doubles.mcp);
133
+ return mcp.pipe(Layer.provideMerge(base));
134
+ };
135
+
136
+ /**
137
+ * The open sequence up to the bridge: read the config, install the
138
+ * registry, open the harness, create the root conversation. Storage, clock,
139
+ * timers, the log sink, skills, models and the MCP host arrive as seams.
140
+ */
141
+ const openParts = (
142
+ config: SessionConfig,
143
+ current: Ref.Ref<SessionHandle | undefined>,
144
+ ): Effect.Effect<HarnessParts, never, SessionSeams> =>
145
+ Effect.gen(function* () {
146
+ const storage = yield* StorageService;
147
+ const now = yield* ClockService;
148
+ const timers = yield* TimersService;
149
+ const log = yield* LogSinkService;
150
+ const skills = yield* SkillsCatalogue;
151
+ const modelSource = yield* ModelSourceService;
152
+ const mcp = yield* McpHostService;
153
+ const delegatesConfig = config.config ?? readDelegatesConfig(config.identity.agentDir);
154
+ for (const diagnostic of delegatesConfig.diagnostics) {
155
+ log.write("warn", diagnostic.code, { detail: diagnostic.detail });
156
+ }
157
+ for (const diagnostic of yield* skills.diagnostics) {
158
+ log.write("warn", diagnostic.code, { detail: diagnostic.detail });
159
+ }
160
+
161
+ const { state, setState, onState } = makeRuntimeState();
162
+ const settle = makeSettleSignal();
163
+
164
+ const holder: RuntimeHolder = {};
165
+ const catalogue = config.catalogue ?? createCatalogue([]);
166
+ const admission: AdmissionHost = {
167
+ inspect: () => {
168
+ if (holder.runtime === undefined) {
169
+ return Promise.reject(new Error("the harness is not open"));
170
+ }
171
+ return holder.runtime.harness.inspect(BACKGROUND_CONTEXT);
172
+ },
173
+ caps: () => ({
174
+ laneCap: delegatesConfig.laneCap,
175
+ sessionCeiling: delegatesConfig.sessionCeiling,
176
+ }),
177
+ pollMs: 1000,
178
+ };
179
+ const installed = createDelegatesRegistry({
180
+ admission,
181
+ skills,
182
+ ...(config.sandbox === undefined ? {} : { sandbox: config.sandbox }),
183
+ mcp,
184
+ log,
185
+ timers,
186
+ mcpPresence: () => holder.runtime?.mcpPresence,
187
+ session: current,
188
+ settle,
189
+ });
190
+
191
+ let opened: Harness | undefined;
192
+ const openedParts = yield* Effect.tryPromise({
193
+ try: () =>
194
+ Harness.open(
195
+ storage,
196
+ {
197
+ models: modelSource.models,
198
+ registry: installed.registry,
199
+ env: conversationEnv(config.identity.cwd),
200
+ now,
201
+ setTimer: setTimerFrom(timers),
202
+ onReport: (report) => {
203
+ logReport(log, report);
204
+ if (report.kind === "storage_failed") {
205
+ setState({ kind: "failing", reason: reasonOf(report.error) });
206
+ }
207
+ },
208
+ },
209
+ BACKGROUND_CONTEXT,
210
+ ),
211
+ catch: (cause) => reasonOf(cause),
212
+ }).pipe(
213
+ Effect.tap((harness) =>
214
+ Effect.sync(() => {
215
+ opened = harness;
216
+ }),
217
+ ),
218
+ Effect.flatMap((harness) =>
219
+ Effect.promise(() =>
220
+ harness.root(BACKGROUND_CONTEXT, { agent: { extensions: [], tools: [] } }),
221
+ ).pipe(Effect.map((root) => ({ harness, root }))),
222
+ ),
223
+ // Both the harness and the registry's sandbox must stop when the open fails.
224
+ Effect.onError(() =>
225
+ Effect.promise(async () => {
226
+ if (opened === undefined) await storage.close(BACKGROUND_CONTEXT).catch(() => undefined);
227
+ else await opened.close(BACKGROUND_CONTEXT).catch(() => undefined);
228
+ await installed.sandbox.close().catch(() => undefined);
229
+ }),
230
+ ),
231
+ Effect.orDie,
232
+ );
233
+ const openedHarness = openedParts.harness;
234
+ const openedRoot = openedParts.root;
235
+ const calls: HarnessCalls = {
236
+ call: (operation, signal) => {
237
+ const now = state();
238
+ if (now.kind === "failing" || now.kind === "closed") {
239
+ return Promise.reject(new SessionFailed(new Error(now.reason ?? "the harness closed")));
240
+ }
241
+ return operation(operationContext(signal));
242
+ },
243
+ };
244
+
245
+ const snapshot = <T extends JsonObject, I extends JsonValue>(
246
+ token: SessionDocToken<T> | SessionDocFamilyToken<T, I>,
247
+ key?: string,
248
+ ): Promise<Readonly<T> | undefined> => {
249
+ if (isFamilyToken(token)) {
250
+ if (key === undefined) {
251
+ return Promise.reject(new Error("A family document token needs a key."));
252
+ }
253
+ return openedHarness.snapshot(token, key, BACKGROUND_CONTEXT);
254
+ }
255
+ return openedHarness.snapshot(token, BACKGROUND_CONTEXT);
256
+ };
257
+
258
+ let closed: Promise<void> | undefined;
259
+ const close = (): Promise<void> =>
260
+ (closed ??= (async () => {
261
+ // `close` above already closed the store. The MCP host belongs to the seam
262
+ // layer, which disposes after this layer.
263
+ await openedHarness.close(BACKGROUND_CONTEXT);
264
+ await installed.sandbox.close().catch(() => undefined);
265
+ })());
266
+
267
+ return {
268
+ storePath: storePathFor(config.identity),
269
+ sessionId: config.identity.sessionId,
270
+ harness: openedHarness,
271
+ root: openedRoot,
272
+ calls,
273
+ config: delegatesConfig,
274
+ log,
275
+ registry: installed.registry,
276
+ tasks: installed.tasks,
277
+ catalogue,
278
+ host: modelSource.host,
279
+ sandbox: installed.sandbox,
280
+ skills,
281
+ mcp,
282
+ mcpPresence: mcp.presence,
283
+ now,
284
+ timers,
285
+ settle,
286
+ state,
287
+ setState,
288
+ onState,
289
+ snapshot,
290
+ close,
291
+ holder,
292
+ };
293
+ });
294
+
295
+ const HarnessLayer = (config: SessionConfig, current: Ref.Ref<SessionHandle | undefined>) =>
296
+ Layer.effect(
297
+ SessionCore,
298
+ // Layer.effect runs this in the layer's scope, so dispose owns the three closes.
299
+ Effect.acquireRelease(openParts(config, current), (core) => Effect.promise(() => core.close())),
300
+ );
301
+
302
+ /** seams → harness → bridge → runtime → workflow: one scope, one owner, finalizers in the runtime's own scope. */
303
+ export const makeSessionGraph = (
304
+ config: SessionConfig,
305
+ current: Ref.Ref<SessionHandle | undefined>,
306
+ seams?: Layer.Layer<SessionSeams, StorageError>,
307
+ // The production layer unless a test instruments construction; the graph owns the build.
308
+ workflowLayer: Layer.Layer<WorkflowService, never, SessionRuntimeTag> = WorkflowService.layer,
309
+ ): SessionGraphLayer => {
310
+ const BridgeLayer = Layer.unwrap(
311
+ Effect.map(SessionCore, (core) => DurableBridge.layer(core.calls)),
312
+ );
313
+ const RuntimeLayer = Layer.effect(
314
+ SessionRuntimeTag,
315
+ Effect.gen(function* () {
316
+ const core = yield* SessionCore;
317
+ const bridge = yield* DurableBridge;
318
+ return yield* Effect.promise(() => buildSessionRuntime(core, bridge));
319
+ }),
320
+ );
321
+ return Layer.merge(RuntimeLayer, workflowLayer.pipe(Layer.provide(RuntimeLayer))).pipe(
322
+ Layer.provideMerge(BridgeLayer),
323
+ Layer.provideMerge(HarnessLayer(config, current)),
324
+ // replaced, never merged: `Layer.mergeAll` would build both sides and open the real store
325
+ Layer.provideMerge(seams ?? makeSessionSeams(config)),
326
+ );
327
+ };
328
+
329
+ /**
330
+ * One session-scoped runtime of the graph; the handle closes through its finalizers.
331
+ *
332
+ * A build that fails releases everything it acquired first: the layer machinery
333
+ * closes those finalizers, so there is nothing to dispose by hand. Nothing else
334
+ * can fail between the build and the handle.
335
+ */
336
+ export const openSessionRuntime = async (
337
+ config: SessionConfig,
338
+ current: Ref.Ref<SessionHandle | undefined> = Ref.makeUnsafe<SessionHandle | undefined>(
339
+ undefined,
340
+ ),
341
+ seams?: Layer.Layer<SessionSeams, StorageError>,
342
+ workflowLayer?: Layer.Layer<WorkflowService, never, SessionRuntimeTag>,
343
+ ): Promise<SessionHandle> => {
344
+ const managed = ManagedRuntime.make(makeSessionGraph(config, current, seams, workflowLayer));
345
+ const resolved = await managed.runPromise(SessionRuntimeTag);
346
+ const handle: SessionHandle = {
347
+ runtime: resolved,
348
+ run: (effect) =>
349
+ Effect.flatMap(Effect.orDie(managed.contextEffect), (context) =>
350
+ Effect.provide(effect, context),
351
+ ),
352
+ close: () => managed.dispose(),
353
+ };
354
+ // Filled before the entry can observe a half-open session.
355
+ Effect.runSync(Ref.set(current, handle));
356
+ return handle;
357
+ };
358
+
359
+ /** One activation: a fresh inspector in its own scope, inside the session's graph. */
360
+ export interface InspectorActivation {
361
+ readonly service: Inspector["Service"];
362
+ /** Runs one effect inside the session graph, with the activation's scope still open. */
363
+ readonly run: <A, E>(effect: Effect.Effect<A, E, SessionGraph>) => Promise<A>;
364
+ /** Forks into the activation's scope; the scope interrupts whatever it still holds. */
365
+ readonly fork: (
366
+ effect: Effect.Effect<void, never, SessionGraph>,
367
+ ) => Promise<Fiber.Fiber<void, never>>;
368
+ /** Interrupts one forked fiber before the scope closes, so teardown can order the steps. */
369
+ readonly interrupt: (fiber: Fiber.Fiber<void, never>) => Promise<void>;
370
+ /** Runs the scope's finalizers: every observation detaches, once. */
371
+ readonly close: () => Promise<void>;
372
+ }
373
+
374
+ /** The activation's operations, all through the session graph and its one scope. */
375
+ const activationOf = (
376
+ handle: SessionHandle,
377
+ scope: Scope.Closeable,
378
+ service: Inspector["Service"],
379
+ ): InspectorActivation => ({
380
+ service,
381
+ run: (effect) => Effect.runPromise(handle.run(effect)),
382
+ fork: (effect) => Effect.runPromise(handle.run(Effect.forkIn(effect, scope))),
383
+ interrupt: (fiber) => Effect.runPromise(handle.run(Fiber.interrupt(fiber))),
384
+ close: () => Effect.runPromise(handle.run(Scope.close(scope, Exit.void))),
385
+ });
386
+
387
+ /**
388
+ * One activation of the inspector: `Layer.fresh` keeps a second press from
389
+ * reusing the session's memoised instance, whose `finish` already ran.
390
+ */
391
+ export const openInspectorActivation = (
392
+ handle: SessionHandle,
393
+ deps: Omit<InspectorDeps, "runtime">,
394
+ ): Effect.Effect<InspectorActivation, InspectorReadFailed> =>
395
+ Effect.gen(function* () {
396
+ const scope = yield* Scope.make("sequential");
397
+ const context = yield* handle.run(
398
+ Effect.provideService(
399
+ Inspector.layer({ runtime: handle.runtime, ...deps }).pipe(Layer.fresh, Layer.build),
400
+ Scope.Scope,
401
+ scope,
402
+ ),
403
+ );
404
+ return activationOf(handle, scope, Context.get(context, Inspector));
405
+ });
@@ -1,11 +1,9 @@
1
- import { readFile, readdir, stat } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
1
  import { assert, it } from "@effect/vitest";
2
+ import { existsPath, join, readDir, readText } from "../test-support/platform.ts";
5
3
 
6
- const PACKAGE_ROOT = fileURLToPath(new URL("..", import.meta.url));
4
+ const PACKAGE_ROOT = join(import.meta.dirname, "..");
7
5
  const PACKAGE_MANIFEST = join(PACKAGE_ROOT, "package.json");
8
- const WORKSPACE_ROOT = fileURLToPath(new URL("../../..", import.meta.url));
6
+ const WORKSPACE_ROOT = join(import.meta.dirname, "../../..");
9
7
 
10
8
  interface Manifest {
11
9
  readonly name?: string;
@@ -25,13 +23,9 @@ interface Manifest {
25
23
  }
26
24
 
27
25
  const readManifest = async (path: string): Promise<Manifest> =>
28
- JSON.parse(await readFile(path, "utf8")) as Manifest;
26
+ JSON.parse(await readText(path)) as Manifest;
29
27
 
30
- const exists = async (path: string): Promise<boolean> =>
31
- stat(path).then(
32
- () => true,
33
- () => false,
34
- );
28
+ const exists = (path: string): Promise<boolean> => existsPath(path);
35
29
 
36
30
  it("the manifest points Pi at paths that exist", async () => {
37
31
  const manifest = await readManifest(PACKAGE_MANIFEST);
@@ -45,7 +39,7 @@ it("the manifest points Pi at paths that exist", async () => {
45
39
  );
46
40
  assert.strictEqual(manifest.dependencies?.["@earendil-works/pi-durable"], "1.6.0");
47
41
  assert.strictEqual(manifest.dependencies?.["@earendil-works/pi-codemode"], "catalog:pi");
48
- assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "1.6.0");
42
+ assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "*");
49
43
  assert.strictEqual(
50
44
  manifest.scripts?.["check:identity"],
51
45
  "bun run scripts/check-dependency-identity.ts",
@@ -67,11 +61,16 @@ const WORKSPACE_PACKAGES = ["inquiry", "qrspi", "test-kit", "tracker", "tui", "d
67
61
 
68
62
  it("the manifest declares the house UI dependency and the host terminal peer", async () => {
69
63
  const manifest = await readManifest(PACKAGE_MANIFEST);
64
+ const houseUi = await readManifest(join(WORKSPACE_ROOT, "packages/tui/package.json"));
70
65
 
71
- assert.strictEqual(manifest.dependencies?.["@ftrdotdev/pi-tui"], "^0.8.0");
66
+ assert.strictEqual(
67
+ manifest.dependencies?.["@ftrdotdev/pi-tui"],
68
+ `^${houseUi.version ?? ""}`,
69
+ "the house UI dependency follows the published version",
70
+ );
72
71
  assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-tui"], "*");
73
72
  assert.strictEqual(manifest.devDependencies?.["@earendil-works/pi-tui"], "catalog:pi");
74
- assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "1.6.0");
73
+ assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "*");
75
74
  });
76
75
 
77
76
  it("the house UI package resolves from inside this package", async () => {
@@ -127,14 +126,14 @@ it("the workspace pins one effect version", async () => {
127
126
  }
128
127
  });
129
128
 
130
- it("the package ships at least one changeset and a grouped roadmap", async () => {
129
+ it("the package ships a changeset or a changelog entry, and a grouped roadmap", async () => {
131
130
  const changesetDir = join(WORKSPACE_ROOT, ".changeset");
132
- const entries = await readdir(changesetDir);
131
+ const entries = await readDir(changesetDir);
133
132
  const fixed = ["@ftrdotdev/pi-tui", "@ftrdotdev/pi-tracker", "@ftrdotdev/pi-inquiry"];
134
133
 
135
134
  const namingDelegates: string[] = [];
136
135
  for (const entry of entries.filter((name) => name.endsWith(".md"))) {
137
- const text = await readFile(join(changesetDir, entry), "utf8");
136
+ const text = await readText(join(changesetDir, entry));
138
137
  const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? "";
139
138
  if (!frontmatter.includes('"@ftrdotdev/pi-delegates"')) continue;
140
139
  namingDelegates.push(entry);
@@ -142,9 +141,23 @@ it("the package ships at least one changeset and a grouped roadmap", async () =>
142
141
  assert.ok(!frontmatter.includes(`"${name}"`), `${entry} names ${name}`);
143
142
  }
144
143
  }
145
- assert.ok(namingDelegates.length >= 1, "no @ftrdotdev/pi-delegates changeset");
146
144
 
147
- const roadmap = await readFile(join(PACKAGE_ROOT, "ROADMAP.md"), "utf8");
145
+ // `changeset version` consumes the pending entries into the changelog, and the
146
+ // release script publishes from the tree it leaves behind. A versioned tree
147
+ // therefore proves the same rule the other way: the newest heading is the
148
+ // version the manifest ships, so no version reaches npm without an entry.
149
+ if (namingDelegates.length === 0) {
150
+ const manifest = await readManifest(PACKAGE_MANIFEST);
151
+ const changelog = await readText(join(PACKAGE_ROOT, "CHANGELOG.md"));
152
+ const newest = /^## (\S+)$/m.exec(changelog)?.[1] ?? "";
153
+ assert.strictEqual(
154
+ newest,
155
+ manifest.version,
156
+ "no pending @ftrdotdev/pi-delegates changeset and no changelog heading for the shipped version",
157
+ );
158
+ }
159
+
160
+ const roadmap = await readText(join(PACKAGE_ROOT, "ROADMAP.md"));
148
161
  for (const heading of [
149
162
  "Durability and hosts",
150
163
  "Work items and authorization",
@@ -1,8 +1,6 @@
1
1
  import { MemoryStorage } from "@earendil-works/pi-durable";
2
- import { mkdtemp } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
2
  import { assert, it } from "@effect/vitest";
3
+ import { makeTempDir } from "../../test-support/platform.ts";
6
4
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
7
5
  import { createCatalogue, defineAgent } from "../domain/definitions.ts";
8
6
  import { CODING_EXTENSION } from "../domain/names.ts";
@@ -11,9 +9,11 @@ import { launch, type HostDefaults } from "../domain/orchestration/launch.ts";
11
9
  import { RunDoc } from "../domain/run-records.ts";
12
10
  import { HostModelAdapter } from "../runtime/models.ts";
13
11
  import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
14
- import type { Timers } from "../runtime/timers.ts";
15
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
12
+ import type { Timers } from "../runtime/clock.ts";
13
+ import { type SessionRuntime } from "../runtime/session.ts";
14
+
16
15
  import { runInspectorAction } from "./actions.ts";
16
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
17
17
 
18
18
  const host: HostDefaults = {
19
19
  model: { provider: "stub", modelId: "stub-1" },
@@ -66,9 +66,9 @@ const recordingLog = (): {
66
66
  };
67
67
  };
68
68
 
69
- const openRuntime = async (clock: Recorder, log?: LogSink): Promise<SessionRuntime> => {
70
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-actions-"));
71
- return openSessionRuntime({
69
+ const openRuntime = async (clock: Recorder, log?: LogSink): Promise<TestSession> => {
70
+ const sessionDir = await makeTempDir("delegates-actions-");
71
+ return openTestSession({
72
72
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
73
73
  models: new HostModelAdapter(
74
74
  stubHostSource({
@@ -1,9 +1,7 @@
1
1
  import { MemoryStorage, type TaskGraph } from "@earendil-works/pi-durable";
2
2
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
- import { mkdtemp } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
3
  import { assert, it } from "@effect/vitest";
4
+ import { makeTempDir } from "../../test-support/platform.ts";
7
5
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
8
6
  import { waitFor } from "../../test-support/wait.ts";
9
7
  import { createCatalogue, defineAgent } from "../domain/definitions.ts";
@@ -15,8 +13,9 @@ import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
15
13
  import { viewRun } from "../domain/view.ts";
16
14
  import { HostModelAdapter } from "../runtime/models.ts";
17
15
  import { observeFamilyDoc, observeSessionDoc, observeTaskGraph } from "../runtime/observe.ts";
18
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
16
+
19
17
  import { watchActivity, type RunActivity } from "./activity.ts";
18
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
20
19
 
21
20
  const host: HostDefaults = {
22
21
  model: { provider: "stub", modelId: "stub-1" },
@@ -34,9 +33,9 @@ const deployer = defineAgent({
34
33
 
35
34
  const catalogue = createCatalogue([deployer]);
36
35
 
37
- const openRuntime = async (): Promise<SessionRuntime> => {
38
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-activity-"));
39
- return openSessionRuntime({
36
+ const openRuntime = async (): Promise<TestSession> => {
37
+ const sessionDir = await makeTempDir("delegates-activity-");
38
+ return openTestSession({
40
39
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
41
40
  models: new HostModelAdapter(
42
41
  stubHostSource({
@@ -49,7 +48,7 @@ const openRuntime = async (): Promise<SessionRuntime> => {
49
48
  };
50
49
 
51
50
  interface ParkedRun {
52
- readonly runtime: SessionRuntime;
51
+ readonly runtime: TestSession;
53
52
  readonly runId: string;
54
53
  readonly childId: number;
55
54
  readonly taskId: number;
@@ -1,10 +1,8 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { makeTempDir } from "../../test-support/platform.ts";
2
3
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
4
  import { MemoryStorage, type Storage } from "@earendil-works/pi-durable";
4
5
  import { Context, Deferred, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect";
5
- import { mkdtemp } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { join } from "node:path";
8
6
  import { failingStorage } from "../../test-support/failing-storage.ts";
9
7
  import { fakeObservations } from "../../test-support/fake-observations.ts";
10
8
  import { inspectorClock } from "../../test-support/inspector-clock.ts";
@@ -12,16 +10,11 @@ import { ProbeDoc } from "../../test-support/probe-doc.ts";
12
10
  import { stubHostSource } from "../../test-support/stub-model-source.ts";
13
11
  import type { ChildView, RunView, SessionView } from "../domain/view.ts";
14
12
  import { HostModelAdapter } from "../runtime/models.ts";
15
- import type { Timers } from "../runtime/timers.ts";
16
- import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
17
- import {
18
- endNotice,
19
- Inspector,
20
- RUN_INDEX_ADDRESS,
21
- type InspectorReadFailed,
22
- type InspectorService,
23
- } from "./inspector.ts";
13
+ import type { Timers } from "../runtime/clock.ts";
14
+
15
+ import { endNotice, Inspector, RUN_INDEX_ADDRESS, type InspectorReadFailed } from "./inspector.ts";
24
16
  import type { InspectorDeps } from "./inspector.ts";
17
+ import { openTestSession, type TestSession } from "../../test-support/seams.ts";
25
18
 
26
19
  const runView = (input: Partial<RunView> & { readonly runId: string }): RunView => ({
27
20
  definition: "scout",
@@ -37,6 +30,9 @@ const runView = (input: Partial<RunView> & { readonly runId: string }): RunView
37
30
  gates: [],
38
31
  requests: [],
39
32
  diagnostic: null,
33
+ execution: "wait",
34
+ maxTurns: null,
35
+ failure: null,
40
36
  ...input,
41
37
  });
42
38
 
@@ -49,6 +45,8 @@ const childView = (
49
45
  status: "running",
50
46
  answer: null,
51
47
  durationMs: null,
48
+ maxTurns: null,
49
+ failure: null,
52
50
  ...input,
53
51
  });
54
52
 
@@ -66,9 +64,9 @@ const oneRunningView = (): SessionView => ({
66
64
  requests: [],
67
65
  });
68
66
 
69
- const openRuntime = async (storage: Storage = new MemoryStorage()): Promise<SessionRuntime> => {
70
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-close-"));
71
- return openSessionRuntime({
67
+ const openRuntime = async (storage: Storage = new MemoryStorage()): Promise<TestSession> => {
68
+ const sessionDir = await makeTempDir("delegates-close-");
69
+ return openTestSession({
72
70
  identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
73
71
  models: new HostModelAdapter(stubHostSource()),
74
72
  storage,
@@ -76,7 +74,7 @@ const openRuntime = async (storage: Storage = new MemoryStorage()): Promise<Sess
76
74
  };
77
75
 
78
76
  interface Built {
79
- readonly inspector: InspectorService;
77
+ readonly inspector: Inspector["Service"];
80
78
  readonly scope: Scope.Closeable;
81
79
  }
82
80