@foldrun/core 22.2.0 → 22.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.
@@ -152,6 +152,9 @@ export interface RevisionView {
152
152
  /** One revision by id, looked up rather than listed (paths []); null when
153
153
  * the store has none. Optional: a view without it is asked through `list`. */
154
154
  get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
155
+ /** Whether the store serves history right now (its journal and reads on).
156
+ * A view without it is taken as serving. */
157
+ on?(): boolean;
155
158
  }
156
159
  export declare function registerRevisionView(v: RevisionView | null): void;
157
160
  export declare function listRevisions(tenant: string, scope: string, opts?: {
@@ -38,6 +38,7 @@ import { processState } from "./process-state.js";
38
38
  import path from "node:path";
39
39
  import crypto from "node:crypto";
40
40
  import { dataRoot } from "./paths.js";
41
+ import { mirrorOn } from "./mirror-base.js";
41
42
  /** What is registered here is one per PROCESS (process-state.ts): the boot
42
43
  * registers the journal and the view, and a route handler compiled apart from
43
44
  * it must see them — until 13 Nov 2026 it did not, and a dashboard save was
@@ -132,6 +133,24 @@ export function recordRevision(tenant, scope, files, meta = {}) {
132
133
  const changed = files.filter((f) => f.before !== f.after);
133
134
  if (changed.length === 0)
134
135
  return null;
136
+ // A pod whose folders are a copy of the heads (revisions.mirror): the
137
+ // revisions store is the history, and this disk is a cache that goes with
138
+ // the pod. A local record and snapshot per save only filled it (FOL-126,
139
+ // 13 Nov 2026) — nothing reads one that is newer than the store's rows.
140
+ if (mirrorOn() && storeServes()) {
141
+ if (meta.commit)
142
+ assertCommitId(meta.commit);
143
+ const at = new Date().toISOString();
144
+ const by = meta.by ?? "system";
145
+ const message = meta.message ?? describe(changed);
146
+ try {
147
+ REG.journal(tenant, scope, changed, { by, message, at });
148
+ }
149
+ catch {
150
+ // the revision store is not allowed to break a save; workspace-revisions logs and retries
151
+ }
152
+ return { id: meta.id ?? newRevisionId(), at, by, message, commit: meta.commit ?? null, files: changed.map((f) => ({ path: f.path, before: clip(f.before), after: clip(f.after) })) };
153
+ }
135
154
  const dir = historyDir(tenant, scope);
136
155
  fs.mkdirSync(dir, { recursive: true });
137
156
  // A commit is the revision's id only the first time it is recorded. A
@@ -467,16 +486,70 @@ function changedIn(revs, from, to) {
467
486
  export function latestRevisionIdLocal(tenant, scope) {
468
487
  return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
469
488
  }
489
+ /** The store is the history: registered, journalling and read (Codex review). */
490
+ function storeServes() {
491
+ if (!REG.view || !REG.journal)
492
+ return false;
493
+ try {
494
+ return REG.view.on ? REG.view.on() === true : true;
495
+ }
496
+ catch {
497
+ return false;
498
+ }
499
+ }
470
500
  export function registerRevisionView(v) {
471
501
  REG.view = v;
472
502
  }
503
+ // The account shelf ("@library") in the store: its folder is the account's,
504
+ // so its revisions name `library/<kind>/<file>` and the account's AGENTS.md
505
+ // beside them; its own history names `<kind>/<file>` (library.ts). Read
506
+ // through this, the shelf's history is the store's like any workspace's
507
+ // (FOL-126, 13 Nov 2026 — until then it was each pod's own .history, which
508
+ // a pod on its own disk does not keep). AGENTS.md is not on the shelf: it is
509
+ // left out, and a revision that changed only it is not a shelf revision.
510
+ const SHELF = "library/";
511
+ const onShelf = (p) => p.startsWith(SHELF);
512
+ const shelfPath = (p) => p.slice(SHELF.length);
513
+ function viewFor(scope) {
514
+ const v = REG.view;
515
+ if (!v || scope !== "@library")
516
+ return v;
517
+ return {
518
+ async list(tenant, s, opts) {
519
+ const want = opts.limit ?? 200;
520
+ const withPaths = opts.paths !== false || !!opts.forPath;
521
+ // A revision that changed only the account's AGENTS.md is dropped
522
+ // after the store's limit was spent on it: ask for more until `want`
523
+ // shelf revisions are found or history ends (Codex review).
524
+ for (let ask = want;; ask = Math.min(ask * 4, Number.MAX_SAFE_INTEGER)) {
525
+ const rows = await v.list(tenant, s, { ...opts, limit: ask, ...(opts.forPath ? { forPath: SHELF + opts.forPath } : {}) });
526
+ if (!rows)
527
+ return null;
528
+ const mine = rows.map((r) => ({ ...r, paths: r.paths.filter(onShelf).map(shelfPath) })).filter((r) => !withPaths || r.paths.length > 0);
529
+ if (mine.length >= want || rows.length < ask || !Number.isFinite(want) || ask >= Number.MAX_SAFE_INTEGER)
530
+ return mine.slice(0, want);
531
+ }
532
+ },
533
+ async read(tenant, s, id, forPath) {
534
+ const r = await v.read(tenant, s, id, forPath === undefined ? undefined : SHELF + forPath);
535
+ return r && { ...r, files: r.files.filter((f) => onShelf(f.path)).map((f) => ({ ...f, path: shelfPath(f.path) })) };
536
+ },
537
+ async snapshot(tenant, s, id) {
538
+ const files = await v.snapshot(tenant, s, id);
539
+ return files && files.filter((f) => onShelf(f.path)).map((f) => ({ ...f, path: shelfPath(f.path) }));
540
+ },
541
+ ...(v.get ? { get: (tenant, s, id) => v.get(tenant, s, id) } : {}),
542
+ ...(v.on ? { on: () => v.on() } : {}),
543
+ };
544
+ }
473
545
  /** Revisions first, then the local entries older than the oldest of them.
474
546
  * `stored` is which rows came from the store (every one a restore point). */
475
547
  async function combinedRows(tenant, scope, opts, restorableOnly = false) {
476
548
  const limit = opts.limit ?? 200;
477
549
  // The whole of `limit`, every page of it: the store's first page is not all
478
550
  // of history (FOL-152).
479
- const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
551
+ const view = viewFor(scope);
552
+ const mine = view ? await view.list(tenant, scope, { ...opts, limit }) : null;
480
553
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
481
554
  if (restorableOnly) {
482
555
  const have = snapshotIds(tenant, scope);
@@ -505,25 +578,28 @@ export async function listRevisionsRestorable(tenant, scope, opts = {}) {
505
578
  }
506
579
  export async function readRevision(tenant, scope, id, forPath) {
507
580
  assertSafeName(id, "revision id");
508
- const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
581
+ const view = viewFor(scope);
582
+ const fromStore = view ? await view.read(tenant, scope, id, forPath) : null;
509
583
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
510
584
  }
511
585
  export async function snapshotAt(tenant, scope, id) {
512
586
  assertSafeName(id, "revision id");
513
- const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
587
+ const view = viewFor(scope);
588
+ const fromStore = view ? await view.snapshot(tenant, scope, id) : null;
514
589
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
515
590
  }
516
591
  export async function hasSnapshot(tenant, scope, id) {
517
592
  assertSafeName(id, "revision id");
518
593
  if (hasSnapshotLocal(tenant, scope, id))
519
594
  return true;
520
- if (!REG.view || scope === "@library")
595
+ const view = viewFor(scope);
596
+ if (!view)
521
597
  return false;
522
598
  // Looked up by id: a listing stops at a page, and a revision older than it
523
599
  // was "not restorable" until 9 Nov 2026 (FOL-152).
524
- if (REG.view.get)
525
- return (await REG.view.get(tenant, scope, id)) !== null;
526
- return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
600
+ if (view.get)
601
+ return (await view.get(tenant, scope, id)) !== null;
602
+ return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
527
603
  }
528
604
  export async function headRevision(tenant, scope) {
529
605
  return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
@@ -533,8 +609,9 @@ export async function resolveRevision(tenant, scope, to, now = Date.now()) {
533
609
  // An id in the store is one lookup; anything else (a date, a local id, a
534
610
  // commit) is answered from ALL of history — every page of the store, without
535
611
  // the changed paths, then the local entries.
536
- if ("id" in want && REG.view?.get && scope !== "@library") {
537
- const hit = await REG.view.get(tenant, scope, want.id);
612
+ const view = viewFor(scope);
613
+ if ("id" in want && view?.get) {
614
+ const hit = await view.get(tenant, scope, want.id);
538
615
  if (hit)
539
616
  return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
540
617
  }
@@ -553,6 +630,10 @@ export async function latestRevisionId(tenant, scope) {
553
630
  /** A scope with no revision at all gets a local baseline, as before. */
554
631
  export async function ensureBaseline(tenant, scope, by = "foldrun") {
555
632
  const head = await headRevision(tenant, scope);
633
+ // A mirrored pod's history is the store's: a baseline on its own disk
634
+ // would be gone with the pod (FOL-126).
635
+ if (!head && mirrorOn() && storeServes())
636
+ return null;
556
637
  return head ? head.id : ensureBaselineLocal(tenant, scope, by);
557
638
  }
558
639
  /**
@@ -21,6 +21,11 @@ export interface RecordsPortAsync {
21
21
  * step-state.ts is the only caller. */
22
22
  stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
23
23
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
24
+ /** Every row of one kind for a run (test writes: one row per file). Optional. */
25
+ stepList?(tenant: string, workspace: string, runId: string, kind: string): Promise<{
26
+ ref: string;
27
+ data: unknown;
28
+ }[]>;
24
29
  /** `ref` null: every ref of the kind. */
25
30
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
26
31
  /** The ids of the runs that have rows of this kind in the workspace. */
@@ -80,6 +80,7 @@ import { earlierTurns, conversationBlock } from "./conversation.js";
80
80
  import { inputsNote } from "./run-inputs.js";
81
81
  import { textCandidates } from "./input-text.js";
82
82
  import { resolveClock, localDate } from "./clock.js";
83
+ import { restoreTestWrites, saveTestWrites } from "./test-writes-store.js";
83
84
  export { localDate } from "./clock.js";
84
85
  // An MCP tool definition becomes an SDK server config. ${SECRET} placeholders
85
86
  // in env and headers resolve server-side, so a credential reaches the server
@@ -2610,6 +2611,7 @@ conversation) {
2610
2611
  // The confinement boundary: agents in a workspace are one team, but the
2611
2612
  // workspace is where isolation is enforced.
2612
2613
  const workspaceRoot = path.resolve(agentDir, "..", "..");
2614
+ const workspaceName = path.basename(workspaceRoot);
2613
2615
  // Where a test run's state/ and storage/ writes go, and the line each
2614
2616
  // one leaves: under the run, beside its archived outputs.
2615
2617
  const divertFor = (id) => ({
@@ -3405,6 +3407,11 @@ conversation) {
3405
3407
  save();
3406
3408
  }
3407
3409
  let out;
3410
+ // A test run's earlier diverted writes, brought back if this worker
3411
+ // does not have them (another worker, a restart: FOL-126).
3412
+ // Not caught: a step must not run without what earlier steps wrote, nor
3413
+ // save an index short of it (Codex review).
3414
+ const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
3408
3415
  try {
3409
3416
  out = await runIsolated(a);
3410
3417
  return out;
@@ -3418,6 +3425,10 @@ conversation) {
3418
3425
  if (!out?.deferred)
3419
3426
  step.roomWait = null;
3420
3427
  save();
3428
+ // Last, after the bookkeeping: not caught — a step whose writes were
3429
+ // not kept fails (Codex review).
3430
+ if (testRun && runId && tenant)
3431
+ await saveTestWrites(tenant, workspaceName, runId, divertFor(runId).to, twStart);
3421
3432
  }
3422
3433
  };
3423
3434
  let attemptFrom = step.events.length;
@@ -3824,6 +3835,7 @@ conversation) {
3824
3835
  // sandbox to write instead, and afterwards what changed is moved
3825
3836
  // under the run and the originals come back.
3826
3837
  const attemptThrough = async (modelEnv, spec) => {
3838
+ const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
3827
3839
  const before = testRun ? snapshotDivertedDirs(workspaceRoot) : null;
3828
3840
  // What earlier steps of this test run wrote, laid over the real files
3829
3841
  // for this attempt; restoreDivertedDirs puts the originals back.
@@ -3841,6 +3853,8 @@ conversation) {
3841
3853
  if (before && runId) {
3842
3854
  const d = divertFor(runId);
3843
3855
  restoreDivertedDirs(workspaceRoot, before, d.to, d.note, handed ?? before);
3856
+ if (tenant)
3857
+ await saveTestWrites(tenant, workspaceName, runId, d.to, twStart);
3844
3858
  }
3845
3859
  }
3846
3860
  };
@@ -1,4 +1,4 @@
1
- export type StepStateKind = "handed-in" | "base" | "storage";
1
+ export type StepStateKind = "handed-in" | "base" | "storage" | "test-writes";
2
2
  /** Stored as a row? False: the caller writes the file. */
3
3
  export declare function putStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string, data: unknown): Promise<boolean>;
4
4
  /** The row, or undefined (look at the file). */
@@ -0,0 +1,17 @@
1
+ /** After a step: the run's diverted files into the store, one row each.
2
+ * Throws: a step whose writes were not kept must not count as done. */
3
+ /** What the folder held when an attempt started (restoreTestWrites' answer):
4
+ * a save writes only what the attempt changed from it, so a file another
5
+ * step changed meanwhile on another worker is never written back stale
6
+ * (Codex review). */
7
+ export type TestWritesStart = Map<string, {
8
+ sha: string;
9
+ mtimeMs: number;
10
+ }>;
11
+ export declare function saveTestWrites(tenant: string, workspace: string, runId: string, dir: string, start?: TestWritesStart): Promise<number>;
12
+ /** Before a step: what the rows name and this worker's folder lacks (or has
13
+ * at another time). Throws: a step must not run without what earlier steps wrote. */
14
+ export declare function restoreTestWrites(tenant: string, workspace: string, runId: string, dir: string): Promise<{
15
+ restored: number;
16
+ start: TestWritesStart;
17
+ }>;
@@ -0,0 +1,170 @@
1
+ // A test run's diverted writes, kept off the pod's disk (FOL-126, the shared
2
+ // volume retired): what a test run's steps wrote to state/ and storage/ goes
3
+ // under runs/<id>/test-writes/ on the worker that ran the step, and the next
4
+ // step — on any worker, after any restart — must see it. So after each step
5
+ // the folder's files are put in the blob store (pinned by the run) and listed
6
+ // in one step-state row; before each step the files that row names and the
7
+ // folder lacks are brought back. Without a database or a blob store (a laptop,
8
+ // the CLI) nothing changes: the folder is all there is.
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { dropStepState } from "./step-state.js";
12
+ import { records } from "./records.js";
13
+ import { revisionBackend } from "./workspace-revisions.js";
14
+ import { blobObjectKey, sha256Hex } from "./manifest.js";
15
+ import { readAll } from "./blob-types.js";
16
+ import { registerRunRemovedHook } from "./store.js";
17
+ import { opsError } from "./ops-log.js";
18
+ import { processState } from "./process-state.js";
19
+ const KIND = "test-writes";
20
+ /** Per run folder on this worker: the version of each file it last brought
21
+ * back or saved. A local file that differs from it is a change not saved yet
22
+ * (another step of the run on this worker); one equal to it is a copy the
23
+ * rows may update. File times never decide this (Codex review). */
24
+ const KNOWN = processState("test-writes-known", () => new Map());
25
+ const knownOf = (dir) => {
26
+ let m = KNOWN.get(dir);
27
+ if (!m)
28
+ KNOWN.set(dir, (m = new Map()));
29
+ return m;
30
+ };
31
+ const holderOf = (runId) => ({ kind: "run", id: `test-writes:${runId}` });
32
+ /** A diverted file kept whole up to this; a bigger one stays on the worker
33
+ * that wrote it (and is named in the ops line), as before. */
34
+ const MAX_FILE = 64 * 1024 * 1024;
35
+ function walk(root) {
36
+ const out = [];
37
+ if (!fs.existsSync(root))
38
+ return out;
39
+ for (const e of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
40
+ if (!e.isFile())
41
+ continue; // links and the rest never leave the worker
42
+ const abs = path.join(e.parentPath, e.name);
43
+ out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
44
+ }
45
+ return out;
46
+ }
47
+ /** The rows' port (null: a laptop, no records port), and whether new rows
48
+ * are written (`runs.step_state_store`). Rows already there are READ either
49
+ * way, as step state's are (Codex review). */
50
+ function rowsPort(tenant, workspace) {
51
+ const p = records(tenant, workspace);
52
+ if (!p?.async?.stepPut || !p.async.stepList || !p.async.stepDrop)
53
+ return null;
54
+ let on = false;
55
+ try {
56
+ on = p.stepStateOn?.() === true;
57
+ }
58
+ catch {
59
+ on = false;
60
+ }
61
+ return { port: p.async, on };
62
+ }
63
+ /** One row per file, keyed by its path's hash: two steps of the run saving at
64
+ * once (a parallel group on two workers) each write their own rows, never
65
+ * one index over the other (Codex review). */
66
+ const refOf = (rel) => sha256Hex(Buffer.from(rel)).slice(0, 40);
67
+ function snapshot(dir) {
68
+ const m = new Map();
69
+ for (const f of walk(dir))
70
+ m.set(f.rel, { sha: sha256Hex(fs.readFileSync(f.abs)), mtimeMs: fs.statSync(f.abs).mtimeMs });
71
+ return m;
72
+ }
73
+ export async function saveTestWrites(tenant, workspace, runId, dir, start) {
74
+ const deps = revisionBackend();
75
+ const rp = rowsPort(tenant, workspace);
76
+ if (!deps || !rp)
77
+ return 0;
78
+ const { port, on } = rp;
79
+ const prior = new Map((await port.stepList(tenant, workspace, runId, KIND)).map((r) => [r.data.path, r.data]));
80
+ let saved = 0;
81
+ for (const f of walk(dir)) {
82
+ const st = fs.statSync(f.abs);
83
+ const was = prior.get(f.rel);
84
+ if (!on) {
85
+ // Rows switched off: the folder is the record; an old row for this file
86
+ // goes, so it is never restored over the newer one.
87
+ if (was && (was.size !== st.size || was.sha !== sha256Hex(fs.readFileSync(f.abs))))
88
+ await port.stepDrop(tenant, workspace, runId, KIND, refOf(f.rel));
89
+ continue;
90
+ }
91
+ if (st.size > MAX_FILE) {
92
+ // Not kept elsewhere, so the step fails rather than let an older copy
93
+ // come back over it on the next step (Codex review).
94
+ throw new Error(`a test run's diverted file is over ${MAX_FILE / 1024 / 1024} MiB and cannot be kept for the next step`);
95
+ }
96
+ const bytes = fs.readFileSync(f.abs);
97
+ const sha = sha256Hex(bytes);
98
+ if (was && was.sha === sha && was.mtimeMs === st.mtimeMs)
99
+ continue; // a newer time with the same bytes counts
100
+ const atStart = start?.get(f.rel);
101
+ // Unchanged by this attempt AND already kept: another step's newer copy
102
+ // stays; a file never kept (the store switched on mid-run) is kept now.
103
+ if (was && atStart && atStart.sha === sha && atStart.mtimeMs === st.mtimeMs)
104
+ continue;
105
+ if (was?.sha !== sha) {
106
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
107
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes);
108
+ }
109
+ await port.stepPut(tenant, workspace, runId, KIND, refOf(f.rel), { path: f.rel, sha, size: bytes.length, mtimeMs: st.mtimeMs });
110
+ knownOf(dir).set(f.rel, sha);
111
+ saved++;
112
+ }
113
+ return saved;
114
+ }
115
+ /** Before a step: what the rows name and this worker's folder lacks (or has
116
+ * at another time). Throws: a step must not run without what earlier steps wrote. */
117
+ export async function restoreTestWrites(tenant, workspace, runId, dir) {
118
+ const deps = revisionBackend();
119
+ const rp = rowsPort(tenant, workspace);
120
+ if (!deps || !rp)
121
+ return { restored: 0, start: new Map() }; // nothing kept elsewhere: nothing to compare (a laptop hashes nothing)
122
+ const { port } = rp;
123
+ let n = 0;
124
+ for (const row of await port.stepList(tenant, workspace, runId, KIND)) {
125
+ const f = row.data;
126
+ if (typeof f?.path !== "string" || refOf(f.path) !== row.ref)
127
+ continue;
128
+ const abs = path.resolve(dir, f.path);
129
+ if (!abs.startsWith(path.resolve(dir) + path.sep))
130
+ continue; // names stay inside the folder
131
+ const t = new Date(f.mtimeMs);
132
+ const known = knownOf(dir);
133
+ if (fs.existsSync(abs)) {
134
+ const local = sha256Hex(fs.readFileSync(abs));
135
+ if (local === f.sha) {
136
+ known.set(f.path, f.sha);
137
+ if (Math.round(fs.statSync(abs).mtimeMs) !== Math.round(f.mtimeMs))
138
+ fs.utimesSync(abs, t, t);
139
+ continue;
140
+ }
141
+ // Changed here since this process last brought or saved it: another
142
+ // step of the run wrote it and has not saved yet — kept (Codex review).
143
+ // No record at all (a restart: no step of this process is mid-write)
144
+ // means a stale copy, refreshed from the rows.
145
+ const was = known.get(f.path);
146
+ if (was !== undefined && local !== was)
147
+ continue;
148
+ }
149
+ const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
150
+ if (sha256Hex(bytes) !== f.sha)
151
+ throw new Error("a diverted file's object does not hash to its name — refused");
152
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
153
+ fs.writeFileSync(abs, bytes);
154
+ fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
155
+ known.set(f.path, f.sha);
156
+ n++;
157
+ }
158
+ return { restored: n, start: snapshot(dir) };
159
+ }
160
+ /** A run deleted: its diverted files' pins and row go. */
161
+ registerRunRemovedHook((tenant, workspace, runId) => {
162
+ for (const dir of [...KNOWN.keys()])
163
+ if (dir.includes(`${path.sep}runs${path.sep}${runId}${path.sep}`))
164
+ KNOWN.delete(dir);
165
+ const deps = revisionBackend();
166
+ void (async () => {
167
+ await deps?.pins?.release(tenant, holderOf(runId));
168
+ await dropStepState(tenant, workspace, runId, KIND, null);
169
+ })().catch((err) => opsError("test_writes.release_failed", err, { tenant, workspace, runId }, "warn"));
170
+ }, "test-writes");
@@ -1616,7 +1616,7 @@ async function syncNow(tenant, workspace) {
1616
1616
  return "skipped"; // a write landed meanwhile: next round
1617
1617
  const bytes = await blobBytes(deps, tenant, e.sha);
1618
1618
  if (!bytes)
1619
- throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
1619
+ throw new Error(`revisions: blob ${e.sha.slice(0, 12)} is missing`); // no file path: ops lines carry no customer content
1620
1620
  const abs = path.join(dir, p);
1621
1621
  // Never through a link: a folder on the way that is a symlink could lead
1622
1622
  // outside the workspace (Codex review). Such a path is left as it is.
@@ -1725,11 +1725,21 @@ export async function syncAllFromHeads() {
1725
1725
  }
1726
1726
  // ------------------------------------------------------------- reading
1727
1727
  async function blobBytes(deps, tenant, sha) {
1728
+ // An object is named by its content: bytes that do not hash to the name
1729
+ // (corruption, or a store someone wrote to) are refused — never written into
1730
+ // a pod's copy, staged into a run or served (FOL-126 security review).
1731
+ const checked = (b, from) => {
1732
+ if (sha256Hex(b) !== sha) {
1733
+ opsError("revisions.blob_mismatch", new Error(`blob ${sha.slice(0, 12)} does not hash to its name`), { tenant, surface: from });
1734
+ throw new Error(`revisions: blob ${sha.slice(0, 12)}… does not hash to its name — refused`);
1735
+ }
1736
+ return b;
1737
+ };
1728
1738
  const hit = await S.cache?.get(tenant, sha);
1729
1739
  if (hit)
1730
- return hit;
1740
+ return checked(hit, "cache");
1731
1741
  try {
1732
- const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1742
+ const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
1733
1743
  void S.cache?.put(tenant, sha, b).catch(() => { });
1734
1744
  return b;
1735
1745
  }
@@ -1907,6 +1917,9 @@ const view = {
1907
1917
  read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1908
1918
  snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1909
1919
  get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1920
+ // guarded() answers null whenever the journal is off; reads too, for a
1921
+ // pod that keeps no history of its own (history.ts storeServes).
1922
+ on: () => revisionReadsOn(),
1910
1923
  };
1911
1924
  // ------------------------------------------------------------- reads through heads
1912
1925
  /** One workspace file, from its head when reads through revisions are on and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "22.2.0",
3
+ "version": "22.4.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/history.ts CHANGED
@@ -39,6 +39,7 @@ import { processState } from "./process-state.ts";
39
39
  import path from "node:path";
40
40
  import crypto from "node:crypto";
41
41
  import { dataRoot } from "./paths.ts";
42
+ import { mirrorOn } from "./mirror-base.ts";
42
43
 
43
44
  /**
44
45
  * The current tree of a scope, so the first commit can be a full import.
@@ -203,6 +204,23 @@ export function recordRevision(
203
204
  const changed = files.filter((f) => f.before !== f.after);
204
205
  if (changed.length === 0) return null;
205
206
 
207
+ // A pod whose folders are a copy of the heads (revisions.mirror): the
208
+ // revisions store is the history, and this disk is a cache that goes with
209
+ // the pod. A local record and snapshot per save only filled it (FOL-126,
210
+ // 13 Nov 2026) — nothing reads one that is newer than the store's rows.
211
+ if (mirrorOn() && storeServes()) {
212
+ if (meta.commit) assertCommitId(meta.commit);
213
+ const at = new Date().toISOString();
214
+ const by = meta.by ?? "system";
215
+ const message = meta.message ?? describe(changed);
216
+ try {
217
+ REG.journal!(tenant, scope, changed, { by, message, at });
218
+ } catch {
219
+ // the revision store is not allowed to break a save; workspace-revisions logs and retries
220
+ }
221
+ return { id: meta.id ?? newRevisionId(), at, by, message, commit: meta.commit ?? null, files: changed.map((f) => ({ path: f.path, before: clip(f.before), after: clip(f.after) })) };
222
+ }
223
+
206
224
  const dir = historyDir(tenant, scope);
207
225
  fs.mkdirSync(dir, { recursive: true });
208
226
  // A commit is the revision's id only the first time it is recorded. A
@@ -559,7 +577,7 @@ export function latestRevisionIdLocal(tenant: string, scope: string): string | n
559
577
  // install with the journal off) or a workspace has no revisions yet, the
560
578
  // local `.history/` answers, exactly as before; where both exist the list is
561
579
  // the revisions followed by the older local entries, so turning revisions on
562
- // loses no history. The account shelf ("@library") is never in revisions.
580
+ // loses no history. The account shelf ("@library") is read through viewFor.
563
581
 
564
582
  export interface RevisionView {
565
583
  /** Newest first, or null when revisions do not serve this scope. Every page
@@ -571,11 +589,63 @@ export interface RevisionView {
571
589
  /** One revision by id, looked up rather than listed (paths []); null when
572
590
  * the store has none. Optional: a view without it is asked through `list`. */
573
591
  get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
592
+ /** Whether the store serves history right now (its journal and reads on).
593
+ * A view without it is taken as serving. */
594
+ on?(): boolean;
595
+ }
596
+ /** The store is the history: registered, journalling and read (Codex review). */
597
+ function storeServes(): boolean {
598
+ if (!REG.view || !REG.journal) return false;
599
+ try {
600
+ return REG.view.on ? REG.view.on() === true : true;
601
+ } catch {
602
+ return false;
603
+ }
574
604
  }
575
605
  export function registerRevisionView(v: RevisionView | null) {
576
606
  REG.view = v;
577
607
  }
578
608
 
609
+ // The account shelf ("@library") in the store: its folder is the account's,
610
+ // so its revisions name `library/<kind>/<file>` and the account's AGENTS.md
611
+ // beside them; its own history names `<kind>/<file>` (library.ts). Read
612
+ // through this, the shelf's history is the store's like any workspace's
613
+ // (FOL-126, 13 Nov 2026 — until then it was each pod's own .history, which
614
+ // a pod on its own disk does not keep). AGENTS.md is not on the shelf: it is
615
+ // left out, and a revision that changed only it is not a shelf revision.
616
+ const SHELF = "library/";
617
+ const onShelf = (p: string) => p.startsWith(SHELF);
618
+ const shelfPath = (p: string) => p.slice(SHELF.length);
619
+ function viewFor(scope: string): RevisionView | null {
620
+ const v = REG.view;
621
+ if (!v || scope !== "@library") return v;
622
+ return {
623
+ async list(tenant, s, opts) {
624
+ const want = opts.limit ?? 200;
625
+ const withPaths = opts.paths !== false || !!opts.forPath;
626
+ // A revision that changed only the account's AGENTS.md is dropped
627
+ // after the store's limit was spent on it: ask for more until `want`
628
+ // shelf revisions are found or history ends (Codex review).
629
+ for (let ask = want; ; ask = Math.min(ask * 4, Number.MAX_SAFE_INTEGER)) {
630
+ const rows = await v.list(tenant, s, { ...opts, limit: ask, ...(opts.forPath ? { forPath: SHELF + opts.forPath } : {}) });
631
+ if (!rows) return null;
632
+ const mine = rows.map((r) => ({ ...r, paths: r.paths.filter(onShelf).map(shelfPath) })).filter((r) => !withPaths || r.paths.length > 0);
633
+ if (mine.length >= want || rows.length < ask || !Number.isFinite(want) || ask >= Number.MAX_SAFE_INTEGER) return mine.slice(0, want);
634
+ }
635
+ },
636
+ async read(tenant, s, id, forPath) {
637
+ const r = await v.read(tenant, s, id, forPath === undefined ? undefined : SHELF + forPath);
638
+ return r && { ...r, files: r.files.filter((f) => onShelf(f.path)).map((f) => ({ ...f, path: shelfPath(f.path) })) };
639
+ },
640
+ async snapshot(tenant, s, id) {
641
+ const files = await v.snapshot(tenant, s, id);
642
+ return files && files.filter((f) => onShelf(f.path)).map((f) => ({ ...f, path: shelfPath(f.path) }));
643
+ },
644
+ ...(v.get ? { get: (tenant: string, s: string, id: string) => v.get!(tenant, s, id) } : {}),
645
+ ...(v.on ? { on: () => v.on!() } : {}),
646
+ };
647
+ }
648
+
579
649
  /** Revisions first, then the local entries older than the oldest of them.
580
650
  * `stored` is which rows came from the store (every one a restore point). */
581
651
  async function combinedRows(
@@ -587,7 +657,8 @@ async function combinedRows(
587
657
  const limit = opts.limit ?? 200;
588
658
  // The whole of `limit`, every page of it: the store's first page is not all
589
659
  // of history (FOL-152).
590
- const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
660
+ const view = viewFor(scope);
661
+ const mine = view ? await view.list(tenant, scope, { ...opts, limit }) : null;
591
662
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
592
663
  if (restorableOnly) {
593
664
  const have = snapshotIds(tenant, scope);
@@ -618,24 +689,27 @@ export async function listRevisionsRestorable(tenant: string, scope: string, opt
618
689
 
619
690
  export async function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null> {
620
691
  assertSafeName(id, "revision id");
621
- const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
692
+ const view = viewFor(scope);
693
+ const fromStore = view ? await view.read(tenant, scope, id, forPath) : null;
622
694
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
623
695
  }
624
696
 
625
697
  export async function snapshotAt(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null> {
626
698
  assertSafeName(id, "revision id");
627
- const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
699
+ const view = viewFor(scope);
700
+ const fromStore = view ? await view.snapshot(tenant, scope, id) : null;
628
701
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
629
702
  }
630
703
 
631
704
  export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
632
705
  assertSafeName(id, "revision id");
633
706
  if (hasSnapshotLocal(tenant, scope, id)) return true;
634
- if (!REG.view || scope === "@library") return false;
707
+ const view = viewFor(scope);
708
+ if (!view) return false;
635
709
  // Looked up by id: a listing stops at a page, and a revision older than it
636
710
  // was "not restorable" until 9 Nov 2026 (FOL-152).
637
- if (REG.view.get) return (await REG.view.get(tenant, scope, id)) !== null;
638
- return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
711
+ if (view.get) return (await view.get(tenant, scope, id)) !== null;
712
+ return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
639
713
  }
640
714
 
641
715
  export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
@@ -647,8 +721,9 @@ export async function resolveRevision(tenant: string, scope: string, to: string,
647
721
  // An id in the store is one lookup; anything else (a date, a local id, a
648
722
  // commit) is answered from ALL of history — every page of the store, without
649
723
  // the changed paths, then the local entries.
650
- if ("id" in want && REG.view?.get && scope !== "@library") {
651
- const hit = await REG.view.get(tenant, scope, want.id);
724
+ const view = viewFor(scope);
725
+ if ("id" in want && view?.get) {
726
+ const hit = await view.get(tenant, scope, want.id);
652
727
  if (hit) return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
653
728
  }
654
729
  return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
@@ -667,6 +742,9 @@ export async function latestRevisionId(tenant: string, scope: string): Promise<s
667
742
  /** A scope with no revision at all gets a local baseline, as before. */
668
743
  export async function ensureBaseline(tenant: string, scope: string, by = "foldrun"): Promise<string | null> {
669
744
  const head = await headRevision(tenant, scope);
745
+ // A mirrored pod's history is the store's: a baseline on its own disk
746
+ // would be gone with the pod (FOL-126).
747
+ if (!head && mirrorOn() && storeServes()) return null;
670
748
  return head ? head.id : ensureBaselineLocal(tenant, scope, by);
671
749
  }
672
750
 
package/src/records.ts CHANGED
@@ -39,6 +39,8 @@ export interface RecordsPortAsync {
39
39
  * step-state.ts is the only caller. */
40
40
  stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
41
41
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
42
+ /** Every row of one kind for a run (test writes: one row per file). Optional. */
43
+ stepList?(tenant: string, workspace: string, runId: string, kind: string): Promise<{ ref: string; data: unknown }[]>;
42
44
  /** `ref` null: every ref of the kind. */
43
45
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
44
46
  /** The ids of the runs that have rows of this kind in the workspace. */
package/src/runner.ts CHANGED
@@ -134,6 +134,7 @@ import { earlierTurns, conversationBlock, type RunContext, type RunInput } from
134
134
  import { inputsNote, type RunInputFile } from "./run-inputs.ts";
135
135
  import { textCandidates } from "./input-text.ts";
136
136
  import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
137
+ import { restoreTestWrites, saveTestWrites } from "./test-writes-store.ts";
137
138
 
138
139
  export { localDate } from "./clock.ts";
139
140
 
@@ -2823,6 +2824,7 @@ async function runStepBody(
2823
2824
  // The confinement boundary: agents in a workspace are one team, but the
2824
2825
  // workspace is where isolation is enforced.
2825
2826
  const workspaceRoot = path.resolve(agentDir, "..", "..");
2827
+ const workspaceName = path.basename(workspaceRoot);
2826
2828
  // Where a test run's state/ and storage/ writes go, and the line each
2827
2829
  // one leaves: under the run, beside its archived outputs.
2828
2830
  const divertFor = (id: string) => ({
@@ -3619,6 +3621,11 @@ async function runStepBody(
3619
3621
  save();
3620
3622
  }
3621
3623
  let out: Awaited<ReturnType<typeof runIsolated>> | undefined;
3624
+ // A test run's earlier diverted writes, brought back if this worker
3625
+ // does not have them (another worker, a restart: FOL-126).
3626
+ // Not caught: a step must not run without what earlier steps wrote, nor
3627
+ // save an index short of it (Codex review).
3628
+ const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
3622
3629
  try {
3623
3630
  out = await runIsolated(a);
3624
3631
  return out;
@@ -3630,6 +3637,9 @@ async function runStepBody(
3630
3637
  // back to the queue keeps its place in line.
3631
3638
  if (!out?.deferred) step.roomWait = null;
3632
3639
  save();
3640
+ // Last, after the bookkeeping: not caught — a step whose writes were
3641
+ // not kept fails (Codex review).
3642
+ if (testRun && runId && tenant) await saveTestWrites(tenant, workspaceName, runId, divertFor(runId).to, twStart);
3633
3643
  }
3634
3644
  };
3635
3645
  let attemptFrom = step.events.length;
@@ -4037,6 +4047,7 @@ async function runStepBody(
4037
4047
  // sandbox to write instead, and afterwards what changed is moved
4038
4048
  // under the run and the originals come back.
4039
4049
  const attemptThrough = async (modelEnv: Record<string, string | undefined>, spec: TranslatorSpec | null) => {
4050
+ const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
4040
4051
  const before = testRun ? snapshotDivertedDirs(workspaceRoot) : null;
4041
4052
  // What earlier steps of this test run wrote, laid over the real files
4042
4053
  // for this attempt; restoreDivertedDirs puts the originals back.
@@ -4053,6 +4064,7 @@ async function runStepBody(
4053
4064
  if (before && runId) {
4054
4065
  const d = divertFor(runId);
4055
4066
  restoreDivertedDirs(workspaceRoot, before, d.to, d.note, handed ?? before);
4067
+ if (tenant) await saveTestWrites(tenant, workspaceName, runId, d.to, twStart);
4056
4068
  }
4057
4069
  }
4058
4070
  };
package/src/step-state.ts CHANGED
@@ -20,7 +20,7 @@ import fs from "node:fs";
20
20
  import path from "node:path";
21
21
  import { records } from "./records.ts";
22
22
 
23
- export type StepStateKind = "handed-in" | "base" | "storage";
23
+ export type StepStateKind = "handed-in" | "base" | "storage" | "test-writes";
24
24
 
25
25
  const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
26
26
  const okIds = (runId: string, ref: string) => SAFE.test(runId) && (ref === "" || SAFE.test(ref));
@@ -0,0 +1,174 @@
1
+ // A test run's diverted writes, kept off the pod's disk (FOL-126, the shared
2
+ // volume retired): what a test run's steps wrote to state/ and storage/ goes
3
+ // under runs/<id>/test-writes/ on the worker that ran the step, and the next
4
+ // step — on any worker, after any restart — must see it. So after each step
5
+ // the folder's files are put in the blob store (pinned by the run) and listed
6
+ // in one step-state row; before each step the files that row names and the
7
+ // folder lacks are brought back. Without a database or a blob store (a laptop,
8
+ // the CLI) nothing changes: the folder is all there is.
9
+
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { dropStepState } from "./step-state.ts";
13
+ import { records } from "./records.ts";
14
+ import { revisionBackend } from "./workspace-revisions.ts";
15
+ import { blobObjectKey, sha256Hex } from "./manifest.ts";
16
+ import { readAll } from "./blob-types.ts";
17
+ import { registerRunRemovedHook } from "./store.ts";
18
+ import { opsError } from "./ops-log.ts";
19
+ import { processState } from "./process-state.ts";
20
+
21
+ interface Listed {
22
+ sha: string;
23
+ size: number;
24
+ mtimeMs: number;
25
+ }
26
+
27
+ const KIND = "test-writes" as const;
28
+ /** Per run folder on this worker: the version of each file it last brought
29
+ * back or saved. A local file that differs from it is a change not saved yet
30
+ * (another step of the run on this worker); one equal to it is a copy the
31
+ * rows may update. File times never decide this (Codex review). */
32
+ const KNOWN = processState("test-writes-known", () => new Map<string, Map<string, string>>());
33
+ const knownOf = (dir: string) => {
34
+ let m = KNOWN.get(dir);
35
+ if (!m) KNOWN.set(dir, (m = new Map()));
36
+ return m;
37
+ };
38
+ const holderOf = (runId: string) => ({ kind: "run" as const, id: `test-writes:${runId}` });
39
+ /** A diverted file kept whole up to this; a bigger one stays on the worker
40
+ * that wrote it (and is named in the ops line), as before. */
41
+ const MAX_FILE = 64 * 1024 * 1024;
42
+
43
+ function walk(root: string): { rel: string; abs: string }[] {
44
+ const out: { rel: string; abs: string }[] = [];
45
+ if (!fs.existsSync(root)) return out;
46
+ for (const e of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
47
+ if (!e.isFile()) continue; // links and the rest never leave the worker
48
+ const abs = path.join(e.parentPath, e.name);
49
+ out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /** The rows' port (null: a laptop, no records port), and whether new rows
55
+ * are written (`runs.step_state_store`). Rows already there are READ either
56
+ * way, as step state's are (Codex review). */
57
+ function rowsPort(tenant: string, workspace: string) {
58
+ const p = records(tenant, workspace);
59
+ if (!p?.async?.stepPut || !p.async.stepList || !p.async.stepDrop) return null;
60
+ let on = false;
61
+ try {
62
+ on = p.stepStateOn?.() === true;
63
+ } catch {
64
+ on = false;
65
+ }
66
+ return { port: p.async, on };
67
+ }
68
+ /** One row per file, keyed by its path's hash: two steps of the run saving at
69
+ * once (a parallel group on two workers) each write their own rows, never
70
+ * one index over the other (Codex review). */
71
+ const refOf = (rel: string) => sha256Hex(Buffer.from(rel)).slice(0, 40);
72
+
73
+ /** After a step: the run's diverted files into the store, one row each.
74
+ * Throws: a step whose writes were not kept must not count as done. */
75
+ /** What the folder held when an attempt started (restoreTestWrites' answer):
76
+ * a save writes only what the attempt changed from it, so a file another
77
+ * step changed meanwhile on another worker is never written back stale
78
+ * (Codex review). */
79
+ export type TestWritesStart = Map<string, { sha: string; mtimeMs: number }>;
80
+
81
+ function snapshot(dir: string): TestWritesStart {
82
+ const m: TestWritesStart = new Map();
83
+ for (const f of walk(dir)) m.set(f.rel, { sha: sha256Hex(fs.readFileSync(f.abs)), mtimeMs: fs.statSync(f.abs).mtimeMs });
84
+ return m;
85
+ }
86
+
87
+ export async function saveTestWrites(tenant: string, workspace: string, runId: string, dir: string, start?: TestWritesStart): Promise<number> {
88
+ const deps = revisionBackend();
89
+ const rp = rowsPort(tenant, workspace);
90
+ if (!deps || !rp) return 0;
91
+ const { port, on } = rp;
92
+ const prior = new Map((await port.stepList!(tenant, workspace, runId, KIND)).map((r) => [(r.data as Listed & { path: string }).path, r.data as Listed]));
93
+ let saved = 0;
94
+ for (const f of walk(dir)) {
95
+ const st = fs.statSync(f.abs);
96
+ const was = prior.get(f.rel);
97
+ if (!on) {
98
+ // Rows switched off: the folder is the record; an old row for this file
99
+ // goes, so it is never restored over the newer one.
100
+ if (was && (was.size !== st.size || was.sha !== sha256Hex(fs.readFileSync(f.abs)))) await port.stepDrop!(tenant, workspace, runId, KIND, refOf(f.rel));
101
+ continue;
102
+ }
103
+ if (st.size > MAX_FILE) {
104
+ // Not kept elsewhere, so the step fails rather than let an older copy
105
+ // come back over it on the next step (Codex review).
106
+ throw new Error(`a test run's diverted file is over ${MAX_FILE / 1024 / 1024} MiB and cannot be kept for the next step`);
107
+ }
108
+ const bytes = fs.readFileSync(f.abs);
109
+ const sha = sha256Hex(bytes);
110
+ if (was && was.sha === sha && was.mtimeMs === st.mtimeMs) continue; // a newer time with the same bytes counts
111
+ const atStart = start?.get(f.rel);
112
+ // Unchanged by this attempt AND already kept: another step's newer copy
113
+ // stays; a file never kept (the store switched on mid-run) is kept now.
114
+ if (was && atStart && atStart.sha === sha && atStart.mtimeMs === st.mtimeMs) continue;
115
+ if (was?.sha !== sha) {
116
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
117
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes);
118
+ }
119
+ await port.stepPut!(tenant, workspace, runId, KIND, refOf(f.rel), { path: f.rel, sha, size: bytes.length, mtimeMs: st.mtimeMs });
120
+ knownOf(dir).set(f.rel, sha);
121
+ saved++;
122
+ }
123
+ return saved;
124
+ }
125
+
126
+ /** Before a step: what the rows name and this worker's folder lacks (or has
127
+ * at another time). Throws: a step must not run without what earlier steps wrote. */
128
+ export async function restoreTestWrites(tenant: string, workspace: string, runId: string, dir: string): Promise<{ restored: number; start: TestWritesStart }> {
129
+ const deps = revisionBackend();
130
+ const rp = rowsPort(tenant, workspace);
131
+ if (!deps || !rp) return { restored: 0, start: new Map() }; // nothing kept elsewhere: nothing to compare (a laptop hashes nothing)
132
+ const { port } = rp;
133
+ let n = 0;
134
+ for (const row of await port.stepList!(tenant, workspace, runId, KIND)) {
135
+ const f = row.data as Listed & { path: string };
136
+ if (typeof f?.path !== "string" || refOf(f.path) !== row.ref) continue;
137
+ const abs = path.resolve(dir, f.path);
138
+ if (!abs.startsWith(path.resolve(dir) + path.sep)) continue; // names stay inside the folder
139
+ const t = new Date(f.mtimeMs);
140
+ const known = knownOf(dir);
141
+ if (fs.existsSync(abs)) {
142
+ const local = sha256Hex(fs.readFileSync(abs));
143
+ if (local === f.sha) {
144
+ known.set(f.path, f.sha);
145
+ if (Math.round(fs.statSync(abs).mtimeMs) !== Math.round(f.mtimeMs)) fs.utimesSync(abs, t, t);
146
+ continue;
147
+ }
148
+ // Changed here since this process last brought or saved it: another
149
+ // step of the run wrote it and has not saved yet — kept (Codex review).
150
+ // No record at all (a restart: no step of this process is mid-write)
151
+ // means a stale copy, refreshed from the rows.
152
+ const was = known.get(f.path);
153
+ if (was !== undefined && local !== was) continue;
154
+ }
155
+ const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
156
+ if (sha256Hex(bytes) !== f.sha) throw new Error("a diverted file's object does not hash to its name — refused");
157
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
158
+ fs.writeFileSync(abs, bytes);
159
+ fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
160
+ known.set(f.path, f.sha);
161
+ n++;
162
+ }
163
+ return { restored: n, start: snapshot(dir) };
164
+ }
165
+
166
+ /** A run deleted: its diverted files' pins and row go. */
167
+ registerRunRemovedHook((tenant, workspace, runId) => {
168
+ for (const dir of [...KNOWN.keys()]) if (dir.includes(`${path.sep}runs${path.sep}${runId}${path.sep}`)) KNOWN.delete(dir);
169
+ const deps = revisionBackend();
170
+ void (async () => {
171
+ await deps?.pins?.release(tenant, holderOf(runId));
172
+ await dropStepState(tenant, workspace, runId, KIND, null);
173
+ })().catch((err) => opsError("test_writes.release_failed", err, { tenant, workspace, runId }, "warn"));
174
+ }, "test-writes");
@@ -1642,7 +1642,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1642
1642
  }
1643
1643
  if (busy()) return "skipped"; // a write landed meanwhile: next round
1644
1644
  const bytes = await blobBytes(deps, tenant, e.sha);
1645
- if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
1645
+ if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)} is missing`); // no file path: ops lines carry no customer content
1646
1646
  const abs = path.join(dir, p);
1647
1647
  // Never through a link: a folder on the way that is a symlink could lead
1648
1648
  // outside the workspace (Codex review). Such a path is left as it is.
@@ -1742,10 +1742,20 @@ export async function syncAllFromHeads(): Promise<{ synced: number; removed: num
1742
1742
  // ------------------------------------------------------------- reading
1743
1743
 
1744
1744
  async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {
1745
+ // An object is named by its content: bytes that do not hash to the name
1746
+ // (corruption, or a store someone wrote to) are refused — never written into
1747
+ // a pod's copy, staged into a run or served (FOL-126 security review).
1748
+ const checked = (b: Buffer, from: string): Buffer => {
1749
+ if (sha256Hex(b) !== sha) {
1750
+ opsError("revisions.blob_mismatch", new Error(`blob ${sha.slice(0, 12)} does not hash to its name`), { tenant, surface: from });
1751
+ throw new Error(`revisions: blob ${sha.slice(0, 12)}… does not hash to its name — refused`);
1752
+ }
1753
+ return b;
1754
+ };
1745
1755
  const hit = await S.cache?.get(tenant, sha);
1746
- if (hit) return hit;
1756
+ if (hit) return checked(hit, "cache");
1747
1757
  try {
1748
- const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1758
+ const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
1749
1759
  void S.cache?.put(tenant, sha, b).catch(() => {});
1750
1760
  return b;
1751
1761
  } catch (err) {
@@ -1912,6 +1922,9 @@ const view: RevisionView = {
1912
1922
  read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1913
1923
  snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1914
1924
  get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1925
+ // guarded() answers null whenever the journal is off; reads too, for a
1926
+ // pod that keeps no history of its own (history.ts storeServes).
1927
+ on: () => revisionReadsOn(),
1915
1928
  };
1916
1929
 
1917
1930
  // ------------------------------------------------------------- reads through heads