@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,583 @@
1
+ /**
2
+ * The ledger's schema migrations (DATA_MODEL §3, §6), in order. Each package that adds tables adds
3
+ * one migration at the end; a released migration never changes. Version 0 is the bootstrap every
4
+ * ledger file is created with (`schema_migration` and `ledger_lock`).
5
+ */
6
+ import type { MigrationDb } from "./types.ts";
7
+
8
+ /** One forward step of the ledger schema. */
9
+ export interface Migration {
10
+ /** 1, 2, 3 … with no gaps. */
11
+ readonly version: number;
12
+ /** A short name for logs and `schema_migration.name`. */
13
+ readonly name: string;
14
+ /** Applies the step. Runs inside the migration transaction. */
15
+ up(db: MigrationDb): void;
16
+ }
17
+
18
+ /** The bootstrap schema, written into every new ledger file before it is linked into place. */
19
+ export const BOOTSTRAP_SQL = `
20
+ CREATE TABLE schema_migration (
21
+ version INTEGER PRIMARY KEY,
22
+ name TEXT NOT NULL,
23
+ runtime_version TEXT NOT NULL,
24
+ applied_at TEXT NOT NULL
25
+ );
26
+ CREATE TABLE ledger_lock (
27
+ id INTEGER PRIMARY KEY CHECK (id = 1),
28
+ pid INTEGER NOT NULL,
29
+ start_time TEXT NOT NULL,
30
+ acquired_at TEXT NOT NULL
31
+ );
32
+ `;
33
+
34
+ /** Every migration of this runtime, in order. */
35
+ export const MIGRATIONS: readonly Migration[] = [
36
+ {
37
+ version: 1,
38
+ name: "child processes",
39
+ up(db) {
40
+ // Every child process the supervisor started, so a restarted supervisor can reap them
41
+ // (RT-09, FAILURE_MODEL §2). `start_time` is the opaque process identity of
42
+ // processes/identity.ts; `pgid` is the group to signal.
43
+ db.exec(`
44
+ CREATE TABLE child (
45
+ pid INTEGER NOT NULL,
46
+ start_time TEXT NOT NULL,
47
+ kind TEXT NOT NULL,
48
+ owner_ref TEXT NOT NULL,
49
+ pgid INTEGER NOT NULL,
50
+ started_at TEXT NOT NULL,
51
+ parent_pid INTEGER,
52
+ PRIMARY KEY (pid, start_time)
53
+ );
54
+ `);
55
+ },
56
+ },
57
+ {
58
+ version: 2,
59
+ name: "artifacts, versions and events",
60
+ up(db) {
61
+ // DATA_MODEL §3. `artifact` mirrors the latest version's manifest metadata; `version` rows
62
+ // are immutable (VR-01, invariant 3) and the trigger refuses any UPDATE. `event` is
63
+ // append-only; WP-03 appends `artifact.created` and `version.published`, WP-06 reads them.
64
+ // `request` records the result of each mutating request with a `requestId` (H-03).
65
+ db.exec(`
66
+ CREATE TABLE artifact (
67
+ id TEXT PRIMARY KEY,
68
+ title TEXT NOT NULL,
69
+ family TEXT,
70
+ links_json TEXT NOT NULL,
71
+ policy_json TEXT,
72
+ created_at TEXT NOT NULL,
73
+ latest_version_id TEXT
74
+ );
75
+ CREATE TABLE source_binding (
76
+ path TEXT PRIMARY KEY,
77
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
78
+ bound_at TEXT NOT NULL
79
+ );
80
+ CREATE INDEX source_binding_artifact ON source_binding (artifact_id);
81
+ CREATE TABLE version (
82
+ id TEXT PRIMARY KEY,
83
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
84
+ number INTEGER NOT NULL CHECK (number >= 1),
85
+ source_digest TEXT NOT NULL,
86
+ env_digest TEXT NOT NULL,
87
+ output_digest TEXT NOT NULL,
88
+ manifest_json TEXT NOT NULL,
89
+ forced_codes_json TEXT,
90
+ published_at TEXT NOT NULL,
91
+ UNIQUE (artifact_id, number)
92
+ );
93
+ CREATE TRIGGER version_immutable BEFORE UPDATE ON version
94
+ BEGIN
95
+ SELECT RAISE(ABORT, 'published versions are immutable');
96
+ END;
97
+ CREATE TABLE event (
98
+ cursor INTEGER PRIMARY KEY AUTOINCREMENT,
99
+ artifact_id TEXT,
100
+ seq INTEGER,
101
+ type TEXT NOT NULL,
102
+ actor_json TEXT NOT NULL,
103
+ causation_json TEXT,
104
+ payload_json TEXT NOT NULL,
105
+ at TEXT NOT NULL,
106
+ UNIQUE (artifact_id, seq)
107
+ );
108
+ CREATE TRIGGER event_append_only BEFORE UPDATE ON event
109
+ BEGIN
110
+ SELECT RAISE(ABORT, 'events are append-only');
111
+ END;
112
+ CREATE TABLE request (
113
+ method TEXT NOT NULL,
114
+ request_id TEXT NOT NULL,
115
+ result_json TEXT NOT NULL,
116
+ created_at TEXT NOT NULL,
117
+ PRIMARY KEY (method, request_id)
118
+ );
119
+ `);
120
+ },
121
+ },
122
+ {
123
+ version: 3,
124
+ name: "dependencies",
125
+ up(db) {
126
+ // D95. `dependency_lock` holds each artifact's working lockfile, keyed by its artifact ID,
127
+ // or by `path:<real path>` until its first publish binds it (re-keyed in that publish's
128
+ // transaction); `added_json` lists the packages added through deps/add, which stay in the
129
+ // lockfile whether or not the source imports them. `dependency_package` indexes what the
130
+ // home's package store holds, so an offline request for anything else fails at once (DP-04).
131
+ db.exec(`
132
+ CREATE TABLE dependency_lock (
133
+ key TEXT PRIMARY KEY,
134
+ lock_text TEXT NOT NULL,
135
+ added_json TEXT NOT NULL,
136
+ updated_at TEXT NOT NULL
137
+ );
138
+ CREATE TABLE dependency_package (
139
+ name TEXT NOT NULL,
140
+ version TEXT NOT NULL,
141
+ stored_at TEXT NOT NULL,
142
+ PRIMARY KEY (name, version)
143
+ );
144
+ `);
145
+ },
146
+ },
147
+ {
148
+ version: 4,
149
+ name: "addressing, tokens and sessions",
150
+ up(db) {
151
+ // DATA_MODEL §3, D97, D98, D99. `port_lease` gives the shell and each artifact a stable
152
+ // port per home. `token` keeps only the SHA-256 of each capability secret; `is_default`
153
+ // marks the artifact's default link (one live default per artifact, by the partial unique
154
+ // index) and `pinned_version` the version number a link's URL names, so a rotation keeps
155
+ // it. `shell_origin` is the address the link was minted for: a link works only there, so a
156
+ // program that later holds an abandoned port can't use the secrets of old links (D97).
157
+ // `session` keeps the SHA-256 of each session cookie, the origin it was issued for and, for
158
+ // an artifact frame, the version it entered (D98 item 5). `request.params_digest` makes a
159
+ // requestId replay only the request it recorded (H-03).
160
+ db.exec(`
161
+ CREATE TABLE port_lease (
162
+ port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535),
163
+ purpose TEXT NOT NULL CHECK (purpose IN ('shell', 'artifact', 'demo')),
164
+ owner_ref TEXT NOT NULL,
165
+ leased_at TEXT NOT NULL,
166
+ UNIQUE (purpose, owner_ref)
167
+ );
168
+ CREATE TABLE token (
169
+ id TEXT PRIMARY KEY,
170
+ secret_hash TEXT NOT NULL UNIQUE,
171
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
172
+ scopes_json TEXT NOT NULL,
173
+ viewer_id TEXT,
174
+ expires_at TEXT,
175
+ revoked_at TEXT,
176
+ created_at TEXT NOT NULL,
177
+ is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),
178
+ pinned_version INTEGER CHECK (pinned_version >= 1),
179
+ shell_origin TEXT NOT NULL,
180
+ replaced_by TEXT,
181
+ CHECK (is_default = 0 OR (revoked_at IS NULL AND expires_at IS NULL))
182
+ );
183
+ CREATE UNIQUE INDEX token_default ON token (artifact_id) WHERE is_default = 1;
184
+ CREATE INDEX token_artifact ON token (artifact_id);
185
+ CREATE TRIGGER token_revocation_final BEFORE UPDATE ON token
186
+ WHEN OLD.revoked_at IS NOT NULL OR NEW.secret_hash IS NOT OLD.secret_hash
187
+ OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scopes_json IS NOT OLD.scopes_json
188
+ OR NEW.expires_at IS NOT OLD.expires_at OR NEW.pinned_version IS NOT OLD.pinned_version
189
+ OR NEW.shell_origin IS NOT OLD.shell_origin
190
+ BEGIN
191
+ SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');
192
+ END;
193
+ CREATE TABLE session (
194
+ id TEXT PRIMARY KEY,
195
+ token_id TEXT NOT NULL REFERENCES token(id),
196
+ origin TEXT NOT NULL,
197
+ mode TEXT NOT NULL CHECK (mode IN ('cookie', 'worker')),
198
+ -- The SHA-256 of the session's CSRF token, which is derived from the cookie (D98).
199
+ csrf TEXT NOT NULL,
200
+ version_id TEXT REFERENCES version(id),
201
+ created_at TEXT NOT NULL,
202
+ last_seen_at TEXT NOT NULL
203
+ );
204
+ CREATE INDEX session_token ON session (token_id);
205
+ ALTER TABLE request ADD COLUMN params_digest TEXT;
206
+ `);
207
+ },
208
+ },
209
+ {
210
+ version: 5,
211
+ name: "interaction ledger",
212
+ up(db) {
213
+ // DATA_MODEL §3, D101 to D106. Viewers are people (one `local`, one `token` viewer per host
214
+ // key); a view is one frame load of one version. A document is a viewer's draft or the
215
+ // artifact's state: its revision and epoch only grow (trigger), and each field keeps the
216
+ // revision that last wrote it, deletions included, so conflicts are exact. A mutation ID
217
+ // replays its recorded result. Submissions are write-once (trigger); `position` is the
218
+ // cursor of their `submission.created` event, the order deliveries replay in. A terminal
219
+ // delivery never changes again (trigger). `subscriber` keeps durable acknowledged cursors.
220
+ // A token's viewer joins its immutable grant. INSERT OR REPLACE would delete a row without
221
+ // the DELETE and UPDATE triggers, so write-once tables also refuse an insert over an
222
+ // existing row (Claude review finding 7). `artifact.policy_chosen_json` keeps the policy a
223
+ // publish named explicitly, which later publishes keep until another names one (D102).
224
+ db.exec(`
225
+ CREATE TABLE viewer (
226
+ id TEXT PRIMARY KEY,
227
+ kind TEXT NOT NULL CHECK (kind IN ('local', 'tailnet', 'token', 'host')),
228
+ external_ref TEXT NOT NULL,
229
+ name TEXT,
230
+ created_at TEXT NOT NULL,
231
+ UNIQUE (kind, external_ref)
232
+ );
233
+ CREATE TABLE view (
234
+ id TEXT PRIMARY KEY,
235
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
236
+ version_id TEXT NOT NULL REFERENCES version(id),
237
+ viewer_id TEXT NOT NULL REFERENCES viewer(id),
238
+ token_id TEXT REFERENCES token(id),
239
+ opened_cursor INTEGER,
240
+ opened_at TEXT NOT NULL,
241
+ closed_at TEXT,
242
+ live_cursor_json TEXT
243
+ );
244
+ CREATE INDEX view_artifact ON view (artifact_id, viewer_id);
245
+ CREATE TABLE document (
246
+ id INTEGER PRIMARY KEY,
247
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
248
+ scope TEXT NOT NULL CHECK (scope IN ('viewer', 'artifact')),
249
+ viewer_id TEXT REFERENCES viewer(id),
250
+ revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),
251
+ epoch INTEGER NOT NULL DEFAULT 1 CHECK (epoch >= 1),
252
+ size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),
253
+ CHECK ((scope = 'viewer') = (viewer_id IS NOT NULL)),
254
+ UNIQUE (artifact_id, scope, viewer_id)
255
+ );
256
+ CREATE UNIQUE INDEX document_state ON document (artifact_id) WHERE scope = 'artifact';
257
+ CREATE TRIGGER document_monotonic BEFORE UPDATE ON document
258
+ WHEN NEW.revision < OLD.revision OR NEW.epoch < OLD.epoch
259
+ OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scope IS NOT OLD.scope
260
+ OR NEW.viewer_id IS NOT OLD.viewer_id
261
+ BEGIN
262
+ SELECT RAISE(ABORT, 'a document''s revision and epoch only grow');
263
+ END;
264
+ CREATE TABLE field (
265
+ document_id INTEGER NOT NULL REFERENCES document(id),
266
+ field_id TEXT NOT NULL,
267
+ value_json TEXT NOT NULL,
268
+ deleted INTEGER NOT NULL DEFAULT 0 CHECK (deleted IN (0, 1)),
269
+ field_rev INTEGER NOT NULL CHECK (field_rev >= 1),
270
+ updated_by_json TEXT,
271
+ updated_at TEXT NOT NULL,
272
+ sensitive INTEGER NOT NULL DEFAULT 0 CHECK (sensitive IN (0, 1)),
273
+ label TEXT,
274
+ required INTEGER CHECK (required IN (0, 1)),
275
+ orphaned_from_version INTEGER,
276
+ PRIMARY KEY (document_id, field_id)
277
+ );
278
+ CREATE TABLE mutation (
279
+ id TEXT PRIMARY KEY,
280
+ document_id INTEGER NOT NULL REFERENCES document(id),
281
+ params_digest TEXT NOT NULL,
282
+ result_json TEXT NOT NULL,
283
+ applied_at TEXT NOT NULL
284
+ );
285
+ CREATE TABLE submission (
286
+ id TEXT PRIMARY KEY,
287
+ position INTEGER NOT NULL UNIQUE,
288
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
289
+ version_id TEXT NOT NULL REFERENCES version(id),
290
+ view_id TEXT NOT NULL REFERENCES view(id),
291
+ viewer_id TEXT NOT NULL REFERENCES viewer(id),
292
+ channel TEXT NOT NULL CHECK (channel IN ('shell', 'artifact')),
293
+ policy_json TEXT NOT NULL,
294
+ epoch INTEGER NOT NULL CHECK (epoch >= 1),
295
+ scope_key TEXT NOT NULL,
296
+ previous_id TEXT REFERENCES submission(id),
297
+ draft_document_id INTEGER NOT NULL REFERENCES document(id),
298
+ draft_revision INTEGER NOT NULL,
299
+ state_revision INTEGER,
300
+ latest_version_number INTEGER,
301
+ snapshot_json TEXT NOT NULL,
302
+ digest TEXT NOT NULL,
303
+ stale_view INTEGER NOT NULL CHECK (stale_view IN (0, 1)),
304
+ request_id TEXT UNIQUE,
305
+ created_at TEXT NOT NULL,
306
+ UNIQUE (artifact_id, scope_key, epoch)
307
+ );
308
+ CREATE INDEX submission_artifact ON submission (artifact_id, position);
309
+ CREATE TRIGGER submission_write_once BEFORE UPDATE ON submission
310
+ BEGIN
311
+ SELECT RAISE(ABORT, 'submissions are immutable');
312
+ END;
313
+ CREATE TRIGGER submission_kept BEFORE DELETE ON submission
314
+ BEGIN
315
+ SELECT RAISE(ABORT, 'submissions are immutable');
316
+ END;
317
+ -- INSERT OR REPLACE deletes the old row without the DELETE trigger: refuse it at insert.
318
+ CREATE TRIGGER submission_not_replaced BEFORE INSERT ON submission
319
+ WHEN EXISTS (SELECT 1 FROM submission WHERE id = NEW.id OR position = NEW.position
320
+ OR (artifact_id = NEW.artifact_id AND scope_key = NEW.scope_key AND epoch = NEW.epoch))
321
+ BEGIN
322
+ SELECT RAISE(ABORT, 'submissions are immutable');
323
+ END;
324
+ CREATE TABLE delivery (
325
+ id TEXT PRIMARY KEY,
326
+ submission_id TEXT NOT NULL REFERENCES submission(id),
327
+ position INTEGER NOT NULL,
328
+ port_owner TEXT NOT NULL,
329
+ state TEXT NOT NULL CHECK (state IN ('pending', 'delivered', 'rejected', 'undeliverable')),
330
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
331
+ next_attempt_at TEXT,
332
+ last_error_json TEXT,
333
+ reason TEXT,
334
+ updated_at TEXT NOT NULL,
335
+ UNIQUE (submission_id, port_owner)
336
+ );
337
+ CREATE INDEX delivery_owner ON delivery (port_owner, state, position);
338
+ CREATE TRIGGER delivery_terminal BEFORE UPDATE ON delivery
339
+ WHEN OLD.state <> 'pending' OR NEW.submission_id IS NOT OLD.submission_id
340
+ OR NEW.port_owner IS NOT OLD.port_owner OR NEW.position IS NOT OLD.position
341
+ BEGIN
342
+ SELECT RAISE(ABORT, 'a delivery''s terminal state never changes');
343
+ END;
344
+ CREATE TRIGGER delivery_kept BEFORE DELETE ON delivery
345
+ BEGIN
346
+ SELECT RAISE(ABORT, 'deliveries are kept with their submissions');
347
+ END;
348
+ CREATE TRIGGER delivery_not_replaced BEFORE INSERT ON delivery
349
+ WHEN EXISTS (SELECT 1 FROM delivery WHERE id = NEW.id
350
+ OR (submission_id = NEW.submission_id AND port_owner = NEW.port_owner))
351
+ BEGIN
352
+ SELECT RAISE(ABORT, 'a delivery''s terminal state never changes');
353
+ END;
354
+ CREATE TRIGGER version_not_replaced BEFORE INSERT ON version
355
+ WHEN EXISTS (SELECT 1 FROM version WHERE id = NEW.id
356
+ OR (artifact_id = NEW.artifact_id AND number = NEW.number))
357
+ BEGIN
358
+ SELECT RAISE(ABORT, 'published versions are immutable');
359
+ END;
360
+ CREATE TRIGGER token_not_replaced BEFORE INSERT ON token
361
+ WHEN EXISTS (SELECT 1 FROM token WHERE id = NEW.id OR secret_hash = NEW.secret_hash)
362
+ BEGIN
363
+ SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');
364
+ END;
365
+ CREATE TABLE subscriber (
366
+ name TEXT PRIMARY KEY,
367
+ filter_json TEXT NOT NULL,
368
+ acked_cursor INTEGER NOT NULL DEFAULT 0 CHECK (acked_cursor >= 0),
369
+ updated_at TEXT NOT NULL
370
+ );
371
+ ALTER TABLE artifact ADD COLUMN policy_chosen_json TEXT;
372
+ CREATE INDEX event_artifact ON event (artifact_id, cursor);
373
+ CREATE INDEX event_artifact_type ON event (artifact_id, type, cursor);
374
+ DROP TRIGGER token_revocation_final;
375
+ CREATE TRIGGER token_revocation_final BEFORE UPDATE ON token
376
+ WHEN OLD.revoked_at IS NOT NULL OR NEW.secret_hash IS NOT OLD.secret_hash
377
+ OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scopes_json IS NOT OLD.scopes_json
378
+ OR NEW.expires_at IS NOT OLD.expires_at OR NEW.pinned_version IS NOT OLD.pinned_version
379
+ OR NEW.shell_origin IS NOT OLD.shell_origin OR NEW.viewer_id IS NOT OLD.viewer_id
380
+ BEGIN
381
+ SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');
382
+ END;
383
+ `);
384
+ },
385
+ },
386
+ {
387
+ version: 6,
388
+ name: "views, follows and field versions",
389
+ up(db) {
390
+ // D108, D109, D63. A view records the submit channels and trusted controls in force when it
391
+ // opened, so the shell, the page and the server judge it alike. `follow` keeps each viewer's
392
+ // "Always follow this artifact". A field records the version whose view last wrote it (an
393
+ // orphan's `fromVersion`): the column WP-06 reserved as `orphaned_from_version`, never set,
394
+ // since orphans are derived per view and never stored.
395
+ db.exec(`
396
+ ALTER TABLE field RENAME COLUMN orphaned_from_version TO version_number;
397
+ ALTER TABLE view ADD COLUMN controls_json TEXT;
398
+ CREATE TABLE follow (
399
+ viewer_id TEXT NOT NULL REFERENCES viewer(id),
400
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
401
+ followed_at TEXT NOT NULL,
402
+ PRIMARY KEY (viewer_id, artifact_id)
403
+ );
404
+ `);
405
+ // Fields written before: each draft change names the view it came from, so the newest
406
+ // change of a field tells its version. Changes whose events were compacted stay unknown.
407
+ const changes = db.all<{
408
+ artifact_id: string;
409
+ payload_json: string;
410
+ version_number: number;
411
+ }>(
412
+ `SELECT event.artifact_id, event.payload_json, version.number AS version_number FROM event
413
+ JOIN view ON view.id = json_extract(event.causation_json, '$.viewId')
414
+ JOIN version ON version.id = view.version_id
415
+ WHERE event.type = 'draft.changed' ORDER BY event.cursor`,
416
+ );
417
+ for (const change of changes) {
418
+ const payload = JSON.parse(change.payload_json) as {
419
+ viewerId?: string;
420
+ changes?: { id: string }[];
421
+ };
422
+ for (const field of payload.changes ?? []) {
423
+ db.run(
424
+ `UPDATE field SET version_number = ? WHERE field_id = ? AND document_id IN
425
+ (SELECT id FROM document WHERE artifact_id = ? AND scope = 'viewer' AND viewer_id = ?)`,
426
+ change.version_number,
427
+ field.id,
428
+ change.artifact_id,
429
+ payload.viewerId ?? null,
430
+ );
431
+ }
432
+ }
433
+ },
434
+ },
435
+ {
436
+ version: 7,
437
+ name: "action runs and live values",
438
+ up(db) {
439
+ // D24, D54, D47, AC-02, AC-03. A run is recorded before any worker starts it. An explicit
440
+ // key allows one run per artifact, function and key, ever (SQLite treats NULL keys as
441
+ // distinct, so keyless runs don't collide); a client key makes a retried request join the
442
+ // run it started. `waiting` is reserved for WP-28's relay (D117, D124). A final run never
443
+ // changes again, and its result batches only grow while it runs.
444
+ db.exec(`
445
+ CREATE TABLE action_run (
446
+ id TEXT PRIMARY KEY,
447
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
448
+ version_id TEXT NOT NULL REFERENCES version(id),
449
+ view_id TEXT REFERENCES view(id),
450
+ viewer_id TEXT REFERENCES viewer(id),
451
+ action TEXT NOT NULL,
452
+ args_json TEXT NOT NULL,
453
+ key TEXT,
454
+ client_key TEXT NOT NULL,
455
+ status TEXT NOT NULL
456
+ CHECK (status IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled')),
457
+ reason TEXT,
458
+ error_json TEXT,
459
+ progress_json TEXT,
460
+ log_text TEXT NOT NULL DEFAULT '',
461
+ log_lines INTEGER NOT NULL DEFAULT 0,
462
+ log_truncated INTEGER NOT NULL DEFAULT 0,
463
+ batches INTEGER NOT NULL DEFAULT 0,
464
+ result_size INTEGER NOT NULL DEFAULT 0,
465
+ started_at TEXT NOT NULL,
466
+ finished_at TEXT,
467
+ UNIQUE (artifact_id, action, key),
468
+ UNIQUE (artifact_id, client_key)
469
+ );
470
+ CREATE INDEX action_run_view ON action_run(view_id);
471
+ CREATE INDEX action_run_open ON action_run(status) WHERE status IN ('queued', 'running', 'waiting');
472
+ CREATE TRIGGER action_run_final_update BEFORE UPDATE ON action_run
473
+ WHEN OLD.status IN ('succeeded', 'failed', 'cancelled')
474
+ BEGIN
475
+ SELECT RAISE(ABORT, 'a finished action run never changes');
476
+ END;
477
+ CREATE TRIGGER action_run_no_delete BEFORE DELETE ON action_run
478
+ BEGIN
479
+ SELECT RAISE(ABORT, 'action runs are kept with their artifact');
480
+ END;
481
+ CREATE TABLE action_run_batch (
482
+ run_id TEXT NOT NULL REFERENCES action_run(id),
483
+ seq INTEGER NOT NULL,
484
+ batch_json TEXT NOT NULL,
485
+ PRIMARY KEY (run_id, seq)
486
+ );
487
+ CREATE TRIGGER action_run_batch_append BEFORE UPDATE ON action_run_batch
488
+ BEGIN
489
+ SELECT RAISE(ABORT, 'a run result batch never changes');
490
+ END;
491
+ -- Write-once like submissions and versions (DATA_MODEL §3): an INSERT OR REPLACE would
492
+ -- delete the row it replaces without firing the DELETE trigger (Opus review 11).
493
+ CREATE TRIGGER action_run_not_replaced BEFORE INSERT ON action_run
494
+ WHEN EXISTS (SELECT 1 FROM action_run WHERE id = NEW.id
495
+ OR (artifact_id = NEW.artifact_id AND client_key = NEW.client_key)
496
+ OR (NEW.key IS NOT NULL AND artifact_id = NEW.artifact_id AND action = NEW.action
497
+ AND key = NEW.key))
498
+ BEGIN
499
+ SELECT RAISE(ABORT, 'an action run is never replaced');
500
+ END;
501
+ CREATE TRIGGER action_run_batch_no_delete BEFORE DELETE ON action_run_batch
502
+ BEGIN
503
+ SELECT RAISE(ABORT, 'a run result batch is kept with its run');
504
+ END;
505
+ CREATE TRIGGER action_run_batch_once BEFORE INSERT ON action_run_batch
506
+ WHEN EXISTS (SELECT 1 FROM action_run_batch WHERE run_id = NEW.run_id AND seq = NEW.seq)
507
+ OR EXISTS (SELECT 1 FROM action_run WHERE id = NEW.run_id
508
+ AND status IN ('succeeded', 'failed', 'cancelled'))
509
+ BEGIN
510
+ SELECT RAISE(ABORT, 'a finished run takes no more result batches');
511
+ END;
512
+ `);
513
+ // D56, D63, LL-04. A live source keeps its latest value with a revision that only grows, and
514
+ // in append mode a bounded ring of recent values. Updates are never events.
515
+ db.exec(`
516
+ CREATE TABLE live_value (
517
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
518
+ key TEXT NOT NULL,
519
+ revision INTEGER NOT NULL,
520
+ value_json TEXT NOT NULL,
521
+ producer_version_id TEXT,
522
+ at TEXT NOT NULL,
523
+ PRIMARY KEY (artifact_id, key)
524
+ );
525
+ CREATE TRIGGER live_value_revision BEFORE UPDATE ON live_value
526
+ WHEN NEW.revision <= OLD.revision
527
+ BEGIN
528
+ SELECT RAISE(ABORT, 'a live value revision only grows');
529
+ END;
530
+ CREATE TABLE live_ring (
531
+ artifact_id TEXT NOT NULL,
532
+ key TEXT NOT NULL,
533
+ revision INTEGER NOT NULL,
534
+ value_json TEXT NOT NULL,
535
+ at TEXT NOT NULL,
536
+ PRIMARY KEY (artifact_id, key, revision)
537
+ );
538
+ `);
539
+ },
540
+ },
541
+ {
542
+ version: 8,
543
+ name: "verify verdicts on versions",
544
+ up(db) {
545
+ // D138 item 4: whether a version passed verify is a recorded fact, written with the version
546
+ // (it is write-once like the rest of the row), so the regression baseline is the newest
547
+ // version that passed even when its build is gone. NULL for versions published before
548
+ // verify, which never count as passing.
549
+ db.exec(`
550
+ ALTER TABLE version ADD COLUMN verify_json TEXT;
551
+ `);
552
+ },
553
+ },
554
+ {
555
+ version: 9,
556
+ name: "collected versions",
557
+ up(db) {
558
+ // D140 item 14: `mostra gc` removes an unreferenced version's files and keeps its row, ID
559
+ // and number forever, so a content-addressed ID never gets a second number. The collection
560
+ // is a row here, never a change to `version`: inserted once, never updated, and deleted only
561
+ // when a publish of the exact source restores the files.
562
+ db.exec(`
563
+ CREATE TABLE version_collected (
564
+ version_id TEXT PRIMARY KEY REFERENCES version(id),
565
+ collected_at TEXT NOT NULL
566
+ );
567
+ CREATE TRIGGER version_collected_write_once BEFORE UPDATE ON version_collected
568
+ BEGIN
569
+ SELECT RAISE(ABORT, 'a collection record never changes');
570
+ END;
571
+ CREATE TRIGGER version_collected_not_replaced BEFORE INSERT ON version_collected
572
+ WHEN EXISTS (SELECT 1 FROM version_collected WHERE version_id = NEW.version_id)
573
+ BEGIN
574
+ SELECT RAISE(ABORT, 'a version is collected once');
575
+ END;
576
+ CREATE TRIGGER version_kept BEFORE DELETE ON version
577
+ BEGIN
578
+ SELECT RAISE(ABORT, 'a version row is kept forever, collected or not');
579
+ END;
580
+ `);
581
+ },
582
+ },
583
+ ];
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Idempotent requests (H-03, FAILURE_MODEL §1 rule 3): a mutating method records its result under
3
+ * the caller's `requestId`, with a digest of the parameters it was called with, in the same
4
+ * transaction as its effect. A retry with the same parameters gets the recorded result; the same
5
+ * `requestId` with other parameters is refused with `MOSTRA_HOST_REQUEST_ID_REUSED`, never answered
6
+ * with a result for a request nobody made.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
10
+ import type { LedgerDb } from "./types.ts";
11
+
12
+ /** A request to record or replay: its method, the caller's `requestId` and a digest of its params. */
13
+ export interface RequestKey {
14
+ readonly method: string;
15
+ readonly requestId: string;
16
+ readonly digest: string;
17
+ }
18
+
19
+ /** JSON with object keys sorted at every depth, so equal parameters give equal text. */
20
+ function stableJson(value: unknown): string {
21
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
22
+ if (value !== null && typeof value === "object") {
23
+ const entries = Object.entries(value as Record<string, unknown>)
24
+ .filter(([, item]) => item !== undefined)
25
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
26
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
27
+ }
28
+ return JSON.stringify(value);
29
+ }
30
+
31
+ /**
32
+ * The key of a request, or `undefined` when the caller sent no `requestId`. The digest covers
33
+ * every parameter but `requestId` itself.
34
+ */
35
+ export function requestKey<P extends { readonly requestId?: string | undefined }>(
36
+ method: string,
37
+ params: P,
38
+ ): RequestKey | undefined {
39
+ const { requestId, ...rest } = params as { requestId?: string } & Record<string, unknown>;
40
+ if (requestId === undefined) return undefined;
41
+ return {
42
+ method,
43
+ requestId,
44
+ digest: createHash("sha256").update(stableJson(rest), "utf8").digest("hex"),
45
+ };
46
+ }
47
+
48
+ function reused(key: RequestKey): RpcError {
49
+ return new RpcError(
50
+ createDiagnostic("MOSTRA_HOST_REQUEST_ID_REUSED", {
51
+ message: `The requestId "${key.requestId}" was used for another ${key.method} request with other parameters.`,
52
+ }),
53
+ );
54
+ }
55
+
56
+ /**
57
+ * The result recorded for `key`, or `undefined` when none is. Throws `MOSTRA_HOST_REQUEST_ID_REUSED`
58
+ * when the `requestId` was recorded with other parameters. A row recorded before digests existed
59
+ * replays as it always did.
60
+ */
61
+ export function recordedResult<T>(db: LedgerDb, key: RequestKey): T | undefined {
62
+ const row = db.get<{ result_json: string; params_digest: string | null }>(
63
+ "SELECT result_json, params_digest FROM request WHERE method = ? AND request_id = ?",
64
+ key.method,
65
+ key.requestId,
66
+ );
67
+ if (!row) return undefined;
68
+ if (row.params_digest !== null && row.params_digest !== key.digest) throw reused(key);
69
+ return JSON.parse(row.result_json) as T;
70
+ }
71
+
72
+ /** Records `result` for `key` in the caller's transaction; a key already recorded is kept. */
73
+ export function recordResult(db: LedgerDb, key: RequestKey, result: unknown): void {
74
+ db.run(
75
+ "INSERT OR IGNORE INTO request (method, request_id, result_json, params_digest, created_at) VALUES (?, ?, ?, ?, ?)",
76
+ key.method,
77
+ key.requestId,
78
+ JSON.stringify(result),
79
+ key.digest,
80
+ new Date().toISOString(),
81
+ );
82
+ }
83
+
84
+ /**
85
+ * Joins concurrent calls of one request, so a retry that arrives while the first attempt runs
86
+ * waits for its result; the same `requestId` with other parameters is refused at once.
87
+ */
88
+ export class InflightRequests {
89
+ readonly #running = new Map<
90
+ string,
91
+ { readonly digest: string; readonly result: Promise<unknown> }
92
+ >();
93
+
94
+ run<T>(key: RequestKey, task: () => Promise<T>): Promise<T> {
95
+ const id = `${key.method} ${key.requestId}`;
96
+ const running = this.#running.get(id);
97
+ if (running) {
98
+ if (running.digest !== key.digest) return Promise.reject(reused(key));
99
+ return running.result as Promise<T>;
100
+ }
101
+ const result = task().finally(() => this.#running.delete(id));
102
+ this.#running.set(id, { digest: key.digest, result });
103
+ return result;
104
+ }
105
+ }