@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.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 (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -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 +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -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 +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,679 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { MemoryStorage } from "@earendil-works/pi-durable";
3
+ import { Context, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect";
4
+ import { mkdtemp } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { countingRuntime } from "../../test-support/counting-runtime.ts";
8
+ import { fakeObservations } from "../../test-support/fake-observations.ts";
9
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
10
+ import { createCatalogue } from "../domain/definitions.ts";
11
+ import type { GateRecord } from "../domain/orchestration/gates.ts";
12
+ import type { RequestRecord } from "../domain/orchestration/requests.ts";
13
+ import { RequestDoc, RequestIndexDoc, requestKey } from "../domain/orchestration/requests.ts";
14
+ import { launch } from "../domain/orchestration/launch.ts";
15
+ import type { ChildView, RunStatus, RunView, SessionView } from "../domain/view.ts";
16
+ import { viewSession } from "../domain/view.ts";
17
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
18
+ import { HostModelAdapter } from "../runtime/models.ts";
19
+ import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
20
+ import type { RunActivity } from "./activity.ts";
21
+ import {
22
+ GATE_INDEX_ADDRESS,
23
+ Inspector,
24
+ REQUEST_INDEX_ADDRESS,
25
+ RUN_INDEX_ADDRESS,
26
+ TASK_GRAPH_ADDRESS,
27
+ liveAddress,
28
+ runAddress,
29
+ type InspectorReadFailed,
30
+ type InspectorService,
31
+ } from "./inspector.ts";
32
+ import type { InspectorDeps } from "./inspector.ts";
33
+ import type { InspectorSnapshot } from "./snapshot.ts";
34
+
35
+ const host = { model: { provider: "stub", modelId: "stub-1" }, thinkingLevel: "low" } as const;
36
+
37
+ const recordingLog = (): {
38
+ readonly sink: LogSink;
39
+ readonly entries: { level: LogLevel; code: string; fields: LogFields }[];
40
+ } => {
41
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
42
+ return {
43
+ entries,
44
+ sink: {
45
+ write: (level, code, fields = {}) => {
46
+ entries.push({ level, code, fields });
47
+ },
48
+ },
49
+ };
50
+ };
51
+
52
+ const openRuntime = async (log?: LogSink): Promise<SessionRuntime> => {
53
+ const sessionDir = await mkdtemp(join(tmpdir(), "delegates-inspector-"));
54
+ return openSessionRuntime({
55
+ identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
56
+ models: new HostModelAdapter(stubHostSource()),
57
+ storage: new MemoryStorage(),
58
+ ...(log === undefined ? {} : { log }),
59
+ });
60
+ };
61
+
62
+ const withRuntime = <A, E, R>(
63
+ use: (runtime: SessionRuntime) => Effect.Effect<A, E, R>,
64
+ log?: LogSink,
65
+ ): Effect.Effect<A, E, R> =>
66
+ Effect.acquireUseRelease(
67
+ Effect.promise(() => openRuntime(log)),
68
+ use,
69
+ (runtime) => Effect.promise(() => runtime.close()),
70
+ );
71
+
72
+ const runView = (
73
+ input: Partial<RunView> & { readonly runId: string; readonly status: RunStatus },
74
+ ): RunView => ({
75
+ definition: "scout",
76
+ mode: "single",
77
+ lane: "default",
78
+ conversationId: null,
79
+ taskId: null,
80
+ answer: null,
81
+ durationMs: null,
82
+ children: [],
83
+ missing: [],
84
+ gates: [],
85
+ requests: [],
86
+ diagnostic: null,
87
+ ...input,
88
+ });
89
+
90
+ const childView = (
91
+ input: Partial<ChildView> & { readonly child: number; readonly runId: string },
92
+ ): ChildView => ({
93
+ conversationId: null,
94
+ taskId: null,
95
+ agent: "scout",
96
+ status: "running",
97
+ answer: null,
98
+ durationMs: null,
99
+ ...input,
100
+ });
101
+
102
+ const gateRecord = (input: Partial<GateRecord> & { readonly gate: string }): GateRecord => ({
103
+ runId: "run:one",
104
+ status: "pending",
105
+ tool: "bash",
106
+ taskId: null,
107
+ taskIds: [],
108
+ childRunIds: [],
109
+ requestedAt: 1_000,
110
+ deadline: 0,
111
+ decision: null,
112
+ decidedBy: null,
113
+ reason: null,
114
+ ...input,
115
+ });
116
+
117
+ const view = (
118
+ runs: readonly RunView[],
119
+ gates: readonly GateRecord[] = [],
120
+ requests: readonly RequestRecord[] = [],
121
+ ): SessionView => ({
122
+ runs,
123
+ lanes: [],
124
+ gates,
125
+ reviews: [],
126
+ requests,
127
+ });
128
+
129
+ const scriptedViews = (
130
+ sequence: readonly SessionView[],
131
+ ): { readonly read: () => Promise<SessionView>; readonly reads: () => number } => {
132
+ let reads = 0;
133
+ return {
134
+ read: () => {
135
+ const index = Math.min(reads, sequence.length - 1);
136
+ reads += 1;
137
+ return Promise.resolve(sequence[index] as SessionView);
138
+ },
139
+ reads: () => reads,
140
+ };
141
+ };
142
+
143
+ interface Built {
144
+ readonly inspector: InspectorService;
145
+ readonly scope: Scope.Closeable;
146
+ }
147
+
148
+ const build = Effect.fn("buildInspector")(function* (
149
+ deps: InspectorDeps,
150
+ scope?: Scope.Closeable,
151
+ ): Effect.fn.Return<Built, InspectorReadFailed> {
152
+ const own = scope ?? (yield* Scope.make("sequential"));
153
+ const context = yield* Effect.provideService(
154
+ Layer.build(Inspector.layer(deps)),
155
+ Scope.Scope,
156
+ own,
157
+ );
158
+ return { inspector: Context.get(context, Inspector), scope: own };
159
+ });
160
+
161
+ const close = (built: Built): Effect.Effect<void> => Scope.close(built.scope, Exit.void);
162
+
163
+ /** Let real promise work run, then fail the test rather than hang. */
164
+ const until = Effect.fn("until")(function* (
165
+ predicate: () => boolean,
166
+ label: string,
167
+ ): Effect.fn.Return<void> {
168
+ for (let attempt = 0; attempt < 2_000; attempt += 1) {
169
+ if (predicate()) return;
170
+ yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 1)));
171
+ }
172
+ return yield* Effect.die(new Error(`condition not reached: ${label}`));
173
+ });
174
+
175
+ const collect = Effect.fn("collectChanges")(function* (
176
+ inspector: InspectorService,
177
+ ): Effect.fn.Return<{ readonly seen: InspectorSnapshot[]; readonly fiber: Fiber.Fiber<void> }> {
178
+ const seen: InspectorSnapshot[] = [];
179
+ const fiber = yield* Effect.forkChild(
180
+ inspector.changes.pipe(Stream.runForEach((snapshot) => Effect.sync(() => seen.push(snapshot)))),
181
+ );
182
+ yield* until(() => seen.length > 0, "the change stream replayed");
183
+ return { seen, fiber };
184
+ });
185
+
186
+ const oneRunningView = (): SessionView =>
187
+ view([
188
+ runView({
189
+ runId: "run:a",
190
+ status: "running",
191
+ conversationId: 10,
192
+ children: [childView({ child: 0, runId: "run:a", conversationId: 10 })],
193
+ }),
194
+ ]);
195
+
196
+ it.effect("building the owner publishes revision 1 with the session's rows", () => {
197
+ const log = recordingLog();
198
+ return withRuntime(
199
+ (runtime) =>
200
+ Effect.gen(function* () {
201
+ yield* Effect.promise(() =>
202
+ launch(
203
+ { kind: "single", agent: "scout", task: "look" },
204
+ { runtime, catalogue: createCatalogue(), host, waitMs: 10_000 },
205
+ ),
206
+ );
207
+ const counted = countingRuntime(runtime);
208
+ const fake = fakeObservations();
209
+ const built = yield* build({ runtime: counted.runtime, observe: fake });
210
+ const snapshot = yield* built.inspector.snapshot;
211
+ assert.strictEqual(snapshot.revision, 1);
212
+ assert.strictEqual(snapshot.rows.length, 1);
213
+ assert.strictEqual(counted.count("delegates.run-index"), 1);
214
+ yield* close(built);
215
+ }),
216
+ log.sink,
217
+ );
218
+ });
219
+
220
+ it.effect("one push folds once and publishes one revision", () => {
221
+ const views = scriptedViews([
222
+ oneRunningView(),
223
+ view([
224
+ runView({
225
+ runId: "run:a",
226
+ status: "answered",
227
+ conversationId: 10,
228
+ children: [childView({ child: 0, runId: "run:a", conversationId: 10, status: "answered" })],
229
+ }),
230
+ ]),
231
+ ]);
232
+ const fake = fakeObservations();
233
+ return withRuntime((runtime) =>
234
+ Effect.gen(function* () {
235
+ const built = yield* build({ runtime, observe: fake, view: views.read });
236
+ const first = yield* built.inspector.snapshot;
237
+ const { seen, fiber } = yield* collect(built.inspector);
238
+ const before = views.reads();
239
+ fake.push(RUN_INDEX_ADDRESS);
240
+ yield* until(() => seen.length >= 2, "the pushed change published");
241
+ assert.deepStrictEqual(
242
+ seen.map((snapshot) => snapshot.revision),
243
+ [1, 2],
244
+ );
245
+ assert.notStrictEqual(seen[1], first);
246
+ assert.strictEqual(views.reads(), before + 1);
247
+ yield* Fiber.interrupt(fiber);
248
+ yield* close(built);
249
+ }),
250
+ );
251
+ });
252
+
253
+ it.effect("an activity arrival publishes from memory without a read", () => {
254
+ const views = scriptedViews([oneRunningView()]);
255
+ const fake = fakeObservations();
256
+ return withRuntime((runtime) =>
257
+ Effect.gen(function* () {
258
+ const built = yield* build({
259
+ runtime,
260
+ observe: fake,
261
+ view: views.read,
262
+ now: () => 4_000,
263
+ });
264
+ const { seen, fiber } = yield* collect(built.inspector);
265
+ const before = views.reads();
266
+ fake.pushActivity(liveAddress(10), { tool: "bash", slot: "running", turns: 2, at: 1_000 });
267
+ yield* until(() => seen.length >= 2, "the activity published");
268
+ const latest = seen.at(-1);
269
+ assert.strictEqual(latest?.revision, 2);
270
+ assert.strictEqual(latest?.rows[0]?.tool, "bash");
271
+ assert.strictEqual(latest?.rows[0]?.slot, "running");
272
+ assert.strictEqual(latest?.rows[0]?.idleMs, 3_000);
273
+ assert.strictEqual(views.reads(), before);
274
+ yield* Fiber.interrupt(fiber);
275
+ yield* close(built);
276
+ }),
277
+ );
278
+ });
279
+
280
+ it.effect("an unchanged projection publishes nothing and keeps the revision", () => {
281
+ const views = scriptedViews([oneRunningView(), oneRunningView()]);
282
+ const fake = fakeObservations();
283
+ return withRuntime((runtime) =>
284
+ Effect.gen(function* () {
285
+ const built = yield* build({ runtime, observe: fake, view: views.read });
286
+ const before = yield* built.inspector.snapshot;
287
+ const readsBefore = views.reads();
288
+ fake.push(RUN_INDEX_ADDRESS);
289
+ yield* until(() => views.reads() > readsBefore, "the pushed change read");
290
+ const after = yield* built.inspector.snapshot;
291
+ assert.strictEqual(after, before);
292
+ assert.strictEqual(after.revision, 1);
293
+ assert.strictEqual(views.reads(), readsBefore + 1);
294
+ yield* close(built);
295
+ }),
296
+ );
297
+ });
298
+
299
+ it.effect("one observation per address the projection names", () => {
300
+ const current = view(
301
+ [
302
+ runView({
303
+ runId: "run:single",
304
+ status: "running",
305
+ conversationId: 100,
306
+ children: [
307
+ childView({ child: 0, runId: "run:single", status: "running", conversationId: 100 }),
308
+ ],
309
+ }),
310
+ runView({
311
+ runId: "run:parent",
312
+ definition: "fanout",
313
+ status: "running",
314
+ children: [
315
+ childView({ child: 0, runId: "run:child1", status: "running", conversationId: 101 }),
316
+ childView({ child: 1, runId: "run:child2", status: "running", conversationId: 102 }),
317
+ ],
318
+ }),
319
+ runView({
320
+ runId: "run:queued",
321
+ status: "queued",
322
+ children: [childView({ child: 0, runId: "run:queued", status: "queued" })],
323
+ }),
324
+ ],
325
+ [gateRecord({ runId: "run:single", gate: "deploy" })],
326
+ );
327
+ const fake = fakeObservations();
328
+ return withRuntime((runtime) =>
329
+ Effect.gen(function* () {
330
+ const built = yield* build({ runtime, observe: fake, view: async () => current });
331
+ assert.deepStrictEqual(
332
+ [...fake.attaches].sort(),
333
+ [
334
+ GATE_INDEX_ADDRESS,
335
+ REQUEST_INDEX_ADDRESS,
336
+ TASK_GRAPH_ADDRESS,
337
+ RUN_INDEX_ADDRESS,
338
+ liveAddress(100),
339
+ liveAddress(101),
340
+ liveAddress(102),
341
+ runAddress("run:child1"),
342
+ runAddress("run:child2"),
343
+ runAddress("run:parent"),
344
+ runAddress("run:queued"),
345
+ runAddress("run:single"),
346
+ "gate:run:single:deploy",
347
+ ].sort(),
348
+ );
349
+ yield* close(built);
350
+ }),
351
+ );
352
+ });
353
+
354
+ it.effect("a request index commit publishes the pending request", () => {
355
+ const record: RequestRecord = {
356
+ runId: "run:one",
357
+ childRunId: "run:one",
358
+ conversationId: 12,
359
+ requestId: "12:c1",
360
+ prompt: "Which environment?",
361
+ options: [{ label: "staging", description: null, recommended: false }],
362
+ allowOther: true,
363
+ status: "pending",
364
+ taskIds: [7],
365
+ requestedAt: 1_000,
366
+ deadline: 9_000,
367
+ answer: null,
368
+ answeredBy: null,
369
+ reason: null,
370
+ };
371
+ const run = runView({ runId: "run:one", status: "running", conversationId: 12 });
372
+ const views = scriptedViews([view([run]), view([run], [], [record])]);
373
+ const fake = fakeObservations();
374
+ return withRuntime((runtime) =>
375
+ Effect.gen(function* () {
376
+ const built = yield* build({
377
+ runtime,
378
+ observe: fake,
379
+ view: views.read,
380
+ now: () => 1_500,
381
+ });
382
+ fake.push(REQUEST_INDEX_ADDRESS);
383
+ yield* until(() => views.reads() >= 2, "the request index fold");
384
+ const snapshot = yield* built.inspector.snapshot;
385
+ assert.deepStrictEqual(
386
+ snapshot.requests.map((row) => row.requestId),
387
+ ["12:c1"],
388
+ );
389
+ assert.strictEqual(snapshot.counts.requests, 1);
390
+ yield* close(built);
391
+ }),
392
+ );
393
+ });
394
+
395
+ it.effect("a committed request reaches the inspector without a restart", () =>
396
+ withRuntime((runtime) =>
397
+ Effect.gen(function* () {
398
+ let reads = 0;
399
+ const existing = yield* Effect.promise(() => runtime.snapshot(RequestIndexDoc));
400
+ assert.strictEqual(existing, undefined, "the request index exists at open");
401
+ const built = yield* build({
402
+ runtime,
403
+ view: () => {
404
+ reads += 1;
405
+ return viewSession(runtime);
406
+ },
407
+ now: () => 1_500,
408
+ });
409
+ yield* until(() => reads >= 1, "the first read");
410
+ // Let every signal the build produced drain, so the commit is the only cause left.
411
+ let stable = reads;
412
+ for (;;) {
413
+ yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50)));
414
+ if (reads === stable) break;
415
+ stable = reads;
416
+ }
417
+ const before = reads;
418
+ const key = requestKey(12, "call_1");
419
+ yield* Effect.promise(() =>
420
+ runtime.run((context) =>
421
+ runtime.harness.commit(async (tx) => {
422
+ const index = await tx.doc(RequestIndexDoc);
423
+ index.rows.push({
424
+ key,
425
+ runId: "run:one",
426
+ requestId: key,
427
+ requestedAt: 1_000,
428
+ deadline: 9_000,
429
+ status: "pending",
430
+ });
431
+ const doc = await tx.doc(RequestDoc, key, { requestId: key });
432
+ doc.runId = "run:one";
433
+ doc.childRunId = "run:one";
434
+ doc.conversationId = 12;
435
+ doc.requestId = key;
436
+ doc.prompt = "Which environment?";
437
+ doc.options = [{ label: "staging", description: null, recommended: false }];
438
+ doc.requestedAt = 1_000;
439
+ doc.deadline = 9_000;
440
+ }, context),
441
+ ),
442
+ );
443
+ let requests: readonly string[] = [];
444
+ for (let attempt = 0; attempt < 2_000 && requests.length === 0; attempt += 1) {
445
+ const snapshot = yield* built.inspector.snapshot;
446
+ requests = snapshot.requests.map((row) => row.requestId);
447
+ if (requests.length === 0) {
448
+ yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 1)));
449
+ }
450
+ }
451
+ assert.deepStrictEqual(requests, [key]);
452
+ assert.ok(reads > before, "the commit did not trigger a read");
453
+ yield* close(built);
454
+ }),
455
+ ),
456
+ );
457
+
458
+ it.effect("a row that turns terminal loses its run address and keeps its row", () => {
459
+ const both = (aStatus: RunStatus, withA: boolean): SessionView =>
460
+ view([
461
+ ...(withA
462
+ ? [
463
+ runView({
464
+ runId: "run:a",
465
+ status: aStatus,
466
+ conversationId: 10,
467
+ children: [
468
+ childView({ child: 0, runId: "run:a", conversationId: 10, status: aStatus }),
469
+ ],
470
+ }),
471
+ ]
472
+ : []),
473
+ runView({
474
+ runId: "run:b",
475
+ status: "running",
476
+ conversationId: 11,
477
+ children: [childView({ child: 0, runId: "run:b", conversationId: 11, status: "running" })],
478
+ }),
479
+ ]);
480
+ const views = scriptedViews([
481
+ both("running", true),
482
+ both("answered", true),
483
+ both("answered", false),
484
+ ]);
485
+ const fake = fakeObservations();
486
+ return withRuntime((runtime) =>
487
+ Effect.gen(function* () {
488
+ const built = yield* build({ runtime, observe: fake, view: views.read });
489
+ fake.push(RUN_INDEX_ADDRESS);
490
+ yield* until(() => views.reads() >= 2, "the first fold read");
491
+ const afterFirst = yield* built.inspector.snapshot;
492
+ assert.deepStrictEqual(afterFirst.rows.map((row) => row.id).sort(), [
493
+ "run:run:a",
494
+ "run:run:b",
495
+ ]);
496
+ assert.ok(fake.detaches.includes(runAddress("run:a")));
497
+ assert.ok(fake.detaches.includes(liveAddress(10)));
498
+ assert.ok(!fake.detaches.includes(TASK_GRAPH_ADDRESS));
499
+
500
+ fake.push(RUN_INDEX_ADDRESS);
501
+ yield* until(() => views.reads() >= 3, "the second fold read");
502
+ const afterSecond = yield* built.inspector.snapshot;
503
+ assert.deepStrictEqual(
504
+ afterSecond.rows.map((row) => row.id),
505
+ ["run:run:b"],
506
+ );
507
+ assert.ok(!fake.detaches.includes(TASK_GRAPH_ADDRESS));
508
+ yield* close(built);
509
+ }),
510
+ );
511
+ });
512
+
513
+ it.effect("an observation end is one more push", () => {
514
+ const log = recordingLog();
515
+ const views = scriptedViews([oneRunningView(), oneRunningView()]);
516
+ const fake = fakeObservations();
517
+ return withRuntime(
518
+ (runtime) =>
519
+ Effect.gen(function* () {
520
+ const built = yield* build({ runtime, observe: fake, view: views.read });
521
+ const readsBefore = views.reads();
522
+ fake.end(runAddress("run:a"), "ended");
523
+ yield* until(() => views.reads() > readsBefore, "the end pushed a read");
524
+ assert.ok(fake.detaches.includes(runAddress("run:a")));
525
+ const ends = log.entries.filter((entry) => entry.code === "inspector.observe_ended");
526
+ assert.strictEqual(ends.length, 1);
527
+ assert.strictEqual(ends[0]?.fields.address, runAddress("run:a"));
528
+ // The consumer still runs: another push folds.
529
+ const afterEnd = views.reads();
530
+ fake.push(RUN_INDEX_ADDRESS);
531
+ yield* until(() => views.reads() > afterEnd, "the consumer survived the end");
532
+ yield* close(built);
533
+ }),
534
+ log.sink,
535
+ );
536
+ });
537
+
538
+ it.effect("an absent address is retried on the next fold", () => {
539
+ const withGate = view(
540
+ [runView({ runId: "run:one", status: "waiting" })],
541
+ [gateRecord({ runId: "run:one", gate: "deploy" })],
542
+ );
543
+ const views = scriptedViews([withGate, withGate]);
544
+ const fake = fakeObservations();
545
+ fake.refuseOnce("gate:run:one:deploy");
546
+ return withRuntime((runtime) =>
547
+ Effect.gen(function* () {
548
+ const built = yield* build({ runtime, observe: fake, view: views.read });
549
+ assert.deepStrictEqual(fake.refusals, ["gate:run:one:deploy"]);
550
+ assert.ok(!fake.attached().includes("gate:run:one:deploy"));
551
+ fake.push(GATE_INDEX_ADDRESS);
552
+ yield* until(
553
+ () => fake.attached().includes("gate:run:one:deploy"),
554
+ "the absent address was retried",
555
+ );
556
+ yield* close(built);
557
+ }),
558
+ );
559
+ });
560
+
561
+ it.effect("a failed attach does not fail the layer", () => {
562
+ const log = recordingLog();
563
+ const withGate = view(
564
+ [runView({ runId: "run:one", status: "waiting" })],
565
+ [gateRecord({ runId: "run:one", gate: "deploy" })],
566
+ );
567
+ const fake = fakeObservations();
568
+ fake.failOnce("gate:run:one:deploy", new Error("attach refused"));
569
+ return withRuntime(
570
+ (runtime) =>
571
+ Effect.gen(function* () {
572
+ const built = yield* build({ runtime, observe: fake, view: async () => withGate });
573
+ const snapshot = yield* built.inspector.snapshot;
574
+ assert.strictEqual(snapshot.revision, 1);
575
+ assert.strictEqual(fake.failures.length, 1);
576
+ assert.ok(fake.attached().includes(RUN_INDEX_ADDRESS));
577
+ assert.ok(fake.attached().includes(TASK_GRAPH_ADDRESS));
578
+ const entries = log.entries.filter(
579
+ (entry) =>
580
+ entry.code === "inspector.observe_failed" &&
581
+ entry.fields.address === "gate:run:one:deploy",
582
+ );
583
+ assert.strictEqual(entries.length, 1);
584
+ // The warn entry keeps the thrown text, not just the tag name.
585
+ assert.strictEqual(entries[0]?.fields.detail, "attach refused");
586
+ yield* close(built);
587
+ }),
588
+ log.sink,
589
+ );
590
+ });
591
+
592
+ it.effect("closing the layer's scope shuts the queue and detaches every observation once", () => {
593
+ const views = scriptedViews([oneRunningView()]);
594
+ const fake = fakeObservations();
595
+ return withRuntime((runtime) =>
596
+ Effect.gen(function* () {
597
+ const built = yield* build({ runtime, observe: fake, view: views.read });
598
+ const addresses = [...fake.attached()];
599
+ const reads = views.reads();
600
+ yield* close(built);
601
+ assert.deepStrictEqual([...fake.detaches].sort(), [...addresses].sort());
602
+ assert.strictEqual(new Set(fake.detaches).size, fake.detaches.length);
603
+ assert.deepStrictEqual(fake.attached(), []);
604
+
605
+ // A refresh requested after the close is a no-op: the queue is shut.
606
+ yield* built.inspector.refresh;
607
+ assert.strictEqual(views.reads(), reads);
608
+ }),
609
+ );
610
+ });
611
+
612
+ it.effect("a second layer build starts at revision 1 with its own observations", () => {
613
+ const views = scriptedViews([oneRunningView(), oneRunningView()]);
614
+ const fake = fakeObservations();
615
+ return withRuntime((runtime) =>
616
+ Effect.gen(function* () {
617
+ const deps = { runtime, observe: fake, view: views.read };
618
+ const first = yield* build(deps);
619
+ const addressCount = fake.attaches.length;
620
+ yield* close(first);
621
+ const firstDetaches = [...fake.detaches];
622
+
623
+ const second = yield* build(deps);
624
+ const snapshot = yield* second.inspector.snapshot;
625
+ assert.strictEqual(snapshot.revision, 1);
626
+ assert.strictEqual(fake.attaches.length, addressCount * 2);
627
+ yield* close(second);
628
+ assert.deepStrictEqual(fake.detaches.slice(0, addressCount), firstDetaches);
629
+ assert.strictEqual(fake.detaches.length, addressCount * 2);
630
+ }),
631
+ );
632
+ });
633
+
634
+ it.effect("a burst of document pushes costs one pending read", () => {
635
+ const first = oneRunningView();
636
+ let reads = 0;
637
+ const pending: Array<(value: SessionView) => void> = [];
638
+ const read = (): Promise<SessionView> => {
639
+ reads += 1;
640
+ if (reads === 1) return Promise.resolve(first);
641
+ return new Promise<SessionView>((resolve) => pending.push(resolve));
642
+ };
643
+ const fake = fakeObservations();
644
+ return withRuntime((runtime) =>
645
+ Effect.gen(function* () {
646
+ const built = yield* build({ runtime, observe: fake, view: read });
647
+ fake.push(RUN_INDEX_ADDRESS);
648
+ yield* until(() => reads === 2, "the first pushed read started");
649
+ fake.push(RUN_INDEX_ADDRESS);
650
+ fake.push(RUN_INDEX_ADDRESS);
651
+ pending.shift()?.(first);
652
+ yield* until(() => reads === 3, "the coalesced signal read once more");
653
+ pending.shift()?.(first);
654
+ assert.strictEqual(reads, 3);
655
+ yield* close(built);
656
+ }),
657
+ );
658
+ });
659
+
660
+ it.effect("an activity burst reads nothing and publishes once", () => {
661
+ const views = scriptedViews([oneRunningView()]);
662
+ const fake = fakeObservations();
663
+ return withRuntime((runtime) =>
664
+ Effect.gen(function* () {
665
+ const built = yield* build({ runtime, observe: fake, view: views.read, now: () => 4_000 });
666
+ const before = views.reads();
667
+ const activity: RunActivity = { tool: "bash", slot: "running", turns: 1, at: 3_000 };
668
+ fake.pushActivity(liveAddress(10), activity);
669
+ fake.pushActivity(liveAddress(10), activity);
670
+ fake.pushActivity(liveAddress(10), activity);
671
+ yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 30)));
672
+ assert.strictEqual(views.reads(), before);
673
+ const snapshot = yield* built.inspector.snapshot;
674
+ assert.strictEqual(snapshot.revision, 2);
675
+ assert.strictEqual(snapshot.rows[0]?.tool, "bash");
676
+ yield* close(built);
677
+ }),
678
+ );
679
+ });