@mostra/runtime 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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-D7_UVdoN.js +15752 -0
  18. package/dist/instance-D7_UVdoN.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -3
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +739 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/index.ts +1209 -0
  51. package/src/gateway/integrity.ts +117 -0
  52. package/src/gateway/listener.ts +217 -0
  53. package/src/gateway/routes.ts +197 -0
  54. package/src/gateway/serve.ts +138 -0
  55. package/src/gc/index.ts +451 -0
  56. package/src/home/acquire.ts +276 -0
  57. package/src/home/index.ts +16 -0
  58. package/src/home/paths.ts +192 -0
  59. package/src/home/platform.ts +34 -0
  60. package/src/home/record.ts +76 -0
  61. package/src/home/settings.ts +113 -0
  62. package/src/index.ts +30 -0
  63. package/src/instance/index.ts +942 -0
  64. package/src/interaction/ephemeral.ts +300 -0
  65. package/src/interaction/events.ts +355 -0
  66. package/src/interaction/fields.ts +392 -0
  67. package/src/interaction/index.ts +1009 -0
  68. package/src/interaction/outbox.ts +493 -0
  69. package/src/interaction/policy.ts +26 -0
  70. package/src/interaction/results.ts +341 -0
  71. package/src/interaction/runs.ts +313 -0
  72. package/src/interaction/signals.ts +120 -0
  73. package/src/interaction/submissions.ts +585 -0
  74. package/src/interaction/subscriptions.ts +258 -0
  75. package/src/interaction/viewers.ts +173 -0
  76. package/src/interaction/wait.ts +201 -0
  77. package/src/ledger/index.ts +442 -0
  78. package/src/ledger/migrations.ts +583 -0
  79. package/src/ledger/requests.ts +105 -0
  80. package/src/ledger/types.ts +28 -0
  81. package/src/live/index.ts +573 -0
  82. package/src/log.ts +316 -0
  83. package/src/processes/child.ts +67 -0
  84. package/src/processes/environment.ts +64 -0
  85. package/src/processes/identity.ts +191 -0
  86. package/src/processes/index.ts +19 -0
  87. package/src/processes/manager.ts +543 -0
  88. package/src/protocol-server/client.ts +94 -0
  89. package/src/protocol-server/index.ts +91 -0
  90. package/src/protocol-server/server.ts +509 -0
  91. package/src/protocol-server/streams.ts +81 -0
  92. package/src/publish/checks.ts +92 -0
  93. package/src/publish/digest.ts +87 -0
  94. package/src/publish/index.ts +23 -0
  95. package/src/publish/manifest.ts +409 -0
  96. package/src/publish/methods.ts +96 -0
  97. package/src/publish/publisher.ts +913 -0
  98. package/src/publish/source.ts +272 -0
  99. package/src/publish/tar.ts +110 -0
  100. package/src/registry/index.ts +481 -0
  101. package/src/registry/store.ts +136 -0
  102. package/src/secrets/index.ts +223 -0
  103. package/src/service/idle.ts +64 -0
  104. package/src/service/index.ts +3 -0
  105. package/src/service/unit.ts +250 -0
  106. package/src/verify/fields.ts +125 -0
  107. package/src/verify/index.ts +913 -0
  108. package/src/verify/regression.ts +157 -0
  109. package/src/verify/runner.ts +230 -0
  110. package/src/verify/sandbox.ts +407 -0
  111. package/src/verify/typecheck.ts +371 -0
  112. package/src/workers/index.ts +17 -0
  113. package/src/workers/launcher.ts +260 -0
  114. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,1009 @@
1
+ /**
2
+ * The interaction core (ARCHITECTURE §6; IN-01 to IN-12, LL-01, LL-02): drafts and artifact
3
+ * state, submissions and their delivery, signals, events, `wait` and results. The supervisor's
4
+ * one owner of them: the gateway reaches it for the browser protocol, the protocol server for the
5
+ * host methods, and every change is one ledger transaction that appends its events.
6
+ *
7
+ * ```ts
8
+ * const interaction = createInteraction({ ledger, log, faults, hosts, settings, artifacts });
9
+ * interaction.start();
10
+ * const { submission } = interaction.submit({ artifactId, viewerId, viewId, expectedRevision, channel });
11
+ * ```
12
+ */
13
+ import {
14
+ type Actor,
15
+ type ArtifactRef,
16
+ type Batches,
17
+ type CapabilityScope,
18
+ type CarryOver,
19
+ type ControlsPolicy,
20
+ createDiagnostic,
21
+ type DeliveryCounts,
22
+ type EventFilter,
23
+ type EventRecord,
24
+ eventsAckMethod,
25
+ eventsReadMethod,
26
+ eventsSubscribeMethod,
27
+ eventsUnsubscribeMethod,
28
+ type FieldOp,
29
+ type FieldScope,
30
+ type FieldState,
31
+ MutationId,
32
+ type MutationResult,
33
+ type Results,
34
+ RpcError,
35
+ type RunState,
36
+ refusal,
37
+ resultsGetMethod,
38
+ type StreamSnapshot,
39
+ type SubmissionSummary,
40
+ type SubmitChannel,
41
+ scopeAllows,
42
+ stateGetMethod,
43
+ statePatchMethod,
44
+ type Viewer,
45
+ type ViewerSpec,
46
+ waitMethod,
47
+ } from "@mostra/protocol";
48
+ import type { Faults } from "../faults.ts";
49
+ import type { Ledger, LedgerDb } from "../ledger/index.ts";
50
+ import type { Log } from "../log.ts";
51
+ import { handler, type MethodHandler, type Session } from "../protocol-server/index.ts";
52
+ import { appendEvent, latestCursor, readEvents } from "./events.ts";
53
+ import {
54
+ applyMutation,
55
+ documentFor,
56
+ type FieldRow,
57
+ liveFields,
58
+ replayedMutation,
59
+ } from "./fields.ts";
60
+ import { type HostConnections, Outbox } from "./outbox.ts";
61
+ import { buildResults, CHOICE, resultsMarkdown, submissionFor } from "./results.ts";
62
+ import {
63
+ appendRunOutput,
64
+ createOrJoinRun,
65
+ finishRun,
66
+ markRunning,
67
+ openRuns,
68
+ type RunEnd,
69
+ type RunFlush,
70
+ type RunOutput,
71
+ type RunRow,
72
+ runById,
73
+ runByKey,
74
+ runState,
75
+ } from "./runs.ts";
76
+ import { raiseSignal } from "./signals.ts";
77
+ import {
78
+ assertChannel,
79
+ assertDraftOpen,
80
+ closingSubmission,
81
+ orphansOf,
82
+ type Snapshot,
83
+ type SubmissionRow,
84
+ submissionSummary,
85
+ submit,
86
+ } from "./submissions.ts";
87
+ import { Subscriptions } from "./subscriptions.ts";
88
+ import {
89
+ localViewerId,
90
+ openView,
91
+ viewControls,
92
+ viewer,
93
+ viewerForSpec,
94
+ viewFor,
95
+ } from "./viewers.ts";
96
+ import { waitFor } from "./wait.ts";
97
+
98
+ export { createEphemeralBus, type EphemeralBus } from "./ephemeral.ts";
99
+ export { appendEvent, compactEvents, redactEvents } from "./events.ts";
100
+ export type { HostConnections } from "./outbox.ts";
101
+ export { policyInForce } from "./policy.ts";
102
+ export type { RunEnd, RunFlush, RunOutput, RunRow } from "./runs.ts";
103
+ export { SubmitConflict } from "./submissions.ts";
104
+
105
+ /** How the interaction core finds an artifact a host names. */
106
+ export interface InteractionArtifacts {
107
+ /** The artifact's ID; throws `MOSTRA_ARTIFACT_NOT_FOUND` for an unknown one. */
108
+ resolve(ref: ArtifactRef): string;
109
+ }
110
+
111
+ /** Options for {@link createInteraction}. */
112
+ export interface InteractionOptions {
113
+ readonly ledger: Ledger;
114
+ readonly log: Log;
115
+ readonly faults: Faults;
116
+ readonly hosts: HostConnections & {
117
+ /** Sends a notification on a connection; `false` when it is gone. */
118
+ notify(session: number, method: string, params: unknown): boolean;
119
+ /** Settles when a full connection drained; `undefined` when it can take more now. */
120
+ drained(session: number): Promise<void> | undefined;
121
+ };
122
+ /** The hosts that always provide the submissions port (`HomeConfig.ports`, D105). */
123
+ readonly expectedHosts: () => readonly string[];
124
+ readonly artifacts: InteractionArtifacts;
125
+ /**
126
+ * Whether a version covers a field ID (D109): from the version's `registry.json`; every ID for
127
+ * a version whose code can use IDs the builder couldn't know.
128
+ */
129
+ readonly coverage: (versionId: string) => (fieldId: string) => boolean;
130
+ /** How long a host has to answer a port call (30 s; tests shorten it). */
131
+ readonly portTimeoutMs?: number;
132
+ }
133
+
134
+ /** A browser session as the interaction core sees it: who it acts as. */
135
+ export interface PageIdentity {
136
+ readonly artifactId: string;
137
+ readonly viewerId: string;
138
+ /** The link the page's session came from: a page names only views its own link opened. */
139
+ readonly tokenId?: string;
140
+ /** The link's scopes (D97): a page writes a review set's choice only with `review`. */
141
+ readonly scopes?: readonly CapabilityScope[];
142
+ }
143
+
144
+ /** The interaction core of one instance. */
145
+ export interface Interaction {
146
+ /** Starts delivering submissions and events. */
147
+ start(): void;
148
+ /** Stops delivering; pending deliveries stay in the outbox. */
149
+ stop(): void;
150
+
151
+ /** The viewer a capability token's sessions act as (D104): its own, or the home's local user. */
152
+ viewerOf(tokenViewerId: string | undefined): string;
153
+ /** A viewer by ID (D104). */
154
+ viewer(viewerId: string): Viewer;
155
+ /** The viewer for `view/url`'s `viewer`, inside the caller's transaction. */
156
+ viewerForSpec(db: LedgerDb, spec: ViewerSpec): string;
157
+ /** Records a frame load of a version (D104), with the controls in force (D108); returns its ID. */
158
+ openView(input: {
159
+ readonly artifactId: string;
160
+ readonly versionId: string;
161
+ readonly viewerId: string;
162
+ readonly tokenId?: string;
163
+ readonly controls?: ControlsPolicy;
164
+ }): string;
165
+ /** The channels and controls a page's view was opened with (D108). */
166
+ viewControls(page: PageIdentity, viewId: string): ControlsPolicy;
167
+
168
+ /** A viewer's mutation of their draft or the artifact's state, from a page (IN-01, LL-01). */
169
+ mutate(
170
+ page: PageIdentity,
171
+ input: {
172
+ readonly viewId: string;
173
+ readonly scope: FieldScope;
174
+ readonly mutationId: string;
175
+ readonly baseRevision: number;
176
+ readonly ops: readonly FieldOp[];
177
+ },
178
+ ): MutationResult;
179
+ /** A viewer's submit (IN-05); `SubmitConflict` under a closed `once`. */
180
+ submit(
181
+ page: PageIdentity,
182
+ input: {
183
+ readonly viewId: string;
184
+ readonly expectedRevision: number;
185
+ readonly channel: SubmitChannel;
186
+ },
187
+ ): SubmissionSummary & { readonly duplicate?: true };
188
+ /**
189
+ * The shell's trusted Choose (D65, D113): writes `review.<set>.choice` in the viewer's draft
190
+ * through the `shell` channel, keeping the candidate's label.
191
+ */
192
+ choose(
193
+ page: PageIdentity,
194
+ input: {
195
+ readonly viewId: string;
196
+ readonly mutationId: string;
197
+ readonly baseRevision: number;
198
+ readonly reviewSetId: string;
199
+ readonly candidateId: string;
200
+ readonly label?: string;
201
+ },
202
+ ): MutationResult;
203
+ /** The viewer's draft fields a version doesn't cover (D42, D109). */
204
+ carryOver(
205
+ page: PageIdentity,
206
+ version: { readonly id: string; readonly number: number },
207
+ ): CarryOver;
208
+ /** Whether the viewer follows the artifact's new versions (D63). */
209
+ following(page: PageIdentity): boolean;
210
+ /** Sets the viewer's "Always follow this artifact" (D63, LL-03). */
211
+ setFollowing(page: PageIdentity, follow: boolean): void;
212
+ /** A viewer's signal (IN-09); returns its cursor. */
213
+ signal(
214
+ page: PageIdentity,
215
+ input: { readonly viewId: string; readonly name: string; readonly payload?: unknown },
216
+ ): string;
217
+ /** Checks that a view belongs to this page's artifact and viewer (D104). */
218
+ checkView(page: PageIdentity, viewId: string): void;
219
+ /** Where a page stands: its viewer, draft, the artifact state and the newest cursor. */
220
+ pageSnapshot(page: PageIdentity): StreamSnapshot;
221
+ /** The events a page may see after a cursor (D104): never another viewer's draft or signals. */
222
+ pageEvents(
223
+ page: PageIdentity,
224
+ after: number,
225
+ limit: number,
226
+ ): { readonly events: EventRecord[]; readonly cursor: string };
227
+ /** Calls `listener` after every commit; returns the unsubscribe function. */
228
+ onCommit(listener: () => void): () => void;
229
+
230
+ /** The host protocol methods: `state/*`, `results/get`, `wait`, `events/*`. */
231
+ methods(): MethodHandler[];
232
+ /** A connection initialized: hosts with ports get their deliveries. */
233
+ connected(session: Session): void;
234
+ /** A connection closed: its subscriptions end. */
235
+ disconnected(session: Session): void;
236
+ /** The outbox per host, for `instance/status`. */
237
+ deliveries(): DeliveryCounts[];
238
+
239
+ // ── Actions (WP-08) ──────────────────────────────────────────────────────────────────────
240
+ /** The version a page's view shows: plain calls and runs run there (D104). */
241
+ viewVersion(page: PageIdentity, viewId: string): string;
242
+ /**
243
+ * Records an action run before any worker starts it, or joins the one its key or client key
244
+ * names (AC-03); `started` tells the caller to run it.
245
+ */
246
+ startRun(
247
+ page: PageIdentity,
248
+ input: {
249
+ readonly viewId: string;
250
+ readonly fnId: string;
251
+ readonly args: Batches;
252
+ readonly key?: string;
253
+ readonly clientKey: string;
254
+ },
255
+ ): { readonly state: RunState; readonly row: RunRow; readonly started: boolean };
256
+ /** Runs a page asks for by ID, or by function and key (re-attach, AC-02). */
257
+ runsFor(
258
+ page: PageIdentity,
259
+ input: {
260
+ readonly viewId: string;
261
+ readonly runIds?: readonly string[];
262
+ readonly keyed?: readonly { readonly fnId: string; readonly key: string }[];
263
+ readonly held?: readonly {
264
+ readonly runId: string;
265
+ readonly log: number;
266
+ readonly batches: number;
267
+ }[];
268
+ },
269
+ ): RunState[];
270
+ /** One run of the page's artifact, for a cancel; `MOSTRA_ACTION_RUN_NOT_FOUND` otherwise. */
271
+ runFor(page: PageIdentity, viewId: string, runId: string): RunRow;
272
+ /** A run its worker has. */
273
+ runRunning(runId: string): void;
274
+ /** A run's new log lines, batches and progress. */
275
+ runOutput(runId: string, output: RunOutput): RunFlush | undefined;
276
+ /** Ends a run with its event. */
277
+ endRun(runId: string, end: RunEnd): RunState | undefined;
278
+ /** The runs not yet ended, optionally of one version. */
279
+ openRuns(versionId?: string): RunRow[];
280
+ /** A run's state now. */
281
+ runState(runId: string): RunState | undefined;
282
+ /** `signal()` from server code: `signal.raised`, source `action`, the run as cause (AC-05). */
283
+ serverSignal(
284
+ artifactId: string,
285
+ input: {
286
+ readonly name: string;
287
+ readonly payload?: unknown;
288
+ readonly runId?: string;
289
+ readonly viewerId?: string;
290
+ },
291
+ ): string;
292
+ /** `emit()` from server code: a `host.<name>` event (AC-05). */
293
+ serverEmit(
294
+ artifactId: string,
295
+ input: {
296
+ readonly type: string;
297
+ readonly payload?: unknown;
298
+ readonly runId?: string;
299
+ readonly viewerId?: string;
300
+ },
301
+ ): string;
302
+ /** The artifact state, for `state.get` in server code. */
303
+ serverState(
304
+ artifactId: string,
305
+ ids?: readonly string[],
306
+ ): { revision: string; fields: Record<string, FieldState> };
307
+ /** A state write from server code, as the agent (D63). */
308
+ serverPatch(
309
+ artifactId: string,
310
+ input: {
311
+ readonly ops: readonly FieldOp[];
312
+ readonly mutationId?: string;
313
+ readonly baseRevision?: string;
314
+ readonly runId?: string;
315
+ },
316
+ ): MutationResult;
317
+ /** The artifacts a host subscription names, whose live producers it keeps running. */
318
+ subscribedArtifacts(): Set<string>;
319
+ /** Appends `worker.crashed` (DATA_MODEL §4, RT-04): the version, the cause, the backoff. */
320
+ workerCrashed(crash: {
321
+ readonly artifactId: string;
322
+ readonly versionId: string;
323
+ readonly cause: string;
324
+ readonly kind: string;
325
+ readonly backoffMs: number;
326
+ readonly parked: boolean;
327
+ }): string;
328
+ /** Hears every `version.published` once it commits, by artifact; returns the stop. */
329
+ onPublished(listener: (artifactId: string, versionId: string) => void): () => void;
330
+ /**
331
+ * Hears every submission once it commits, with its Results (INTERFACES §8): how a `mostra dev`
332
+ * session reports what its preview's submits would deliver (D140 item 12). Returns the stop.
333
+ */
334
+ onSubmission(listener: (results: Results) => void): () => void;
335
+ /** How many host subscriptions are open. */
336
+ subscriptionCount(): number;
337
+ }
338
+
339
+ function runNotFound(runId: string): RpcError {
340
+ return new RpcError(
341
+ createDiagnostic("MOSTRA_ACTION_RUN_NOT_FOUND", {
342
+ message: `This artifact has no action run ${String(runId).slice(0, 64)}.`,
343
+ }),
344
+ );
345
+ }
346
+
347
+ /** The number of a version. */
348
+ function versionNumber(db: LedgerDb, versionId: string): number {
349
+ const row = db.get<{ number: number }>("SELECT number FROM version WHERE id = ?", versionId);
350
+ if (!row) throw new Error(`No version ${versionId}.`);
351
+ return row.number;
352
+ }
353
+
354
+ /**
355
+ * Whether a page may see an event (D104, D130): never another viewer's draft, signal or view;
356
+ * server code's signals only by the viewer whose call raised them; `host.*` events never (they
357
+ * are for hosts, AC-05); an action's run events only through a link that may see its run.
358
+ * `run` looks a run up by its ID.
359
+ */
360
+ function visibleTo(
361
+ event: EventRecord,
362
+ page: PageIdentity,
363
+ run: (runId: string) => RunRow | undefined,
364
+ ): boolean {
365
+ const viewerId = page.viewerId;
366
+ if (event.type.startsWith("draft.")) return event.payload["viewerId"] === viewerId;
367
+ if (event.type.startsWith("host.")) return false;
368
+ if (event.type.startsWith("action.")) {
369
+ const row = run(String(event.payload["runId"] ?? ""));
370
+ return row !== undefined && runVisible(row, page);
371
+ }
372
+ if (event.type === "signal.raised" && event.payload["source"] === "action") {
373
+ return event.payload["viewerId"] === viewerId;
374
+ }
375
+ if (event.type === "signal.raised" || event.type.startsWith("view.")) {
376
+ return event.actor.kind !== "viewer" || event.actor.id === viewerId;
377
+ }
378
+ return true;
379
+ }
380
+
381
+ /**
382
+ * Another viewer as a page sees them: kind and display name, never their viewer or view IDs
383
+ * (D104; Claude review finding 12). The name stays, so a conflict can say who changed a field.
384
+ */
385
+ function actorForPage(actor: Actor, viewerId: string): Actor {
386
+ if (actor.kind !== "viewer" || actor.id === viewerId) return actor;
387
+ return { kind: "viewer", ...(actor.name !== undefined ? { name: actor.name } : {}) };
388
+ }
389
+
390
+ /** An event as a page sees it: other viewers' identities left out. */
391
+ function eventForPage(event: EventRecord, viewerId: string): EventRecord {
392
+ // A worker's crash shows a page only what the shell's notice needs: never the server code's
393
+ // own output, which its cause quotes (Opus review 4).
394
+ if (event.type === "worker.crashed") {
395
+ const { cause: _cause, ...payload } = event.payload as Record<string, unknown>;
396
+ return { ...event, payload };
397
+ }
398
+ if (event.type.startsWith("action.") || event.type === "signal.raised") {
399
+ // A run's or a signal's own viewer: a page sees only its own runs' viewer, so leave it out.
400
+ const { viewerId: _viewer, ...payload } = event.payload as Record<string, unknown>;
401
+ if (event.actor.kind !== "viewer") return { ...event, payload };
402
+ }
403
+ const own = event.actor.kind !== "viewer" || event.actor.id === viewerId;
404
+ if (own) return event;
405
+ const { viewerId: _viewer, viewId: _view, ...payload } = event.payload as Record<string, unknown>;
406
+ const causation = event.causation
407
+ ? Object.fromEntries(Object.entries(event.causation).filter(([key]) => key !== "viewId"))
408
+ : undefined;
409
+ return {
410
+ ...event,
411
+ actor: actorForPage(event.actor, viewerId),
412
+ ...(causation ? { causation } : {}),
413
+ payload,
414
+ };
415
+ }
416
+
417
+ /** Fields as a page sees them: who last wrote each, without another viewer's ID. */
418
+ function fieldsForPage(
419
+ fields: Record<string, FieldState>,
420
+ viewerId: string,
421
+ ): Record<string, FieldState> {
422
+ return Object.fromEntries(
423
+ Object.entries(fields).map(([id, field]) => [
424
+ id,
425
+ field.updatedBy ? { ...field, updatedBy: actorForPage(field.updatedBy, viewerId) } : field,
426
+ ]),
427
+ );
428
+ }
429
+
430
+ /**
431
+ * Whether a page may see a run (D97 item 4, D104, D130): only through a link that may run its
432
+ * function, and then a keyed run belongs to the artifact, since its key makes it one invocation
433
+ * for everyone who may run it, while a run without a key is its viewer's own.
434
+ */
435
+ function runVisible(row: RunRow, page: PageIdentity): boolean {
436
+ if (!scopeAllows(page.scopes ?? [], `action:${row.action}` as CapabilityScope)) return false;
437
+ return row.key !== null || row.viewer_id === page.viewerId;
438
+ }
439
+
440
+ /** Creates the interaction core. */
441
+
442
+ export function createInteraction(options: InteractionOptions): Interaction {
443
+ const { ledger, log, hosts } = options;
444
+ const outbox = new Outbox({
445
+ ledger,
446
+ log,
447
+ hosts,
448
+ expected: options.expectedHosts,
449
+ faults: options.faults,
450
+ ...(options.portTimeoutMs !== undefined ? { portTimeoutMs: options.portTimeoutMs } : {}),
451
+ });
452
+ const subscriptions = new Subscriptions({
453
+ ledger,
454
+ log,
455
+ notify: (session, method, params) => hosts.notify(session, method, params),
456
+ drained: (session) => hosts.drained(session),
457
+ });
458
+
459
+ const pageActor = (page: PageIdentity): Actor => {
460
+ const record = ledger.read((db) => viewer(db, page.viewerId));
461
+ return {
462
+ kind: "viewer",
463
+ id: page.viewerId,
464
+ ...(record.name !== undefined ? { name: record.name } : {}),
465
+ };
466
+ };
467
+
468
+ const documentSnapshot = (db: LedgerDb, artifactId: string, viewerId: string | null) => {
469
+ const document = documentFor(db, artifactId, viewerId);
470
+ return {
471
+ revision: String(document?.revision ?? 0),
472
+ epoch: document?.epoch ?? 1,
473
+ fields: liveFields(db, document?.id),
474
+ };
475
+ };
476
+
477
+ const clientActor = (session: Session, as: "agent" | "host" = "agent"): Actor => ({
478
+ kind: as,
479
+ ...(session.client ? { id: session.client.name } : {}),
480
+ });
481
+
482
+ return {
483
+ start() {
484
+ outbox.start();
485
+ subscriptions.start();
486
+ },
487
+ stop() {
488
+ outbox.stop();
489
+ subscriptions.stop();
490
+ },
491
+
492
+ viewerOf(tokenViewerId) {
493
+ if (tokenViewerId !== undefined) return tokenViewerId;
494
+ const existing = ledger.read((db) =>
495
+ db.get<{ id: string }>(
496
+ "SELECT id FROM viewer WHERE kind = 'local' AND external_ref = 'local'",
497
+ ),
498
+ );
499
+ return existing?.id ?? ledger.write((db) => localViewerId(db));
500
+ },
501
+ viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
502
+ viewerForSpec,
503
+ openView(input) {
504
+ return ledger.write((db) => openView(db, input));
505
+ },
506
+ viewControls(page, viewId) {
507
+ return ledger.read((db) =>
508
+ viewControls(viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId)),
509
+ );
510
+ },
511
+
512
+ mutate(page, input) {
513
+ const actor = pageActor(page);
514
+ const outcome = ledger.write((db) => {
515
+ const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);
516
+ const mutation = {
517
+ artifactId: page.artifactId,
518
+ scope: input.scope,
519
+ ...(input.scope === "viewer" ? { viewerId: page.viewerId } : {}),
520
+ mutationId: input.mutationId,
521
+ baseRevision: input.baseRevision,
522
+ ops: input.ops,
523
+ actor,
524
+ viewId: input.viewId,
525
+ versionNumber: versionNumber(db, view.version_id),
526
+ };
527
+ // A committed mutation replays its result even after a submission closed the draft (D106):
528
+ // the retry of a save whose answer was lost must not turn into a failure.
529
+ const replay = replayedMutation(db, mutation);
530
+ if (replay) return { result: replay, changed: false, replayed: true };
531
+ if (input.scope === "viewer") {
532
+ assertDraftOpen(db, page.artifactId, page.viewerId);
533
+ if (input.ops.some((op) => CHOICE.test(op.id))) {
534
+ // A choice needs the `review` scope however it is written, as the trusted Choose
535
+ // does (D97; Claude review finding 7)…
536
+ if (page.scopes !== undefined && !scopeAllows(page.scopes, "review")) {
537
+ throw new RpcError(
538
+ refusal("MOSTRA_HYGIENE_SCOPE_DENIED", "This link doesn't carry the review scope.")
539
+ .diagnostic,
540
+ );
541
+ }
542
+ // …and a page's own choice is the artifact channel, which the host may not allow (D108).
543
+ assertChannel(view, "artifact");
544
+ }
545
+ }
546
+ return applyMutation(db, mutation);
547
+ });
548
+ const result = {
549
+ ...outcome.result,
550
+ conflicts: outcome.result.conflicts.map((conflict) =>
551
+ conflict.updatedBy
552
+ ? { ...conflict, updatedBy: actorForPage(conflict.updatedBy, page.viewerId) }
553
+ : conflict,
554
+ ),
555
+ };
556
+ if (outcome.changed && input.scope === "viewer")
557
+ outbox.mirror(page.artifactId, page.viewerId);
558
+ return result;
559
+ },
560
+ submit(page, input) {
561
+ const owners = outbox.owners();
562
+ const outcome = ledger.write((db) =>
563
+ submit(db, {
564
+ artifactId: page.artifactId,
565
+ viewerId: page.viewerId,
566
+ ...(page.tokenId !== undefined ? { tokenId: page.tokenId } : {}),
567
+ viewId: input.viewId,
568
+ expectedRevision: input.expectedRevision,
569
+ channel: input.channel,
570
+ owners,
571
+ covers: options.coverage,
572
+ }),
573
+ );
574
+ if (outcome.created) {
575
+ log.info("interaction.submitted", {
576
+ artifactId: page.artifactId,
577
+ submissionId: outcome.submission.id,
578
+ channel: input.channel,
579
+ });
580
+ }
581
+ // Read again after the commit: the outbox's first step runs on commit and may already have
582
+ // marked a delivery waiting, which the answer must not contradict (Claude review finding 8).
583
+ const fresh = ledger.read((db) => {
584
+ const row = db.get<SubmissionRow>(
585
+ "SELECT * FROM submission WHERE id = ?",
586
+ outcome.submission.id,
587
+ );
588
+ return row ? submissionSummary(db, row) : undefined;
589
+ });
590
+ if (!fresh) return outcome.submission;
591
+ return outcome.submission.duplicate ? { ...fresh, duplicate: true } : fresh;
592
+ },
593
+ choose(page, input) {
594
+ const actor = pageActor(page);
595
+ const outcome = ledger.write((db) => {
596
+ const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);
597
+ assertChannel(view, "shell");
598
+ const mutation = {
599
+ artifactId: page.artifactId,
600
+ scope: "viewer" as const,
601
+ viewerId: page.viewerId,
602
+ mutationId: input.mutationId,
603
+ baseRevision: input.baseRevision,
604
+ ops: [
605
+ {
606
+ id: `review.${input.reviewSetId}.choice`,
607
+ value: input.candidateId,
608
+ ...(input.label !== undefined ? { label: input.label } : {}),
609
+ },
610
+ ],
611
+ actor,
612
+ viewId: input.viewId,
613
+ versionNumber: versionNumber(db, view.version_id),
614
+ channel: "shell" as const,
615
+ };
616
+ const replay = replayedMutation(db, mutation);
617
+ if (replay) return { result: replay, changed: false, replayed: true };
618
+ assertDraftOpen(db, page.artifactId, page.viewerId);
619
+ return applyMutation(db, mutation);
620
+ });
621
+ if (outcome.changed) outbox.mirror(page.artifactId, page.viewerId);
622
+ return outcome.result;
623
+ },
624
+ carryOver(page, version) {
625
+ const covers = options.coverage(version.id);
626
+ return ledger.read((db) => {
627
+ const draft = documentFor(db, page.artifactId, page.viewerId);
628
+ const rows =
629
+ draft === undefined
630
+ ? []
631
+ : db.all<FieldRow>(
632
+ "SELECT * FROM field WHERE document_id = ? AND deleted = 0 ORDER BY field_id",
633
+ draft.id,
634
+ );
635
+ return { version, orphans: orphansOf(rows.filter((row) => !covers(row.field_id))) };
636
+ });
637
+ },
638
+ following(page) {
639
+ return ledger.read(
640
+ (db) =>
641
+ db.get(
642
+ "SELECT 1 FROM follow WHERE viewer_id = ? AND artifact_id = ?",
643
+ page.viewerId,
644
+ page.artifactId,
645
+ ) !== undefined,
646
+ );
647
+ },
648
+ setFollowing(page, follow) {
649
+ ledger.write((db) => {
650
+ if (follow) {
651
+ db.run(
652
+ "INSERT OR IGNORE INTO follow (viewer_id, artifact_id, followed_at) VALUES (?, ?, ?)",
653
+ page.viewerId,
654
+ page.artifactId,
655
+ new Date().toISOString(),
656
+ );
657
+ } else {
658
+ db.run(
659
+ "DELETE FROM follow WHERE viewer_id = ? AND artifact_id = ?",
660
+ page.viewerId,
661
+ page.artifactId,
662
+ );
663
+ }
664
+ });
665
+ },
666
+ signal(page, input) {
667
+ const actor = pageActor(page);
668
+ return ledger.write((db) => {
669
+ viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);
670
+ return raiseSignal(db, {
671
+ artifactId: page.artifactId,
672
+ name: input.name,
673
+ ...(input.payload !== undefined ? { payload: input.payload } : {}),
674
+ source: "artifact",
675
+ actor,
676
+ viewId: input.viewId,
677
+ });
678
+ });
679
+ },
680
+ checkView(page, viewId) {
681
+ ledger.read((db) => viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId));
682
+ },
683
+ pageSnapshot(page) {
684
+ return ledger.read((db) => {
685
+ const closing = closingSubmission(db, page.artifactId, page.viewerId);
686
+ const latestOwn =
687
+ closing ??
688
+ db.get<SubmissionRow>(
689
+ "SELECT * FROM submission WHERE artifact_id = ? AND viewer_id = ? ORDER BY position DESC LIMIT 1",
690
+ page.artifactId,
691
+ page.viewerId,
692
+ );
693
+ return {
694
+ cursor: String(latestCursor(db)),
695
+ viewer: viewer(db, page.viewerId),
696
+ draft: documentSnapshot(db, page.artifactId, page.viewerId),
697
+ state: (() => {
698
+ const state = documentSnapshot(db, page.artifactId, null);
699
+ return { ...state, fields: fieldsForPage(state.fields, page.viewerId) };
700
+ })(),
701
+ ...(latestOwn ? { submission: submissionSummary(db, latestOwn) } : {}),
702
+ ...(() => {
703
+ // The latest version, so a page that missed its `version.published` learns of it.
704
+ const latest = db.get<{ id: string; number: number }>(
705
+ `SELECT version.id, version.number FROM artifact
706
+ JOIN version ON version.id = artifact.latest_version_id WHERE artifact.id = ?`,
707
+ page.artifactId,
708
+ );
709
+ return latest ? { latest: { id: latest.id, number: latest.number } } : {};
710
+ })(),
711
+ };
712
+ });
713
+ },
714
+ pageEvents(page, after, limit) {
715
+ // Read in pages until enough visible events or the end, so other viewers' events never
716
+ // stall a page.
717
+ return ledger.read((db) => {
718
+ const events: EventRecord[] = [];
719
+ let cursor = after;
720
+ const runs = new Map<string, RunRow | undefined>();
721
+ const runOf = (runId: string): RunRow | undefined => {
722
+ if (!runs.has(runId)) runs.set(runId, runById(db, page.artifactId, runId));
723
+ return runs.get(runId);
724
+ };
725
+ for (;;) {
726
+ const read = readEvents(db, {
727
+ filter: { artifacts: [page.artifactId] },
728
+ after: cursor,
729
+ limit,
730
+ });
731
+ for (const event of read.events) {
732
+ if (events.length === limit) return { events, cursor: String(cursor) };
733
+ cursor = Number(event.cursor);
734
+ if (visibleTo(event, page, runOf)) events.push(eventForPage(event, page.viewerId));
735
+ }
736
+ cursor = Math.max(cursor, Number(read.cursor));
737
+ if (read.events.length < limit || events.length === limit) {
738
+ return { events, cursor: String(cursor) };
739
+ }
740
+ }
741
+ });
742
+ },
743
+ onCommit: (listener) => ledger.onCommit(listener),
744
+
745
+ methods: () => [
746
+ handler(stateGetMethod, (params) => {
747
+ const artifactId = options.artifacts.resolve(params.artifact);
748
+ return ledger.read((db) => {
749
+ const snapshot = documentSnapshot(db, artifactId, null);
750
+ const fields =
751
+ params.ids === undefined
752
+ ? snapshot.fields
753
+ : Object.fromEntries(
754
+ Object.entries(snapshot.fields).filter(([id]) => params.ids?.includes(id)),
755
+ );
756
+ return { revision: snapshot.revision, fields };
757
+ });
758
+ }),
759
+ handler(statePatchMethod, (params, session) => {
760
+ const artifactId = options.artifacts.resolve(params.artifact);
761
+ return ledger.write(
762
+ (db) =>
763
+ applyMutation(db, {
764
+ artifactId,
765
+ scope: "artifact",
766
+ mutationId: params.mutationId,
767
+ ...(params.baseRevision !== undefined
768
+ ? { baseRevision: Number(params.baseRevision) }
769
+ : {}),
770
+ ops: params.ops,
771
+ actor: clientActor(session, params.as),
772
+ }).result,
773
+ );
774
+ }),
775
+ handler(resultsGetMethod, (params) => {
776
+ const artifactId = options.artifacts.resolve(params.artifact);
777
+ return ledger.read((db) => {
778
+ const row = submissionFor(db, artifactId, params.submission);
779
+ const results = buildResults(db, row);
780
+ if (params.format !== "md") return results;
781
+ return {
782
+ submissionId: row.id,
783
+ markdown: resultsMarkdown(results, JSON.parse(row.snapshot_json) as Snapshot),
784
+ };
785
+ });
786
+ }),
787
+ handler(waitMethod, (params, session) =>
788
+ waitFor({
789
+ ledger,
790
+ artifactId: options.artifacts.resolve(params.artifact),
791
+ until: params.until,
792
+ after: params.after === undefined ? undefined : Number(params.after),
793
+ timeoutMs: params.timeoutMs,
794
+ signal: session.signal,
795
+ }),
796
+ ),
797
+ handler(eventsReadMethod, (params) =>
798
+ ledger.read((db) =>
799
+ readEvents(db, {
800
+ filter: params.filter as EventFilter | undefined,
801
+ after: params.after === undefined ? 0 : Number(params.after),
802
+ limit: params.limit ?? 100,
803
+ ...(params.acceptCompacted ? { acceptCompacted: true } : {}),
804
+ }),
805
+ ),
806
+ ),
807
+ handler(eventsSubscribeMethod, (params, session) => subscriptions.subscribe(session, params)),
808
+ handler(eventsUnsubscribeMethod, (params, session) => {
809
+ subscriptions.unsubscribe(session, params.subscriptionId);
810
+ return {};
811
+ }),
812
+ handler(eventsAckMethod, (params, session) => {
813
+ subscriptions.ack(session, params.subscriptionId, Number(params.cursor));
814
+ return {};
815
+ }),
816
+ ],
817
+ connected(session) {
818
+ if (session.ports.has("submissions") && session.client)
819
+ outbox.registered(session.client.name);
820
+ },
821
+ disconnected(session) {
822
+ subscriptions.closed(session.id);
823
+ },
824
+ deliveries: () => outbox.counts(),
825
+
826
+ viewVersion(page, viewId) {
827
+ return ledger.read(
828
+ (db) => viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId).version_id,
829
+ );
830
+ },
831
+ startRun(page, input) {
832
+ const actor = pageActor(page);
833
+ return ledger.write((db) => {
834
+ const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);
835
+ const { row, joined } = createOrJoinRun(db, {
836
+ artifactId: page.artifactId,
837
+ versionId: view.version_id,
838
+ viewId: view.id,
839
+ viewerId: page.viewerId,
840
+ fnId: input.fnId,
841
+ args: input.args,
842
+ ...(input.key !== undefined ? { key: input.key } : {}),
843
+ clientKey: input.clientKey,
844
+ actor,
845
+ });
846
+ // A joined run is shown only to a link that may see it (D130): the scope was checked for
847
+ // the function asked, and the run joined is of that function, but say so here too.
848
+ if (joined && !runVisible(row, page)) throw runNotFound(row.id);
849
+ return { row, state: runState(db, row, joined), started: !joined };
850
+ });
851
+ },
852
+ runsFor(page, input) {
853
+ return ledger.read((db) => {
854
+ viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);
855
+ const rows = new Map<string, RunRow>();
856
+ for (const runId of input.runIds ?? []) {
857
+ const row = runById(db, page.artifactId, runId);
858
+ if (row && runVisible(row, page)) rows.set(row.id, row);
859
+ }
860
+ for (const entry of input.keyed ?? []) {
861
+ const row = runByKey(db, page.artifactId, entry.fnId, entry.key);
862
+ if (row && runVisible(row, page)) rows.set(row.id, row);
863
+ }
864
+ const held = new Map((input.held ?? []).map((entry) => [entry.runId, entry]));
865
+ return [...rows.values()].map((row) => runState(db, row, undefined, held.get(row.id)));
866
+ });
867
+ },
868
+ runFor(page, viewId, runId) {
869
+ return ledger.read((db) => {
870
+ viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId);
871
+ const row = runById(db, page.artifactId, runId);
872
+ if (!row || !runVisible(row, page)) throw runNotFound(runId);
873
+ return row;
874
+ });
875
+ },
876
+ runRunning(runId) {
877
+ ledger.write((db) => markRunning(db, runId));
878
+ },
879
+ runOutput(runId, output) {
880
+ return ledger.write((db) => appendRunOutput(db, runId, output));
881
+ },
882
+ endRun(runId, end) {
883
+ return ledger.write((db) => {
884
+ const row = finishRun(db, runId, end);
885
+ return row ? runState(db, row) : undefined;
886
+ });
887
+ },
888
+ openRuns(versionId) {
889
+ return ledger.read((db) => openRuns(db, versionId));
890
+ },
891
+ runState(runId) {
892
+ return ledger.read((db) => {
893
+ const row = db.get<RunRow>("SELECT * FROM action_run WHERE id = ?", runId);
894
+ return row ? runState(db, row) : undefined;
895
+ });
896
+ },
897
+ serverSignal(artifactId, input) {
898
+ return ledger.write((db) =>
899
+ raiseSignal(db, {
900
+ artifactId,
901
+ name: input.name,
902
+ ...(input.payload !== undefined ? { payload: input.payload } : {}),
903
+ source: "action",
904
+ actor: { kind: "agent" },
905
+ // No view: a page never learns another viewer's view from an action's signal (D104).
906
+ // The viewer whose call raised it decides which page may see it.
907
+ ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),
908
+ ...(input.runId !== undefined ? { causation: { runId: input.runId } } : {}),
909
+ }),
910
+ );
911
+ },
912
+ serverEmit(artifactId, input) {
913
+ return ledger.write((db) =>
914
+ appendEvent(db, {
915
+ artifactId,
916
+ type: input.type,
917
+ actor: { kind: "agent" },
918
+ ...(input.runId !== undefined ? { causation: { runId: input.runId } } : {}),
919
+ payload: {
920
+ ...(input.payload === undefined ? {} : { data: input.payload }),
921
+ ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),
922
+ },
923
+ }),
924
+ );
925
+ },
926
+ serverState(artifactId, ids) {
927
+ return ledger.read((db) => {
928
+ const snapshot = documentSnapshot(db, artifactId, null);
929
+ const fields =
930
+ ids === undefined
931
+ ? snapshot.fields
932
+ : Object.fromEntries(
933
+ Object.entries(snapshot.fields).filter(([id]) => ids.includes(id)),
934
+ );
935
+ return { revision: snapshot.revision, fields };
936
+ });
937
+ },
938
+ serverPatch(artifactId, input) {
939
+ return ledger.write(
940
+ (db) =>
941
+ applyMutation(db, {
942
+ artifactId,
943
+ scope: "artifact",
944
+ mutationId: input.mutationId ?? MutationId.create(),
945
+ ...(input.baseRevision !== undefined
946
+ ? { baseRevision: Number(input.baseRevision) }
947
+ : {}),
948
+ ops: input.ops,
949
+ actor: { kind: "agent", ...(input.runId !== undefined ? { id: input.runId } : {}) },
950
+ }).result,
951
+ );
952
+ },
953
+ subscribedArtifacts: () => subscriptions.subscribedArtifacts(),
954
+ workerCrashed(crash) {
955
+ return ledger.write((db) =>
956
+ appendEvent(db, {
957
+ artifactId: crash.artifactId,
958
+ type: "worker.crashed",
959
+ actor: { kind: "mostra" },
960
+ payload: {
961
+ versionId: crash.versionId,
962
+ cause: crash.cause,
963
+ kind: crash.kind,
964
+ backoffMs: crash.backoffMs,
965
+ parked: crash.parked,
966
+ },
967
+ }),
968
+ );
969
+ },
970
+ onSubmission(listener) {
971
+ let position = ledger.read(
972
+ (db) =>
973
+ db.get<{ last: number | null }>("SELECT MAX(position) AS last FROM submission")?.last ??
974
+ 0,
975
+ );
976
+ return ledger.onCommit(() => {
977
+ const made = ledger.read((db) =>
978
+ db
979
+ .all<SubmissionRow>(
980
+ "SELECT * FROM submission WHERE position > ? ORDER BY position",
981
+ position,
982
+ )
983
+ .map((row) => ({ position: row.position, results: buildResults(db, row) })),
984
+ );
985
+ for (const { position: at, results } of made) {
986
+ position = at;
987
+ listener(results);
988
+ }
989
+ });
990
+ },
991
+ onPublished(listener) {
992
+ let cursor = ledger.read((db) => latestCursor(db));
993
+ return ledger.onCommit(() => {
994
+ const published = ledger.read((db) =>
995
+ db.all<{ cursor: number; artifact_id: string; payload_json: string }>(
996
+ "SELECT cursor, artifact_id, payload_json FROM event WHERE cursor > ? AND type = 'version.published' ORDER BY cursor",
997
+ cursor,
998
+ ),
999
+ );
1000
+ cursor = ledger.read((db) => latestCursor(db));
1001
+ for (const row of published) {
1002
+ const { versionId } = JSON.parse(row.payload_json) as { versionId: string };
1003
+ listener(row.artifact_id, versionId);
1004
+ }
1005
+ });
1006
+ },
1007
+ subscriptionCount: () => subscriptions.size,
1008
+ };
1009
+ }