@foldrun/core 17.2.0 → 17.4.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 (70) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +309 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +357 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +254 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/browse-egress.d.ts +31 -0
  13. package/dist/src/browse-egress.js +43 -0
  14. package/dist/src/egress.d.ts +9 -0
  15. package/dist/src/evals.js +1 -1
  16. package/dist/src/history.d.ts +86 -9
  17. package/dist/src/history.js +132 -16
  18. package/dist/src/journal-store.d.ts +58 -0
  19. package/dist/src/journal-store.js +117 -0
  20. package/dist/src/manifest.d.ts +92 -0
  21. package/dist/src/manifest.js +239 -0
  22. package/dist/src/ops-log.js +26 -3
  23. package/dist/src/platform.d.ts +7 -0
  24. package/dist/src/platform.js +1 -0
  25. package/dist/src/publish.d.ts +134 -0
  26. package/dist/src/publish.js +434 -0
  27. package/dist/src/records.d.ts +72 -0
  28. package/dist/src/records.js +24 -0
  29. package/dist/src/revision-store.d.ts +161 -0
  30. package/dist/src/revision-store.js +378 -0
  31. package/dist/src/run-container.d.ts +20 -0
  32. package/dist/src/run-container.js +61 -0
  33. package/dist/src/runner.js +22 -4
  34. package/dist/src/s3-blob-store.d.ts +29 -0
  35. package/dist/src/s3-blob-store.js +458 -0
  36. package/dist/src/state-retention.d.ts +15 -0
  37. package/dist/src/state-retention.js +65 -0
  38. package/dist/src/storage.d.ts +29 -1
  39. package/dist/src/storage.js +331 -81
  40. package/dist/src/store.d.ts +41 -0
  41. package/dist/src/store.js +188 -5
  42. package/dist/src/trigger-log.js +17 -0
  43. package/dist/src/workspace-revisions.d.ts +259 -0
  44. package/dist/src/workspace-revisions.js +1274 -0
  45. package/package.json +1 -1
  46. package/src/approvals.ts +3 -3
  47. package/src/blob-cache.ts +354 -0
  48. package/src/blob-pins.ts +99 -0
  49. package/src/blob-store.ts +385 -0
  50. package/src/blob-sweeper.ts +308 -0
  51. package/src/blob-types.ts +216 -0
  52. package/src/browse-egress.ts +49 -1
  53. package/src/egress.ts +6 -0
  54. package/src/evals.ts +1 -1
  55. package/src/history.ts +182 -16
  56. package/src/journal-store.ts +152 -0
  57. package/src/manifest.ts +274 -0
  58. package/src/ops-log.ts +25 -3
  59. package/src/platform.ts +8 -0
  60. package/src/publish.ts +520 -0
  61. package/src/records.ts +105 -0
  62. package/src/revision-store.ts +513 -0
  63. package/src/run-container.ts +62 -0
  64. package/src/runner.ts +21 -4
  65. package/src/s3-blob-store.ts +489 -0
  66. package/src/state-retention.ts +83 -0
  67. package/src/storage.ts +335 -81
  68. package/src/store.ts +178 -5
  69. package/src/trigger-log.ts +15 -0
  70. package/src/workspace-revisions.ts +1324 -0
@@ -0,0 +1,434 @@
1
+ // The publish protocol (FOL-126, phase 1). No caller uses it yet.
2
+ //
3
+ // Every write to a workspace — a run's copy-back, a dashboard save, /deploy,
4
+ // the assistant, /import, /restore — ends the same way:
5
+ //
6
+ // 1. The writer starts from a pinned base: it staged a revision, and every
7
+ // change it makes records the sha it STARTED from (`PathChange.base`).
8
+ // 2. publish() uploads the new blobs (conditional put: identical content is
9
+ // a no-op) — outside any transaction, so slow uploads never hold one.
10
+ // 3. It folds the changes onto the CURRENT head:
11
+ // - the head still holds the sha the writer started from → apply;
12
+ // - the head already holds what the writer wants → nothing to do;
13
+ // - the head holds something else → a CONFLICT on that path: the head's
14
+ // version stays, the writer's version is kept beside it as
15
+ // `<stem>.conflict-<op>.<ext>`. Different paths never conflict, so
16
+ // two runs editing different memory files both land. There is no
17
+ // merge of text, JSON or binaries (applyContainerChanges' append
18
+ // merge stays where it is, before the changes reach here).
19
+ // 4. It uploads the new manifests, confirms every blob the result names is
20
+ // still in the store (a sweeper may have removed one that nothing
21
+ // referenced yet — we hold the bytes, so we put it back), and then makes
22
+ // ONE commit: compare-and-set the head, insert the revision, record the
23
+ // op id. Nothing before that step changes what anyone reads.
24
+ // 5. The head moved meanwhile → stale → fold again on the new head.
25
+ // 6. The op id committed already (a retry after a lost answer) → `duplicate`
26
+ // with the original revision. A retry never publishes twice.
27
+ //
28
+ // A crash anywhere before step 4's commit leaves orphan blobs and manifests —
29
+ // unreferenced, invisible, collected later — and the old head. A crash after
30
+ // the commit leaves the new head. Never a mix: the head moves in one step.
31
+ //
32
+ // THE GC WINDOW (closed in phase 2). A sweeper that deleted between "the blobs
33
+ // are there" and "the commit landed" would strand the new revision. Now the
34
+ // publisher pins its blobs (BlobPins, blob-pins.ts) BEFORE it checks they
35
+ // exist and releases them after the commit; a revision pins its manifests in
36
+ // the same transaction as the commit; the sweeper deletes only through
37
+ // `guardDelete`. See blob-pins.ts for the argument.
38
+ //
39
+ // TWO HEADS (decided 6 Nov 2026). Authored files move on the workspace head and
40
+ // `state/` on its own state head, so a per-step state checkpoint never makes a
41
+ // source save replay (or the reverse). One publish() call whose changes touch
42
+ // both sides is therefore two commits — workspace first, then state, with a
43
+ // derived op id — and each is idempotent on its own: a crash between them is
44
+ // finished by retrying the same call. A revision names the manifest of its own
45
+ // side and EMPTY_MANIFEST_ID for the other.
46
+ //
47
+ // Restore is a publish too: a new revision whose manifest is an old one.
48
+ // History is never rewritten; `state/` is rewound only when asked, by naming a
49
+ // state revision (`stateTo`).
50
+ import { BlobNotFound, readAll } from "./blob-store.js";
51
+ import { PUBLISH_PIN_TTL_MS } from "./blob-pins.js";
52
+ import { applyChanges, assertManifest, assertManifestPath, blobObjectKey, canonicalManifest, conflictPath, EMPTY_MANIFEST_ID, emptyManifest, entryId, manifestId, manifestObjectKey, parseManifest, sha256Hex, sideOf, MODE_EXEC, MODE_FILE, } from "./manifest.js";
53
+ import { assertOpId, OpIdReused } from "./revision-store.js";
54
+ /** A revision (or a publish) names a blob the store does not have. Explicit,
55
+ * never an empty file: the caller decides whether this is a repair or a
56
+ * refusal. */
57
+ export class BlobMissing extends Error {
58
+ path;
59
+ sha;
60
+ constructor(path, sha) {
61
+ super(`${path}: its content (${sha.slice(0, 12)}…) is missing from the store`);
62
+ this.name = "BlobMissing";
63
+ this.path = path;
64
+ this.sha = sha;
65
+ }
66
+ }
67
+ export class PublishError extends Error {
68
+ code;
69
+ constructor(message, code) {
70
+ super(message);
71
+ this.name = "PublishError";
72
+ this.code = code;
73
+ }
74
+ }
75
+ export async function headsOf(deps, ws) {
76
+ const [workspace, state] = await Promise.all([deps.revisions.head({ ...ws, scope: "workspace" }), deps.revisions.head({ ...ws, scope: "state" })]);
77
+ return { workspace, state };
78
+ }
79
+ /** The revision that owns a path: the state head for `state/…`, the workspace
80
+ * head for everything else. null when the path is on neither side. */
81
+ export function revisionFor(heads, rel) {
82
+ const side = sideOf(rel);
83
+ return side === "state" ? heads.state : side === "authored" ? heads.workspace : null;
84
+ }
85
+ /** The two manifests as the pair of heads defines them. */
86
+ export async function manifestsAt(deps, tenant, heads) {
87
+ const [authored, state] = await Promise.all([
88
+ heads.workspace ? loadManifest(deps, tenant, heads.workspace.authored) : emptyManifest(),
89
+ heads.state ? loadManifest(deps, tenant, heads.state.state) : emptyManifest(),
90
+ ]);
91
+ return { authored, state };
92
+ }
93
+ // ---------- reading ----------
94
+ export async function loadManifest(deps, tenant, id) {
95
+ if (id === EMPTY_MANIFEST_ID)
96
+ return emptyManifest();
97
+ let bytes;
98
+ try {
99
+ bytes = await readAll(deps.blobs, manifestObjectKey(tenant, id));
100
+ }
101
+ catch (err) {
102
+ if (err instanceof BlobNotFound)
103
+ throw new BlobMissing(`manifest ${id.slice(0, 12)}…`, id);
104
+ throw err;
105
+ }
106
+ // An object is named by its content; one that is not that content is
107
+ // corruption (or an overwrite), and every revision pointing at it is wrong.
108
+ if (sha256Hex(bytes) !== id)
109
+ throw new Error(`manifest ${id.slice(0, 12)}… does not hash to its name — the stored object is corrupt`);
110
+ return parseManifest(bytes.toString("utf8"));
111
+ }
112
+ /** The two manifests a revision names (one of them is empty: a revision lives
113
+ * on one head; see manifestsAt for the workspace as a whole). */
114
+ export async function manifestsOf(deps, tenant, rev) {
115
+ if (!rev)
116
+ return { authored: emptyManifest(), state: emptyManifest() };
117
+ const [authored, state] = await Promise.all([loadManifest(deps, tenant, rev.authored), loadManifest(deps, tenant, rev.state)]);
118
+ return { authored, state };
119
+ }
120
+ /** One file of a revision, as a stream. Pass the revision of the head that
121
+ * owns the path (revisionFor); a path on the other side is simply absent. */
122
+ export async function openPath(deps, tenant, rev, rel) {
123
+ const side = sideOf(rel);
124
+ if (!side)
125
+ return null;
126
+ const m = await loadManifest(deps, tenant, rev[side]);
127
+ const e = m.files[rel];
128
+ if (!e)
129
+ return null;
130
+ try {
131
+ return { size: e.size, body: await deps.blobs.get(blobObjectKey(tenant, e.sha)) };
132
+ }
133
+ catch (err) {
134
+ if (err instanceof BlobNotFound)
135
+ throw new BlobMissing(rel, e.sha);
136
+ throw err;
137
+ }
138
+ }
139
+ /** Every blob a revision names, checked present. Returns the missing ones. */
140
+ export async function missingBlobs(deps, tenant, rev, opts = {}) {
141
+ const parallel = opts.parallel ?? 8;
142
+ const authored = opts.authored === false ? emptyManifest() : await loadManifest(deps, tenant, rev.authored);
143
+ const state = opts.state === false ? emptyManifest() : await loadManifest(deps, tenant, rev.state);
144
+ const entries = [...Object.entries(authored.files), ...Object.entries(state.files)];
145
+ const missing = [];
146
+ let next = 0;
147
+ await Promise.all(Array.from({ length: Math.min(parallel, entries.length) }, async () => {
148
+ while (next < entries.length) {
149
+ const [p, e] = entries[next++];
150
+ if (!(await deps.blobs.head(blobObjectKey(tenant, e.sha))))
151
+ missing.push({ path: p, sha: e.sha });
152
+ }
153
+ }));
154
+ return missing.sort((a, b) => a.path.localeCompare(b.path));
155
+ }
156
+ // ---------- publishing ----------
157
+ const ENTRY_ID = /^[0-9a-f]{64}:\d+$/;
158
+ function validate(changes) {
159
+ for (const [p, c] of Object.entries(changes)) {
160
+ assertManifestPath(p);
161
+ if (c.base !== null && !(typeof c.base === "string" && ENTRY_ID.test(c.base)))
162
+ throw new PublishError(`change for ${p} has a malformed base`, "bad_change");
163
+ if (c.op === "put") {
164
+ if (!/^[0-9a-f]{64}$/.test(c.sha) || !Number.isSafeInteger(c.size) || c.size < 0 || (c.mode !== MODE_FILE && c.mode !== MODE_EXEC)) {
165
+ throw new PublishError(`change for ${p} is malformed`, "bad_change");
166
+ }
167
+ }
168
+ else if (c.op === "delete") {
169
+ if (c.base === null)
170
+ throw new PublishError(`delete of ${p} names no base`, "bad_change");
171
+ }
172
+ else {
173
+ throw new PublishError(`change for ${p} has no operation`, "bad_change");
174
+ }
175
+ }
176
+ }
177
+ /** The request's identity, for the operation record. Same changes, author and
178
+ * message → same digest; the op id alone does not say "this is a retry". */
179
+ export function requestDigest(kind, parts) {
180
+ const canon = (v) => Array.isArray(v) ? v.map(canon) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v;
181
+ return sha256Hex(JSON.stringify([kind, canon(parts)]));
182
+ }
183
+ /** Fold `changes` onto `head`'s manifests. Pure. */
184
+ export function fold(head, changes, opId) {
185
+ const apply = { authored: {}, state: {} };
186
+ const conflicts = [];
187
+ for (const [p, c] of Object.entries(changes)) {
188
+ const side = sideOf(p);
189
+ const here = head[side].files[p];
190
+ const cur = here ? entryId(here) : null;
191
+ const want = c.op === "put" ? entryId(c) : null;
192
+ if (cur === want)
193
+ continue; // the head already holds exactly that (bytes and mode)
194
+ if (cur === c.base) {
195
+ apply[side][p] = c;
196
+ continue;
197
+ }
198
+ // The head holds something the writer did not start from, and not what it
199
+ // wants: keep the head's, and keep the writer's put beside it — under a
200
+ // name that is free (never over something else), and the same name on a
201
+ // retry.
202
+ if (c.op === "put") {
203
+ let keptAs = "";
204
+ for (let attempt = 0;; attempt++) {
205
+ keptAs = conflictPath(p, opId, attempt);
206
+ const taken = apply[side][keptAs] ?? null;
207
+ const occupant = head[side].files[keptAs];
208
+ if (!occupant && !taken)
209
+ break;
210
+ if (occupant && entryId(occupant) === entryId(c))
211
+ break; // this very copy is already there
212
+ if (attempt > 20)
213
+ throw new PublishError(`no free name for the conflict copy of ${p}`, "bad_change");
214
+ }
215
+ const occupant = head[side].files[keptAs];
216
+ apply[side][keptAs] = { op: "put", base: occupant ? entryId(occupant) : null, sha: c.sha, size: c.size, mode: c.mode };
217
+ conflicts.push({ path: p, keptAs });
218
+ }
219
+ else {
220
+ conflicts.push({ path: p, keptAs: null });
221
+ }
222
+ }
223
+ return {
224
+ authored: applyChanges(head.authored, apply.authored),
225
+ state: applyChanges(head.state, apply.state),
226
+ conflicts,
227
+ applied: { ...apply.authored, ...apply.state },
228
+ };
229
+ }
230
+ async function putManifest(deps, tenant, m) {
231
+ const id = manifestId(m);
232
+ await deps.blobs.putIfAbsent(manifestObjectKey(tenant, id), Buffer.from(canonicalManifest(m)), { contentType: "application/json" });
233
+ return id;
234
+ }
235
+ /** Make sure every sha in `applied` is in the store, uploading from `bytesOf`
236
+ * any that are not. Cheap when they are (one head each). */
237
+ async function ensureBlobs(deps, tenant, applied, bytesOf, parallel = 8) {
238
+ const want = new Map(); // sha → the size the changes declare
239
+ for (const c of Object.values(applied)) {
240
+ if (c.op !== "put")
241
+ continue;
242
+ if (want.has(c.sha) && want.get(c.sha) !== c.size)
243
+ throw new PublishError(`two changes declare different sizes for ${c.sha.slice(0, 12)}…`, "bad_change");
244
+ want.set(c.sha, c.size);
245
+ }
246
+ const list = [...want];
247
+ let next = 0;
248
+ await Promise.all(Array.from({ length: Math.min(parallel, list.length) }, async () => {
249
+ while (next < list.length) {
250
+ const [sha, size] = list[next++];
251
+ const key = blobObjectKey(tenant, sha);
252
+ const there = await deps.blobs.head(key);
253
+ if (there) {
254
+ if (there.size !== size)
255
+ throw new PublishError(`${sha.slice(0, 12)}… is stored with ${there.size} bytes but the change says ${size}`, "bad_change");
256
+ continue;
257
+ }
258
+ const bytes = await bytesOf(sha);
259
+ if (sha256Hex(bytes) !== sha)
260
+ throw new PublishError(`the bytes for ${sha.slice(0, 12)}… do not hash to it`, "bad_change");
261
+ if (bytes.length !== size)
262
+ throw new PublishError(`the bytes for ${sha.slice(0, 12)}… are ${bytes.length} long but the change says ${size}`, "bad_change");
263
+ await deps.blobs.putIfAbsent(key, bytes);
264
+ }
265
+ }));
266
+ }
267
+ function replay(op) {
268
+ // The conflict list is not stored beyond the paths (revision.conflicts);
269
+ // the duplicate answer says which revision was made, not how it got there.
270
+ return op.outcome === "committed" && op.revision
271
+ ? { status: "duplicate", revision: op.revision, conflicts: [] }
272
+ : { status: "unchanged", revision: op.revision, conflicts: [] };
273
+ }
274
+ /** The op id of the state half of a publish/restore: derived, so a retry
275
+ * makes the same one, and kept within the op-id length limit. */
276
+ export function stateOpId(opId) {
277
+ return `${opId.slice(0, 120)}+state+${sha256Hex(opId).slice(0, 16)}`;
278
+ }
279
+ const RANK = { committed: 2, duplicate: 1, unchanged: 0 };
280
+ const guardOf = (deps, ws) => (deps.workspaceExists ? { guard: () => deps.workspaceExists({ tenant: ws.tenant, workspace: ws.workspace }) } : {});
281
+ /** One head's half of a publish. */
282
+ async function publishScope(deps, input, scope, changes, opId) {
283
+ const ws = { ...input.ws, scope };
284
+ const side = scope === "workspace" ? "authored" : "state";
285
+ const digest = requestDigest("publish", { by: input.by, message: input.message, changes });
286
+ const earlier = await deps.revisions.operation(ws, opId);
287
+ if (earlier) {
288
+ if (earlier.digest !== digest)
289
+ throw new OpIdReused(opId);
290
+ return replay(earlier);
291
+ }
292
+ // Upload first, outside any transaction. ensureBlobs inside the loop repeats
293
+ // the existence check right before each commit; the pins (taken by publish())
294
+ // are what make a sweep between here and there harmless.
295
+ await ensureBlobs(deps, ws.tenant, changes, input.bytesOf);
296
+ const max = input.maxReplays ?? 8;
297
+ for (let attempt = 0; attempt <= max; attempt++) {
298
+ const head = await deps.revisions.head(ws);
299
+ const current = head ? await loadManifest(deps, ws.tenant, head[side]) : emptyManifest();
300
+ const next = fold(side === "authored" ? { authored: current, state: emptyManifest() } : { authored: emptyManifest(), state: current }, changes, opId);
301
+ const nextManifest = next[side];
302
+ // Never write a manifest we could not read back.
303
+ assertManifest(nextManifest);
304
+ const id = manifestId(nextManifest);
305
+ if (head && id === head[side]) {
306
+ await deps.revisions.recordNoop(ws, opId, digest);
307
+ return { status: "unchanged", revision: head, conflicts: next.conflicts };
308
+ }
309
+ await ensureBlobs(deps, ws.tenant, next.applied, input.bytesOf);
310
+ if (id !== head?.[side])
311
+ await putManifest(deps, ws.tenant, nextManifest);
312
+ const res = await deps.revisions.commit(ws, {
313
+ base: head?.id ?? null,
314
+ authored: side === "authored" ? id : EMPTY_MANIFEST_ID,
315
+ state: side === "state" ? id : EMPTY_MANIFEST_ID,
316
+ opId,
317
+ digest,
318
+ by: input.by,
319
+ message: input.message,
320
+ conflicts: next.conflicts.map((c) => c.path),
321
+ ...(input.restoredFrom && side === "authored" ? { restoredFrom: input.restoredFrom } : {}),
322
+ ...guardOf(deps, input.ws),
323
+ });
324
+ if (res.status === "gone")
325
+ throw new PublishError(`${input.ws.workspace} does not exist (any more)`, "gone");
326
+ if (res.status === "committed")
327
+ return { status: "committed", revision: res.revision, conflicts: next.conflicts };
328
+ if (res.status === "duplicate")
329
+ return { status: "duplicate", revision: res.revision, conflicts: [] };
330
+ // stale: the head moved. Fold again onto it.
331
+ }
332
+ throw new PublishError("the workspace changed too often while publishing; try again", "too_many_replays");
333
+ }
334
+ /** Combine the two heads' answers: the workspace revision is `revision`, the
335
+ * state one `stateRevision`; the status is the strongest of the two. */
336
+ function combine(ws, st) {
337
+ const parts = [ws, st].filter((x) => x !== null);
338
+ const strongest = parts.reduce((a, b) => (RANK[b.status] > RANK[a.status] ? b : a));
339
+ return {
340
+ status: strongest.status,
341
+ revision: (ws ?? st).revision,
342
+ conflicts: parts.flatMap((x) => x.conflicts),
343
+ ...(st ? { stateRevision: st.revision } : {}),
344
+ };
345
+ }
346
+ export async function publish(deps, input) {
347
+ assertOpId(input.opId);
348
+ validate(input.changes);
349
+ const split = { authored: {}, state: {} };
350
+ for (const [p, c] of Object.entries(input.changes))
351
+ split[sideOf(p)][p] = c;
352
+ const hasAuthored = Object.keys(split.authored).length > 0;
353
+ const hasState = Object.keys(split.state).length > 0;
354
+ // Pin every blob this publish may name BEFORE anything checks that it exists.
355
+ const shas = [...new Set(Object.values(input.changes).flatMap((c) => (c.op === "put" ? [c.sha] : [])))];
356
+ const holder = { kind: "publish", id: input.opId };
357
+ if (shas.length)
358
+ await deps.pins?.pinBlobs(input.ws.tenant, shas, holder, { ttlMs: PUBLISH_PIN_TTL_MS });
359
+ try {
360
+ // A call with no changes at all is the (empty) first publish of a workspace.
361
+ const ws = hasAuthored || !hasState ? await publishScope(deps, input, "workspace", split.authored, input.opId) : null;
362
+ const st = hasState ? await publishScope(deps, input, "state", split.state, stateOpId(input.opId)) : null;
363
+ return combine(ws, st);
364
+ }
365
+ finally {
366
+ // Committed: the revision's own manifest pin protects the blobs now.
367
+ // Failed: nothing references them, and the lease would have expired anyway.
368
+ if (shas.length)
369
+ await deps.pins?.release(input.ws.tenant, holder).catch(() => { });
370
+ }
371
+ }
372
+ async function restoreScope(deps, input, scope, toId, opId) {
373
+ const ws = { ...input.ws, scope };
374
+ const side = scope === "workspace" ? "authored" : "state";
375
+ const digest = requestDigest("restore", { to: toId, scope, by: input.by, message: input.message ?? null });
376
+ const earlier = await deps.revisions.operation(ws, opId);
377
+ if (earlier) {
378
+ if (earlier.digest !== digest)
379
+ throw new OpIdReused(opId);
380
+ return replay(earlier);
381
+ }
382
+ const target = await deps.revisions.revision(ws, toId);
383
+ if (!target)
384
+ throw new PublishError(`no ${scope} revision ${toId}`, "bad_change");
385
+ // Check exactly what the new revision will point at, and nothing else:
386
+ // missing history it never references must not block it.
387
+ const missing = await missingBlobs(deps, ws.tenant, target, side === "authored" ? { state: false } : { authored: false });
388
+ if (missing.length)
389
+ throw new BlobMissing(missing[0].path, missing[0].sha);
390
+ const max = input.maxReplays ?? 8;
391
+ for (let attempt = 0; attempt <= max; attempt++) {
392
+ const head = await deps.revisions.head(ws);
393
+ if (head && head[side] === target[side]) {
394
+ await deps.revisions.recordNoop(ws, opId, digest);
395
+ return { status: "unchanged", revision: head, conflicts: [] };
396
+ }
397
+ const res = await deps.revisions.commit(ws, {
398
+ base: head?.id ?? null,
399
+ authored: side === "authored" ? target.authored : EMPTY_MANIFEST_ID,
400
+ state: side === "state" ? target.state : EMPTY_MANIFEST_ID,
401
+ opId,
402
+ digest,
403
+ by: input.by,
404
+ message: input.message ?? `restore ${target.id}`,
405
+ restoredFrom: target.id,
406
+ ...guardOf(deps, input.ws),
407
+ });
408
+ if (res.status === "gone")
409
+ throw new PublishError(`${input.ws.workspace} does not exist (any more)`, "gone");
410
+ if (res.status === "committed")
411
+ return { status: "committed", revision: res.revision, conflicts: [] };
412
+ if (res.status === "duplicate")
413
+ return { status: "duplicate", revision: res.revision, conflicts: [] };
414
+ }
415
+ throw new PublishError("the workspace changed too often while restoring; try again", "too_many_replays");
416
+ }
417
+ /** A new revision with an old one's content. History is untouched. Refuses,
418
+ * before committing anything, when a blob the old revision names is gone. */
419
+ export async function restore(deps, input) {
420
+ assertOpId(input.opId);
421
+ // Both targets are checked before either head moves: a bad state target must
422
+ // not leave the source half restored.
423
+ if (input.stateTo) {
424
+ const st = await deps.revisions.revision({ ...input.ws, scope: "state" }, input.stateTo);
425
+ if (!st)
426
+ throw new PublishError(`no state revision ${input.stateTo}`, "bad_change");
427
+ const missing = await missingBlobs(deps, input.ws.tenant, st, { authored: false });
428
+ if (missing.length)
429
+ throw new BlobMissing(missing[0].path, missing[0].sha);
430
+ }
431
+ const ws = await restoreScope(deps, input, "workspace", input.to, input.opId);
432
+ const st = input.stateTo ? await restoreScope(deps, input, "state", input.stateTo, stateOpId(input.opId)) : null;
433
+ return combine(ws, st);
434
+ }
@@ -0,0 +1,72 @@
1
+ import type { RunRecord, RunSummary } from "./store.ts";
2
+ import type { TriggerEvent } from "./trigger-log.ts";
3
+ import type { FileRecord } from "./storage.ts";
4
+ /** The read half of the port without blocking the event loop (FOL-126 phase
5
+ * 3b): the hot reads — one run, a workspace's run list, its live runs — asked
6
+ * of the database directly. Optional: a port without it is read through its
7
+ * synchronous twin, so a caller can always ask the async form. The rest of
8
+ * the port (writes, the trigger log, the storage index, counts, moves) is
9
+ * still synchronous: see the phase 3b report for the list. */
10
+ export interface RecordsPortAsync {
11
+ runGet(tenant: string, workspace: string, id: string): Promise<RunRecord | null>;
12
+ runSummaries(tenant: string, workspace: string): Promise<RunSummary[]>;
13
+ runLive(tenant: string, workspace: string): Promise<RunRecord[]>;
14
+ /** The write half, for a caller that is async anyway (FOL-126 phase 4):
15
+ * the same upsert as the synchronous runPut, honouring the fence of the
16
+ * lock its async context holds, with the event loop free while it waits.
17
+ * Optional like the reads: a port without it is written through runPut. */
18
+ runPut?(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): Promise<void>;
19
+ }
20
+ export interface RecordsPort {
21
+ /** Async reads (see RecordsPortAsync). */
22
+ async?: RecordsPortAsync;
23
+ /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
24
+ runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
25
+ runGet(tenant: string, workspace: string, id: string): RunRecord | null;
26
+ /** True when a row was there. */
27
+ runDelete(tenant: string, workspace: string, id: string): boolean;
28
+ /** Every run's row, newest first. */
29
+ runSummaries(tenant: string, workspace: string): RunSummary[];
30
+ /** The live runs, whole, newest first. */
31
+ runLive(tenant: string, workspace: string): RunRecord[];
32
+ runCount(tenant: string, workspace: string): number;
33
+ /** Every workspace's run count in one question (the workspace list asks it once, not once per workspace). */
34
+ runCounts(tenant: string): Record<string, number>;
35
+ /** Every run, whole, newest first. */
36
+ runAll(tenant: string, workspace: string): RunRecord[];
37
+ /** Up to `limit` of one flow's runs, whole, newest first. */
38
+ runRecent(tenant: string, workspace: string, flow: string, limit: number): RunRecord[];
39
+ /** Runs that started at or after `sinceMs`, whole, newest first. */
40
+ runsSince(tenant: string, workspace: string, sinceMs: number): RunRecord[];
41
+ /** When the row last changed, in epoch MICROseconds, or null when there is
42
+ * none — what a poller compares instead of a file's mtime (two writes in one
43
+ * millisecond still differ), and what runUpdatedMs divides by 1000 for the
44
+ * age checks that want milliseconds. */
45
+ runStamp(tenant: string, workspace: string, id: string): number | null;
46
+ triggerAppend(tenant: string, workspace: string, event: TriggerEvent): void;
47
+ /** Newest first. */
48
+ triggerRead(tenant: string, workspace: string, limit: number): TriggerEvent[];
49
+ fileList(tenant: string, workspace: string): FileRecord[];
50
+ filePut(tenant: string, workspace: string, record: FileRecord): void;
51
+ fileDelete(tenant: string, workspace: string, path: string): boolean;
52
+ /** Every record of the workspace is gone (it was deleted). Safe to repeat. */
53
+ workspaceDrop(tenant: string, workspace: string): void;
54
+ /** The workspace was renamed: its runs and trigger log follow. The file
55
+ * index does NOT — it moves with the bytes it names (fileMove), after they
56
+ * are copied, so a failed copy leaves index and bytes together. */
57
+ workspaceMove(tenant: string, from: string, to: string): void;
58
+ /** The storage file index follows the workspace's new name. */
59
+ fileMove(tenant: string, from: string, to: string): void;
60
+ /** True while this workspace's records are still FILES on this process: its
61
+ * boot import could not move them (records-import.ts), so every function
62
+ * answers from the files for it, and the next boot tries again. Optional:
63
+ * a port without it has no such workspaces. */
64
+ onFiles?(tenant: string, workspace: string): boolean;
65
+ /** A short named lock across processes, with stale-holder fencing: while
66
+ * `fn` runs, every write of this port made in its async context is refused
67
+ * if a newer holder took the lock over. */
68
+ lock<T>(name: string, fn: () => Promise<T>): Promise<T>;
69
+ }
70
+ /** The registered port, or null: files, as before. With a workspace, null also
71
+ * when that workspace is still on files (its import is pending). */
72
+ export declare function records(tenant?: string, workspace?: string): RecordsPort | null;
@@ -0,0 +1,24 @@
1
+ // The records a workspace accumulates, behind a seam (FOL-126, phase 2).
2
+ //
3
+ // Runs, the run index, the trigger log and the storage file index used to be
4
+ // files on the data volume. On a hosted install they are rows in Postgres —
5
+ // but core has no database, and its callers are synchronous (readRun is called
6
+ // from dozens of places). So this is a small SYNCHRONOUS port: the platform
7
+ // registers an implementation (foldrun-platform src/records-pg.ts, which asks
8
+ // Postgres through a thread so the caller can keep its shape) and every
9
+ // function here falls back to the files when none is registered. A laptop, the
10
+ // CLI and a self-hosted install with no database never register one, so none
11
+ // of them changes by a byte.
12
+ //
13
+ // What is NOT here: run outputs and captured calls (bytes, phase 5), the
14
+ // ledger (platform, its own table), secrets (phase 6), workspace files
15
+ // (phase 3, revisions).
16
+ import { platform } from "./platform.js";
17
+ /** The registered port, or null: files, as before. With a workspace, null also
18
+ * when that workspace is still on files (its import is pending). */
19
+ export function records(tenant, workspace) {
20
+ const port = platform.records ?? null;
21
+ if (port && tenant !== undefined && workspace !== undefined && port.onFiles?.(tenant, workspace))
22
+ return null;
23
+ return port;
24
+ }