@foldrun/core 17.3.0 → 18.0.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 (65) 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 +312 -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 +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +92 -9
  14. package/dist/src/history.js +168 -20
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +531 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +560 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1423 -0
@@ -0,0 +1,1382 @@
1
+ // Workspaces as revisions (FOL-126, phase 3 — first slice).
2
+ //
3
+ // What this is: the bridge between the writers that exist (they change the
4
+ // workspace folder and call history.ts recordRevision) and the revision store
5
+ // of phase 1 (heads, manifests, blobs, the publish protocol).
6
+ //
7
+ // write path ──► history.recordRevision ──► journalChange ──► [journal]
8
+ // │ flushRevisions / background drain
9
+ // ▼
10
+ // publish(): upload blobs, fold onto the head, ONE commit
11
+ //
12
+ // Every writer — dashboard saves, /source PUT/PATCH/DELETE, /deploy, /import,
13
+ // /restore, the assistant, agent import, a run's copy-back — already ends in
14
+ // recordRevision, so the journal sees all of them without touching them. It
15
+ // is registered only where a backend is (setRevisionBackend: the hosted
16
+ // platform with a database, or an install that opts in), so a laptop and the
17
+ // CLI never journal anything.
18
+ //
19
+ // While the workspace FOLDER is still the working copy (phase 4 stages runs
20
+ // from a pinned revision and phase 8 retires the volume), the folder is what
21
+ // the writer just changed, so the journal commits "the head, plus this
22
+ // change": its base is whatever the head holds, not a pinned base. The first
23
+ // commit of a workspace is its whole tree (the baseline), taken from disk.
24
+ // Conflict copies arrive with phase 4's pinned bases; here there is one
25
+ // writer of the folder at a time. A journal entry that cannot commit (the
26
+ // database is down) stays queued, retried with a backoff; if the queue
27
+ // overflows the workspace is marked and reconcileWorkspace brings the head to
28
+ // the folder's content in one revision.
29
+ //
30
+ // Reads: readAtHead resolves head → manifest → blob through the BlobStore,
31
+ // with a seam for the bounded node-local cache another session is building
32
+ // (setBlobCache). History, a revision's diff, its snapshot and restore are
33
+ // answered from revisions in the shapes history.ts has always returned.
34
+ import fs from "node:fs";
35
+ import path from "node:path";
36
+ import crypto from "node:crypto";
37
+ import { currentTree, registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle } from "./history.js";
38
+ import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath } from "./store.js";
39
+ import { dataRoot } from "./paths.js";
40
+ import { opsError, opsLog } from "./ops-log.js";
41
+ import { readAll, BlobNotFound } from "./blob-store.js";
42
+ import { fsJournalStore } from "./journal-store.js";
43
+ import { blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
44
+ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
45
+ import { OpIdReused } from "./revision-store.js";
46
+ import { pruneStateRevisions } from "./state-retention.js";
47
+ // ------------------------------------------------------------- the backend
48
+ let backend = null;
49
+ let gate = { journal: () => false, read: () => false };
50
+ let retention = null;
51
+ let orphanMarks = null;
52
+ let orphanGrace = 3_600_000;
53
+ let retentionEvery = 10 * 60_000;
54
+ /** The legacy place: files on the volume. Always replayed at boot (and then
55
+ * empty), whatever new entries are written to. */
56
+ const legacyFiles = fsJournalStore(() => journalRoot());
57
+ let primary = null;
58
+ const journalStores = () => (primary && primary !== legacyFiles ? [primary, legacyFiles] : [legacyFiles]);
59
+ const entryStore = () => primary ?? legacyFiles;
60
+ /** Where revisions live, or null (no journal, nothing changes). */
61
+ export function setRevisionBackend(deps, opts = {}) {
62
+ // Every commit asks, inside the store's workspace lock, whether the folder is
63
+ // still there: a delete or rename on another pod removes it under that lock.
64
+ backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
65
+ gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
66
+ primary = opts.journalStore ?? null;
67
+ retention = opts.stateRetention ?? null;
68
+ retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
69
+ orphanMarks = opts.sweepMarks ?? null;
70
+ orphanGrace = opts.orphanGraceMs ?? 3_600_000;
71
+ registerJournal(deps ? journalChange : null);
72
+ registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
73
+ registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
74
+ registerRevisionView(deps ? view : null);
75
+ }
76
+ export const revisionBackend = () => backend;
77
+ const journalOn = () => !!backend && safe(gate.journal);
78
+ /** Reads of content from heads (and run stage-in): its own switch, and only
79
+ * where the journal runs too (a head that is not kept current is not a source). */
80
+ export const revisionReadsOn = () => journalOn() && safe(gate.read);
81
+ function safe(fn) {
82
+ try {
83
+ return fn();
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ let cache = null;
90
+ export function setBlobCache(c) {
91
+ cache = c;
92
+ }
93
+ const MAX_QUEUED = 2000;
94
+ /** A journal file this old, that no queue of this process holds, was left by a
95
+ * process that died (a live one commits within seconds or keeps retrying). */
96
+ const ORPHAN_MS = 120_000;
97
+ const queues = new Map();
98
+ const chains = new Map();
99
+ const marked = new Set(); // overflowed or dropped: needs reconcileWorkspace
100
+ const verified = new Set(); // reconciled once in this process
101
+ const unjournalled = new Set(); // changed here while the journal was off: the head has not seen it
102
+ const repairing = new Set(); // a reconcile is publishing: the head is about to change
103
+ const retryAt = new Map();
104
+ const wantPrune = new Set(); // a state checkpoint was committed since the last look
105
+ const prunedAt = new Map();
106
+ /** Workspaces whose commits are held while a delete or rename runs. */
107
+ const frozen = new Map();
108
+ const restoring = new Map();
109
+ const key = (tenant, workspace) => `${tenant}\0${workspace}`;
110
+ const split = (k) => k.split("\0");
111
+ const journalRoot = () => path.join(dataRoot(), ".revision-journal");
112
+ /** Write the entry down, atomically. A store that refuses leaves the entry in
113
+ * memory only (said once per failure), as the journal always was. */
114
+ function persist(tenant, workspace, e) {
115
+ const store = entryStore();
116
+ try {
117
+ e.handle = store.put({ v: 1, tenant, workspace, id: e.id, files: e.files, by: e.by, message: e.message, at: e.at, restoredFrom: e.restoredFrom, baseRev: e.baseRev });
118
+ e.store = store;
119
+ }
120
+ catch (err) {
121
+ opsError("revisions.journal_not_persisted", err, { tenant, workspace, store: store.kind }, "warn");
122
+ }
123
+ }
124
+ function forget(tenant, workspace, e) {
125
+ if (!e.store || e.handle === undefined)
126
+ return;
127
+ try {
128
+ e.store.remove(tenant, workspace, e.handle);
129
+ }
130
+ catch (err) {
131
+ opsError("revisions.journal_not_removed", err, { tenant, workspace }, "warn");
132
+ }
133
+ }
134
+ /** Called by history.recordRevision for every change set. Synchronous and
135
+ * cheap; the commit happens in the background (flushRevisions waits for it). */
136
+ function journalChange(tenant, scope, files, meta) {
137
+ if (!backend || scope === "@library")
138
+ return; // the account shelf is not a workspace
139
+ const k = key(tenant, scope);
140
+ if (!safe(gate.journal)) {
141
+ verified.delete(k); // a change the head will not see: reconcile before trusting it again
142
+ unjournalled.add(k);
143
+ return;
144
+ }
145
+ // Only what the head needs: the new content. The old text is the writer's
146
+ // history record, not the journal's (it can be a quarter megabyte a file).
147
+ const slim = files.map((f) => ({ path: f.path, before: null, after: f.after }));
148
+ enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
149
+ }
150
+ function enqueue(tenant, scope, entry) {
151
+ const k = key(tenant, scope);
152
+ const q = queues.get(k) ?? [];
153
+ persist(tenant, scope, entry);
154
+ q.push(entry);
155
+ if (q.length > MAX_QUEUED) {
156
+ for (const old of q.splice(0, q.length - MAX_QUEUED))
157
+ forget(tenant, scope, old);
158
+ marked.add(k);
159
+ opsLog("error", "revisions.journal_overflow", { tenant, workspace: scope, count: MAX_QUEUED });
160
+ }
161
+ queues.set(k, q);
162
+ setImmediate(() => void drain(k));
163
+ }
164
+ /** A step's file in the journal is held to this size; a bigger one is left to
165
+ * the reconcile, which reads it from the folder (the journal file carries the
166
+ * bytes, and a state index can be tens of megabytes). */
167
+ const MAX_STEP_FILE = 1024 * 1024;
168
+ /** And one step's entry as a whole: it is written down in one go (a file, or a
169
+ * row through the synchronous bridge), so it is bounded. What does not fit is
170
+ * left to the reconcile too. */
171
+ const MAX_STEP_ENTRY = 8 * 1024 * 1024;
172
+ /**
173
+ * FOL-126 phase 4. A step's copy-back lands as ONE revision (one journal
174
+ * entry, one publish): the paths it wrote on the workspace head and the ones
175
+ * under state/ on the state head (two commits, each idempotent, as decided on
176
+ * 6 Nov). Never a half-written tree: the entry is on disk before anything is
177
+ * queued, and a commit is all of the step's paths or none.
178
+ *
179
+ * Pinned base: each path carries the sha the folder held before the write, so
180
+ * a head that moved since (another run, a person) is a CONFLICT on that path —
181
+ * the head's version stays, the step's is kept beside it as
182
+ * `<stem>.conflict-<op>.<ext>` — while paths nobody else touched go through.
183
+ * The id is derived from the run and step, so a step whose copy-back is
184
+ * applied twice (a resumed driver) publishes once.
185
+ *
186
+ * The rule for a failed step, written down: applyContainerChanges runs after a
187
+ * failure too (a failed step's partial outputs are usually the interesting
188
+ * ones), so they are committed as well, as today's folder gets them. A step
189
+ * whose copy-out itself failed wrote nothing and commits nothing. A test run's
190
+ * diverted state/ and storage/ writes never reach the folder and never here.
191
+ *
192
+ * Text only: a binary file is not versioned yet (see phase 3). Returns the
193
+ * number of paths queued.
194
+ */
195
+ export function recordStepOutputs(tenant, workspace, writes, meta) {
196
+ if (!backend || workspace === "@library")
197
+ return 0;
198
+ const k = key(tenant, workspace);
199
+ if (!safe(gate.journal)) {
200
+ verified.delete(k); // the head will not see this: reconcile before trusting it again
201
+ unjournalled.add(k);
202
+ return 0;
203
+ }
204
+ const files = [];
205
+ let total = 0;
206
+ for (const w of writes) {
207
+ if (!sideOf(w.path))
208
+ continue; // not workspace content (runs/, .foldrun/ …)
209
+ const text = w.after.toString("utf8");
210
+ if (!Buffer.from(text, "utf8").equals(w.after))
211
+ continue; // binary: not versioned
212
+ if (w.after.length > MAX_STEP_FILE) {
213
+ marked.add(k); // the folder has it; the reconcile records it
214
+ continue;
215
+ }
216
+ if (total + w.after.length > MAX_STEP_ENTRY) {
217
+ marked.add(k);
218
+ continue;
219
+ }
220
+ total += w.after.length;
221
+ files.push({ path: w.path, before: null, after: text, base: w.base, ...(w.handed !== undefined ? { handed: w.handed } : {}) });
222
+ }
223
+ if (!files.length)
224
+ return 0;
225
+ const idSource = meta.runId ? `${meta.runId}\0${meta.step ?? ""}` : crypto.randomBytes(12).toString("hex");
226
+ enqueue(tenant, workspace, {
227
+ id: `st${sha256Hex(Buffer.from(idSource)).slice(0, 22)}`,
228
+ files,
229
+ by: meta.by ?? (meta.runId ? `run:${meta.runId}` : "run"),
230
+ message: meta.runId ? `run ${meta.runId}${meta.step !== undefined ? ` step ${meta.step}` : ""}` : "run output",
231
+ at: new Date().toISOString(),
232
+ baseRev: meta.base ?? undefined,
233
+ });
234
+ return files.length;
235
+ }
236
+ /** Run `fn` (a synchronous writer) so that the change it records is committed
237
+ * as a restore of `revisionId` — the history then says "restored from". */
238
+ export function asRestoreOf(tenant, workspace, revisionId, fn) {
239
+ const k = key(tenant, workspace);
240
+ if (!revisionId || !journalOn())
241
+ return fn();
242
+ restoring.set(k, revisionId);
243
+ try {
244
+ return fn();
245
+ }
246
+ finally {
247
+ restoring.delete(k);
248
+ }
249
+ }
250
+ export function pendingRevisions() {
251
+ let n = 0;
252
+ for (const q of queues.values())
253
+ n += q.length;
254
+ return n;
255
+ }
256
+ function drain(k) {
257
+ // A delete or a rename of this workspace is in progress: nothing commits
258
+ // until it is done (the gate is read now, so a drain started BEFORE it is
259
+ // never behind it — that is what lets the lifecycle wait for those).
260
+ const gate = frozen.get(k);
261
+ const next = (chains.get(k) ?? Promise.resolve())
262
+ .catch(() => { })
263
+ .then(() => gate)
264
+ .then(() => drainOne(k));
265
+ chains.set(k, next);
266
+ return next;
267
+ }
268
+ async function drainOne(k) {
269
+ const [tenant, workspace] = split(k);
270
+ const q = queues.get(k);
271
+ while (q && q.length && backend) {
272
+ const entry = q[0];
273
+ // The workspace was deleted while this waited (or retried): nothing to
274
+ // publish, and nothing for a later boot to replay.
275
+ if (!fs.existsSync(workspaceDir(tenant, workspace))) {
276
+ q.shift();
277
+ forget(tenant, workspace, entry);
278
+ continue;
279
+ }
280
+ try {
281
+ const res = await commitEntry(backend, tenant, workspace, entry);
282
+ if (res?.status === "committed" && res.stateRevision)
283
+ wantPrune.add(k);
284
+ q.shift();
285
+ forget(tenant, workspace, entry);
286
+ retryAt.delete(k);
287
+ }
288
+ catch (err) {
289
+ if (err instanceof PublishError && err.code === "gone") {
290
+ // The folder is gone (deleted or renamed, here or on another pod): the
291
+ // change has nowhere to go, and nothing should be recorded under the name.
292
+ q.shift();
293
+ forget(tenant, workspace, entry);
294
+ continue;
295
+ }
296
+ if (permanent(err)) {
297
+ // Retrying cannot change a verdict about the CONTENT (a path the
298
+ // manifest refuses, two names differing by case): drop this entry so
299
+ // it does not block every later one, say so, and leave the workspace
300
+ // for a reconcile once the cause is fixed.
301
+ opsError("revisions.entry_dropped", err, { tenant, workspace });
302
+ q.shift();
303
+ forget(tenant, workspace, entry);
304
+ marked.add(k);
305
+ continue;
306
+ }
307
+ opsError("revisions.commit_failed", err, { tenant, workspace });
308
+ const attempts = (retryAt.get(k) ?? 0) + 1;
309
+ retryAt.set(k, attempts);
310
+ const wait = Math.min(30_000, 1_000 * 2 ** Math.min(5, attempts - 1));
311
+ const t = setTimeout(() => void drain(k), wait);
312
+ t.unref?.();
313
+ return;
314
+ }
315
+ }
316
+ if (q && !q.length)
317
+ queues.delete(k);
318
+ if (wantPrune.delete(k))
319
+ await pruneIfDue(tenant, workspace);
320
+ // Once per process per workspace, with nothing queued: the folder is the
321
+ // truth, so a head that disagrees with it (a crash lost an entry, the
322
+ // journal was off for a while, a run wrote the folder directly) is brought
323
+ // to it. After the entries, never before: replaying an older change over a
324
+ // reconciled head would write it backwards.
325
+ if (backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
326
+ verified.add(k);
327
+ try {
328
+ await reconcileWorkspace(tenant, workspace, "reconcile");
329
+ }
330
+ catch (err) {
331
+ verified.delete(k);
332
+ opsError("revisions.reconcile_failed", err, { tenant, workspace }, "warn");
333
+ }
334
+ }
335
+ }
336
+ /** An error that retrying will not cure: the manifest refused the content. */
337
+ function permanent(err) {
338
+ if (err instanceof PublishError)
339
+ return err.code === "bad_change";
340
+ if (err instanceof OpIdReused)
341
+ return true; // commitEntry asked again and it still is: see there
342
+ const m = err instanceof Error ? err.message : "";
343
+ return /^illegal manifest path|differ only by case|a manifest holds at most|is not workspace content/.test(m);
344
+ }
345
+ /** Wait until every queued change (of one workspace, or all) is committed.
346
+ * A barrier for an edge that wants "committed" before it answers. Returns
347
+ * what is still queued (a database that is down leaves some). */
348
+ export async function flushRevisions(only) {
349
+ const keys = only ? [key(only.tenant, only.workspace)] : [...queues.keys()];
350
+ await Promise.all(keys.map((k) => drain(k)));
351
+ return { pending: only ? (queues.get(key(only.tenant, only.workspace))?.length ?? 0) : pendingRevisions() };
352
+ }
353
+ /** Tests: forget every queued change and pending retry (journal FILES stay:
354
+ * that is what a crash leaves). */
355
+ export function resetJournalForTests() {
356
+ queues.clear();
357
+ chains.clear();
358
+ marked.clear();
359
+ verified.clear();
360
+ unjournalled.clear();
361
+ repairing.clear();
362
+ retryAt.clear();
363
+ restoring.clear();
364
+ wantPrune.clear();
365
+ prunedAt.clear();
366
+ frozen.clear();
367
+ }
368
+ /** An account is gone (or one workspace is): forget its queued changes and
369
+ * remove its journal files, so nothing of it is replayed or committed later
370
+ * and no workspace text outlives it outside the folder. Safe to repeat. */
371
+ export function dropJournal(tenant, workspace) {
372
+ for (const k of [...queues.keys()]) {
373
+ const [t, w] = split(k);
374
+ if (t === tenant && (workspace === undefined || w === workspace)) {
375
+ // A drain already running holds this array: empty it, or it commits the rest.
376
+ if (queues.get(k))
377
+ queues.get(k).length = 0;
378
+ queues.delete(k);
379
+ marked.delete(k);
380
+ verified.delete(k);
381
+ unjournalled.delete(k);
382
+ retryAt.delete(k);
383
+ }
384
+ }
385
+ for (const st of journalStores()) {
386
+ try {
387
+ st.drop(tenant, workspace);
388
+ }
389
+ catch (err) {
390
+ opsError("revisions.journal_not_dropped", err, { tenant, workspace, store: st.kind }, "warn");
391
+ }
392
+ }
393
+ }
394
+ // ------------------------------------------------------------- delete and rename
395
+ //
396
+ // A workspace is named by its folder, and the history is kept under that name.
397
+ // Until 8 Nov 2026 a delete left the heads and revisions where they were and a
398
+ // rename left them under the old name: a NEW workspace given either name then
399
+ // started on the old one's head — its history, and through a restore or a
400
+ // read from the head, its files. Now both follow the folder.
401
+ /** Hold the commits of these workspaces until the returned function is called.
402
+ * Waits for an earlier hold on the same workspace first. */
403
+ async function freeze(keys) {
404
+ for (const k of keys)
405
+ while (frozen.has(k))
406
+ await frozen.get(k).catch(() => { });
407
+ let release;
408
+ const gate = new Promise((r) => (release = r));
409
+ for (const k of keys)
410
+ frozen.set(k, gate);
411
+ return () => {
412
+ for (const k of keys)
413
+ if (frozen.get(k) === gate)
414
+ frozen.delete(k);
415
+ release();
416
+ for (const k of keys)
417
+ if (queues.get(k)?.length)
418
+ void drain(k);
419
+ };
420
+ }
421
+ const lifecycleBusy = new Set(); // keys a lifecycle call is handling (the sync hooks stay out of its way)
422
+ /** What the sync hooks started and has not finished (tests, and a process that is ending). */
423
+ const background = new Set();
424
+ export async function settleLifecycle() {
425
+ while (background.size)
426
+ await Promise.allSettled([...background]);
427
+ }
428
+ function inBackground(p) {
429
+ const q = p.finally(() => background.delete(q));
430
+ background.add(q);
431
+ }
432
+ /** Try again a few times, then say so: the folder is gone and cannot be asked. */
433
+ async function persistently(fn, giveUp) {
434
+ for (let attempt = 0;; attempt++) {
435
+ try {
436
+ return await fn();
437
+ }
438
+ catch (err) {
439
+ if (attempt >= 4)
440
+ return giveUp(err);
441
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
442
+ }
443
+ }
444
+ }
445
+ /** The sync hook: a folder was removed by a caller that did not wait for us. */
446
+ function goneNow(tenant, workspace) {
447
+ dropJournal(tenant, workspace);
448
+ if (lifecycleBusy.has(key(tenant, workspace)))
449
+ return;
450
+ inBackground(persistently(() => dropWorkspaceRevisions(tenant, workspace, () => { }), (err) => opsError("revisions.drop_failed", err, { tenant, workspace })));
451
+ }
452
+ /**
453
+ * A workspace is being deleted: its queued changes, its journal entries and
454
+ * its history (both heads, every revision, the operations, the pins on their
455
+ * manifests) go, so that nothing of it can be seen by, or committed under, the
456
+ * next workspace of that name. `remove` is the folder's own removal. Order:
457
+ * hold the commits; drop; remove the folder; drop again for whatever slipped
458
+ * in between. A store that cannot be reached throws BEFORE `remove` runs.
459
+ */
460
+ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
461
+ const deps = backend;
462
+ if (!deps || workspace === "@library") {
463
+ remove?.();
464
+ return;
465
+ }
466
+ const k = key(tenant, workspace);
467
+ lifecycleBusy.add(k);
468
+ const before = chains.get(k);
469
+ const release = await freeze([k]);
470
+ try {
471
+ dropJournal(tenant, workspace);
472
+ await before?.catch(() => { });
473
+ try {
474
+ await deps.revisions.drop({ tenant, workspace });
475
+ }
476
+ catch (err) {
477
+ // Nothing was removed and the workspace stays: whatever was queued is lost to the queue, so it is reconciled from the folder.
478
+ marked.add(k);
479
+ verified.delete(k);
480
+ throw err;
481
+ }
482
+ remove?.();
483
+ dropJournal(tenant, workspace);
484
+ await deps.revisions.drop({ tenant, workspace });
485
+ marked.delete(k);
486
+ verified.delete(k);
487
+ }
488
+ finally {
489
+ lifecycleBusy.delete(k);
490
+ release();
491
+ }
492
+ }
493
+ /** An account is gone: its journal, its history and the blobs under its name.
494
+ * Throws when the store cannot be reached (the caller says so; nothing of the
495
+ * rest depends on it). */
496
+ export async function dropTenantRevisions(tenant) {
497
+ dropJournal(tenant);
498
+ const deps = backend;
499
+ if (!deps)
500
+ return;
501
+ const mine = [...chains.keys()].filter((k) => split(k)[0] === tenant);
502
+ await Promise.all(mine.map((k) => chains.get(k).catch(() => { })));
503
+ for (const k of mine) {
504
+ chains.delete(k);
505
+ marked.delete(k);
506
+ verified.delete(k);
507
+ }
508
+ await deps.revisions.drop({ tenant });
509
+ await deps.blobs.purgeTenant?.(tenant);
510
+ }
511
+ /** The sync hook: a folder was renamed by a caller that did not wait for us. */
512
+ function movedNow(tenant, from, to) {
513
+ if (lifecycleBusy.has(key(tenant, from)) || lifecycleBusy.has(key(tenant, to)))
514
+ return;
515
+ inBackground(moveWorkspaceRevisions(tenant, from, to).catch((err) => opsError("revisions.move_failed", err, { tenant, workspace: from, to })));
516
+ }
517
+ /**
518
+ * A workspace is being renamed: its queued changes wait, its history is
519
+ * re-keyed to the new name (whatever the new name held belonged to a workspace
520
+ * that no longer exists), `rename` moves the folder, and the queue and the
521
+ * journal entries follow. If the folder cannot move, the history goes back. A
522
+ * store that cannot be reached throws BEFORE `rename` runs.
523
+ */
524
+ export async function moveWorkspaceRevisions(tenant, from, to, rename) {
525
+ const deps = backend;
526
+ if (!deps || from === "@library" || to === "@library") {
527
+ rename?.();
528
+ return;
529
+ }
530
+ const ka = key(tenant, from);
531
+ const kb = key(tenant, to);
532
+ lifecycleBusy.add(ka);
533
+ lifecycleBusy.add(kb);
534
+ const befores = [chains.get(ka), chains.get(kb)];
535
+ const release = await freeze([ka, kb].sort());
536
+ try {
537
+ await Promise.all(befores.map((b) => b?.catch(() => { })));
538
+ // Nothing is queued for the new name (no folder has it); what a dead
539
+ // process left for it is stale.
540
+ dropJournal(tenant, to);
541
+ await deps.revisions.move(tenant, from, to);
542
+ if (rename) {
543
+ try {
544
+ rename();
545
+ }
546
+ catch (err) {
547
+ await deps.revisions.move(tenant, to, from).catch((e) => opsError("revisions.move_back_failed", e, { tenant, workspace: from, to }));
548
+ throw err;
549
+ }
550
+ }
551
+ rekeyQueue(tenant, from, to);
552
+ if (rename) {
553
+ // A commit on another pod that passed its guard between the move and the
554
+ // folder rename left rows under the OLD name; its content is in the
555
+ // folder now, so the old name's rows go and the new name is reconciled.
556
+ await deps.revisions.drop({ tenant, workspace: from });
557
+ marked.add(kb);
558
+ }
559
+ }
560
+ finally {
561
+ lifecycleBusy.delete(ka);
562
+ lifecycleBusy.delete(kb);
563
+ release();
564
+ }
565
+ if (rename)
566
+ void drain(kb); // the reconcile marked above
567
+ }
568
+ /** Queued changes and journal entries of `from` become `to`'s. */
569
+ function rekeyQueue(tenant, from, to) {
570
+ const ka = key(tenant, from);
571
+ const kb = key(tenant, to);
572
+ const q = queues.get(ka) ?? [];
573
+ for (const e of q)
574
+ forget(tenant, from, e); // the old handles
575
+ for (const st of journalStores()) {
576
+ try {
577
+ st.move(tenant, from, to); // entries no live queue holds (a dead process's)
578
+ }
579
+ catch (err) {
580
+ opsError("revisions.journal_not_moved", err, { tenant, workspace: from, to, store: st.kind }, "warn");
581
+ }
582
+ }
583
+ const moved = q.map((e) => ({ ...e, store: undefined, handle: undefined }));
584
+ for (const e of moved)
585
+ persist(tenant, to, e);
586
+ q.length = 0; // a drain that holds the old array has nothing left
587
+ queues.delete(ka);
588
+ if (moved.length)
589
+ queues.set(kb, moved);
590
+ if (marked.delete(ka))
591
+ marked.add(kb);
592
+ verified.delete(ka);
593
+ verified.delete(kb);
594
+ retryAt.delete(ka);
595
+ retryAt.delete(kb);
596
+ }
597
+ /** A run's pin on the manifests of its base lasts this long without a renewal. */
598
+ const RUN_PIN_TTL_MS = 2 * 60 * 60_000;
599
+ /**
600
+ * FOL-126 fixes (8 Nov). At stage-in: record which revisions the run starts
601
+ * from and pin their manifests (holder kind `run`, a lease renewed while the
602
+ * step lives), so retention and the sweeper leave them alone. The copy-back is
603
+ * then published against THIS base: a path the head changed since is a
604
+ * conflict, not an overwrite, whatever the folder holds by then.
605
+ *
606
+ * The queue is flushed first, so the head is not behind a save made a moment
607
+ * ago (a head behind the folder would make every such path look conflicting).
608
+ * Null — and the caller carries on as before, with the folder as the base —
609
+ * when revisions are off, there is no head yet (the baseline will hold the
610
+ * whole tree), changes are still queued (the store is down), or the pin cannot
611
+ * be taken.
612
+ */
613
+ export async function pinRunBase(tenant, workspace, holder) {
614
+ const deps = backend;
615
+ if (!deps || !journalOn() || workspace === "@library")
616
+ return null;
617
+ try {
618
+ const { pending } = await flushRevisions({ tenant, workspace });
619
+ if (pending)
620
+ return null;
621
+ const heads = await headsOf(deps, { tenant, workspace });
622
+ if (!heads.workspace && !heads.state)
623
+ return null;
624
+ return await holdRunBase(deps, tenant, { workspace: heads.workspace?.id ?? null, state: heads.state?.id ?? null }, heads, holder);
625
+ }
626
+ catch (err) {
627
+ opsError("revisions.run_base_failed", err, { tenant, workspace }, "warn");
628
+ return null;
629
+ }
630
+ }
631
+ /** The same pin for a base that was recorded earlier (a driver that took over a
632
+ * step): null when either revision is gone. */
633
+ export async function repinRunBase(tenant, workspace, base, holder) {
634
+ const deps = backend;
635
+ if (!deps || !journalOn())
636
+ return null;
637
+ try {
638
+ const w = base.workspace ? await deps.revisions.revision({ tenant, workspace, scope: "workspace" }, base.workspace) : null;
639
+ const s = base.state ? await deps.revisions.revision({ tenant, workspace, scope: "state" }, base.state) : null;
640
+ if ((base.workspace && !w) || (base.state && !s))
641
+ return null;
642
+ return await holdRunBase(deps, tenant, base, { workspace: w, state: s }, holder);
643
+ }
644
+ catch (err) {
645
+ opsError("revisions.run_base_failed", err, { tenant, workspace }, "warn");
646
+ return null;
647
+ }
648
+ }
649
+ async function holdRunBase(deps, tenant, base, revs, holder) {
650
+ const pins = deps.pins;
651
+ const pinHolder = { kind: "run", id: holder.slice(0, 200) };
652
+ let timer = null;
653
+ if (pins) {
654
+ const ids = [revs.workspace?.authored, revs.state?.state].filter((m) => !!m && m !== EMPTY_MANIFEST_ID);
655
+ await pins.pinManifests(tenant, ids, pinHolder, { ttlMs: RUN_PIN_TTL_MS });
656
+ timer = setInterval(() => void pins.renew(tenant, pinHolder, RUN_PIN_TTL_MS).catch(() => { }), RUN_PIN_TTL_MS / 4);
657
+ timer.unref?.();
658
+ }
659
+ let released = false;
660
+ return {
661
+ base,
662
+ async release() {
663
+ if (released)
664
+ return;
665
+ released = true;
666
+ if (timer)
667
+ clearInterval(timer);
668
+ await pins?.release(tenant, pinHolder).catch((err) => opsError("revisions.run_pin_not_released", err, { tenant }, "warn"));
669
+ },
670
+ };
671
+ }
672
+ // ------------------------------------------------------------- state retention
673
+ /** Look at one workspace's `state/` checkpoints now (the host's window). */
674
+ export async function pruneStateNow(tenant, workspace) {
675
+ const deps = backend;
676
+ if (!deps || !retention || !journalOn())
677
+ return null;
678
+ const policy = safe2(retention);
679
+ if (!policy)
680
+ return null;
681
+ try {
682
+ const res = await pruneStateRevisions(deps, { tenant, workspace }, policy);
683
+ prunedAt.set(key(tenant, workspace), Date.now());
684
+ if (res.pruned)
685
+ opsLog("info", "revisions.state_pruned", { tenant, workspace, pruned: res.pruned, kept: res.kept, held: res.held });
686
+ return res;
687
+ }
688
+ catch (err) {
689
+ opsError("revisions.state_prune_failed", err, { tenant, workspace }, "warn");
690
+ return null;
691
+ }
692
+ }
693
+ const safe2 = (fn) => {
694
+ try {
695
+ return fn();
696
+ }
697
+ catch {
698
+ return null;
699
+ }
700
+ };
701
+ /** After a state commit: look, but not on every one (a checkpoint per step). */
702
+ async function pruneIfDue(tenant, workspace) {
703
+ const last = prunedAt.get(key(tenant, workspace)) ?? 0;
704
+ if (Date.now() - last < retentionEvery)
705
+ return;
706
+ await pruneStateNow(tenant, workspace);
707
+ }
708
+ // ------------------------------------------------------------- history without a workspace
709
+ /**
710
+ * FOL-126 fixes (8 Nov 2026), once and idempotent: before the delete took the
711
+ * history with it, the heads and revisions of a deleted workspace stayed, and a
712
+ * new workspace of that name started on them. Any workspace the store has
713
+ * rows for and the volume has no folder for is such a leftover.
714
+ *
715
+ * Removing history is not undone, so it is done carefully: a workspace is
716
+ * RECORDED the first time it is seen without a folder and removed only when it
717
+ * has been seen without one for `graceMs` (a volume that is briefly not
718
+ * mounted, or a listing that came back short, passes); an account whose
719
+ * folders are mostly missing is left alone and said (a partial mount looks
720
+ * exactly like that); nothing is done when the data root itself is empty or
721
+ * absent. A workspace whose folder is back is forgotten. Each removal takes the
722
+ * same lock as a delete (dropWorkspaceRevisions).
723
+ */
724
+ export async function cleanOrphanedHistory(marks, opts) {
725
+ const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
726
+ const deps = backend;
727
+ if (!deps)
728
+ return out;
729
+ const root = dataRoot();
730
+ let rootEntries = 0;
731
+ try {
732
+ rootEntries = fs.readdirSync(root).filter((n) => !n.startsWith(".")).length;
733
+ }
734
+ catch {
735
+ // not there
736
+ }
737
+ if (!rootEntries) {
738
+ opsLog("warn", "revisions.orphans_skipped", { reason: "data_root_empty" });
739
+ return out;
740
+ }
741
+ const byTenant = new Map();
742
+ for (const w of await deps.revisions.workspaces()) {
743
+ if (w.workspace === "@library")
744
+ continue;
745
+ byTenant.set(w.tenant, [...(byTenant.get(w.tenant) ?? []), w.workspace]);
746
+ }
747
+ const exists = (t, w) => fs.existsSync(workspaceDir(t, w));
748
+ for (const [tenant, list] of byTenant) {
749
+ out.checked += list.length;
750
+ const missing = list.filter((w) => !exists(tenant, w));
751
+ const known = await marks.load(tenant, "workspace");
752
+ const back = [...known.keys()].filter((w) => !missing.includes(w));
753
+ if (back.length && !opts.dryRun)
754
+ await marks.clear(tenant, "workspace", back);
755
+ if (!missing.length)
756
+ continue;
757
+ out.orphans += missing.length;
758
+ if (!opts.force && list.length > 5 && missing.length > list.length / 2) {
759
+ out.skipped += missing.length;
760
+ opsLog("warn", "revisions.orphans_skipped", { tenant, reason: "most_folders_missing", missing: missing.length, total: list.length });
761
+ continue;
762
+ }
763
+ const at = await marks.now();
764
+ const fresh = missing.filter((w) => !known.has(w));
765
+ if (fresh.length && !opts.dryRun)
766
+ await marks.put(tenant, "workspace", fresh.map((ref) => ({ ref, size: 0 })), at);
767
+ out.marked += fresh.length;
768
+ for (const w of missing) {
769
+ const m = known.get(w);
770
+ if (!m || at.getTime() - m.firstSeen.getTime() < opts.graceMs || opts.dryRun)
771
+ continue;
772
+ if (exists(tenant, w))
773
+ continue; // came back while we looked
774
+ try {
775
+ await dropWorkspaceRevisions(tenant, w);
776
+ await marks.clear(tenant, "workspace", [w]);
777
+ out.dropped++;
778
+ }
779
+ catch (err) {
780
+ out.skipped++;
781
+ opsError("revisions.orphan_not_dropped", err, { tenant, workspace: w }, "warn");
782
+ }
783
+ }
784
+ }
785
+ if (out.orphans)
786
+ opsLog("info", "revisions.orphans", { ...out });
787
+ return out;
788
+ }
789
+ /** Does this workspace need a reconcile (its journal overflowed)? */
790
+ export const needsReconcile = (tenant, workspace) => marked.has(key(tenant, workspace));
791
+ /** Boot: replay what a dead process left in the journal directory, oldest
792
+ * first, then wait for it to commit. Entries of a workspace that no longer
793
+ * exists are discarded. `minAgeMs` keeps clear of a live process's files. */
794
+ export async function recoverJournal(opts = {}) {
795
+ if (!journalOn())
796
+ return { entries: 0, workspaces: 0 };
797
+ const minAge = opts.minAgeMs ?? ORPHAN_MS;
798
+ let entries = 0;
799
+ const touched = new Set();
800
+ for (const store of journalStores()) {
801
+ let list = [];
802
+ try {
803
+ list = store.workspaces();
804
+ }
805
+ catch (err) {
806
+ opsError("revisions.journal_unavailable", err, { store: store.kind }, "warn");
807
+ continue;
808
+ }
809
+ for (const { tenant, workspace } of list) {
810
+ const k = key(tenant, workspace);
811
+ const q = queues.get(k) ?? [];
812
+ const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
813
+ const gone = !fs.existsSync(workspaceDir(tenant, workspace));
814
+ const found = [];
815
+ let names = [];
816
+ try {
817
+ store.sweep(tenant, workspace, minAge);
818
+ names = store.entries(tenant, workspace);
819
+ }
820
+ catch (err) {
821
+ opsError("revisions.journal_unavailable", err, { tenant, workspace, store: store.kind }, "warn");
822
+ continue;
823
+ }
824
+ for (const { handle, ageMs } of names) {
825
+ if (held.has(handle))
826
+ continue;
827
+ try {
828
+ if (gone) {
829
+ store.remove(tenant, workspace, handle);
830
+ continue;
831
+ }
832
+ if (minAge > 0 && ageMs < minAge)
833
+ continue;
834
+ const e = store.read(tenant, workspace, handle);
835
+ if (e.v !== 1 || !Array.isArray(e.files))
836
+ throw new Error("not a journal entry");
837
+ found.push({ id: e.id, files: e.files, by: e.by, message: e.message, at: e.at, restoredFrom: e.restoredFrom, baseRev: e.baseRev, store, handle });
838
+ }
839
+ catch (err) {
840
+ // a torn or foreign entry: set it aside, never replay it
841
+ opsError("revisions.journal_file_unreadable", err, { tenant, workspace }, "warn");
842
+ try {
843
+ store.setAside(tenant, workspace, handle);
844
+ }
845
+ catch {
846
+ // leave it
847
+ }
848
+ }
849
+ }
850
+ if (!found.length)
851
+ continue;
852
+ queues.set(k, [...found, ...q]);
853
+ entries += found.length;
854
+ touched.add(k);
855
+ }
856
+ }
857
+ await Promise.all([...touched].map((k) => drain(k)));
858
+ return { entries, workspaces: touched.size };
859
+ }
860
+ /** Boot: bring every workspace's heads to its folder (reconcile each, one at
861
+ * a time, yielding between). A workspace with changes still queued is left
862
+ * to its queue. Returns how many were checked and how many needed repair. */
863
+ export async function reconcileAll(opts = {}) {
864
+ const out = { checked: 0, repaired: 0, failed: 0 };
865
+ if (!journalOn())
866
+ return out;
867
+ // First, the history of workspaces that were deleted before the delete took
868
+ // it with them (8 Nov 2026): it must not be reconciled, or found by a new
869
+ // workspace of the same name.
870
+ if (orphanMarks)
871
+ await cleanOrphanedHistory(orphanMarks, { graceMs: orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
872
+ for (const tenant of opts.tenants ?? listTenants()) {
873
+ for (const w of listWorkspaces(tenant)) {
874
+ const k = key(tenant, w.name);
875
+ try {
876
+ verified.add(k); // reconciled explicitly below, and counted
877
+ await drain(k);
878
+ if (queues.get(k)?.length) {
879
+ verified.delete(k);
880
+ continue; // the store is not taking writes: leave it
881
+ }
882
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileWorkspace(tenant, w.name, opts.by ?? "reconcile"));
883
+ chains.set(k, next);
884
+ const res = await next;
885
+ verified.add(k);
886
+ out.checked++;
887
+ if (res && res.status === "committed")
888
+ out.repaired++;
889
+ await pruneStateNow(tenant, w.name);
890
+ }
891
+ catch (err) {
892
+ out.failed++;
893
+ opsError("revisions.reconcile_failed", err, { tenant, workspace: w.name }, "warn");
894
+ }
895
+ await new Promise((r) => setImmediate(r));
896
+ }
897
+ }
898
+ opsLog("info", "revisions.reconciled", out);
899
+ return out;
900
+ }
901
+ // ------------------------------------------------------------- committing
902
+ function modeOf(tenant, workspace, rel) {
903
+ try {
904
+ return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
905
+ }
906
+ catch {
907
+ return MODE_FILE;
908
+ }
909
+ }
910
+ const opIdOf = (prefix, id) => `${prefix}-${id}`;
911
+ /** The change's base for a writer that started from `sha`: the head's own
912
+ * entry when it still holds that content (so the change applies), else an id
913
+ * the head cannot hold (so the path is a conflict, not an overwrite). */
914
+ function pinnedBase(sha, was) {
915
+ if (sha === null)
916
+ return was ? entryId({ sha: "0".repeat(64), mode: MODE_FILE }) : null; // started from "no file", the head has one now (a sha nothing hashes to)
917
+ if (was && was.sha === sha)
918
+ return entryId(was);
919
+ return entryId({ sha, mode: MODE_FILE });
920
+ }
921
+ /** The manifests a run's stage-in started from, per side; a side whose revision
922
+ * is gone (or that had no head) is absent and the caller falls back. */
923
+ async function baseManifests(deps, tenant, workspace, base) {
924
+ const out = {};
925
+ if (!base)
926
+ return out;
927
+ try {
928
+ if (base.workspace) {
929
+ const r = await deps.revisions.revision({ tenant, workspace, scope: "workspace" }, base.workspace);
930
+ if (r)
931
+ out.authored = await loadManifest(deps, tenant, r.authored);
932
+ }
933
+ if (base.state) {
934
+ const r = await deps.revisions.revision({ tenant, workspace, scope: "state" }, base.state);
935
+ if (r)
936
+ out.state = await loadManifest(deps, tenant, r.state);
937
+ }
938
+ }
939
+ catch (err) {
940
+ opsError("revisions.base_unreadable", err, { tenant, workspace }, "warn");
941
+ return {};
942
+ }
943
+ return out;
944
+ }
945
+ /** One journal entry → one publish. The first commit of a workspace is its
946
+ * whole tree. */
947
+ async function commitEntry(deps, tenant, workspace, entry) {
948
+ const ws = { tenant, workspace };
949
+ const heads = await headsOf(deps, ws);
950
+ const head = await manifestsAt(deps, tenant, heads);
951
+ const bytes = new Map();
952
+ const changes = {};
953
+ const baseline = { authored: !heads.workspace, state: !heads.state };
954
+ // A run's copy-back is pinned to the revisions its stage-in started from: a
955
+ // path's base is what THAT revision held, so a head that moved since (another
956
+ // run, a person) is a conflict on the path, and disjoint paths replay. Where
957
+ // the revision cannot be read any more, the folder's sha stands in.
958
+ const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
959
+ const put = (rel, text, side, pinned, handed) => {
960
+ const buf = Buffer.from(text, "utf8");
961
+ const sha = sha256Hex(buf);
962
+ bytes.set(sha, buf);
963
+ const was = head[side].files[rel];
964
+ const mode = modeOf(tenant, workspace, rel);
965
+ if (was && was.sha === sha && was.mode === mode)
966
+ return; // the head already holds it
967
+ // The pinned revision's copy of the path is the base only if it is what the
968
+ // step was handed; otherwise (handed from the folder, which was ahead of or
969
+ // different from the head) the folder's sha is the honest base.
970
+ const atRev = fromRev[side]?.files[rel];
971
+ const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
972
+ const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
973
+ changes[rel] = { op: "put", base: pinned === undefined ? (was ? entryId(was) : null) : pinnedTo, sha, size: buf.length, mode };
974
+ };
975
+ if (baseline.authored || baseline.state) {
976
+ // Nothing is recorded for (part of) this workspace yet: its tree, as the
977
+ // folder holds it now, is the first revision. That already contains this
978
+ // entry's change, since the writer wrote before it journalled.
979
+ for (const f of currentTree(tenant, workspace) ?? []) {
980
+ const side = sideOf(f.path);
981
+ if (!side || f.after === null)
982
+ continue;
983
+ if ((side === "authored" && !baseline.authored) || (side === "state" && !baseline.state))
984
+ continue;
985
+ put(f.path, f.after, side);
986
+ }
987
+ }
988
+ for (const f of entry.files) {
989
+ const side = sideOf(f.path);
990
+ if (!side)
991
+ continue;
992
+ if ((side === "authored" && baseline.authored) || (side === "state" && baseline.state))
993
+ continue; // in the baseline
994
+ const was = head[side].files[f.path];
995
+ if (f.after === null) {
996
+ if (was)
997
+ changes[f.path] = { op: "delete", base: entryId(was) };
998
+ }
999
+ else {
1000
+ put(f.path, f.after, side, f.base, f.handed);
1001
+ }
1002
+ }
1003
+ if (!Object.keys(changes).length)
1004
+ return null;
1005
+ // A restore tag only counts when that revision is in the store.
1006
+ const restoredFrom = entry.restoredFrom && (await deps.revisions.revision(ws, entry.restoredFrom)) ? entry.restoredFrom : undefined;
1007
+ const prefix = baseline.authored || baseline.state ? "jb" : "jr";
1008
+ // An entry is two commits (workspace head, then state head), each with its
1009
+ // own op id. A retry after only the first landed must still make the second:
1010
+ // so a side whose op id has finished is left out, rather than recomputed —
1011
+ // recomputed, its changes differ (what landed now matches the head and drops
1012
+ // out, a conflict does not), the op id would be "reused", and until 9 Nov
1013
+ // 2026 that was taken as the whole entry being done and the state half was
1014
+ // never committed (FOL-152). Asked again after an OpIdReused: another pod
1015
+ // replaying the same entry may finish a side between the look and the publish.
1016
+ for (let attempt = 0;; attempt++) {
1017
+ const done = await sidesDone(deps, ws, entry.id);
1018
+ const todo = {};
1019
+ for (const [p, c] of Object.entries(changes))
1020
+ if (!done[sideOf(p)])
1021
+ todo[p] = c;
1022
+ if (!Object.keys(todo).length)
1023
+ return null;
1024
+ try {
1025
+ return await publish(deps, {
1026
+ ws,
1027
+ // The op id of a side that finished, when one did, so the other side's
1028
+ // conflict copies are named the way the first attempt would have.
1029
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1030
+ by: entry.by,
1031
+ message: entry.message,
1032
+ changes: todo,
1033
+ restoredFrom: done.authored ? undefined : restoredFrom,
1034
+ bytesOf: async (sha) => {
1035
+ const b = bytes.get(sha);
1036
+ if (!b)
1037
+ throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1038
+ return b;
1039
+ },
1040
+ });
1041
+ }
1042
+ catch (err) {
1043
+ // Never "done" by itself: a side that finished is found by sidesDone on
1044
+ // the next look. One that keeps answering OpIdReused without having
1045
+ // finished is a bug, and permanent(): the entry is dropped and the
1046
+ // workspace reconciled from the folder, so nothing is lost silently.
1047
+ if (!(err instanceof OpIdReused) || attempt >= 2)
1048
+ throw err;
1049
+ }
1050
+ }
1051
+ }
1052
+ /** Which halves of a journal entry finished in an earlier attempt (an
1053
+ * operation is recorded for each, committed or unchanged). Both prefixes are
1054
+ * asked: an entry that was a baseline when it first ran is not one on retry. */
1055
+ async function sidesDone(deps, ws, id) {
1056
+ const out = { authored: false, state: false };
1057
+ const ids = ["jb", "jr"].map((prefix) => opIdOf(prefix, id));
1058
+ const found = await Promise.all(ids.map((opId) => Promise.all([deps.revisions.operation({ ...ws, scope: "workspace" }, opId), deps.revisions.operation({ ...ws, scope: "state" }, stateOpId(opId))])));
1059
+ found.forEach(([a, s], i) => {
1060
+ if (a)
1061
+ out.authored = true;
1062
+ if (s)
1063
+ out.state = true;
1064
+ if ((a || s) && !out.opId)
1065
+ out.opId = ids[i];
1066
+ });
1067
+ return out;
1068
+ }
1069
+ /** Bring the heads to the folder's content in one revision: the way in for a
1070
+ * workspace that predates the journal (the importer, phase 8), and the repair
1071
+ * after a journal overflow. Text files only, as the tree reader lists them. */
1072
+ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1073
+ const deps = backend;
1074
+ if (!deps)
1075
+ return null;
1076
+ const ws = { tenant, workspace };
1077
+ const k = key(tenant, workspace);
1078
+ // The mark goes BEFORE the folder is read, so one set after the read (a run
1079
+ // writing a file too big to journal while this publishes) asks for another
1080
+ // repair; a repair that fails puts it back for the next one.
1081
+ const wasMarked = marked.delete(k);
1082
+ const wasUnjournalled = unjournalled.delete(k);
1083
+ repairing.add(k);
1084
+ try {
1085
+ // The heads first, then the folder: a folder read older than the heads
1086
+ // would diff a stale copy against a newer head, and with that head as each
1087
+ // path's base the publish would undo the newer write without a conflict.
1088
+ const heads = await headsOf(deps, ws);
1089
+ const tree = currentTree(tenant, workspace);
1090
+ if (!tree)
1091
+ return null;
1092
+ const head = await manifestsAt(deps, tenant, heads);
1093
+ const bytes = new Map();
1094
+ const want = emptyManifest();
1095
+ const have = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1096
+ for (const f of tree) {
1097
+ const side = sideOf(f.path);
1098
+ if (!side || f.after === null)
1099
+ continue;
1100
+ const buf = Buffer.from(f.after, "utf8");
1101
+ const sha = sha256Hex(buf);
1102
+ bytes.set(sha, buf);
1103
+ want.files[f.path] = { sha, size: buf.length, mode: modeOf(tenant, workspace, f.path) };
1104
+ }
1105
+ // A path the tree reader does not list but the folder still holds (a binary
1106
+ // file) is neither added nor removed here; one that is gone from the folder
1107
+ // is gone from the head.
1108
+ const dir = workspaceDir(tenant, workspace);
1109
+ for (const p of Object.keys(have.files)) {
1110
+ if (!(p in want.files) && fs.existsSync(path.join(dir, p)))
1111
+ want.files[p] = have.files[p];
1112
+ }
1113
+ const changes = diffManifests(have, want);
1114
+ if (!Object.keys(changes).length)
1115
+ return null;
1116
+ return await publish(deps, {
1117
+ ws,
1118
+ // The heads it was diffed against are part of the id: the same changes
1119
+ // over a different head (the head was restored since) are a new repair,
1120
+ // not a retry of the earlier one.
1121
+ opId: opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40)),
1122
+ by,
1123
+ message: "workspace content recorded",
1124
+ changes,
1125
+ bytesOf: async (sha) => bytes.get(sha),
1126
+ });
1127
+ }
1128
+ catch (err) {
1129
+ if (wasMarked)
1130
+ marked.add(k);
1131
+ if (wasUnjournalled)
1132
+ unjournalled.add(k);
1133
+ throw err;
1134
+ }
1135
+ finally {
1136
+ repairing.delete(k);
1137
+ }
1138
+ }
1139
+ // ------------------------------------------------------------- reading
1140
+ async function blobBytes(deps, tenant, sha) {
1141
+ const hit = await cache?.get(tenant, sha);
1142
+ if (hit)
1143
+ return hit;
1144
+ try {
1145
+ const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1146
+ void cache?.put(tenant, sha, b).catch(() => { });
1147
+ return b;
1148
+ }
1149
+ catch (err) {
1150
+ if (err instanceof BlobNotFound)
1151
+ return null;
1152
+ throw err;
1153
+ }
1154
+ }
1155
+ /** One file of the workspace as its heads hold it: head → manifest → blob.
1156
+ * Null when there is no such file (or no head yet). */
1157
+ export async function readAtHead(tenant, workspace, rel) {
1158
+ const deps = backend;
1159
+ if (!deps)
1160
+ return null;
1161
+ const side = sideOf(rel);
1162
+ if (!side)
1163
+ return null;
1164
+ const heads = await headsOf(deps, { tenant, workspace });
1165
+ const rev = side === "authored" ? heads.workspace : heads.state;
1166
+ if (!rev)
1167
+ return null;
1168
+ const e = (await loadManifest(deps, tenant, rev[side])).files[rel];
1169
+ return e ? blobBytes(deps, tenant, e.sha) : null;
1170
+ }
1171
+ const MAX_INLINE = 256 * 1024;
1172
+ const clip = (s) => (s === null ? null : s.length > MAX_INLINE ? s.slice(0, MAX_INLINE) : s);
1173
+ async function parentManifest(deps, tenant, workspace, rev) {
1174
+ if (!rev.parent)
1175
+ return emptyManifest();
1176
+ const parent = await deps.revisions.revision({ tenant, workspace }, rev.parent);
1177
+ return parent ? (await manifestsOf(deps, tenant, parent)).authored : emptyManifest();
1178
+ }
1179
+ /** The history page's rows, newest first: the workspace head's revisions in
1180
+ * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
1181
+ * the message); the id is the revision's. */
1182
+ export async function listRevisionSummaries(tenant, workspace, opts = {}) {
1183
+ const deps = backend;
1184
+ if (!deps)
1185
+ return [];
1186
+ const want = opts.limit ?? 200;
1187
+ // `paths: false` (resolving a restore point) needs only who, when and why:
1188
+ // no manifest is read, and every row says paths [].
1189
+ const withPaths = opts.paths !== false || !!opts.forPath;
1190
+ // Page by page: the store answers at most PAGE revisions a call, and until
1191
+ // 9 Nov 2026 that first page was taken as the whole history, so a revision
1192
+ // older than the 500th could not be listed or resolved (FOL-152). A search
1193
+ // for one path still looks at no more than FOR_PATH_SCAN of them: each is two
1194
+ // manifest reads.
1195
+ const scanUpTo = opts.forPath ? FOR_PATH_SCAN : Infinity;
1196
+ const out = [];
1197
+ let before;
1198
+ for (let scanned = 0; out.length < want && scanned < scanUpTo;) {
1199
+ const ask = opts.forPath ? Math.min(PAGE, scanUpTo - scanned) : Math.min(PAGE, want - out.length);
1200
+ const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: ask, ...(before !== undefined ? { before } : {}) });
1201
+ if (!revs.length)
1202
+ break;
1203
+ scanned += revs.length;
1204
+ // Eight at a time: each revision is two manifest reads, and a history page
1205
+ // asks for hundreds.
1206
+ for (let i = 0; i < revs.length && out.length < want; i += 8) {
1207
+ const rows = await Promise.all(revs.slice(i, i + 8).map(async (r) => {
1208
+ if (!withPaths)
1209
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] };
1210
+ const [mine, parent] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1211
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(parent, mine)).sort() };
1212
+ }));
1213
+ for (const row of rows) {
1214
+ if (opts.forPath && !row.paths.includes(opts.forPath))
1215
+ continue;
1216
+ if (out.length < want)
1217
+ out.push(row);
1218
+ }
1219
+ }
1220
+ before = revs[revs.length - 1].seq;
1221
+ if (before <= 1)
1222
+ break; // that was the first revision: nothing older to ask for
1223
+ }
1224
+ return out;
1225
+ }
1226
+ /** The most revisions the store answers in one call (revision-store.ts). */
1227
+ const PAGE = 500;
1228
+ const FOR_PATH_SCAN = 500;
1229
+ /** One revision of the workspace head, by id, without listing: the history's
1230
+ * "is this a restore point" and "which revision is that id". */
1231
+ export async function revisionSummary(tenant, workspace, id) {
1232
+ const deps = backend;
1233
+ if (!deps)
1234
+ return null;
1235
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1236
+ return r ? { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } : null;
1237
+ }
1238
+ /** One revision with what changed, in history.ts's Revision shape (text
1239
+ * before/after, clipped). */
1240
+ export async function readRevisionDetail(tenant, workspace, id, forPath) {
1241
+ const deps = backend;
1242
+ if (!deps)
1243
+ return null;
1244
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1245
+ if (!r)
1246
+ return null;
1247
+ const [mine, before] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1248
+ const changes = diffManifests(before, mine);
1249
+ const files = [];
1250
+ for (const [p, c] of Object.entries(changes).sort(([a], [b]) => a.localeCompare(b))) {
1251
+ if (forPath && p !== forPath)
1252
+ continue;
1253
+ const was = before.files[p];
1254
+ const now = mine.files[p];
1255
+ const text = async (e) => (e ? (await blobBytes(deps, tenant, e.sha))?.toString("utf8") ?? null : null);
1256
+ files.push({ path: p, before: clip(await text(was)), after: c.op === "delete" ? null : clip(await text(now)) });
1257
+ }
1258
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
1259
+ }
1260
+ /** The whole tree at a revision (the files a restore would bring back), text.
1261
+ * All of it or an error: a file whose blob cannot be had throws BlobMissing.
1262
+ * Until 9 Nov 2026 such a file was left out, and a tree that lacks a file is
1263
+ * indistinguishable from one where it was deleted — a restore from it would
1264
+ * have removed the file from the folder (FOL-152). Through history.ts the
1265
+ * error answers "no snapshot", and the restore refuses. */
1266
+ export async function snapshotFiles(tenant, workspace, id) {
1267
+ const deps = backend;
1268
+ if (!deps)
1269
+ return null;
1270
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1271
+ if (!r)
1272
+ return null;
1273
+ const m = await loadManifest(deps, tenant, r.authored);
1274
+ const out = [];
1275
+ for (const [p, e] of Object.entries(m.files).sort(([a], [b]) => a.localeCompare(b))) {
1276
+ const b = await blobBytes(deps, tenant, e.sha);
1277
+ if (!b)
1278
+ throw new BlobMissing(p, e.sha);
1279
+ out.push({ path: p, content: b.toString("utf8") });
1280
+ }
1281
+ return out;
1282
+ }
1283
+ /** Restore = a NEW revision pointing at an old one's blobs. History is kept;
1284
+ * `state/` is rewound only when `stateTo` names a state revision. The caller
1285
+ * then writes the files to the folder (snapshotFiles) as the restore route
1286
+ * always did; the journal sees that write as a no-op because the head already
1287
+ * holds the content. */
1288
+ export async function restoreRevision(tenant, workspace, to, opts) {
1289
+ const deps = backend;
1290
+ if (!deps)
1291
+ return null;
1292
+ return restore(deps, { ws: { tenant, workspace }, to, opId: opts.opId, by: opts.by, message: opts.message, stateTo: opts.stateTo });
1293
+ }
1294
+ // ------------------------------------------------------------- history view
1295
+ /** What history.ts asks for, answered from revisions where the journal runs.
1296
+ * A store that errors answers null (the local history is used) and says so. */
1297
+ async function guarded(what, tenant, workspace, fn) {
1298
+ if (!journalOn())
1299
+ return null;
1300
+ try {
1301
+ return await fn();
1302
+ }
1303
+ catch (err) {
1304
+ opsError("revisions.history_unavailable", err, { tenant, workspace, what }, "warn");
1305
+ return null;
1306
+ }
1307
+ }
1308
+ const view = {
1309
+ list: (t, w, o) => guarded("list", t, w, () => listRevisionSummaries(t, w, o)),
1310
+ read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1311
+ snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1312
+ get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1313
+ };
1314
+ // ------------------------------------------------------------- reads through heads
1315
+ /** One workspace file, from its head when reads through revisions are on and
1316
+ * the head has it; null otherwise, and the caller reads the folder (the
1317
+ * fallback is the point: a head behind the folder, a missing blob, a store
1318
+ * that is down, a binary file the tree reader never recorded). */
1319
+ export async function readHeadText(tenant, workspace, rel) {
1320
+ if (!revisionReadsOn() || headBehind(tenant, workspace, rel))
1321
+ return null;
1322
+ try {
1323
+ const b = await readAtHead(tenant, workspace, rel);
1324
+ return b ? b.toString("utf8") : null;
1325
+ }
1326
+ catch (err) {
1327
+ opsError("revisions.read_failed", err, { tenant, workspace }, "warn");
1328
+ return null;
1329
+ }
1330
+ }
1331
+ /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1332
+ * A change to it is queued (its commit failed or has not run yet), the
1333
+ * workspace is marked for a repair or being repaired, or it was written while
1334
+ * the journal was off. The folder is the working copy and what a save's
1335
+ * `ifMatch` is checked against, so a read that answered the older head there
1336
+ * would tell the client a hash its next save can never match (FOL-152).
1337
+ * In-memory only, so it costs nothing per read; a change another process
1338
+ * has queued is not seen here. */
1339
+ function headBehind(tenant, workspace, rel) {
1340
+ const k = key(tenant, workspace);
1341
+ if (marked.has(k) || unjournalled.has(k) || repairing.has(k))
1342
+ return true;
1343
+ return !!queues.get(k)?.some((e) => e.files.some((f) => f.path === rel));
1344
+ }
1345
+ /** Every file of the workspace head with its bytes and mode (both heads), for
1346
+ * a stage-in; null when reads through revisions are off, there is no head,
1347
+ * or any blob could not be had (the caller then stages from the folder). */
1348
+ export async function readHeadTree(tenant, workspace) {
1349
+ const deps = backend;
1350
+ if (!deps || !revisionReadsOn())
1351
+ return null;
1352
+ try {
1353
+ const heads = await headsOf(deps, { tenant, workspace });
1354
+ if (!heads.workspace)
1355
+ return null;
1356
+ const m = await manifestsAt(deps, tenant, heads);
1357
+ const out = [];
1358
+ for (const side of ["authored", "state"]) {
1359
+ for (const [p, e] of Object.entries(m[side].files)) {
1360
+ const b = await blobBytes(deps, tenant, e.sha);
1361
+ if (!b)
1362
+ return null;
1363
+ out.push({ path: p, bytes: b, mode: e.mode });
1364
+ }
1365
+ }
1366
+ return out;
1367
+ }
1368
+ catch (err) {
1369
+ opsError("revisions.read_failed", err, { tenant, workspace }, "warn");
1370
+ return null;
1371
+ }
1372
+ }
1373
+ /** The dashboard's and the API's read of one editable file: the head's bytes
1374
+ * when reads through revisions are on, the head has the file and nothing in
1375
+ * this process says the head is behind the folder for it (headBehind), otherwise
1376
+ * the folder exactly as readWorkspaceFile answers (same path rules, same
1377
+ * "file not found"). */
1378
+ export async function readWorkspaceFileVia(tenant, workspace, rel) {
1379
+ const p = assertEditablePath(rel);
1380
+ const head = await readHeadText(tenant, workspace, p);
1381
+ return head !== null ? head : readWorkspaceFile(tenant, workspace, rel);
1382
+ }