@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
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
+ });
@@ -0,0 +1,170 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { existsPath, join, readDir, readText } from "../test-support/platform.ts";
3
+
4
+ const PACKAGE_ROOT = join(import.meta.dirname, "..");
5
+ const PACKAGE_MANIFEST = join(PACKAGE_ROOT, "package.json");
6
+ const WORKSPACE_ROOT = join(import.meta.dirname, "../../..");
7
+
8
+ interface Manifest {
9
+ readonly name?: string;
10
+ readonly version?: string;
11
+ readonly publishConfig?: { readonly access?: string };
12
+ readonly exports?: Readonly<Record<string, string>>;
13
+ readonly files?: readonly string[];
14
+ readonly dependencies?: Readonly<Record<string, string>>;
15
+ readonly devDependencies?: Readonly<Record<string, string>>;
16
+ readonly peerDependencies?: Readonly<Record<string, string>>;
17
+ readonly catalogs?: Readonly<Record<string, Readonly<Record<string, string>>>>;
18
+ readonly pi?: {
19
+ readonly extensions?: readonly string[];
20
+ readonly skills?: readonly string[];
21
+ };
22
+ readonly scripts?: Readonly<Record<string, string>>;
23
+ }
24
+
25
+ const readManifest = async (path: string): Promise<Manifest> =>
26
+ JSON.parse(await readText(path)) as Manifest;
27
+
28
+ const exists = (path: string): Promise<boolean> => existsPath(path);
29
+
30
+ it("the manifest points Pi at paths that exist", async () => {
31
+ const manifest = await readManifest(PACKAGE_MANIFEST);
32
+
33
+ assert.strictEqual(manifest.name, "@ftrdotdev/pi-delegates");
34
+ assert.strictEqual(manifest.publishConfig?.access, "public");
35
+ assert.ok(manifest.files?.includes("examples"), "the package publishes examples");
36
+ assert.ok(
37
+ manifest.files?.includes("OPERATIONS.md"),
38
+ "the package publishes the operations guide",
39
+ );
40
+ assert.strictEqual(manifest.dependencies?.["@earendil-works/pi-durable"], "1.6.0");
41
+ assert.strictEqual(manifest.dependencies?.["@earendil-works/pi-codemode"], "catalog:pi");
42
+ assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "*");
43
+ assert.strictEqual(
44
+ manifest.scripts?.["check:identity"],
45
+ "bun run scripts/check-dependency-identity.ts",
46
+ );
47
+
48
+ const declared = [
49
+ ...(manifest.pi?.extensions ?? []),
50
+ ...(manifest.pi?.skills ?? []),
51
+ ...Object.values(manifest.exports ?? {}),
52
+ ];
53
+ assert.ok(declared.length > 0, "the manifest declares at least one entry");
54
+ for (const relative of declared) {
55
+ const path = join(PACKAGE_ROOT, relative);
56
+ assert.ok(await exists(path), `${relative} exists`);
57
+ }
58
+ });
59
+
60
+ const WORKSPACE_PACKAGES = ["inquiry", "qrspi", "test-kit", "tracker", "tui", "delegates"];
61
+
62
+ it("the manifest declares the house UI dependency and the host terminal peer", async () => {
63
+ const manifest = await readManifest(PACKAGE_MANIFEST);
64
+ const houseUi = await readManifest(join(WORKSPACE_ROOT, "packages/tui/package.json"));
65
+
66
+ assert.strictEqual(
67
+ manifest.dependencies?.["@ftrdotdev/pi-tui"],
68
+ `^${houseUi.version ?? ""}`,
69
+ "the house UI dependency follows the published version",
70
+ );
71
+ assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-tui"], "*");
72
+ assert.strictEqual(manifest.devDependencies?.["@earendil-works/pi-tui"], "catalog:pi");
73
+ assert.strictEqual(manifest.peerDependencies?.["@earendil-works/pi-coding-agent"], "*");
74
+ });
75
+
76
+ it("the house UI package resolves from inside this package", async () => {
77
+ const house = (await import("@ftrdotdev/pi-tui")) as {
78
+ readonly defineComponent?: unknown;
79
+ };
80
+ assert.strictEqual(typeof house.defineComponent, "function");
81
+ const component = (
82
+ house as unknown as {
83
+ readonly defineComponent: (methods: {
84
+ readonly render: (width: number) => string[];
85
+ readonly invalidate: () => void;
86
+ }) => { readonly render: (width: number) => string[] };
87
+ }
88
+ ).defineComponent({ render: () => ["row"], invalidate: () => {} });
89
+ assert.ok(Array.isArray(component.render(10)));
90
+ });
91
+
92
+ it("the terminal types resolve from inside this package", async () => {
93
+ const terminal = (await import("@earendil-works/pi-tui")) as {
94
+ readonly matchesKey?: unknown;
95
+ readonly Key?: unknown;
96
+ readonly visibleWidth?: unknown;
97
+ };
98
+ assert.strictEqual(typeof terminal.matchesKey, "function");
99
+ assert.ok(terminal.Key !== undefined);
100
+ assert.strictEqual(typeof terminal.visibleWidth, "function");
101
+ });
102
+
103
+ it("the workspace pins one effect version", async () => {
104
+ const root = await readManifest(join(WORKSPACE_ROOT, "package.json"));
105
+ const effect = root.catalogs?.effect;
106
+ assert.strictEqual(effect?.["effect"], "4.1.5");
107
+ assert.strictEqual(effect?.["@effect/vitest"], "4.1.5");
108
+ assert.strictEqual(effect?.["@effect/platform-node"], "4.1.5");
109
+
110
+ const specifiers = ["effect", "@effect/vitest", "@effect/platform-node"];
111
+ for (const packageName of WORKSPACE_PACKAGES) {
112
+ const path = join(WORKSPACE_ROOT, "packages", packageName, "package.json");
113
+ const manifest = await readManifest(path);
114
+ for (const name of specifiers) {
115
+ const specifier =
116
+ manifest.dependencies?.[name] ??
117
+ manifest.devDependencies?.[name] ??
118
+ manifest.peerDependencies?.[name];
119
+ if (specifier === undefined) continue;
120
+ assert.strictEqual(specifier, "catalog:effect", `${packageName}: ${name}`);
121
+ }
122
+ const tsgo = manifest.devDependencies?.["@effect/tsgo"];
123
+ if (tsgo !== undefined) {
124
+ assert.strictEqual(tsgo, "catalog:effect", `${packageName}: @effect/tsgo`);
125
+ }
126
+ }
127
+ });
128
+
129
+ it("the package ships a changeset or a changelog entry, and a grouped roadmap", async () => {
130
+ const changesetDir = join(WORKSPACE_ROOT, ".changeset");
131
+ const entries = await readDir(changesetDir);
132
+ const fixed = ["@ftrdotdev/pi-tui", "@ftrdotdev/pi-tracker", "@ftrdotdev/pi-inquiry"];
133
+
134
+ const namingDelegates: string[] = [];
135
+ for (const entry of entries.filter((name) => name.endsWith(".md"))) {
136
+ const text = await readText(join(changesetDir, entry));
137
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? "";
138
+ if (!frontmatter.includes('"@ftrdotdev/pi-delegates"')) continue;
139
+ namingDelegates.push(entry);
140
+ for (const name of fixed) {
141
+ assert.ok(!frontmatter.includes(`"${name}"`), `${entry} names ${name}`);
142
+ }
143
+ }
144
+
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"));
161
+ for (const heading of [
162
+ "Durability and hosts",
163
+ "Work items and authorization",
164
+ "Surfaces and observability",
165
+ "Agent definitions and toolkits",
166
+ "Isolation and execution",
167
+ ]) {
168
+ assert.ok(roadmap.includes(heading), `roadmap names ${heading}`);
169
+ }
170
+ });