@foldrun/core 20.3.0 → 21.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,13 +35,19 @@
35
35
  import fs from "node:fs";
36
36
  import path from "node:path";
37
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";
38
+ import { pipeline } from "node:stream/promises";
39
+ import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle, type RevisionView, type RevisionFile, type RevisionSummary, type Revision as HistoryRevision } from "./history.ts";
40
+ import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath } from "./store.ts";
40
41
  import { dataRoot } from "./paths.ts";
42
+ import { processState } from "./process-state.ts";
41
43
  import { opsError, opsLog } from "./ops-log.ts";
42
- import { readAll, BlobNotFound, type BlobSweeper } from "./blob-store.ts";
44
+ import { readAll, fileSource, BlobNotFound, type BlobSweeper } from "./blob-store.ts";
43
45
  import { fsJournalStore, type JournalStore, type JournalRecord } from "./journal-store.ts";
44
46
  import {
47
+ AUTHORED_DIRS,
48
+ AUTHORED_ROOT_FILES,
49
+ STATE_DIRS,
50
+ assertManifestPath,
45
51
  blobObjectKey,
46
52
  diffManifests,
47
53
  emptyManifest,
@@ -62,7 +68,35 @@ import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRu
62
68
 
63
69
  // ------------------------------------------------------------- the backend
64
70
 
65
- let backend: Deps | null = null;
71
+ /** Everything this module is told at boot, and every queue that goes with it,
72
+ * is one per PROCESS (process-state.ts), not one per copy of the module: the
73
+ * dashboard's route handlers are compiled apart from the boot, and until 13
74
+ * Nov 2026 they saw no backend — a save there was never journalled, and a read
75
+ * never came from a head. */
76
+ const S = processState("workspace-revisions", () => ({
77
+ backend: null as Deps | null,
78
+ gate: { journal: (): boolean => false, read: (): boolean => false },
79
+ retention: null as (() => StateRetention) | null,
80
+ orphanMarks: null as SweepMarks | null,
81
+ orphanGrace: 3_600_000,
82
+ retentionEvery: 10 * 60_000,
83
+ primary: null as JournalStore | null,
84
+ cache: null as BlobCache | null,
85
+ legacy: null as JournalStore | null,
86
+ queues: new Map<string, Entry[]>(),
87
+ chains: new Map<string, Promise<unknown>>(),
88
+ marked: new Set<string>(),
89
+ verified: new Set<string>(),
90
+ unjournalled: new Set<string>(),
91
+ repairing: new Set<string>(),
92
+ retryAt: new Map<string, number>(),
93
+ wantPrune: new Set<string>(),
94
+ prunedAt: new Map<string, number>(),
95
+ frozen: new Map<string, Promise<void>>(),
96
+ restoring: new Map<string, string>(),
97
+ lifecycleBusy: new Set<string>(),
98
+ background: new Set<Promise<unknown>>(),
99
+ }));
66
100
 
67
101
  /** Two switches the host decides on every call (the settings registry's
68
102
  * `revisions.journal` and `revisions.read`): the journal and history from
@@ -87,39 +121,33 @@ export interface BackendOptions {
87
121
  * history is removed. Default one hour. */
88
122
  orphanGraceMs?: number;
89
123
  }
90
- let gate: { journal: () => boolean; read: () => boolean } = { journal: () => false, read: () => false };
91
- let retention: (() => StateRetention) | null = null;
92
- let orphanMarks: SweepMarks | null = null;
93
- let orphanGrace = 3_600_000;
94
- let retentionEvery = 10 * 60_000;
95
124
  /** The legacy place: files on the volume. Always replayed at boot (and then
96
125
  * empty), whatever new entries are written to. */
97
- const legacyFiles = fsJournalStore(() => journalRoot());
98
- let primary: JournalStore | null = null;
99
- const journalStores = (): JournalStore[] => (primary && primary !== legacyFiles ? [primary, legacyFiles] : [legacyFiles]);
100
- const entryStore = (): JournalStore => primary ?? legacyFiles;
126
+ const legacyFiles = (S.legacy ??= fsJournalStore(() => journalRoot()));
127
+ const journalStores = (): JournalStore[] => (S.primary && S.primary !== legacyFiles ? [S.primary, legacyFiles] : [legacyFiles]);
128
+ const entryStore = (): JournalStore => S.primary ?? legacyFiles;
101
129
 
102
130
  /** Where revisions live, or null (no journal, nothing changes). */
103
131
  export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {}): void {
104
132
  // Every commit asks, inside the store's workspace lock, whether the folder is
105
133
  // still there: a delete or rename on another pod removes it under that lock.
106
- backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
107
- gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
108
- primary = opts.journalStore ?? null;
109
- retention = opts.stateRetention ?? null;
110
- retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
111
- orphanMarks = opts.sweepMarks ?? null;
112
- orphanGrace = opts.orphanGraceMs ?? 3_600_000;
134
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
135
+ S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
136
+ S.primary = opts.journalStore ?? null;
137
+ S.retention = opts.stateRetention ?? null;
138
+ S.retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
139
+ S.orphanMarks = opts.sweepMarks ?? null;
140
+ S.orphanGrace = opts.orphanGraceMs ?? 3_600_000;
113
141
  registerJournal(deps ? journalChange : null);
114
142
  registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
115
143
  registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
116
144
  registerRevisionView(deps ? view : null);
117
145
  }
118
- export const revisionBackend = (): Deps | null => backend;
119
- const journalOn = (): boolean => !!backend && safe(gate.journal);
146
+ export const revisionBackend = (): Deps | null => S.backend;
147
+ const journalOn = (): boolean => !!S.backend && safe(S.gate.journal);
120
148
  /** Reads of content from heads (and run stage-in): its own switch, and only
121
149
  * where the journal runs too (a head that is not kept current is not a source). */
122
- export const revisionReadsOn = (): boolean => journalOn() && safe(gate.read);
150
+ export const revisionReadsOn = (): boolean => journalOn() && safe(S.gate.read);
123
151
  function safe(fn: () => boolean): boolean {
124
152
  try {
125
153
  return fn();
@@ -134,9 +162,8 @@ export interface BlobCache {
134
162
  get(tenant: string, sha: string): Promise<Buffer | null>;
135
163
  put(tenant: string, sha: string, bytes: Buffer): Promise<void>;
136
164
  }
137
- let cache: BlobCache | null = null;
138
165
  export function setBlobCache(c: BlobCache | null): void {
139
- cache = c;
166
+ S.cache = c;
140
167
  }
141
168
 
142
169
  // ------------------------------------------------------------- the journal
@@ -159,7 +186,18 @@ export function setBlobCache(c: BlobCache | null): void {
159
186
  * writer STARTED from (null: the path did not exist), so the commit can tell
160
187
  * a concurrent writer apart (same path = conflict, disjoint paths replay). A
161
188
  * dashboard save has none: its base is whatever the head holds. */
162
- type EntryFile = RevisionFile & { base?: string | null; handed?: string | null };
189
+ type EntryFile = RevisionFile & {
190
+ base?: string | null;
191
+ handed?: string | null;
192
+ /** `after` is the file's bytes in base64: a file that is not UTF-8 text (an
193
+ * image, a database). Such an entry is written down as version 2, which a
194
+ * release from before 13 Nov 2026 sets aside instead of committing the
195
+ * base64 as the file's text. */
196
+ enc?: "base64";
197
+ };
198
+ const bytesOfEntry = (f: EntryFile): Buffer => Buffer.from(f.after ?? "", f.enc === "base64" ? "base64" : "utf8");
199
+ /** Is this exactly the UTF-8 of some text? (What a history page can show.) */
200
+ const isText = (b: Buffer): boolean => Buffer.from(b.toString("utf8"), "utf8").equals(b);
163
201
  interface Entry {
164
202
  id: string;
165
203
  files: EntryFile[];
@@ -178,18 +216,18 @@ const MAX_QUEUED = 2000;
178
216
  /** A journal file this old, that no queue of this process holds, was left by a
179
217
  * process that died (a live one commits within seconds or keeps retrying). */
180
218
  const ORPHAN_MS = 120_000;
181
- const queues = new Map<string, Entry[]>();
182
- const chains = new Map<string, Promise<unknown>>();
183
- const marked = new Set<string>(); // overflowed or dropped: needs reconcileWorkspace
184
- const verified = new Set<string>(); // reconciled once in this process
185
- const unjournalled = new Set<string>(); // changed here while the journal was off: the head has not seen it
186
- const repairing = new Set<string>(); // a reconcile is publishing: the head is about to change
187
- const retryAt = new Map<string, number>();
188
- const wantPrune = new Set<string>(); // a state checkpoint was committed since the last look
189
- const prunedAt = new Map<string, number>();
219
+ const queues = S.queues;
220
+ const chains = S.chains;
221
+ const marked = S.marked; // overflowed or dropped: needs reconcileWorkspace
222
+ const verified = S.verified; // reconciled once in this process
223
+ const unjournalled = S.unjournalled; // changed here while the journal was off: the head has not seen it
224
+ const repairing = S.repairing; // a reconcile is publishing: the head is about to change
225
+ const retryAt = S.retryAt;
226
+ const wantPrune = S.wantPrune; // a state checkpoint was committed since the last look
227
+ const prunedAt = S.prunedAt;
190
228
  /** Workspaces whose commits are held while a delete or rename runs. */
191
- const frozen = new Map<string, Promise<void>>();
192
- const restoring = new Map<string, string>();
229
+ const frozen = S.frozen;
230
+ const restoring = S.restoring;
193
231
  const key = (tenant: string, workspace: string) => `${tenant}\0${workspace}`;
194
232
  const split = (k: string): [string, string] => k.split("\0") as [string, string];
195
233
 
@@ -200,7 +238,7 @@ const journalRoot = () => path.join(dataRoot(), ".revision-journal");
200
238
  function persist(tenant: string, workspace: string, e: Entry): void {
201
239
  const store = entryStore();
202
240
  try {
203
- 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 });
241
+ e.handle = store.put({ v: e.files.some((f) => f.enc) ? 2 : 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 });
204
242
  e.store = store;
205
243
  } catch (err) {
206
244
  opsError("revisions.journal_not_persisted", err, { tenant, workspace, store: store.kind }, "warn");
@@ -219,9 +257,9 @@ function forget(tenant: string, workspace: string, e: Entry): void {
219
257
  /** Called by history.recordRevision for every change set. Synchronous and
220
258
  * cheap; the commit happens in the background (flushRevisions waits for it). */
221
259
  function journalChange(tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }): void {
222
- if (!backend || scope === "@library") return; // the account shelf is not a workspace
260
+ if (!S.backend || scope === "@library") return; // the account shelf is not a workspace
223
261
  const k = key(tenant, scope);
224
- if (!safe(gate.journal)) {
262
+ if (!safe(S.gate.journal)) {
225
263
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
226
264
  unjournalled.add(k);
227
265
  return;
@@ -288,8 +326,9 @@ const MAX_STEP_ENTRY = 8 * 1024 * 1024;
288
326
  * whose copy-out itself failed wrote nothing and commits nothing. A test run's
289
327
  * diverted state/ and storage/ writes never reach the folder and never here.
290
328
  *
291
- * Text only: a binary file is not versioned yet (see phase 3). Returns the
292
- * number of paths queued.
329
+ * Every file, whatever it holds: one that is not text rides as base64 (13 Nov
330
+ * 2026; until then a binary file was left out, and the head went stale against
331
+ * the folder). Returns the number of paths queued.
293
332
  */
294
333
  export function recordStepOutputs(
295
334
  tenant: string,
@@ -297,9 +336,9 @@ export function recordStepOutputs(
297
336
  writes: StepWrite[],
298
337
  meta: { runId?: string; step?: string | number; by?: string; base?: RunBase | null },
299
338
  ): number {
300
- if (!backend || workspace === "@library") return 0;
339
+ if (!S.backend || workspace === "@library") return 0;
301
340
  const k = key(tenant, workspace);
302
- if (!safe(gate.journal)) {
341
+ if (!safe(S.gate.journal)) {
303
342
  verified.delete(k); // the head will not see this: reconcile before trusting it again
304
343
  unjournalled.add(k);
305
344
  return 0;
@@ -308,8 +347,7 @@ export function recordStepOutputs(
308
347
  let total = 0;
309
348
  for (const w of writes) {
310
349
  if (!sideOf(w.path)) continue; // not workspace content (runs/, .foldrun/ …)
311
- const text = w.after.toString("utf8");
312
- if (!Buffer.from(text, "utf8").equals(w.after)) continue; // binary: not versioned
350
+ if (isPlatformPath(w.path)) continue; // the engine's own files: never content
313
351
  if (w.after.length > MAX_STEP_FILE) {
314
352
  marked.add(k); // the folder has it; the reconcile records it
315
353
  continue;
@@ -319,7 +357,9 @@ export function recordStepOutputs(
319
357
  continue;
320
358
  }
321
359
  total += w.after.length;
322
- files.push({ path: w.path, before: null, after: text, base: w.base, ...(w.handed !== undefined ? { handed: w.handed } : {}) });
360
+ // Bytes that are not text (an image, a database) ride as base64.
361
+ const body = isText(w.after) ? { after: w.after.toString("utf8") } : { after: w.after.toString("base64"), enc: "base64" as const };
362
+ files.push({ path: w.path, before: null, ...body, base: w.base, ...(w.handed !== undefined ? { handed: w.handed } : {}) });
323
363
  }
324
364
  if (!files.length) return 0;
325
365
  const idSource = meta.runId ? `${meta.runId}\0${meta.step ?? ""}` : crypto.randomBytes(12).toString("hex");
@@ -369,7 +409,7 @@ function drain(k: string): Promise<void> {
369
409
  async function drainOne(k: string): Promise<void> {
370
410
  const [tenant, workspace] = split(k);
371
411
  const q = queues.get(k);
372
- while (q && q.length && backend) {
412
+ while (q && q.length && S.backend) {
373
413
  const entry = q[0];
374
414
  // The workspace was deleted while this waited (or retried): nothing to
375
415
  // publish, and nothing for a later boot to replay.
@@ -379,7 +419,7 @@ async function drainOne(k: string): Promise<void> {
379
419
  continue;
380
420
  }
381
421
  try {
382
- const res = await commitEntry(backend, tenant, workspace, entry);
422
+ const res = await commitEntry(S.backend, tenant, workspace, entry);
383
423
  if (res?.status === "committed" && res.stateRevision) wantPrune.add(k);
384
424
  q.shift();
385
425
  forget(tenant, workspace, entry);
@@ -419,7 +459,7 @@ async function drainOne(k: string): Promise<void> {
419
459
  // journal was off for a while, a run wrote the folder directly) is brought
420
460
  // to it. After the entries, never before: replaying an older change over a
421
461
  // reconciled head would write it backwards.
422
- if (backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
462
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
423
463
  verified.add(k);
424
464
  try {
425
465
  await reconcileWorkspace(tenant, workspace, "reconcile");
@@ -510,10 +550,10 @@ async function freeze(keys: string[]): Promise<() => void> {
510
550
  };
511
551
  }
512
552
 
513
- const lifecycleBusy = new Set<string>(); // keys a lifecycle call is handling (the sync hooks stay out of its way)
553
+ const lifecycleBusy = S.lifecycleBusy; // keys a lifecycle call is handling (the sync hooks stay out of its way)
514
554
 
515
555
  /** What the sync hooks started and has not finished (tests, and a process that is ending). */
516
- const background = new Set<Promise<unknown>>();
556
+ const background = S.background;
517
557
  export async function settleLifecycle(): Promise<void> {
518
558
  while (background.size) await Promise.allSettled([...background]);
519
559
  await settleRunOutputs();
@@ -555,7 +595,7 @@ function goneNow(tenant: string, workspace: string): void {
555
595
  * in between. A store that cannot be reached throws BEFORE `remove` runs.
556
596
  */
557
597
  export async function dropWorkspaceRevisions(tenant: string, workspace: string, remove?: () => void): Promise<void> {
558
- const deps = backend;
598
+ const deps = S.backend;
559
599
  if (!deps || workspace === "@library") {
560
600
  remove?.();
561
601
  return;
@@ -594,7 +634,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
594
634
  * rest depends on it). */
595
635
  export async function dropTenantRevisions(tenant: string): Promise<void> {
596
636
  dropJournal(tenant);
597
- const deps = backend;
637
+ const deps = S.backend;
598
638
  if (!deps) return;
599
639
  const mine = [...chains.keys()].filter((k) => split(k)[0] === tenant);
600
640
  await Promise.all(mine.map((k) => chains.get(k)!.catch(() => {})));
@@ -622,7 +662,7 @@ function movedNow(tenant: string, from: string, to: string): void {
622
662
  * store that cannot be reached throws BEFORE `rename` runs.
623
663
  */
624
664
  export async function moveWorkspaceRevisions(tenant: string, from: string, to: string, rename?: () => void): Promise<void> {
625
- const deps = backend;
665
+ const deps = S.backend;
626
666
  if (!deps || from === "@library" || to === "@library") {
627
667
  rename?.();
628
668
  return;
@@ -719,7 +759,7 @@ const RUN_PIN_TTL_MS = 2 * 60 * 60_000;
719
759
  * be taken.
720
760
  */
721
761
  export async function pinRunBase(tenant: string, workspace: string, holder: string): Promise<{ base: RunBase; release(): Promise<void> } | null> {
722
- const deps = backend;
762
+ const deps = S.backend;
723
763
  if (!deps || !journalOn() || workspace === "@library") return null;
724
764
  try {
725
765
  const { pending } = await flushRevisions({ tenant, workspace });
@@ -736,7 +776,7 @@ export async function pinRunBase(tenant: string, workspace: string, holder: stri
736
776
  /** The same pin for a base that was recorded earlier (a driver that took over a
737
777
  * step): null when either revision is gone. */
738
778
  export async function repinRunBase(tenant: string, workspace: string, base: RunBase, holder: string): Promise<{ base: RunBase; release(): Promise<void> } | null> {
739
- const deps = backend;
779
+ const deps = S.backend;
740
780
  if (!deps || !journalOn()) return null;
741
781
  try {
742
782
  const w = base.workspace ? await deps.revisions.revision({ tenant, workspace, scope: "workspace" }, base.workspace) : null;
@@ -775,9 +815,9 @@ async function holdRunBase(deps: Deps, tenant: string, base: RunBase, revs: Head
775
815
 
776
816
  /** Look at one workspace's `state/` checkpoints now (the host's window). */
777
817
  export async function pruneStateNow(tenant: string, workspace: string): Promise<{ pruned: number; kept: number; held: number } | null> {
778
- const deps = backend;
779
- if (!deps || !retention || !journalOn()) return null;
780
- const policy = safe2(retention);
818
+ const deps = S.backend;
819
+ if (!deps || !S.retention || !journalOn()) return null;
820
+ const policy = safe2(S.retention);
781
821
  if (!policy) return null;
782
822
  try {
783
823
  const res = await pruneStateRevisions(deps, { tenant, workspace }, policy);
@@ -800,7 +840,7 @@ const safe2 = (fn: () => StateRetention): StateRetention | null => {
800
840
  /** After a state commit: look, but not on every one (a checkpoint per step). */
801
841
  async function pruneIfDue(tenant: string, workspace: string): Promise<void> {
802
842
  const last = prunedAt.get(key(tenant, workspace)) ?? 0;
803
- if (Date.now() - last < retentionEvery) return;
843
+ if (Date.now() - last < S.retentionEvery) return;
804
844
  await pruneStateNow(tenant, workspace);
805
845
  }
806
846
 
@@ -826,7 +866,7 @@ export async function cleanOrphanedHistory(
826
866
  opts: { graceMs: number; force?: boolean; dryRun?: boolean },
827
867
  ): Promise<{ checked: number; orphans: number; marked: number; dropped: number; skipped: number }> {
828
868
  const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
829
- const deps = backend;
869
+ const deps = S.backend;
830
870
  if (!deps) return out;
831
871
  const root = dataRoot();
832
872
  let rootEntries = 0;
@@ -922,7 +962,7 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
922
962
  }
923
963
  if (minAge > 0 && ageMs < minAge) continue;
924
964
  const e = store.read(tenant, workspace, handle);
925
- if (e.v !== 1 || !Array.isArray(e.files)) throw new Error("not a journal entry");
965
+ if ((e.v !== 1 && e.v !== 2) || !Array.isArray(e.files)) throw new Error("not a journal entry");
926
966
  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 });
927
967
  } catch (err) {
928
968
  // a torn or foreign entry: set it aside, never replay it
@@ -953,7 +993,7 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
953
993
  // First, the history of workspaces that were deleted before the delete took
954
994
  // it with them (8 Nov 2026): it must not be reconciled, or found by a new
955
995
  // workspace of the same name.
956
- if (orphanMarks) await cleanOrphanedHistory(orphanMarks, { graceMs: orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
996
+ if (S.orphanMarks) await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
957
997
  for (const tenant of opts.tenants ?? listTenants()) {
958
998
  for (const w of listWorkspaces(tenant)) {
959
999
  const k = key(tenant, w.name);
@@ -984,6 +1024,120 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
984
1024
 
985
1025
  // ------------------------------------------------------------- committing
986
1026
 
1027
+ /** A file this big is sent to the store from disk, never read whole. */
1028
+ const LARGE_FILE = 8 * 1024 * 1024;
1029
+ const LARGE_PIN_TTL_MS = 30 * 60_000;
1030
+
1031
+ interface FolderFile {
1032
+ abs: string;
1033
+ sha: string;
1034
+ size: number;
1035
+ mode: number;
1036
+ }
1037
+
1038
+ async function hashOf(abs: string, size: number): Promise<string> {
1039
+ // Read off the event loop: a dashboard process runs this too, and a desk can
1040
+ // hold thousands of files.
1041
+ if (size <= LARGE_FILE) return sha256Hex(await fs.promises.readFile(abs));
1042
+ const h = crypto.createHash("sha256");
1043
+ await pipeline(fs.createReadStream(abs), h);
1044
+ return h.digest("hex");
1045
+ }
1046
+
1047
+ /**
1048
+ * The workspace's content as the folder holds it now: every regular file on
1049
+ * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
1050
+ * the data importer has (data-import.ts scanWorkspace) and what a run's
1051
+ * stage-in copies, so a head made from it is the folder. Left out, and listed
1052
+ * in `left` when the folder holds them: a symbolic link (never followed), the
1053
+ * platform's and the engine's own files (isPlatformPath), a name a manifest
1054
+ * refuses, the later of two names that differ only by case, a file that could
1055
+ * not be read. Null when the folder is not there.
1056
+ */
1057
+ async function scanFolder(tenant: string, workspace: string): Promise<{ files: Map<string, FolderFile>; left: Set<string> } | null> {
1058
+ const dir = workspaceDir(tenant, workspace);
1059
+ if (!fs.existsSync(dir)) return null;
1060
+ const found: { rel: string; abs: string; st: fs.Stats }[] = [];
1061
+ const left = new Set<string>();
1062
+ const walk = (rel: string) => {
1063
+ // A folder that cannot be listed (gone since its parent was read aside)
1064
+ // ends the scan: skipped, everything under it would read as deleted.
1065
+ let names: string[];
1066
+ try {
1067
+ names = fs.readdirSync(path.join(dir, rel)).sort();
1068
+ } catch (err) {
1069
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
1070
+ throw err;
1071
+ }
1072
+ for (const name of names) {
1073
+ const r = `${rel}/${name}`;
1074
+ const abs = path.join(dir, r);
1075
+ let st: fs.Stats;
1076
+ try {
1077
+ st = fs.lstatSync(abs);
1078
+ } catch (err) {
1079
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue; // deleted meanwhile
1080
+ throw err;
1081
+ }
1082
+ if (st.isDirectory()) walk(r);
1083
+ else if (st.isFile()) found.push({ rel: r, abs, st });
1084
+ else left.add(r);
1085
+ }
1086
+ };
1087
+ let top: string[];
1088
+ try {
1089
+ top = fs.readdirSync(dir).sort();
1090
+ } catch {
1091
+ return null;
1092
+ }
1093
+ for (const name of top) {
1094
+ const abs = path.join(dir, name);
1095
+ let st: fs.Stats;
1096
+ try {
1097
+ st = fs.lstatSync(abs);
1098
+ } catch {
1099
+ continue;
1100
+ }
1101
+ if (st.isDirectory() && (AUTHORED_DIRS.includes(name) || STATE_DIRS.includes(name))) walk(name);
1102
+ else if (st.isFile() && sideOf(name) === "authored") found.push({ rel: name, abs, st });
1103
+ else if (AUTHORED_ROOT_FILES.includes(name)) left.add(name);
1104
+ }
1105
+ const files = new Map<string, FolderFile>();
1106
+ const lower = new Set<string>();
1107
+ for (const f of found.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))) {
1108
+ if (isPlatformPath(f.rel)) continue;
1109
+ const fold = f.rel.toLowerCase();
1110
+ try {
1111
+ assertManifestPath(f.rel);
1112
+ if (lower.has(fold)) throw new Error("differs only by case");
1113
+ files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1114
+ lower.add(fold);
1115
+ } catch {
1116
+ left.add(f.rel);
1117
+ }
1118
+ }
1119
+ return { files, left };
1120
+ }
1121
+
1122
+ /** Send the large files among `changes` to the store from disk, pinned first
1123
+ * (as a publish pins what it uploads), so none is held whole in memory; the
1124
+ * publish then finds each in the store and does not ask for its bytes. */
1125
+ async function uploadLarge(deps: Deps, tenant: string, changes: Changes, onDisk: Map<string, string>, opId: string): Promise<() => Promise<void>> {
1126
+ const large = [...new Set(Object.values(changes).flatMap((c) => (c.op === "put" && c.size > LARGE_FILE && onDisk.has(c.sha) ? [c.sha] : [])))];
1127
+ if (!large.length) return async () => {};
1128
+ const holder = { kind: "publish" as const, id: `${opId}-large` };
1129
+ // The pin is held until the caller's publish is over (it returns the release).
1130
+ const release = async () => void (await deps.pins?.release(tenant, holder).catch(() => {}));
1131
+ await deps.pins?.pinBlobs(tenant, large, holder, { ttlMs: LARGE_PIN_TTL_MS });
1132
+ try {
1133
+ for (const sha of large) await deps.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), fileSource(onDisk.get(sha)!), { sha256: sha });
1134
+ } catch (err) {
1135
+ await release();
1136
+ throw err;
1137
+ }
1138
+ return release;
1139
+ }
1140
+
987
1141
  function modeOf(tenant: string, workspace: string, rel: string): number {
988
1142
  try {
989
1143
  return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
@@ -1031,6 +1185,8 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1031
1185
  const heads = await headsOf(deps, ws);
1032
1186
  const head = await manifestsAt(deps, tenant, heads);
1033
1187
  const bytes = new Map<string, Buffer>();
1188
+ const onDisk = new Map<string, string>(); // sha → a file of the folder that holds it
1189
+ let releaseLarge: () => Promise<void> = async () => {};
1034
1190
  const changes: Changes = {};
1035
1191
  const baseline: { authored: boolean; state: boolean } = { authored: !heads.workspace, state: !heads.state };
1036
1192
 
@@ -1040,8 +1196,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1040
1196
  // the revision cannot be read any more, the folder's sha stands in.
1041
1197
  const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
1042
1198
 
1043
- const put = (rel: string, text: string, side: "authored" | "state", pinned?: string | null, handed?: string | null) => {
1044
- const buf = Buffer.from(text, "utf8");
1199
+ const put = (rel: string, buf: Buffer, side: "authored" | "state", pinned?: string | null, handed?: string | null) => {
1045
1200
  const sha = sha256Hex(buf);
1046
1201
  bytes.set(sha, buf);
1047
1202
  const was = head[side].files[rel];
@@ -1060,12 +1215,15 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1060
1215
  // Nothing is recorded for (part of) this workspace yet: its tree, as the
1061
1216
  // folder holds it now, is the first revision. That already contains this
1062
1217
  // entry's change, since the writer wrote before it journalled.
1063
- for (const f of currentTree(tenant, workspace) ?? []) {
1064
- const side = sideOf(f.path);
1065
- if (!side || f.after === null) continue;
1218
+ // Every file, as scanFolder lists them (binaries too); each one's bytes are
1219
+ // read when the publish asks for them, never all at once.
1220
+ for (const [rel, f] of (await scanFolder(tenant, workspace))?.files ?? []) {
1221
+ const side = sideOf(rel)!;
1066
1222
  if ((side === "authored" && !baseline.authored) || (side === "state" && !baseline.state)) continue;
1067
- put(f.path, f.after, side);
1223
+ onDisk.set(f.sha, f.abs);
1224
+ changes[rel] = { op: "put", base: null, sha: f.sha, size: f.size, mode: f.mode };
1068
1225
  }
1226
+ releaseLarge = await uploadLarge(deps, tenant, changes, onDisk, `jb-${entry.id}`);
1069
1227
  }
1070
1228
  for (const f of entry.files) {
1071
1229
  const side = sideOf(f.path);
@@ -1075,7 +1233,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1075
1233
  if (f.after === null) {
1076
1234
  if (was) changes[f.path] = { op: "delete", base: entryId(was) };
1077
1235
  } else {
1078
- put(f.path, f.after, side, f.base, f.handed);
1236
+ put(f.path, bytesOfEntry(f), side, f.base, f.handed);
1079
1237
  }
1080
1238
  }
1081
1239
  if (!Object.keys(changes).length) return null;
@@ -1090,34 +1248,38 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1090
1248
  // 2026 that was taken as the whole entry being done and the state half was
1091
1249
  // never committed (FOL-152). Asked again after an OpIdReused: another pod
1092
1250
  // replaying the same entry may finish a side between the look and the publish.
1093
- for (let attempt = 0; ; attempt++) {
1094
- const done = await sidesDone(deps, ws, entry.id);
1095
- const todo: Changes = {};
1096
- for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
1097
- if (!Object.keys(todo).length) return null;
1098
- try {
1099
- return await publish(deps, {
1100
- ws,
1101
- // The op id of a side that finished, when one did, so the other side's
1102
- // conflict copies are named the way the first attempt would have.
1103
- opId: done.opId ?? opIdOf(prefix, entry.id),
1104
- by: entry.by,
1105
- message: entry.message,
1106
- changes: todo,
1107
- restoredFrom: done.authored ? undefined : restoredFrom,
1108
- bytesOf: async (sha) => {
1109
- const b = bytes.get(sha);
1110
- if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1111
- return b;
1112
- },
1113
- });
1114
- } catch (err) {
1115
- // Never "done" by itself: a side that finished is found by sidesDone on
1116
- // the next look. One that keeps answering OpIdReused without having
1117
- // finished is a bug, and permanent(): the entry is dropped and the
1118
- // workspace reconciled from the folder, so nothing is lost silently.
1119
- if (!(err instanceof OpIdReused) || attempt >= 2) throw err;
1251
+ try {
1252
+ for (let attempt = 0; ; attempt++) {
1253
+ const done = await sidesDone(deps, ws, entry.id);
1254
+ const todo: Changes = {};
1255
+ for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
1256
+ if (!Object.keys(todo).length) return null;
1257
+ try {
1258
+ return await publish(deps, {
1259
+ ws,
1260
+ // The op id of a side that finished, when one did, so the other side's
1261
+ // conflict copies are named the way the first attempt would have.
1262
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1263
+ by: entry.by,
1264
+ message: entry.message,
1265
+ changes: todo,
1266
+ restoredFrom: done.authored ? undefined : restoredFrom,
1267
+ bytesOf: async (sha) => {
1268
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)!) : null);
1269
+ if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1270
+ return b;
1271
+ },
1272
+ });
1273
+ } catch (err) {
1274
+ // Never "done" by itself: a side that finished is found by sidesDone on
1275
+ // the next look. One that keeps answering OpIdReused without having
1276
+ // finished is a bug, and permanent(): the entry is dropped and the
1277
+ // workspace reconciled from the folder, so nothing is lost silently.
1278
+ if (!(err instanceof OpIdReused) || attempt >= 2) throw err;
1279
+ }
1120
1280
  }
1281
+ } finally {
1282
+ await releaseLarge();
1121
1283
  }
1122
1284
  }
1123
1285
 
@@ -1140,9 +1302,12 @@ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ au
1140
1302
 
1141
1303
  /** Bring the heads to the folder's content in one revision: the way in for a
1142
1304
  * workspace that predates the journal (the importer, phase 8), and the repair
1143
- * after a journal overflow. Text files only, as the tree reader lists them. */
1305
+ * after a journal overflow. Every file scanFolder lists, whatever it holds
1306
+ * (until 13 Nov 2026: only the text files the editor lists, so a binary file
1307
+ * never reached a head and one the importer had put there was never updated
1308
+ * or removed — a run staged from the head was handed files deleted days ago). */
1144
1309
  export async function reconcileWorkspace(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
1145
- const deps = backend;
1310
+ const deps = S.backend;
1146
1311
  if (!deps) return null;
1147
1312
  const ws: WorkspaceRef = { tenant, workspace };
1148
1313
  const k = key(tenant, workspace);
@@ -1157,40 +1322,47 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1157
1322
  // would diff a stale copy against a newer head, and with that head as each
1158
1323
  // path's base the publish would undo the newer write without a conflict.
1159
1324
  const heads = await headsOf(deps, ws);
1160
- const tree = currentTree(tenant, workspace);
1161
- if (!tree) return null;
1325
+ const scan = await scanFolder(tenant, workspace);
1326
+ if (!scan) return null;
1162
1327
  const head = await manifestsAt(deps, tenant, heads);
1163
- const bytes = new Map<string, Buffer>();
1328
+ const onDisk = new Map<string, string>();
1164
1329
  const want: Manifest = emptyManifest();
1165
1330
  const have: Manifest = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1166
- for (const f of tree) {
1167
- const side = sideOf(f.path);
1168
- if (!side || f.after === null) continue;
1169
- const buf = Buffer.from(f.after, "utf8");
1170
- const sha = sha256Hex(buf);
1171
- bytes.set(sha, buf);
1172
- want.files[f.path] = { sha, size: buf.length, mode: modeOf(tenant, workspace, f.path) };
1331
+ for (const [rel, f] of scan.files) {
1332
+ onDisk.set(f.sha, f.abs);
1333
+ want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
1173
1334
  }
1174
- // A path the tree reader does not list but the folder still holds (a binary
1175
- // file) is neither added nor removed here; one that is gone from the folder
1176
- // is gone from the head.
1177
- const dir = workspaceDir(tenant, workspace);
1335
+ // A path the scan could not take (unreadable now, a name the manifest
1336
+ // refuses) but the folder still holds is neither added nor removed here;
1337
+ // one that is gone from the folder is gone from the head.
1338
+ // Never beside a name that differs from it only by case (a manifest holds
1339
+ // one of the two): the folder's first, as the scan chose, is the one kept.
1340
+ const taken = new Set(Object.keys(want.files).map((p) => p.toLowerCase()));
1178
1341
  for (const p of Object.keys(have.files)) {
1179
- if (!(p in want.files) && fs.existsSync(path.join(dir, p))) want.files[p] = have.files[p];
1342
+ if (!(p in want.files) && scan.left.has(p) && !taken.has(p.toLowerCase())) want.files[p] = have.files[p];
1180
1343
  }
1181
1344
  const changes = diffManifests(have, want);
1182
1345
  if (!Object.keys(changes).length) return null;
1183
- return await publish(deps, {
1346
+ // The heads it was diffed against are part of the id: the same changes
1347
+ // over a different head (the head was restored since) are a new repair,
1348
+ // not a retry of the earlier one.
1349
+ const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
1350
+ const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
1351
+ try {
1352
+ return await publish(deps, {
1184
1353
  ws,
1185
- // The heads it was diffed against are part of the id: the same changes
1186
- // over a different head (the head was restored since) are a new repair,
1187
- // not a retry of the earlier one.
1188
- opId: opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40)),
1354
+ opId,
1189
1355
  by,
1190
1356
  message: "workspace content recorded",
1191
1357
  changes,
1192
- bytesOf: async (sha) => bytes.get(sha)!,
1193
- });
1358
+ // Read when asked, one file at a time; publish checks the bytes against
1359
+ // the sha, so a file that changed since the scan fails this repair (the
1360
+ // mark is put back and the next one sees the new bytes).
1361
+ bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)!),
1362
+ });
1363
+ } finally {
1364
+ await release();
1365
+ }
1194
1366
  } catch (err) {
1195
1367
  if (wasMarked) marked.add(k);
1196
1368
  if (wasUnjournalled) unjournalled.add(k);
@@ -1203,11 +1375,11 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1203
1375
  // ------------------------------------------------------------- reading
1204
1376
 
1205
1377
  async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {
1206
- const hit = await cache?.get(tenant, sha);
1378
+ const hit = await S.cache?.get(tenant, sha);
1207
1379
  if (hit) return hit;
1208
1380
  try {
1209
1381
  const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1210
- void cache?.put(tenant, sha, b).catch(() => {});
1382
+ void S.cache?.put(tenant, sha, b).catch(() => {});
1211
1383
  return b;
1212
1384
  } catch (err) {
1213
1385
  if (err instanceof BlobNotFound) return null;
@@ -1218,7 +1390,7 @@ async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffe
1218
1390
  /** One file of the workspace as its heads hold it: head → manifest → blob.
1219
1391
  * Null when there is no such file (or no head yet). */
1220
1392
  export async function readAtHead(tenant: string, workspace: string, rel: string): Promise<Buffer | null> {
1221
- const deps = backend;
1393
+ const deps = S.backend;
1222
1394
  if (!deps) return null;
1223
1395
  const side = sideOf(rel);
1224
1396
  if (!side) return null;
@@ -1242,7 +1414,7 @@ async function parentManifest(deps: Deps, tenant: string, workspace: string, rev
1242
1414
  * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
1243
1415
  * the message); the id is the revision's. */
1244
1416
  export async function listRevisionSummaries(tenant: string, workspace: string, opts: { limit?: number; forPath?: string; paths?: boolean } = {}): Promise<RevisionSummary[]> {
1245
- const deps = backend;
1417
+ const deps = S.backend;
1246
1418
  if (!deps) return [];
1247
1419
  const want = opts.limit ?? 200;
1248
1420
  // `paths: false` (resolving a restore point) needs only who, when and why:
@@ -1288,7 +1460,7 @@ const FOR_PATH_SCAN = 500;
1288
1460
  /** One revision of the workspace head, by id, without listing: the history's
1289
1461
  * "is this a restore point" and "which revision is that id". */
1290
1462
  export async function revisionSummary(tenant: string, workspace: string, id: string): Promise<RevisionSummary | null> {
1291
- const deps = backend;
1463
+ const deps = S.backend;
1292
1464
  if (!deps) return null;
1293
1465
  const r = await deps.revisions.revision({ tenant, workspace }, id);
1294
1466
  return r ? { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } : null;
@@ -1297,7 +1469,7 @@ export async function revisionSummary(tenant: string, workspace: string, id: str
1297
1469
  /** One revision with what changed, in history.ts's Revision shape (text
1298
1470
  * before/after, clipped). */
1299
1471
  export async function readRevisionDetail(tenant: string, workspace: string, id: string, forPath?: string): Promise<HistoryRevision | null> {
1300
- const deps = backend;
1472
+ const deps = S.backend;
1301
1473
  if (!deps) return null;
1302
1474
  const r = await deps.revisions.revision({ tenant, workspace }, id);
1303
1475
  if (!r) return null;
@@ -1308,7 +1480,11 @@ export async function readRevisionDetail(tenant: string, workspace: string, id:
1308
1480
  if (forPath && p !== forPath) continue;
1309
1481
  const was = before.files[p];
1310
1482
  const now = mine.files[p];
1311
- const text = async (e: typeof was) => (e ? (await blobBytes(deps, tenant, e.sha))?.toString("utf8") ?? null : null);
1483
+ const text = async (e: typeof was) => {
1484
+ const b = e ? await blobBytes(deps, tenant, e.sha) : null;
1485
+ // A file that is not text has nothing to diff: say what it is.
1486
+ return b ? (isText(b) ? b.toString("utf8") : `(binary file, ${b.length} bytes, sha256 ${e!.sha.slice(0, 12)})`) : null;
1487
+ };
1312
1488
  files.push({ path: p, before: clip(await text(was)), after: c.op === "delete" ? null : clip(await text(now)) });
1313
1489
  }
1314
1490
  return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
@@ -1321,7 +1497,7 @@ export async function readRevisionDetail(tenant: string, workspace: string, id:
1321
1497
  * have removed the file from the folder (FOL-152). Through history.ts the
1322
1498
  * error answers "no snapshot", and the restore refuses. */
1323
1499
  export async function snapshotFiles(tenant: string, workspace: string, id: string): Promise<{ path: string; content: string }[] | null> {
1324
- const deps = backend;
1500
+ const deps = S.backend;
1325
1501
  if (!deps) return null;
1326
1502
  const r = await deps.revisions.revision({ tenant, workspace }, id);
1327
1503
  if (!r) return null;
@@ -1330,6 +1506,11 @@ export async function snapshotFiles(tenant: string, workspace: string, id: strin
1330
1506
  for (const [p, e] of Object.entries(m.files).sort(([a], [b]) => a.localeCompare(b))) {
1331
1507
  const b = await blobBytes(deps, tenant, e.sha);
1332
1508
  if (!b) throw new BlobMissing(p, e.sha);
1509
+ // Text only: this is what a restore writes back through a deploy, as text.
1510
+ // A binary file is left where it is, as files outside history always were
1511
+ // (13 Nov 2026: until then its bytes were decoded as text here, and a
1512
+ // restore would have written the damaged copy over the file).
1513
+ if (!isText(b)) continue;
1333
1514
  out.push({ path: p, content: b.toString("utf8") });
1334
1515
  }
1335
1516
  return out;
@@ -1341,7 +1522,7 @@ export async function snapshotFiles(tenant: string, workspace: string, id: strin
1341
1522
  * always did; the journal sees that write as a no-op because the head already
1342
1523
  * holds the content. */
1343
1524
  export async function restoreRevision(tenant: string, workspace: string, to: string, opts: { by: string; opId: string; message?: string; stateTo?: string }): Promise<PublishResult | null> {
1344
- const deps = backend;
1525
+ const deps = S.backend;
1345
1526
  if (!deps) return null;
1346
1527
  return restore(deps, { ws: { tenant, workspace }, to, opId: opts.opId, by: opts.by, message: opts.message, stateTo: opts.stateTo });
1347
1528
  }
@@ -1383,6 +1564,16 @@ export async function readHeadText(tenant: string, workspace: string, rel: strin
1383
1564
  }
1384
1565
  }
1385
1566
 
1567
+ /** The folder and the head were seen to disagree (a run's stage-in compares
1568
+ * them): bring the head to the folder, in the background. */
1569
+ export function requestReconcile(tenant: string, workspace: string): void {
1570
+ if (!journalOn()) return;
1571
+ const k = key(tenant, workspace);
1572
+ if (marked.has(k)) return;
1573
+ marked.add(k);
1574
+ setImmediate(() => void drain(k));
1575
+ }
1576
+
1386
1577
  /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1387
1578
  * A change to it is queued (its commit failed or has not run yet), the
1388
1579
  * workspace is marked for a repair or being repaired, or it was written while
@@ -1401,7 +1592,7 @@ function headBehind(tenant: string, workspace: string, rel: string): boolean {
1401
1592
  * a stage-in; null when reads through revisions are off, there is no head,
1402
1593
  * or any blob could not be had (the caller then stages from the folder). */
1403
1594
  export async function readHeadTree(tenant: string, workspace: string): Promise<{ path: string; bytes: Buffer; mode: number }[] | null> {
1404
- const deps = backend;
1595
+ const deps = S.backend;
1405
1596
  if (!deps || !revisionReadsOn()) return null;
1406
1597
  try {
1407
1598
  const heads = await headsOf(deps, { tenant, workspace });