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