@mostra/runtime 0.0.0-placeholder → 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 +38 -1
  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 -4
  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,258 @@
1
+ /**
2
+ * Event subscriptions (IN-08, H-09; INTERFACES §6): `events/subscribe` delivers a connection the
3
+ * events that pass its filter, as `events/notify` notifications in cursor order without gaps;
4
+ * `events/ack` records how far a named subscriber got, durably, so its next subscription with the
5
+ * same name resumes there after any disconnect or restart. Delivery follows every commit.
6
+ */
7
+ import {
8
+ createDiagnostic,
9
+ EVENTS_NOTIFY,
10
+ type EventFilter,
11
+ type EventsNotifyParams,
12
+ type EventsSubscribeParams,
13
+ type EventsSubscribeResult,
14
+ RpcError,
15
+ } from "@mostra/protocol";
16
+ import type { Ledger } from "../ledger/index.ts";
17
+ import type { Log } from "../log.ts";
18
+ import { latestCursor, readEvents } from "./events.ts";
19
+
20
+ /** Events per notification. */
21
+ const PAGE = 100;
22
+
23
+ /** Pages one pump sends before yielding, so a long backlog never blocks the instance. */
24
+ const PAGES_PER_TURN = 10;
25
+
26
+ /** Bytes one pump sends before yielding. */
27
+ const BYTES_PER_TURN: number = 8 * 1024 * 1024;
28
+
29
+ /** A connection as subscriptions see it. */
30
+ export interface SubscriberSession {
31
+ readonly id: number;
32
+ /** The notifications the client accepted in `mostra/initialize` (D84). */
33
+ readonly notifications: ReadonlySet<string>;
34
+ }
35
+
36
+ interface Subscription {
37
+ readonly id: string;
38
+ readonly session: number;
39
+ readonly filter: EventFilter | undefined;
40
+ readonly name: string | undefined;
41
+ /** Every event up to here was examined and the matching ones sent. */
42
+ cursor: number;
43
+ /** Whether the pump waits for the connection to drain. */
44
+ waiting: boolean;
45
+ }
46
+
47
+ /** Options for {@link Subscriptions}. */
48
+ export interface SubscriptionsOptions {
49
+ readonly ledger: Ledger;
50
+ readonly log: Log;
51
+ /** Sends a notification on a connection; `false` when the connection is gone. */
52
+ readonly notify: (session: number, method: string, params: EventsNotifyParams) => boolean;
53
+ /** A promise that settles when the connection can take more, or `undefined` when it can now. */
54
+ readonly drained: (session: number) => Promise<void> | undefined;
55
+ }
56
+
57
+ /** The event subscriptions of one instance. */
58
+ export class Subscriptions {
59
+ readonly #options: SubscriptionsOptions;
60
+ readonly #all = new Map<string, Subscription>();
61
+ #next = 1;
62
+ #unsubscribe: (() => void) | undefined;
63
+ #scheduled = false;
64
+
65
+ constructor(options: SubscriptionsOptions) {
66
+ this.#options = options;
67
+ }
68
+
69
+ /** Delivers after every commit. */
70
+ start(): void {
71
+ this.#unsubscribe = this.#options.ledger.onCommit(() => this.#pumpAll());
72
+ }
73
+
74
+ /**
75
+ * The artifacts some host subscription names in its filter (`artifacts`): their live producers
76
+ * run while it lasts (LL-04). A subscription without an artifacts filter starts none.
77
+ */
78
+ subscribedArtifacts(): Set<string> {
79
+ const artifacts = new Set<string>();
80
+ for (const subscription of this.#all.values()) {
81
+ for (const artifact of subscription.filter?.artifacts ?? []) artifacts.add(artifact);
82
+ }
83
+ return artifacts;
84
+ }
85
+
86
+ /** How many subscriptions are open: the daemon stays while hosts listen (D62). */
87
+ get size(): number {
88
+ return this.#all.size;
89
+ }
90
+
91
+ stop(): void {
92
+ this.#unsubscribe?.();
93
+ this.#all.clear();
94
+ }
95
+
96
+ /** `events/subscribe` on a connection. */
97
+ subscribe(session: SubscriberSession, params: EventsSubscribeParams): EventsSubscribeResult {
98
+ if (!session.notifications.has(EVENTS_NOTIFY)) {
99
+ throw new RpcError(
100
+ createDiagnostic("MOSTRA_HOST_NOTIFICATION_UNSUPPORTED", {
101
+ message: `events/subscribe sends ${EVENTS_NOTIFY}, which this connection didn't accept in mostra/initialize.`,
102
+ }),
103
+ );
104
+ }
105
+ const { ledger } = this.#options;
106
+ const cursor = ledger.write((db) => {
107
+ const latest = latestCursor(db);
108
+ let start: number;
109
+ if (params.after !== undefined) start = Number(params.after);
110
+ else {
111
+ // A known name resumes after its acknowledged cursor; a new one, like an unnamed
112
+ // subscription, starts now (the history stays readable through events/read).
113
+ const known =
114
+ params.name === undefined
115
+ ? undefined
116
+ : db.get<{ acked_cursor: number }>(
117
+ "SELECT acked_cursor FROM subscriber WHERE name = ?",
118
+ params.name,
119
+ );
120
+ start = known?.acked_cursor ?? latest;
121
+ }
122
+ if (params.name !== undefined) {
123
+ db.run(
124
+ `INSERT INTO subscriber (name, filter_json, acked_cursor, updated_at) VALUES (?, ?, ?, ?)
125
+ ON CONFLICT (name) DO UPDATE SET filter_json = excluded.filter_json, updated_at = excluded.updated_at`,
126
+ params.name,
127
+ JSON.stringify(params.filter ?? {}),
128
+ start,
129
+ new Date().toISOString(),
130
+ );
131
+ }
132
+ // A cursor inside a compacted range isn't refused: the subscription delivers the summary
133
+ // in order, flagged `compacted`, and goes on.
134
+ return start;
135
+ });
136
+ const subscription: Subscription = {
137
+ id: `sub-${session.id}-${this.#next++}`,
138
+ session: session.id,
139
+ filter: params.filter,
140
+ name: params.name,
141
+ cursor,
142
+ waiting: false,
143
+ };
144
+ this.#all.set(subscription.id, subscription);
145
+ // The answer goes out first; the backlog follows it.
146
+ setImmediate(() => this.#pump(subscription));
147
+ return { subscriptionId: subscription.id, cursor: String(cursor) };
148
+ }
149
+
150
+ /** `events/unsubscribe`. */
151
+ unsubscribe(session: SubscriberSession, subscriptionId: string): void {
152
+ this.#owned(session, subscriptionId);
153
+ this.#all.delete(subscriptionId);
154
+ }
155
+
156
+ /** `events/ack`: durable for a named subscriber; an earlier cursor changes nothing. */
157
+ ack(session: SubscriberSession, subscriptionId: string, cursor: number): void {
158
+ const subscription = this.#owned(session, subscriptionId);
159
+ if (subscription.name === undefined) return;
160
+ this.#options.ledger.write((db) =>
161
+ db.run(
162
+ "UPDATE subscriber SET acked_cursor = MAX(acked_cursor, MIN(?, ?)), updated_at = ? WHERE name = ?",
163
+ cursor,
164
+ latestCursor(db),
165
+ new Date().toISOString(),
166
+ subscription.name as string,
167
+ ),
168
+ );
169
+ }
170
+
171
+ /** Ends a closed connection's subscriptions; named cursors stay. */
172
+ closed(session: number): void {
173
+ for (const [id, subscription] of this.#all)
174
+ if (subscription.session === session) this.#all.delete(id);
175
+ }
176
+
177
+ #owned(session: SubscriberSession, subscriptionId: string): Subscription {
178
+ const subscription = this.#all.get(subscriptionId);
179
+ if (!subscription || subscription.session !== session.id) {
180
+ throw new RpcError(
181
+ createDiagnostic("MOSTRA_HOST_SUBSCRIPTION_UNKNOWN", {
182
+ message: `No subscription ${subscriptionId} exists on this connection.`,
183
+ }),
184
+ );
185
+ }
186
+ return subscription;
187
+ }
188
+
189
+ #pumpAll(): void {
190
+ if (this.#scheduled) return;
191
+ this.#scheduled = true;
192
+ // After the committing call returns: a commit inside a request is answered first.
193
+ setImmediate(() => {
194
+ this.#scheduled = false;
195
+ for (const subscription of this.#all.values()) this.#pump(subscription);
196
+ });
197
+ }
198
+
199
+ #pump(subscription: Subscription): void {
200
+ const { ledger, log, notify, drained } = this.#options;
201
+ // While the host's connection is full, the pump waits for it to drain (flow control).
202
+ if (subscription.waiting) return;
203
+ let bytes = 0;
204
+ for (let page = 0; page < PAGES_PER_TURN && bytes < BYTES_PER_TURN; page++) {
205
+ if (!this.#all.has(subscription.id)) return;
206
+ let read: ReturnType<typeof readEvents>;
207
+ try {
208
+ // Through a compacted range, not past it: the summary arrives in cursor order among the
209
+ // other artifacts' events, flagged `compacted`, and nothing between is skipped (DATA_MODEL §4).
210
+ read = ledger.read((db) =>
211
+ readEvents(db, {
212
+ filter: subscription.filter,
213
+ after: subscription.cursor,
214
+ limit: PAGE,
215
+ acceptCompacted: true,
216
+ }),
217
+ );
218
+ } catch (error) {
219
+ log.error("events.subscription_failed", { subscriptionId: subscription.id, error });
220
+ this.#all.delete(subscription.id);
221
+ return;
222
+ }
223
+ const next = Number(read.cursor);
224
+ if (read.events.length > 0) {
225
+ if (read.compacted) {
226
+ log.warn("events.subscription_compacted", {
227
+ subscriptionId: subscription.id,
228
+ after: subscription.cursor,
229
+ });
230
+ }
231
+ const sent = notify(subscription.session, EVENTS_NOTIFY, {
232
+ subscriptionId: subscription.id,
233
+ events: read.events,
234
+ cursor: read.cursor,
235
+ ...(read.compacted ? { compacted: read.compacted } : {}),
236
+ });
237
+ if (!sent) {
238
+ this.#all.delete(subscription.id);
239
+ return;
240
+ }
241
+ bytes += read.events.reduce((sum, event) => sum + JSON.stringify(event).length, 0);
242
+ }
243
+ subscription.cursor = next;
244
+ const waiting = drained(subscription.session);
245
+ if (waiting) {
246
+ subscription.waiting = true;
247
+ void waiting.then(() => {
248
+ subscription.waiting = false;
249
+ this.#pump(subscription);
250
+ });
251
+ return;
252
+ }
253
+ // A page cut short by size (READ_MAX_BYTES) ends before the newest cursor: read on.
254
+ if (read.events.length < PAGE && next >= ledger.read((db) => latestCursor(db))) return;
255
+ }
256
+ setImmediate(() => this.#pump(subscription));
257
+ }
258
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Viewers and views (D104, DATA_MODEL §3). A viewer is a person: the home's local user, or the
3
+ * person a capability link was minted for (`view/url`'s `viewer`), mapped idempotently by the
4
+ * host's key. A view is one frame load of one version by one viewer; mutations and submits name
5
+ * it, and a submission takes its version from it.
6
+ */
7
+ import {
8
+ type ControlsPolicy,
9
+ createDiagnostic,
10
+ RpcError,
11
+ type Viewer,
12
+ ViewerId,
13
+ type ViewerKind,
14
+ type ViewerSpec,
15
+ ViewId,
16
+ } from "@mostra/protocol";
17
+ import type { LedgerDb } from "../ledger/index.ts";
18
+ import { appendEvent } from "./events.ts";
19
+
20
+ interface ViewerRow {
21
+ id: string;
22
+ kind: ViewerKind;
23
+ external_ref: string;
24
+ name: string | null;
25
+ }
26
+
27
+ /** A `view` row. */
28
+ export interface ViewRow {
29
+ readonly id: string;
30
+ readonly artifact_id: string;
31
+ readonly version_id: string;
32
+ readonly viewer_id: string;
33
+ readonly token_id: string | null;
34
+ readonly opened_cursor: number | null;
35
+ /** The channels and controls in force for the view (D108); null for views from before them. */
36
+ readonly controls_json: string | null;
37
+ }
38
+
39
+ /** Both channels, every control: D40's standalone default. */
40
+ export const OPEN_CONTROLS: ControlsPolicy = { submitChannels: ["shell", "artifact"] };
41
+
42
+ /** The channels and controls a view was opened with (D108). */
43
+ export function viewControls(view: ViewRow): ControlsPolicy {
44
+ return view.controls_json === null
45
+ ? OPEN_CONTROLS
46
+ : (JSON.parse(view.controls_json) as ControlsPolicy);
47
+ }
48
+
49
+ /** The `external_ref` of the home's one local user. */
50
+ const LOCAL_REF = "local";
51
+
52
+ function viewerOf(row: ViewerRow): Viewer {
53
+ return {
54
+ id: row.id,
55
+ kind: row.kind,
56
+ ...(row.name !== null ? { name: row.name } : {}),
57
+ ...(row.kind === "token" || row.kind === "host" ? { ref: row.external_ref } : {}),
58
+ };
59
+ }
60
+
61
+ /** The home's local user (created on first use): who every session acts as without a viewer. */
62
+ export function localViewerId(db: LedgerDb): string {
63
+ const found = db.get<{ id: string }>(
64
+ "SELECT id FROM viewer WHERE kind = 'local' AND external_ref = ?",
65
+ LOCAL_REF,
66
+ );
67
+ if (found) return found.id;
68
+ const id = ViewerId.create();
69
+ db.run(
70
+ "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'local', ?, NULL, ?)",
71
+ id,
72
+ LOCAL_REF,
73
+ new Date().toISOString(),
74
+ );
75
+ return id;
76
+ }
77
+
78
+ /**
79
+ * The viewer a link minted with `viewer` acts for: the same `ref` always gives the same viewer, and
80
+ * a `name` given again replaces the stored one.
81
+ */
82
+ export function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {
83
+ const found = db.get<ViewerRow>(
84
+ "SELECT * FROM viewer WHERE kind = 'token' AND external_ref = ?",
85
+ spec.ref,
86
+ );
87
+ if (found) {
88
+ if (spec.name !== undefined && spec.name !== found.name) {
89
+ db.run("UPDATE viewer SET name = ? WHERE id = ?", spec.name, found.id);
90
+ }
91
+ return found.id;
92
+ }
93
+ const id = ViewerId.create();
94
+ db.run(
95
+ "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'token', ?, ?, ?)",
96
+ id,
97
+ spec.ref,
98
+ spec.name ?? null,
99
+ new Date().toISOString(),
100
+ );
101
+ return id;
102
+ }
103
+
104
+ /** A viewer by ID; throws for an unknown one, which would be a defect. */
105
+ export function viewer(db: LedgerDb, id: string): Viewer {
106
+ const row = db.get<ViewerRow>("SELECT * FROM viewer WHERE id = ?", id);
107
+ if (!row) throw new Error(`No viewer ${id}.`);
108
+ return viewerOf(row);
109
+ }
110
+
111
+ /** Records one frame load of a version (D104) and appends `view.opened`. */
112
+ export function openView(
113
+ db: LedgerDb,
114
+ input: {
115
+ readonly artifactId: string;
116
+ readonly versionId: string;
117
+ readonly viewerId: string;
118
+ readonly tokenId?: string | undefined;
119
+ /** The channels and controls in force for this view (D108). */
120
+ readonly controls?: ControlsPolicy;
121
+ },
122
+ ): string {
123
+ const id = ViewId.create();
124
+ const cursor = appendEvent(db, {
125
+ artifactId: input.artifactId,
126
+ type: "view.opened",
127
+ actor: { kind: "viewer", id: input.viewerId },
128
+ payload: { viewId: id, versionId: input.versionId, viewerId: input.viewerId },
129
+ });
130
+ db.run(
131
+ "INSERT INTO view (id, artifact_id, version_id, viewer_id, token_id, opened_cursor, opened_at, controls_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
132
+ id,
133
+ input.artifactId,
134
+ input.versionId,
135
+ input.viewerId,
136
+ input.tokenId ?? null,
137
+ Number(cursor),
138
+ new Date().toISOString(),
139
+ JSON.stringify(input.controls ?? OPEN_CONTROLS),
140
+ );
141
+ return id;
142
+ }
143
+
144
+ /**
145
+ * The view a request names, checked against the artifact and the viewer it must belong to, and,
146
+ * for a page, the link it was opened through: a page can't name a view another link opened, such
147
+ * as one of a version its own link may not open (Claude review finding 11).
148
+ * `MOSTRA_SUBMIT_VIEW_INVALID` otherwise (D104).
149
+ */
150
+ export function viewFor(
151
+ db: LedgerDb,
152
+ viewId: string,
153
+ artifactId: string,
154
+ viewerId: string,
155
+ tokenId?: string,
156
+ ): ViewRow {
157
+ const row = ViewId.is(viewId)
158
+ ? db.get<ViewRow>("SELECT * FROM view WHERE id = ?", viewId)
159
+ : undefined;
160
+ if (
161
+ !row ||
162
+ row.artifact_id !== artifactId ||
163
+ row.viewer_id !== viewerId ||
164
+ (tokenId !== undefined && row.token_id !== tokenId)
165
+ ) {
166
+ throw new RpcError(
167
+ createDiagnostic("MOSTRA_SUBMIT_VIEW_INVALID", {
168
+ message: `The view ${viewId} isn't one this page's link opened for this artifact.`,
169
+ }),
170
+ );
171
+ }
172
+ return row;
173
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `wait` (IN-10, ARCHITECTURE §6, D103): blocks until a condition holds or the timeout passes.
3
+ * `submitted` is level-triggered under `once` (any submission satisfies it, whatever the cursor) and
4
+ * edge-triggered under `epochs`; `signal:`, `state:` and `event:` are edge-triggered after the
5
+ * cursor, which defaults to the artifact's latest publish. A timeout answers `still_waiting` with
6
+ * the newest cursor examined, so a later wait from it misses nothing: every condition is a query of
7
+ * durable events, so nothing that happened while no one waited is lost.
8
+ */
9
+ import {
10
+ type Cursor,
11
+ createDiagnostic,
12
+ type EventRecord,
13
+ RpcError,
14
+ type WaitResult,
15
+ } from "@mostra/protocol";
16
+ import type { Ledger, LedgerDb } from "../ledger/index.ts";
17
+ import { COMPACTED, checkCompaction, type EventRow, eventRecord, latestCursor } from "./events.ts";
18
+ import { storedPolicy } from "./policy.ts";
19
+ import type { SubmissionRow } from "./submissions.ts";
20
+
21
+ /** The cursor a wait starts from by default: the artifact's latest publish (D103). */
22
+ export function defaultWaitCursor(db: LedgerDb, artifactId: string): number {
23
+ const published =
24
+ db.get<{ cursor: number | null }>(
25
+ "SELECT MAX(cursor) AS cursor FROM event WHERE artifact_id = ? AND type = 'version.published'",
26
+ artifactId,
27
+ )?.cursor ?? 0;
28
+ // A publish that was compacted away is still known by its cursor, which its summary records:
29
+ // waiting after the summary instead would skip what happened between (Claude review finding 9).
30
+ const compacted =
31
+ db.get<{ cursor: number | null }>(
32
+ `SELECT MAX(json_extract(payload_json, '$.latestVersion.cursor')) AS cursor FROM event WHERE artifact_id = ? AND type = '${COMPACTED}'`,
33
+ artifactId,
34
+ )?.cursor ?? 0;
35
+ return Math.max(published, compacted);
36
+ }
37
+
38
+ /** Builds a `submission.created` record from its row, when compaction removed the event. */
39
+ function submissionEvent(db: LedgerDb, row: SubmissionRow): EventRecord {
40
+ const event = db.get<EventRow>("SELECT * FROM event WHERE cursor = ?", row.position);
41
+ if (event && event.type === "submission.created") return eventRecord(event);
42
+ return {
43
+ cursor: String(row.position) as Cursor,
44
+ artifactId: row.artifact_id,
45
+ seq: null,
46
+ type: "submission.created",
47
+ at: row.created_at,
48
+ actor: { kind: "viewer", id: row.viewer_id },
49
+ causation: { submissionId: row.id },
50
+ payload: {
51
+ submissionId: row.id,
52
+ versionId: row.version_id,
53
+ version: (JSON.parse(row.snapshot_json) as { version: number }).version,
54
+ viewId: row.view_id,
55
+ viewerId: row.viewer_id,
56
+ channel: row.channel,
57
+ epoch: row.epoch,
58
+ staleView: row.stale_view === 1,
59
+ digest: row.digest,
60
+ },
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Checks a condition once, inside the caller's read transaction: the event that satisfies it, or
66
+ * the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact
67
+ * without submissions, and `MOSTRA_HOST_CURSOR_COMPACTED` for a cursor inside a compacted range.
68
+ */
69
+ export function checkCondition(
70
+ db: LedgerDb,
71
+ artifactId: string,
72
+ until: string,
73
+ after: number,
74
+ explicitAfter = true,
75
+ ): { readonly event: EventRecord } | { readonly cursor: number } {
76
+ const upTo = latestCursor(db);
77
+ const first = (sql: string, ...params: (string | number)[]): EventRow | undefined =>
78
+ db.get<EventRow>(
79
+ `SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND ${sql} ORDER BY cursor LIMIT 1`,
80
+ artifactId,
81
+ after,
82
+ upTo,
83
+ ...params,
84
+ );
85
+ let found: EventRow | undefined;
86
+ if (until === "submitted") {
87
+ const artifact = db.get<{ policy_json: string | null }>(
88
+ "SELECT policy_json FROM artifact WHERE id = ?",
89
+ artifactId,
90
+ );
91
+ const policy = storedPolicy(artifact?.policy_json ?? null);
92
+ if (policy.policy === "none") {
93
+ throw new RpcError(
94
+ createDiagnostic("MOSTRA_SUBMIT_POLICY_NONE", {
95
+ message:
96
+ "This artifact's submission policy is none: nothing will be submitted to wait for.",
97
+ }),
98
+ );
99
+ }
100
+ // Level-triggered under once per-artifact, and under once per-viewer while no cursor was
101
+ // given: any submission satisfies it. After an explicit cursor, per-viewer is edge-triggered,
102
+ // so a survey's agent can wait for the next respondent (D107).
103
+ const level = policy.policy === "once" && (policy.scope !== "per-viewer" || !explicitAfter);
104
+ const row = level
105
+ ? db.get<SubmissionRow>(
106
+ "SELECT * FROM submission WHERE artifact_id = ? ORDER BY position LIMIT 1",
107
+ artifactId,
108
+ )
109
+ : db.get<SubmissionRow>(
110
+ "SELECT * FROM submission WHERE artifact_id = ? AND position > ? AND position <= ? ORDER BY position LIMIT 1",
111
+ artifactId,
112
+ after,
113
+ upTo,
114
+ );
115
+ if (row) return { event: submissionEvent(db, row) };
116
+ checkCompaction(db, { artifacts: [artifactId] }, after);
117
+ return { cursor: Math.max(upTo, after) };
118
+ }
119
+ checkCompaction(db, { artifacts: [artifactId] }, after);
120
+ const separator = until.indexOf(":");
121
+ const kind = until.slice(0, separator);
122
+ const subject = until.slice(separator + 1);
123
+ if (kind === "signal") {
124
+ found = first("type = 'signal.raised' AND json_extract(payload_json, '$.name') = ?", subject);
125
+ } else if (kind === "state") {
126
+ found = first(
127
+ "type = 'state.changed' AND EXISTS (SELECT 1 FROM json_each(payload_json, '$.changes') WHERE json_extract(json_each.value, '$.id') = ?)",
128
+ subject,
129
+ );
130
+ } else if (kind === "event") {
131
+ found = subject.endsWith(".*")
132
+ ? first("substr(type, 1, ?) = ?", subject.length - 1, subject.slice(0, -1))
133
+ : first("type = ?", subject);
134
+ } else {
135
+ throw new Error(`Unknown wait condition ${until}.`);
136
+ }
137
+ return found ? { event: eventRecord(found) } : { cursor: Math.max(upTo, after) };
138
+ }
139
+
140
+ /** Options for {@link waitFor}. */
141
+ export interface WaitOptions {
142
+ readonly ledger: Ledger;
143
+ readonly artifactId: string;
144
+ readonly until: string;
145
+ /** The cursor to wait after; absent: the artifact's latest publish. */
146
+ readonly after?: number | undefined;
147
+ readonly timeoutMs: number;
148
+ /** Ends the wait early (the connection closed, the instance stops): it answers `still_waiting`. */
149
+ readonly signal?: AbortSignal | undefined;
150
+ }
151
+
152
+ /**
153
+ * Waits for a condition: checks it now, then again after every commit, until it holds, the timeout
154
+ * passes or `signal` aborts.
155
+ */
156
+ export async function waitFor(options: WaitOptions): Promise<WaitResult> {
157
+ const { ledger, artifactId, until } = options;
158
+ const after = options.after ?? ledger.read((db) => defaultWaitCursor(db, artifactId));
159
+ const explicit = options.after !== undefined;
160
+ const check = () => ledger.read((db) => checkCondition(db, artifactId, until, after, explicit));
161
+ const answer = (outcome: ReturnType<typeof check>): WaitResult =>
162
+ "event" in outcome
163
+ ? { status: "satisfied", event: outcome.event, cursor: outcome.event.cursor }
164
+ : { status: "still_waiting", cursor: String(outcome.cursor) };
165
+ const now = check();
166
+ if ("event" in now || options.timeoutMs === 0 || options.signal?.aborted) return answer(now);
167
+ return new Promise<WaitResult>((resolve, reject) => {
168
+ let last: ReturnType<typeof check> = now;
169
+ let settled = false;
170
+ const finish = (result: WaitResult | Error): void => {
171
+ if (settled) return;
172
+ settled = true;
173
+ clearTimeout(timer);
174
+ unsubscribe();
175
+ options.signal?.removeEventListener("abort", onAbort);
176
+ if (result instanceof Error) reject(result);
177
+ else resolve(result);
178
+ };
179
+ const onCommit = (): void => {
180
+ try {
181
+ last = check();
182
+ } catch (error) {
183
+ finish(error as Error);
184
+ return;
185
+ }
186
+ if ("event" in last) finish(answer(last));
187
+ };
188
+ const onAbort = (): void => finish(answer(last));
189
+ const unsubscribe = ledger.onCommit(onCommit);
190
+ const timer = setTimeout(() => {
191
+ // One last look, so a commit at the deadline isn't missed.
192
+ try {
193
+ finish(answer(check()));
194
+ } catch (error) {
195
+ finish(error as Error);
196
+ }
197
+ }, options.timeoutMs);
198
+ timer.unref?.();
199
+ options.signal?.addEventListener("abort", onAbort, { once: true });
200
+ });
201
+ }