@foldrun/core 17.2.0 → 17.4.0

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