@foldrun/core 20.3.0 → 21.1.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 (43) hide show
  1. package/dist/src/capture.d.ts +7 -1
  2. package/dist/src/capture.js +5 -2
  3. package/dist/src/deploy.js +12 -2
  4. package/dist/src/evals.d.ts +1 -0
  5. package/dist/src/evals.js +60 -13
  6. package/dist/src/grades.js +78 -24
  7. package/dist/src/history.d.ts +5 -1
  8. package/dist/src/history.js +41 -25
  9. package/dist/src/journal-store.d.ts +3 -1
  10. package/dist/src/library.js +1 -1
  11. package/dist/src/process-state.d.ts +2 -0
  12. package/dist/src/process-state.js +20 -0
  13. package/dist/src/records.d.ts +41 -0
  14. package/dist/src/run-outputs.js +22 -19
  15. package/dist/src/runner.js +2 -2
  16. package/dist/src/secret-health.js +8 -6
  17. package/dist/src/secrets.js +8 -6
  18. package/dist/src/store.d.ts +7 -5
  19. package/dist/src/store.js +33 -11
  20. package/dist/src/webhook.d.ts +5 -0
  21. package/dist/src/webhook.js +61 -8
  22. package/dist/src/workspace-docs.d.ts +9 -0
  23. package/dist/src/workspace-docs.js +31 -0
  24. package/dist/src/workspace-revisions.d.ts +10 -3
  25. package/dist/src/workspace-revisions.js +336 -146
  26. package/package.json +1 -1
  27. package/src/capture.ts +4 -1
  28. package/src/deploy.ts +10 -2
  29. package/src/evals.ts +54 -13
  30. package/src/grades.ts +75 -21
  31. package/src/history.ts +39 -24
  32. package/src/journal-store.ts +3 -2
  33. package/src/library.ts +1 -1
  34. package/src/process-state.ts +21 -0
  35. package/src/records.ts +36 -0
  36. package/src/run-outputs.ts +22 -19
  37. package/src/runner.ts +2 -2
  38. package/src/secret-health.ts +8 -6
  39. package/src/secrets.ts +8 -6
  40. package/src/store.ts +33 -12
  41. package/src/webhook.ts +63 -8
  42. package/src/workspace-docs.ts +33 -0
  43. package/src/workspace-revisions.ts +323 -132
@@ -34,51 +34,75 @@
34
34
  import fs from "node:fs";
35
35
  import path from "node:path";
36
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";
37
+ import { pipeline } from "node:stream/promises";
38
+ import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle } from "./history.js";
39
+ import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath } from "./store.js";
39
40
  import { dataRoot } from "./paths.js";
41
+ import { processState } from "./process-state.js";
40
42
  import { opsError, opsLog } from "./ops-log.js";
41
- import { readAll, BlobNotFound } from "./blob-store.js";
43
+ import { readAll, fileSource, BlobNotFound } from "./blob-store.js";
42
44
  import { fsJournalStore } from "./journal-store.js";
43
- import { blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
45
+ import { AUTHORED_DIRS, AUTHORED_ROOT_FILES, STATE_DIRS, assertManifestPath, blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
44
46
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
45
47
  import { OpIdReused } from "./revision-store.js";
46
48
  import { pruneStateRevisions } from "./state-retention.js";
47
49
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
48
50
  // ------------------------------------------------------------- the backend
49
- let backend = null;
50
- let gate = { journal: () => false, read: () => false };
51
- let retention = null;
52
- let orphanMarks = null;
53
- let orphanGrace = 3_600_000;
54
- let retentionEvery = 10 * 60_000;
51
+ /** Everything this module is told at boot, and every queue that goes with it,
52
+ * is one per PROCESS (process-state.ts), not one per copy of the module: the
53
+ * dashboard's route handlers are compiled apart from the boot, and until 13
54
+ * Nov 2026 they saw no backend — a save there was never journalled, and a read
55
+ * never came from a head. */
56
+ const S = processState("workspace-revisions", () => ({
57
+ backend: null,
58
+ gate: { journal: () => false, read: () => false },
59
+ retention: null,
60
+ orphanMarks: null,
61
+ orphanGrace: 3_600_000,
62
+ retentionEvery: 10 * 60_000,
63
+ primary: null,
64
+ cache: null,
65
+ legacy: null,
66
+ queues: new Map(),
67
+ chains: new Map(),
68
+ marked: new Set(),
69
+ verified: new Set(),
70
+ unjournalled: new Set(),
71
+ repairing: new Set(),
72
+ retryAt: new Map(),
73
+ wantPrune: new Set(),
74
+ prunedAt: new Map(),
75
+ frozen: new Map(),
76
+ restoring: new Map(),
77
+ lifecycleBusy: new Set(),
78
+ background: new Set(),
79
+ }));
55
80
  /** The legacy place: files on the volume. Always replayed at boot (and then
56
81
  * empty), whatever new entries are written to. */
57
- const legacyFiles = fsJournalStore(() => journalRoot());
58
- let primary = null;
59
- const journalStores = () => (primary && primary !== legacyFiles ? [primary, legacyFiles] : [legacyFiles]);
60
- const entryStore = () => primary ?? legacyFiles;
82
+ const legacyFiles = (S.legacy ??= fsJournalStore(() => journalRoot()));
83
+ const journalStores = () => (S.primary && S.primary !== legacyFiles ? [S.primary, legacyFiles] : [legacyFiles]);
84
+ const entryStore = () => S.primary ?? legacyFiles;
61
85
  /** Where revisions live, or null (no journal, nothing changes). */
62
86
  export function setRevisionBackend(deps, opts = {}) {
63
87
  // Every commit asks, inside the store's workspace lock, whether the folder is
64
88
  // still there: a delete or rename on another pod removes it under that lock.
65
- backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
66
- gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
67
- primary = opts.journalStore ?? null;
68
- retention = opts.stateRetention ?? null;
69
- retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
70
- orphanMarks = opts.sweepMarks ?? null;
71
- orphanGrace = opts.orphanGraceMs ?? 3_600_000;
89
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
90
+ S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
91
+ S.primary = opts.journalStore ?? null;
92
+ S.retention = opts.stateRetention ?? null;
93
+ S.retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
94
+ S.orphanMarks = opts.sweepMarks ?? null;
95
+ S.orphanGrace = opts.orphanGraceMs ?? 3_600_000;
72
96
  registerJournal(deps ? journalChange : null);
73
97
  registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
74
98
  registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
75
99
  registerRevisionView(deps ? view : null);
76
100
  }
77
- export const revisionBackend = () => backend;
78
- const journalOn = () => !!backend && safe(gate.journal);
101
+ export const revisionBackend = () => S.backend;
102
+ const journalOn = () => !!S.backend && safe(S.gate.journal);
79
103
  /** Reads of content from heads (and run stage-in): its own switch, and only
80
104
  * where the journal runs too (a head that is not kept current is not a source). */
81
- export const revisionReadsOn = () => journalOn() && safe(gate.read);
105
+ export const revisionReadsOn = () => journalOn() && safe(S.gate.read);
82
106
  function safe(fn) {
83
107
  try {
84
108
  return fn();
@@ -87,26 +111,28 @@ function safe(fn) {
87
111
  return false;
88
112
  }
89
113
  }
90
- let cache = null;
91
114
  export function setBlobCache(c) {
92
- cache = c;
115
+ S.cache = c;
93
116
  }
117
+ const bytesOfEntry = (f) => Buffer.from(f.after ?? "", f.enc === "base64" ? "base64" : "utf8");
118
+ /** Is this exactly the UTF-8 of some text? (What a history page can show.) */
119
+ const isText = (b) => Buffer.from(b.toString("utf8"), "utf8").equals(b);
94
120
  const MAX_QUEUED = 2000;
95
121
  /** A journal file this old, that no queue of this process holds, was left by a
96
122
  * process that died (a live one commits within seconds or keeps retrying). */
97
123
  const ORPHAN_MS = 120_000;
98
- const queues = new Map();
99
- const chains = new Map();
100
- const marked = new Set(); // overflowed or dropped: needs reconcileWorkspace
101
- const verified = new Set(); // reconciled once in this process
102
- const unjournalled = new Set(); // changed here while the journal was off: the head has not seen it
103
- const repairing = new Set(); // a reconcile is publishing: the head is about to change
104
- const retryAt = new Map();
105
- const wantPrune = new Set(); // a state checkpoint was committed since the last look
106
- const prunedAt = new Map();
124
+ const queues = S.queues;
125
+ const chains = S.chains;
126
+ const marked = S.marked; // overflowed or dropped: needs reconcileWorkspace
127
+ const verified = S.verified; // reconciled once in this process
128
+ const unjournalled = S.unjournalled; // changed here while the journal was off: the head has not seen it
129
+ const repairing = S.repairing; // a reconcile is publishing: the head is about to change
130
+ const retryAt = S.retryAt;
131
+ const wantPrune = S.wantPrune; // a state checkpoint was committed since the last look
132
+ const prunedAt = S.prunedAt;
107
133
  /** Workspaces whose commits are held while a delete or rename runs. */
108
- const frozen = new Map();
109
- const restoring = new Map();
134
+ const frozen = S.frozen;
135
+ const restoring = S.restoring;
110
136
  const key = (tenant, workspace) => `${tenant}\0${workspace}`;
111
137
  const split = (k) => k.split("\0");
112
138
  const journalRoot = () => path.join(dataRoot(), ".revision-journal");
@@ -115,7 +141,7 @@ const journalRoot = () => path.join(dataRoot(), ".revision-journal");
115
141
  function persist(tenant, workspace, e) {
116
142
  const store = entryStore();
117
143
  try {
118
- 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 });
144
+ e.handle = store.put({ v: e.files.some((f) => f.enc) ? 2 : 1, tenant, workspace, id: e.id, files: e.files, by: e.by, message: e.message, at: e.at, restoredFrom: e.restoredFrom, baseRev: e.baseRev });
119
145
  e.store = store;
120
146
  }
121
147
  catch (err) {
@@ -135,10 +161,10 @@ function forget(tenant, workspace, e) {
135
161
  /** Called by history.recordRevision for every change set. Synchronous and
136
162
  * cheap; the commit happens in the background (flushRevisions waits for it). */
137
163
  function journalChange(tenant, scope, files, meta) {
138
- if (!backend || scope === "@library")
164
+ if (!S.backend || scope === "@library")
139
165
  return; // the account shelf is not a workspace
140
166
  const k = key(tenant, scope);
141
- if (!safe(gate.journal)) {
167
+ if (!safe(S.gate.journal)) {
142
168
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
143
169
  unjournalled.add(k);
144
170
  return;
@@ -190,14 +216,15 @@ const MAX_STEP_ENTRY = 8 * 1024 * 1024;
190
216
  * whose copy-out itself failed wrote nothing and commits nothing. A test run's
191
217
  * diverted state/ and storage/ writes never reach the folder and never here.
192
218
  *
193
- * Text only: a binary file is not versioned yet (see phase 3). Returns the
194
- * number of paths queued.
219
+ * Every file, whatever it holds: one that is not text rides as base64 (13 Nov
220
+ * 2026; until then a binary file was left out, and the head went stale against
221
+ * the folder). Returns the number of paths queued.
195
222
  */
196
223
  export function recordStepOutputs(tenant, workspace, writes, meta) {
197
- if (!backend || workspace === "@library")
224
+ if (!S.backend || workspace === "@library")
198
225
  return 0;
199
226
  const k = key(tenant, workspace);
200
- if (!safe(gate.journal)) {
227
+ if (!safe(S.gate.journal)) {
201
228
  verified.delete(k); // the head will not see this: reconcile before trusting it again
202
229
  unjournalled.add(k);
203
230
  return 0;
@@ -207,9 +234,8 @@ export function recordStepOutputs(tenant, workspace, writes, meta) {
207
234
  for (const w of writes) {
208
235
  if (!sideOf(w.path))
209
236
  continue; // not workspace content (runs/, .foldrun/ …)
210
- const text = w.after.toString("utf8");
211
- if (!Buffer.from(text, "utf8").equals(w.after))
212
- continue; // binary: not versioned
237
+ if (isPlatformPath(w.path))
238
+ continue; // the engine's own files: never content
213
239
  if (w.after.length > MAX_STEP_FILE) {
214
240
  marked.add(k); // the folder has it; the reconcile records it
215
241
  continue;
@@ -219,7 +245,9 @@ export function recordStepOutputs(tenant, workspace, writes, meta) {
219
245
  continue;
220
246
  }
221
247
  total += w.after.length;
222
- files.push({ path: w.path, before: null, after: text, base: w.base, ...(w.handed !== undefined ? { handed: w.handed } : {}) });
248
+ // Bytes that are not text (an image, a database) ride as base64.
249
+ const body = isText(w.after) ? { after: w.after.toString("utf8") } : { after: w.after.toString("base64"), enc: "base64" };
250
+ files.push({ path: w.path, before: null, ...body, base: w.base, ...(w.handed !== undefined ? { handed: w.handed } : {}) });
223
251
  }
224
252
  if (!files.length)
225
253
  return 0;
@@ -269,7 +297,7 @@ function drain(k) {
269
297
  async function drainOne(k) {
270
298
  const [tenant, workspace] = split(k);
271
299
  const q = queues.get(k);
272
- while (q && q.length && backend) {
300
+ while (q && q.length && S.backend) {
273
301
  const entry = q[0];
274
302
  // The workspace was deleted while this waited (or retried): nothing to
275
303
  // publish, and nothing for a later boot to replay.
@@ -279,7 +307,7 @@ async function drainOne(k) {
279
307
  continue;
280
308
  }
281
309
  try {
282
- const res = await commitEntry(backend, tenant, workspace, entry);
310
+ const res = await commitEntry(S.backend, tenant, workspace, entry);
283
311
  if (res?.status === "committed" && res.stateRevision)
284
312
  wantPrune.add(k);
285
313
  q.shift();
@@ -323,7 +351,7 @@ async function drainOne(k) {
323
351
  // journal was off for a while, a run wrote the folder directly) is brought
324
352
  // to it. After the entries, never before: replaying an older change over a
325
353
  // reconciled head would write it backwards.
326
- if (backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
354
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
327
355
  verified.add(k);
328
356
  try {
329
357
  await reconcileWorkspace(tenant, workspace, "reconcile");
@@ -419,9 +447,9 @@ async function freeze(keys) {
419
447
  void drain(k);
420
448
  };
421
449
  }
422
- const lifecycleBusy = new Set(); // keys a lifecycle call is handling (the sync hooks stay out of its way)
450
+ const lifecycleBusy = S.lifecycleBusy; // keys a lifecycle call is handling (the sync hooks stay out of its way)
423
451
  /** What the sync hooks started and has not finished (tests, and a process that is ending). */
424
- const background = new Set();
452
+ const background = S.background;
425
453
  export async function settleLifecycle() {
426
454
  while (background.size)
427
455
  await Promise.allSettled([...background]);
@@ -460,7 +488,7 @@ function goneNow(tenant, workspace) {
460
488
  * in between. A store that cannot be reached throws BEFORE `remove` runs.
461
489
  */
462
490
  export async function dropWorkspaceRevisions(tenant, workspace, remove) {
463
- const deps = backend;
491
+ const deps = S.backend;
464
492
  if (!deps || workspace === "@library") {
465
493
  remove?.();
466
494
  return;
@@ -500,7 +528,7 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
500
528
  * rest depends on it). */
501
529
  export async function dropTenantRevisions(tenant) {
502
530
  dropJournal(tenant);
503
- const deps = backend;
531
+ const deps = S.backend;
504
532
  if (!deps)
505
533
  return;
506
534
  const mine = [...chains.keys()].filter((k) => split(k)[0] === tenant);
@@ -528,7 +556,7 @@ function movedNow(tenant, from, to) {
528
556
  * store that cannot be reached throws BEFORE `rename` runs.
529
557
  */
530
558
  export async function moveWorkspaceRevisions(tenant, from, to, rename) {
531
- const deps = backend;
559
+ const deps = S.backend;
532
560
  if (!deps || from === "@library" || to === "@library") {
533
561
  rename?.();
534
562
  return;
@@ -622,7 +650,7 @@ const RUN_PIN_TTL_MS = 2 * 60 * 60_000;
622
650
  * be taken.
623
651
  */
624
652
  export async function pinRunBase(tenant, workspace, holder) {
625
- const deps = backend;
653
+ const deps = S.backend;
626
654
  if (!deps || !journalOn() || workspace === "@library")
627
655
  return null;
628
656
  try {
@@ -642,7 +670,7 @@ export async function pinRunBase(tenant, workspace, holder) {
642
670
  /** The same pin for a base that was recorded earlier (a driver that took over a
643
671
  * step): null when either revision is gone. */
644
672
  export async function repinRunBase(tenant, workspace, base, holder) {
645
- const deps = backend;
673
+ const deps = S.backend;
646
674
  if (!deps || !journalOn())
647
675
  return null;
648
676
  try {
@@ -683,10 +711,10 @@ async function holdRunBase(deps, tenant, base, revs, holder) {
683
711
  // ------------------------------------------------------------- state retention
684
712
  /** Look at one workspace's `state/` checkpoints now (the host's window). */
685
713
  export async function pruneStateNow(tenant, workspace) {
686
- const deps = backend;
687
- if (!deps || !retention || !journalOn())
714
+ const deps = S.backend;
715
+ if (!deps || !S.retention || !journalOn())
688
716
  return null;
689
- const policy = safe2(retention);
717
+ const policy = safe2(S.retention);
690
718
  if (!policy)
691
719
  return null;
692
720
  try {
@@ -712,7 +740,7 @@ const safe2 = (fn) => {
712
740
  /** After a state commit: look, but not on every one (a checkpoint per step). */
713
741
  async function pruneIfDue(tenant, workspace) {
714
742
  const last = prunedAt.get(key(tenant, workspace)) ?? 0;
715
- if (Date.now() - last < retentionEvery)
743
+ if (Date.now() - last < S.retentionEvery)
716
744
  return;
717
745
  await pruneStateNow(tenant, workspace);
718
746
  }
@@ -734,7 +762,7 @@ async function pruneIfDue(tenant, workspace) {
734
762
  */
735
763
  export async function cleanOrphanedHistory(marks, opts) {
736
764
  const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
737
- const deps = backend;
765
+ const deps = S.backend;
738
766
  if (!deps)
739
767
  return out;
740
768
  const root = dataRoot();
@@ -843,7 +871,7 @@ export async function recoverJournal(opts = {}) {
843
871
  if (minAge > 0 && ageMs < minAge)
844
872
  continue;
845
873
  const e = store.read(tenant, workspace, handle);
846
- if (e.v !== 1 || !Array.isArray(e.files))
874
+ if ((e.v !== 1 && e.v !== 2) || !Array.isArray(e.files))
847
875
  throw new Error("not a journal entry");
848
876
  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 });
849
877
  }
@@ -878,8 +906,8 @@ export async function reconcileAll(opts = {}) {
878
906
  // First, the history of workspaces that were deleted before the delete took
879
907
  // it with them (8 Nov 2026): it must not be reconciled, or found by a new
880
908
  // workspace of the same name.
881
- if (orphanMarks)
882
- await cleanOrphanedHistory(orphanMarks, { graceMs: orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
909
+ if (S.orphanMarks)
910
+ await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
883
911
  for (const tenant of opts.tenants ?? listTenants()) {
884
912
  for (const w of listWorkspaces(tenant)) {
885
913
  const k = key(tenant, w.name);
@@ -910,6 +938,129 @@ export async function reconcileAll(opts = {}) {
910
938
  return out;
911
939
  }
912
940
  // ------------------------------------------------------------- committing
941
+ /** A file this big is sent to the store from disk, never read whole. */
942
+ const LARGE_FILE = 8 * 1024 * 1024;
943
+ const LARGE_PIN_TTL_MS = 30 * 60_000;
944
+ async function hashOf(abs, size) {
945
+ // Read off the event loop: a dashboard process runs this too, and a desk can
946
+ // hold thousands of files.
947
+ if (size <= LARGE_FILE)
948
+ return sha256Hex(await fs.promises.readFile(abs));
949
+ const h = crypto.createHash("sha256");
950
+ await pipeline(fs.createReadStream(abs), h);
951
+ return h.digest("hex");
952
+ }
953
+ /**
954
+ * The workspace's content as the folder holds it now: every regular file on
955
+ * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
956
+ * the data importer has (data-import.ts scanWorkspace) and what a run's
957
+ * stage-in copies, so a head made from it is the folder. Left out, and listed
958
+ * in `left` when the folder holds them: a symbolic link (never followed), the
959
+ * platform's and the engine's own files (isPlatformPath), a name a manifest
960
+ * refuses, the later of two names that differ only by case, a file that could
961
+ * not be read. Null when the folder is not there.
962
+ */
963
+ async function scanFolder(tenant, workspace) {
964
+ const dir = workspaceDir(tenant, workspace);
965
+ if (!fs.existsSync(dir))
966
+ return null;
967
+ const found = [];
968
+ const left = new Set();
969
+ const walk = (rel) => {
970
+ // A folder that cannot be listed (gone since its parent was read aside)
971
+ // ends the scan: skipped, everything under it would read as deleted.
972
+ let names;
973
+ try {
974
+ names = fs.readdirSync(path.join(dir, rel)).sort();
975
+ }
976
+ catch (err) {
977
+ if (err.code === "ENOENT")
978
+ return;
979
+ throw err;
980
+ }
981
+ for (const name of names) {
982
+ const r = `${rel}/${name}`;
983
+ const abs = path.join(dir, r);
984
+ let st;
985
+ try {
986
+ st = fs.lstatSync(abs);
987
+ }
988
+ catch (err) {
989
+ if (err.code === "ENOENT")
990
+ continue; // deleted meanwhile
991
+ throw err;
992
+ }
993
+ if (st.isDirectory())
994
+ walk(r);
995
+ else if (st.isFile())
996
+ found.push({ rel: r, abs, st });
997
+ else
998
+ left.add(r);
999
+ }
1000
+ };
1001
+ let top;
1002
+ try {
1003
+ top = fs.readdirSync(dir).sort();
1004
+ }
1005
+ catch {
1006
+ return null;
1007
+ }
1008
+ for (const name of top) {
1009
+ const abs = path.join(dir, name);
1010
+ let st;
1011
+ try {
1012
+ st = fs.lstatSync(abs);
1013
+ }
1014
+ catch {
1015
+ continue;
1016
+ }
1017
+ if (st.isDirectory() && (AUTHORED_DIRS.includes(name) || STATE_DIRS.includes(name)))
1018
+ walk(name);
1019
+ else if (st.isFile() && sideOf(name) === "authored")
1020
+ found.push({ rel: name, abs, st });
1021
+ else if (AUTHORED_ROOT_FILES.includes(name))
1022
+ left.add(name);
1023
+ }
1024
+ const files = new Map();
1025
+ const lower = new Set();
1026
+ for (const f of found.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))) {
1027
+ if (isPlatformPath(f.rel))
1028
+ continue;
1029
+ const fold = f.rel.toLowerCase();
1030
+ try {
1031
+ assertManifestPath(f.rel);
1032
+ if (lower.has(fold))
1033
+ throw new Error("differs only by case");
1034
+ 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 });
1035
+ lower.add(fold);
1036
+ }
1037
+ catch {
1038
+ left.add(f.rel);
1039
+ }
1040
+ }
1041
+ return { files, left };
1042
+ }
1043
+ /** Send the large files among `changes` to the store from disk, pinned first
1044
+ * (as a publish pins what it uploads), so none is held whole in memory; the
1045
+ * publish then finds each in the store and does not ask for its bytes. */
1046
+ async function uploadLarge(deps, tenant, changes, onDisk, opId) {
1047
+ const large = [...new Set(Object.values(changes).flatMap((c) => (c.op === "put" && c.size > LARGE_FILE && onDisk.has(c.sha) ? [c.sha] : [])))];
1048
+ if (!large.length)
1049
+ return async () => { };
1050
+ const holder = { kind: "publish", id: `${opId}-large` };
1051
+ // The pin is held until the caller's publish is over (it returns the release).
1052
+ const release = async () => void (await deps.pins?.release(tenant, holder).catch(() => { }));
1053
+ await deps.pins?.pinBlobs(tenant, large, holder, { ttlMs: LARGE_PIN_TTL_MS });
1054
+ try {
1055
+ for (const sha of large)
1056
+ await deps.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), fileSource(onDisk.get(sha)), { sha256: sha });
1057
+ }
1058
+ catch (err) {
1059
+ await release();
1060
+ throw err;
1061
+ }
1062
+ return release;
1063
+ }
913
1064
  function modeOf(tenant, workspace, rel) {
914
1065
  try {
915
1066
  return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
@@ -960,6 +1111,8 @@ async function commitEntry(deps, tenant, workspace, entry) {
960
1111
  const heads = await headsOf(deps, ws);
961
1112
  const head = await manifestsAt(deps, tenant, heads);
962
1113
  const bytes = new Map();
1114
+ const onDisk = new Map(); // sha → a file of the folder that holds it
1115
+ let releaseLarge = async () => { };
963
1116
  const changes = {};
964
1117
  const baseline = { authored: !heads.workspace, state: !heads.state };
965
1118
  // A run's copy-back is pinned to the revisions its stage-in started from: a
@@ -967,8 +1120,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
967
1120
  // run, a person) is a conflict on the path, and disjoint paths replay. Where
968
1121
  // the revision cannot be read any more, the folder's sha stands in.
969
1122
  const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
970
- const put = (rel, text, side, pinned, handed) => {
971
- const buf = Buffer.from(text, "utf8");
1123
+ const put = (rel, buf, side, pinned, handed) => {
972
1124
  const sha = sha256Hex(buf);
973
1125
  bytes.set(sha, buf);
974
1126
  const was = head[side].files[rel];
@@ -987,14 +1139,16 @@ async function commitEntry(deps, tenant, workspace, entry) {
987
1139
  // Nothing is recorded for (part of) this workspace yet: its tree, as the
988
1140
  // folder holds it now, is the first revision. That already contains this
989
1141
  // entry's change, since the writer wrote before it journalled.
990
- for (const f of currentTree(tenant, workspace) ?? []) {
991
- const side = sideOf(f.path);
992
- if (!side || f.after === null)
993
- continue;
1142
+ // Every file, as scanFolder lists them (binaries too); each one's bytes are
1143
+ // read when the publish asks for them, never all at once.
1144
+ for (const [rel, f] of (await scanFolder(tenant, workspace))?.files ?? []) {
1145
+ const side = sideOf(rel);
994
1146
  if ((side === "authored" && !baseline.authored) || (side === "state" && !baseline.state))
995
1147
  continue;
996
- put(f.path, f.after, side);
1148
+ onDisk.set(f.sha, f.abs);
1149
+ changes[rel] = { op: "put", base: null, sha: f.sha, size: f.size, mode: f.mode };
997
1150
  }
1151
+ releaseLarge = await uploadLarge(deps, tenant, changes, onDisk, `jb-${entry.id}`);
998
1152
  }
999
1153
  for (const f of entry.files) {
1000
1154
  const side = sideOf(f.path);
@@ -1008,7 +1162,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1008
1162
  changes[f.path] = { op: "delete", base: entryId(was) };
1009
1163
  }
1010
1164
  else {
1011
- put(f.path, f.after, side, f.base, f.handed);
1165
+ put(f.path, bytesOfEntry(f), side, f.base, f.handed);
1012
1166
  }
1013
1167
  }
1014
1168
  if (!Object.keys(changes).length)
@@ -1024,41 +1178,46 @@ async function commitEntry(deps, tenant, workspace, entry) {
1024
1178
  // 2026 that was taken as the whole entry being done and the state half was
1025
1179
  // never committed (FOL-152). Asked again after an OpIdReused: another pod
1026
1180
  // replaying the same entry may finish a side between the look and the publish.
1027
- for (let attempt = 0;; attempt++) {
1028
- const done = await sidesDone(deps, ws, entry.id);
1029
- const todo = {};
1030
- for (const [p, c] of Object.entries(changes))
1031
- if (!done[sideOf(p)])
1032
- todo[p] = c;
1033
- if (!Object.keys(todo).length)
1034
- return null;
1035
- try {
1036
- return await publish(deps, {
1037
- ws,
1038
- // The op id of a side that finished, when one did, so the other side's
1039
- // conflict copies are named the way the first attempt would have.
1040
- opId: done.opId ?? opIdOf(prefix, entry.id),
1041
- by: entry.by,
1042
- message: entry.message,
1043
- changes: todo,
1044
- restoredFrom: done.authored ? undefined : restoredFrom,
1045
- bytesOf: async (sha) => {
1046
- const b = bytes.get(sha);
1047
- if (!b)
1048
- throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1049
- return b;
1050
- },
1051
- });
1052
- }
1053
- catch (err) {
1054
- // Never "done" by itself: a side that finished is found by sidesDone on
1055
- // the next look. One that keeps answering OpIdReused without having
1056
- // finished is a bug, and permanent(): the entry is dropped and the
1057
- // workspace reconciled from the folder, so nothing is lost silently.
1058
- if (!(err instanceof OpIdReused) || attempt >= 2)
1059
- throw err;
1181
+ try {
1182
+ for (let attempt = 0;; attempt++) {
1183
+ const done = await sidesDone(deps, ws, entry.id);
1184
+ const todo = {};
1185
+ for (const [p, c] of Object.entries(changes))
1186
+ if (!done[sideOf(p)])
1187
+ todo[p] = c;
1188
+ if (!Object.keys(todo).length)
1189
+ return null;
1190
+ try {
1191
+ return await publish(deps, {
1192
+ ws,
1193
+ // The op id of a side that finished, when one did, so the other side's
1194
+ // conflict copies are named the way the first attempt would have.
1195
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1196
+ by: entry.by,
1197
+ message: entry.message,
1198
+ changes: todo,
1199
+ restoredFrom: done.authored ? undefined : restoredFrom,
1200
+ bytesOf: async (sha) => {
1201
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)) : null);
1202
+ if (!b)
1203
+ throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1204
+ return b;
1205
+ },
1206
+ });
1207
+ }
1208
+ catch (err) {
1209
+ // Never "done" by itself: a side that finished is found by sidesDone on
1210
+ // the next look. One that keeps answering OpIdReused without having
1211
+ // finished is a bug, and permanent(): the entry is dropped and the
1212
+ // workspace reconciled from the folder, so nothing is lost silently.
1213
+ if (!(err instanceof OpIdReused) || attempt >= 2)
1214
+ throw err;
1215
+ }
1060
1216
  }
1061
1217
  }
1218
+ finally {
1219
+ await releaseLarge();
1220
+ }
1062
1221
  }
1063
1222
  /** Which halves of a journal entry finished in an earlier attempt (an
1064
1223
  * operation is recorded for each, committed or unchanged). Both prefixes are
@@ -1079,9 +1238,12 @@ async function sidesDone(deps, ws, id) {
1079
1238
  }
1080
1239
  /** Bring the heads to the folder's content in one revision: the way in for a
1081
1240
  * workspace that predates the journal (the importer, phase 8), and the repair
1082
- * after a journal overflow. Text files only, as the tree reader lists them. */
1241
+ * after a journal overflow. Every file scanFolder lists, whatever it holds
1242
+ * (until 13 Nov 2026: only the text files the editor lists, so a binary file
1243
+ * never reached a head and one the importer had put there was never updated
1244
+ * or removed — a run staged from the head was handed files deleted days ago). */
1083
1245
  export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1084
- const deps = backend;
1246
+ const deps = S.backend;
1085
1247
  if (!deps)
1086
1248
  return null;
1087
1249
  const ws = { tenant, workspace };
@@ -1097,44 +1259,51 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1097
1259
  // would diff a stale copy against a newer head, and with that head as each
1098
1260
  // path's base the publish would undo the newer write without a conflict.
1099
1261
  const heads = await headsOf(deps, ws);
1100
- const tree = currentTree(tenant, workspace);
1101
- if (!tree)
1262
+ const scan = await scanFolder(tenant, workspace);
1263
+ if (!scan)
1102
1264
  return null;
1103
1265
  const head = await manifestsAt(deps, tenant, heads);
1104
- const bytes = new Map();
1266
+ const onDisk = new Map();
1105
1267
  const want = emptyManifest();
1106
1268
  const have = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1107
- for (const f of tree) {
1108
- const side = sideOf(f.path);
1109
- if (!side || f.after === null)
1110
- continue;
1111
- const buf = Buffer.from(f.after, "utf8");
1112
- const sha = sha256Hex(buf);
1113
- bytes.set(sha, buf);
1114
- want.files[f.path] = { sha, size: buf.length, mode: modeOf(tenant, workspace, f.path) };
1269
+ for (const [rel, f] of scan.files) {
1270
+ onDisk.set(f.sha, f.abs);
1271
+ want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
1115
1272
  }
1116
- // A path the tree reader does not list but the folder still holds (a binary
1117
- // file) is neither added nor removed here; one that is gone from the folder
1118
- // is gone from the head.
1119
- const dir = workspaceDir(tenant, workspace);
1273
+ // A path the scan could not take (unreadable now, a name the manifest
1274
+ // refuses) but the folder still holds is neither added nor removed here;
1275
+ // one that is gone from the folder is gone from the head.
1276
+ // Never beside a name that differs from it only by case (a manifest holds
1277
+ // one of the two): the folder's first, as the scan chose, is the one kept.
1278
+ const taken = new Set(Object.keys(want.files).map((p) => p.toLowerCase()));
1120
1279
  for (const p of Object.keys(have.files)) {
1121
- if (!(p in want.files) && fs.existsSync(path.join(dir, p)))
1280
+ if (!(p in want.files) && scan.left.has(p) && !taken.has(p.toLowerCase()))
1122
1281
  want.files[p] = have.files[p];
1123
1282
  }
1124
1283
  const changes = diffManifests(have, want);
1125
1284
  if (!Object.keys(changes).length)
1126
1285
  return null;
1127
- return await publish(deps, {
1128
- ws,
1129
- // The heads it was diffed against are part of the id: the same changes
1130
- // over a different head (the head was restored since) are a new repair,
1131
- // not a retry of the earlier one.
1132
- opId: opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40)),
1133
- by,
1134
- message: "workspace content recorded",
1135
- changes,
1136
- bytesOf: async (sha) => bytes.get(sha),
1137
- });
1286
+ // The heads it was diffed against are part of the id: the same changes
1287
+ // over a different head (the head was restored since) are a new repair,
1288
+ // not a retry of the earlier one.
1289
+ const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
1290
+ const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
1291
+ try {
1292
+ return await publish(deps, {
1293
+ ws,
1294
+ opId,
1295
+ by,
1296
+ message: "workspace content recorded",
1297
+ changes,
1298
+ // Read when asked, one file at a time; publish checks the bytes against
1299
+ // the sha, so a file that changed since the scan fails this repair (the
1300
+ // mark is put back and the next one sees the new bytes).
1301
+ bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)),
1302
+ });
1303
+ }
1304
+ finally {
1305
+ await release();
1306
+ }
1138
1307
  }
1139
1308
  catch (err) {
1140
1309
  if (wasMarked)
@@ -1149,12 +1318,12 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1149
1318
  }
1150
1319
  // ------------------------------------------------------------- reading
1151
1320
  async function blobBytes(deps, tenant, sha) {
1152
- const hit = await cache?.get(tenant, sha);
1321
+ const hit = await S.cache?.get(tenant, sha);
1153
1322
  if (hit)
1154
1323
  return hit;
1155
1324
  try {
1156
1325
  const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1157
- void cache?.put(tenant, sha, b).catch(() => { });
1326
+ void S.cache?.put(tenant, sha, b).catch(() => { });
1158
1327
  return b;
1159
1328
  }
1160
1329
  catch (err) {
@@ -1166,7 +1335,7 @@ async function blobBytes(deps, tenant, sha) {
1166
1335
  /** One file of the workspace as its heads hold it: head → manifest → blob.
1167
1336
  * Null when there is no such file (or no head yet). */
1168
1337
  export async function readAtHead(tenant, workspace, rel) {
1169
- const deps = backend;
1338
+ const deps = S.backend;
1170
1339
  if (!deps)
1171
1340
  return null;
1172
1341
  const side = sideOf(rel);
@@ -1191,7 +1360,7 @@ async function parentManifest(deps, tenant, workspace, rev) {
1191
1360
  * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
1192
1361
  * the message); the id is the revision's. */
1193
1362
  export async function listRevisionSummaries(tenant, workspace, opts = {}) {
1194
- const deps = backend;
1363
+ const deps = S.backend;
1195
1364
  if (!deps)
1196
1365
  return [];
1197
1366
  const want = opts.limit ?? 200;
@@ -1240,7 +1409,7 @@ const FOR_PATH_SCAN = 500;
1240
1409
  /** One revision of the workspace head, by id, without listing: the history's
1241
1410
  * "is this a restore point" and "which revision is that id". */
1242
1411
  export async function revisionSummary(tenant, workspace, id) {
1243
- const deps = backend;
1412
+ const deps = S.backend;
1244
1413
  if (!deps)
1245
1414
  return null;
1246
1415
  const r = await deps.revisions.revision({ tenant, workspace }, id);
@@ -1249,7 +1418,7 @@ export async function revisionSummary(tenant, workspace, id) {
1249
1418
  /** One revision with what changed, in history.ts's Revision shape (text
1250
1419
  * before/after, clipped). */
1251
1420
  export async function readRevisionDetail(tenant, workspace, id, forPath) {
1252
- const deps = backend;
1421
+ const deps = S.backend;
1253
1422
  if (!deps)
1254
1423
  return null;
1255
1424
  const r = await deps.revisions.revision({ tenant, workspace }, id);
@@ -1263,7 +1432,11 @@ export async function readRevisionDetail(tenant, workspace, id, forPath) {
1263
1432
  continue;
1264
1433
  const was = before.files[p];
1265
1434
  const now = mine.files[p];
1266
- const text = async (e) => (e ? (await blobBytes(deps, tenant, e.sha))?.toString("utf8") ?? null : null);
1435
+ const text = async (e) => {
1436
+ const b = e ? await blobBytes(deps, tenant, e.sha) : null;
1437
+ // A file that is not text has nothing to diff: say what it is.
1438
+ return b ? (isText(b) ? b.toString("utf8") : `(binary file, ${b.length} bytes, sha256 ${e.sha.slice(0, 12)})`) : null;
1439
+ };
1267
1440
  files.push({ path: p, before: clip(await text(was)), after: c.op === "delete" ? null : clip(await text(now)) });
1268
1441
  }
1269
1442
  return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
@@ -1275,7 +1448,7 @@ export async function readRevisionDetail(tenant, workspace, id, forPath) {
1275
1448
  * have removed the file from the folder (FOL-152). Through history.ts the
1276
1449
  * error answers "no snapshot", and the restore refuses. */
1277
1450
  export async function snapshotFiles(tenant, workspace, id) {
1278
- const deps = backend;
1451
+ const deps = S.backend;
1279
1452
  if (!deps)
1280
1453
  return null;
1281
1454
  const r = await deps.revisions.revision({ tenant, workspace }, id);
@@ -1287,6 +1460,12 @@ export async function snapshotFiles(tenant, workspace, id) {
1287
1460
  const b = await blobBytes(deps, tenant, e.sha);
1288
1461
  if (!b)
1289
1462
  throw new BlobMissing(p, e.sha);
1463
+ // Text only: this is what a restore writes back through a deploy, as text.
1464
+ // A binary file is left where it is, as files outside history always were
1465
+ // (13 Nov 2026: until then its bytes were decoded as text here, and a
1466
+ // restore would have written the damaged copy over the file).
1467
+ if (!isText(b))
1468
+ continue;
1290
1469
  out.push({ path: p, content: b.toString("utf8") });
1291
1470
  }
1292
1471
  return out;
@@ -1297,7 +1476,7 @@ export async function snapshotFiles(tenant, workspace, id) {
1297
1476
  * always did; the journal sees that write as a no-op because the head already
1298
1477
  * holds the content. */
1299
1478
  export async function restoreRevision(tenant, workspace, to, opts) {
1300
- const deps = backend;
1479
+ const deps = S.backend;
1301
1480
  if (!deps)
1302
1481
  return null;
1303
1482
  return restore(deps, { ws: { tenant, workspace }, to, opId: opts.opId, by: opts.by, message: opts.message, stateTo: opts.stateTo });
@@ -1339,6 +1518,17 @@ export async function readHeadText(tenant, workspace, rel) {
1339
1518
  return null;
1340
1519
  }
1341
1520
  }
1521
+ /** The folder and the head were seen to disagree (a run's stage-in compares
1522
+ * them): bring the head to the folder, in the background. */
1523
+ export function requestReconcile(tenant, workspace) {
1524
+ if (!journalOn())
1525
+ return;
1526
+ const k = key(tenant, workspace);
1527
+ if (marked.has(k))
1528
+ return;
1529
+ marked.add(k);
1530
+ setImmediate(() => void drain(k));
1531
+ }
1342
1532
  /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1343
1533
  * A change to it is queued (its commit failed or has not run yet), the
1344
1534
  * workspace is marked for a repair or being repaired, or it was written while
@@ -1357,7 +1547,7 @@ function headBehind(tenant, workspace, rel) {
1357
1547
  * a stage-in; null when reads through revisions are off, there is no head,
1358
1548
  * or any blob could not be had (the caller then stages from the folder). */
1359
1549
  export async function readHeadTree(tenant, workspace) {
1360
- const deps = backend;
1550
+ const deps = S.backend;
1361
1551
  if (!deps || !revisionReadsOn())
1362
1552
  return null;
1363
1553
  try {