@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,442 @@
1
+ import type { JsonObject, TaskGraph } from "@earendil-works/pi-durable";
2
+ import {
3
+ Cause,
4
+ Context,
5
+ Deferred,
6
+ Effect,
7
+ Exit,
8
+ Fiber,
9
+ Layer,
10
+ Queue,
11
+ Ref,
12
+ Schema,
13
+ Stream,
14
+ SubscriptionRef,
15
+ } from "effect";
16
+ import { GateDoc, gateKey, GateIndexDoc } from "../domain/orchestration/gates.ts";
17
+ import { RequestIndexDoc } from "../domain/orchestration/requests.ts";
18
+ import { RunDoc, RunIndexDoc } from "../domain/run-records.ts";
19
+ import { viewSession, type SessionView } from "../domain/view.ts";
20
+ import { errorFields, type LogFields } from "../runtime/log.ts";
21
+ import {
22
+ observeFamilyDoc,
23
+ observeSessionDoc,
24
+ observeTaskGraph,
25
+ type Detach,
26
+ type DocEndKind,
27
+ type DocSink,
28
+ type ObservationSeam,
29
+ } from "../runtime/observe.ts";
30
+ import type { SessionRuntime } from "../runtime/session.ts";
31
+ import type { RuntimeState } from "../runtime/session.ts";
32
+ import type { Timers } from "../runtime/clock.ts";
33
+ import { watchActivity as attachActivity, type RunActivity } from "./activity.ts";
34
+ import {
35
+ emptySnapshot,
36
+ InspectorSnapshot,
37
+ InspectorSnapshotEquivalence,
38
+ projectSnapshot,
39
+ } from "./snapshot.ts";
40
+
41
+ /** The owner's names for the addresses it attaches. */
42
+ export const RUN_INDEX_ADDRESS = "index:runs";
43
+ export const GATE_INDEX_ADDRESS = "index:gates";
44
+ export const REQUEST_INDEX_ADDRESS = "index:requests";
45
+ export const TASK_GRAPH_ADDRESS = "graph:tasks";
46
+ export const runAddress = (runId: string): string => `run:${runId}`;
47
+ export const liveAddress = (conversationId: number): string => `live:${conversationId}`;
48
+
49
+ /** One second: the only cadence left, and it buys rendered ages, not reads. */
50
+ export const REPAINT_INTERVAL_MS = 1_000;
51
+
52
+ export type InspectorEnd =
53
+ | { readonly kind: "runtime-ended"; readonly reason?: string }
54
+ | { readonly kind: "stopped" };
55
+
56
+ /** The single notice line; `undefined` when nothing may be written (a user shutdown). */
57
+ export const endNotice = (end: InspectorEnd): string | undefined =>
58
+ end.kind === "runtime-ended"
59
+ ? `delegates inspector ended: ${end.reason ?? "the session closed"}`
60
+ : undefined;
61
+
62
+ /** A live row is one that can still change: terminal rows hold no attachment. */
63
+ export const isLiveStatus = (status: InspectorSnapshot["rows"][number]["status"]): boolean =>
64
+ status === "queued" || status === "running" || status === "waiting";
65
+
66
+ /** Only two classes of arrival exist, and only one of them reads. */
67
+ type Signal =
68
+ | { readonly kind: "doc" }
69
+ | { readonly kind: "activity"; readonly runId: string; readonly activity: RunActivity };
70
+
71
+ /** A committed read failed; the layer refuses to build rather than observe a stale view. */
72
+ export class InspectorReadFailed extends Schema.TaggedError<
73
+ InspectorReadFailed,
74
+ { readonly brand: unique symbol }
75
+ >()("InspectorReadFailed", { cause: Schema.Defect() }) {}
76
+
77
+ /** An attachment failed; the row keeps its previous state and the run continues. */
78
+ export class InspectorAttachFailed extends Schema.TaggedError<
79
+ InspectorAttachFailed,
80
+ { readonly brand: unique symbol }
81
+ >()("InspectorAttachFailed", { address: Schema.String, cause: Schema.Defect() }) {}
82
+
83
+ /**
84
+ * One field set per cause. A tagged failure keeps its text in the cause, and
85
+ * `errorFields` reads only the message, so unwrap it before logging.
86
+ */
87
+ const describeFailure = (cause: Cause.Cause<unknown>): LogFields => {
88
+ const failure = Cause.squash(cause);
89
+ return errorFields(
90
+ failure instanceof InspectorReadFailed || failure instanceof InspectorAttachFailed
91
+ ? failure.cause
92
+ : failure,
93
+ );
94
+ };
95
+
96
+ export interface InspectorDeps {
97
+ readonly runtime: SessionRuntime;
98
+ /** Defaults to the real seam; tests inject a recording double. */
99
+ readonly observe?: ObservationSeam;
100
+ /** Defaults to `runtime.now`. */
101
+ readonly now?: () => number;
102
+ /** Defaults to `runtime.timers`: the harness and the age clock share one source. */
103
+ readonly timers?: Timers;
104
+ /** Defaults to the committed read; tests inject a scripted view sequence. */
105
+ readonly view?: () => Promise<SessionView>;
106
+ /** Test seam: the fiber that awaits the end and runs `finish`, so a test can interrupt it mid-teardown. */
107
+ readonly onEndFiber?: (fiber: Fiber.Fiber<void>) => void;
108
+ /** Test seam: the consumer's interrupt completed inside `finish`. */
109
+ readonly onConsumerInterrupted?: () => void;
110
+ }
111
+
112
+ const realSeam = (runtime: SessionRuntime): ObservationSeam => ({
113
+ observeSessionDoc: (_address, token, sink) => observeSessionDoc(runtime, token, sink),
114
+ observeFamilyDoc: (_address, token, key, sink) => observeFamilyDoc(runtime, token, key, sink),
115
+ observeTaskGraph: (_address, sink) => observeTaskGraph(runtime, sink),
116
+ watchActivity: (_address, conversationId, onActivity, onEnd) =>
117
+ attachActivity(runtime, conversationId, onActivity, onEnd),
118
+ });
119
+
120
+ /** A lifecycle state as an end event; only `failing` and `closed` are ends. */
121
+ const endFor = (state: RuntimeState): InspectorEnd =>
122
+ state.kind === "failing" || state.kind === "closed"
123
+ ? {
124
+ kind: "runtime-ended",
125
+ ...(state.reason === undefined ? {} : { reason: state.reason }),
126
+ }
127
+ : { kind: "stopped" };
128
+
129
+ /** One interval through the package's single timer source; interrupting it clears the timer. */
130
+ const sleepFor = (timers: Timers, ms: number): Effect.Effect<void> =>
131
+ Effect.callback<void>((resume) => {
132
+ const handle = timers.setTimeout(() => resume(Effect.void), ms);
133
+ return Effect.sync(() => timers.clearTimeout(handle));
134
+ });
135
+
136
+ /**
137
+ * The single observation owner: one scoped Effect service per session
138
+ * runtime. Every observation `advance` offers one signal to a
139
+ * `Queue.sliding(1)`; one consumer folds it. A document signal performs one
140
+ * committed read; an activity signal re-projects the cached view and reads
141
+ * nothing. It never writes.
142
+ */
143
+ export class Inspector extends Context.Service<
144
+ Inspector,
145
+ {
146
+ /** The snapshot that is current now. */
147
+ readonly snapshot: Effect.Effect<InspectorSnapshot>;
148
+ /** The current snapshot, then one value per publication. */
149
+ readonly changes: Stream.Stream<InspectorSnapshot>;
150
+ /** One committed read, one projection, one reconciliation, one publication if the content moved. */
151
+ readonly refresh: Effect.Effect<void>;
152
+ /** Recompose from the cached view: no read, only a changed age publishes. */
153
+ readonly repaint: Effect.Effect<void>;
154
+ /** The single end event: a runtime end, or the owner's scope closing. */
155
+ readonly end: Stream.Stream<InspectorEnd>;
156
+ }
157
+ >()("@ftrdotdev/pi-delegates/presentation/inspector") {
158
+ static readonly layer = (deps: InspectorDeps): Layer.Layer<Inspector, InspectorReadFailed> =>
159
+ Layer.effect(
160
+ Inspector,
161
+ Effect.gen(function* () {
162
+ const pending = yield* Queue.sliding<Signal>(1);
163
+ const current = yield* SubscriptionRef.make(emptySnapshot());
164
+ const revision = yield* Ref.make(0);
165
+ const viewRef = yield* Ref.make<SessionView | undefined>(undefined);
166
+ const activity = yield* Ref.make<ReadonlyMap<string, RunActivity>>(new Map());
167
+ const closed = yield* Ref.make(false);
168
+
169
+ const observe = deps.observe ?? realSeam(deps.runtime);
170
+ const readView = deps.view ?? (() => viewSession(deps.runtime));
171
+ const now = deps.now ?? deps.runtime.now;
172
+ const timers = deps.timers ?? deps.runtime.timers;
173
+ const attached = new Map<string, Detach>();
174
+
175
+ const offer = (signal: Signal): void => {
176
+ Queue.offerUnsafe(pending, signal);
177
+ };
178
+
179
+ const logEnd = (address: string, kind: DocEndKind, reason?: string): void => {
180
+ if (kind === "failed") {
181
+ deps.runtime.log.write("warn", "inspector.observe_failed", {
182
+ address,
183
+ ...errorFields(reason ?? "the observation failed"),
184
+ });
185
+ return;
186
+ }
187
+ deps.runtime.log.write("info", "inspector.observe_ended", { address });
188
+ };
189
+
190
+ /** An end detaches the address and becomes one more document push. */
191
+ const endAddress = (address: string, kind: DocEndKind, reason?: string): void => {
192
+ const detach = attached.get(address);
193
+ attached.delete(address);
194
+ detach?.();
195
+ logEnd(address, kind, reason);
196
+ offer({ kind: "doc" });
197
+ };
198
+
199
+ const docSinkFor = <T>(address: string): DocSink<T> => ({
200
+ advance: () => {
201
+ offer({ kind: "doc" });
202
+ },
203
+ end: (kind, reason) => endAddress(address, kind, reason),
204
+ });
205
+
206
+ const targetsOf = (
207
+ snapshot: InspectorSnapshot,
208
+ ): Map<string, () => Promise<Detach | undefined>> => {
209
+ const targets = new Map<string, () => Promise<Detach | undefined>>();
210
+ targets.set(RUN_INDEX_ADDRESS, () =>
211
+ observe.observeSessionDoc(
212
+ RUN_INDEX_ADDRESS,
213
+ RunIndexDoc,
214
+ docSinkFor(RUN_INDEX_ADDRESS),
215
+ ),
216
+ );
217
+ targets.set(GATE_INDEX_ADDRESS, () =>
218
+ observe.observeSessionDoc(
219
+ GATE_INDEX_ADDRESS,
220
+ GateIndexDoc,
221
+ docSinkFor(GATE_INDEX_ADDRESS),
222
+ ),
223
+ );
224
+ // A pending request commits only its request doc and this index, so
225
+ // nothing else would repaint the row that names it.
226
+ targets.set(REQUEST_INDEX_ADDRESS, () =>
227
+ observe.observeSessionDoc(
228
+ REQUEST_INDEX_ADDRESS,
229
+ RequestIndexDoc,
230
+ docSinkFor(REQUEST_INDEX_ADDRESS),
231
+ ),
232
+ );
233
+ targets.set(TASK_GRAPH_ADDRESS, () =>
234
+ observe.observeTaskGraph(TASK_GRAPH_ADDRESS, docSinkFor<TaskGraph>(TASK_GRAPH_ADDRESS)),
235
+ );
236
+ for (const row of snapshot.rows) {
237
+ if (!isLiveStatus(row.status)) continue;
238
+ const address = runAddress(row.runId);
239
+ targets.set(address, () =>
240
+ observe.observeFamilyDoc(address, RunDoc, row.runId, docSinkFor<JsonObject>(address)),
241
+ );
242
+ }
243
+ for (const gate of snapshot.gates) {
244
+ targets.set(gate.id, () =>
245
+ observe.observeFamilyDoc(
246
+ gate.id,
247
+ GateDoc,
248
+ gateKey(gate.runId, gate.gate),
249
+ docSinkFor<JsonObject>(gate.id),
250
+ ),
251
+ );
252
+ }
253
+ for (const row of snapshot.rows) {
254
+ if (!isLiveStatus(row.status) || row.conversationId === null) continue;
255
+ const address = liveAddress(row.conversationId);
256
+ const runId = row.runId;
257
+ targets.set(address, () =>
258
+ observe.watchActivity(
259
+ address,
260
+ row.conversationId as number,
261
+ (next) => offer({ kind: "activity", runId, activity: next }),
262
+ (kind, reason) => endAddress(address, kind, reason),
263
+ ),
264
+ );
265
+ }
266
+ return targets;
267
+ };
268
+
269
+ /** Attach what is new and present; detach what left the projection. */
270
+ const reconcile = Effect.fn("Inspector.reconcile")(function* (snapshot: InspectorSnapshot) {
271
+ const targets = targetsOf(snapshot);
272
+ for (const [address, detach] of attached) {
273
+ if (targets.has(address)) continue;
274
+ attached.delete(address);
275
+ detach();
276
+ }
277
+ for (const [address, attach] of targets) {
278
+ if (attached.has(address)) continue;
279
+ const exit = yield* Effect.exit(
280
+ Effect.tryPromise({
281
+ try: () => attach(),
282
+ catch: (cause) => InspectorAttachFailed.make({ address, cause }),
283
+ }),
284
+ );
285
+ if (Exit.isSuccess(exit)) {
286
+ if (exit.value !== undefined) attached.set(address, exit.value);
287
+ continue;
288
+ }
289
+ deps.runtime.log.write("warn", "inspector.observe_failed", {
290
+ address,
291
+ ...describeFailure(exit.cause),
292
+ });
293
+ }
294
+ });
295
+
296
+ /** One replacement per content change: the revision counts publications, not reads. */
297
+ const publishIfChanged = Effect.fn("Inspector.publish")(function* (
298
+ next: InspectorSnapshot,
299
+ ) {
300
+ const previous = yield* SubscriptionRef.get(current);
301
+ if (InspectorSnapshotEquivalence(previous, next)) return;
302
+ const number = yield* Ref.updateAndGet(revision, (value) => value + 1);
303
+ yield* SubscriptionRef.set(current, { ...next, revision: number });
304
+ });
305
+
306
+ /** One committed read, one projection, one publication, one reconciliation. */
307
+ const readAndPublish: Effect.Effect<void, InspectorReadFailed> = Effect.gen(function* () {
308
+ if (yield* Ref.get(closed)) return;
309
+ const view = yield* Effect.tryPromise({
310
+ try: () => readView(),
311
+ catch: (cause) => InspectorReadFailed.make({ cause }),
312
+ });
313
+ yield* Ref.set(viewRef, view);
314
+ const activityByRun = yield* Ref.get(activity);
315
+ const previous = yield* SubscriptionRef.get(current);
316
+ const next = projectSnapshot({
317
+ view,
318
+ activity: activityByRun,
319
+ now: now(),
320
+ revision: previous.revision,
321
+ });
322
+ yield* publishIfChanged(next);
323
+ yield* reconcile(next);
324
+ });
325
+
326
+ /** An activity arrival: no store read, one projection over the cached view. */
327
+ const foldActivity = Effect.fn("Inspector.foldActivity")(function* (signal: {
328
+ readonly runId: string;
329
+ readonly activity: RunActivity;
330
+ }) {
331
+ const view = yield* Ref.get(viewRef);
332
+ if (view === undefined) return;
333
+ const previous = yield* SubscriptionRef.get(current);
334
+ yield* Ref.update(activity, (map) => new Map(map).set(signal.runId, signal.activity));
335
+ const activityByRun = yield* Ref.get(activity);
336
+ yield* publishIfChanged(
337
+ projectSnapshot({
338
+ view,
339
+ activity: activityByRun,
340
+ now: now(),
341
+ revision: previous.revision,
342
+ }),
343
+ );
344
+ });
345
+
346
+ const logRefreshFailure = (cause: Cause.Cause<unknown>): void => {
347
+ deps.runtime.log.write("warn", "inspector.refresh_failed", describeFailure(cause));
348
+ };
349
+
350
+ /** The member call never fails: a failed refresh is one log entry. */
351
+ const refresh: Effect.Effect<void> = readAndPublish.pipe(
352
+ Effect.catchCause((cause) => {
353
+ logRefreshFailure(cause);
354
+ return Effect.void;
355
+ }),
356
+ );
357
+
358
+ /** Recompose from the cached view: no read, and an unchanged age publishes nothing. */
359
+ const repaint: Effect.Effect<void> = Effect.gen(function* () {
360
+ if (yield* Ref.get(closed)) return;
361
+ const view = yield* Ref.get(viewRef);
362
+ if (view === undefined) return;
363
+ const activityByRun = yield* Ref.get(activity);
364
+ const previous = yield* SubscriptionRef.get(current);
365
+ const next = projectSnapshot({
366
+ view,
367
+ activity: activityByRun,
368
+ now: now(),
369
+ revision: previous.revision,
370
+ });
371
+ yield* publishIfChanged(next);
372
+ // An address that did not exist at attach returns no detach; retry it here so a
373
+ // document created after the inspector started is still observed.
374
+ yield* reconcile(next);
375
+ });
376
+
377
+ const repaintFiber = yield* Effect.andThen(
378
+ sleepFor(timers, REPAINT_INTERVAL_MS),
379
+ repaint,
380
+ ).pipe(Effect.forever, Effect.forkScoped);
381
+ // The clock arms its first interval before the build returns, so a
382
+ // caller that reads the snapshot can rely on the cadence existing.
383
+ yield* Effect.yieldNow;
384
+ const consumerFiber = yield* Queue.take(pending).pipe(
385
+ Effect.flatMap((signal) =>
386
+ Effect.catchCause(signal.kind === "doc" ? refresh : foldActivity(signal), (cause) => {
387
+ logRefreshFailure(cause);
388
+ return Effect.void;
389
+ }),
390
+ ),
391
+ Effect.forever,
392
+ Effect.forkScoped,
393
+ );
394
+
395
+ const endSignal = yield* Deferred.make<InspectorEnd>();
396
+
397
+ /**
398
+ * Stop the age clock, the consumer, the queue and every observation —
399
+ * once. Uninterruptible: an interrupt queued after `closed` is set must
400
+ * not skip a detach.
401
+ */
402
+ const finishSteps = Effect.fn("Inspector.finish")(function* (end: InspectorEnd) {
403
+ if (yield* Ref.getAndSet(closed, true)) return;
404
+ yield* Fiber.interrupt(repaintFiber);
405
+ yield* Fiber.interrupt(consumerFiber);
406
+ deps.onConsumerInterrupted?.();
407
+ yield* Queue.shutdown(pending);
408
+ const open = [...attached.values()];
409
+ attached.clear();
410
+ for (const detach of open) yield* Effect.sync(detach);
411
+ yield* Deferred.succeed(endSignal, end);
412
+ });
413
+ const finish = (end: InspectorEnd): Effect.Effect<void> =>
414
+ Effect.uninterruptible(finishSteps(end));
415
+
416
+ const unsubscribe = deps.runtime.onState((state) => {
417
+ if (state.kind === "closed" || state.kind === "failing") {
418
+ Deferred.doneUnsafe(endSignal, Exit.succeed(endFor(state)));
419
+ }
420
+ });
421
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
422
+ yield* Effect.addFinalizer(() => finish({ kind: "stopped" }));
423
+ const endFiber = yield* Deferred.await(endSignal).pipe(
424
+ Effect.flatMap((end) => finish(end)),
425
+ Effect.forkScoped,
426
+ );
427
+ deps.onEndFiber?.(endFiber);
428
+
429
+ // The first committed read is part of the build: if it fails, no
430
+ // inspector exists to observe with.
431
+ yield* readAndPublish;
432
+
433
+ return Inspector.of({
434
+ snapshot: SubscriptionRef.get(current),
435
+ changes: SubscriptionRef.changes(current),
436
+ refresh,
437
+ repaint,
438
+ end: Deferred.await(endSignal).pipe(Stream.fromEffect),
439
+ });
440
+ }),
441
+ );
442
+ }