@foldrun/core 22.1.0 → 22.3.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.
@@ -22,6 +22,16 @@ export declare function callSink(owner: object, ctx: Ctx): (part: CapturedCall)
22
22
  export declare function flushCalls(owner: object): Promise<void>;
23
23
  /** One recorded call, or null (not recorded). The row first, then the file. */
24
24
  export declare function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null>;
25
+ /**
26
+ * One call from a run's folder into the store, whatever the switch says
27
+ * (FOL-126: the one-time copy of the runs written before calls went to the
28
+ * store, before the shared volume goes). "stored", "present" (already in the
29
+ * store), or "unavailable": the store is not set up here — never mistaken for
30
+ * present (Codex review).
31
+ */
32
+ export declare function backfillCall(tenant: string, workspace: string, runId: string, call: CapturedCall, opts?: {
33
+ dryRun?: boolean;
34
+ }): Promise<"stored" | "present" | "unavailable">;
25
35
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
26
36
  export declare function settleCalls(): Promise<void>;
27
37
  /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
@@ -179,6 +179,31 @@ export async function readCapturedCallAsync(tenant, workspace, runId, callId) {
179
179
  }
180
180
  return readCapturedCall(tenant, workspace, runId, callId);
181
181
  }
182
+ /**
183
+ * One call from a run's folder into the store, whatever the switch says
184
+ * (FOL-126: the one-time copy of the runs written before calls went to the
185
+ * store, before the shared volume goes). "stored", "present" (already in the
186
+ * store), or "unavailable": the store is not set up here — never mistaken for
187
+ * present (Codex review).
188
+ */
189
+ export async function backfillCall(tenant, workspace, runId, call, opts = {}) {
190
+ const deps = CALLS.backend;
191
+ const port = portFor(tenant, workspace);
192
+ if (!deps || !port)
193
+ return "unavailable";
194
+ if (!SAFE.test(runId) || !SAFE.test(call.id))
195
+ throw new Error(`not a call id: ${call.id}`);
196
+ if (await port.async.stepGet(tenant, workspace, runId, KIND, call.id))
197
+ return "present";
198
+ if (opts.dryRun)
199
+ return "stored"; // would be
200
+ const bytes = Buffer.from(JSON.stringify(call));
201
+ const sha = sha256Hex(bytes);
202
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
203
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes, { contentType: "application/json" });
204
+ await port.async.stepPut(tenant, workspace, runId, KIND, call.id, { sha, size: bytes.length });
205
+ return "stored";
206
+ }
182
207
  // ---------------------------------------------------------------- lifecycle
183
208
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
184
209
  export async function settleCalls() {
@@ -61,7 +61,9 @@ export const MODE_EXEC = 0o755;
61
61
  // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
62
62
  // they differ — the failure is the prompt to decide which side the new folder
63
63
  // is on, and whether that needs manifest v2.
64
- export const AUTHORED_DIRS = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
64
+ // "library": the account's shelf, kept as the scope "@library" whose folder is
65
+ // the account's (account AGENTS.md + library/**, FOL-126); no workspace has one.
66
+ export const AUTHORED_DIRS = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks", "library"];
65
67
  export const STATE_DIRS = ["state"];
66
68
  export const AUTHORED_ROOT_FILES = ["AGENTS.md", "project.md"];
67
69
  /** A conflict copy of a root file (conflictPath) is a root file too. */
@@ -26,7 +26,7 @@ export function mirrorOn() {
26
26
  return false;
27
27
  }
28
28
  }
29
- const SAFE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
29
+ const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
30
30
  export const mirrorBaseFile = (tenant, workspace) => SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
31
31
  export function readMirrorBase(tenant, workspace) {
32
32
  const f = mirrorBaseFile(tenant, workspace);
@@ -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. */
@@ -79,7 +79,8 @@ export function newRevisionId() {
79
79
  export function localRevisionStore(root = path.join(dataRoot(), ".revisions")) {
80
80
  const dirOf = (ws) => {
81
81
  assertSafeName(ws.tenant, "tenant");
82
- assertSafeName(ws.workspace, "workspace");
82
+ if (ws.workspace !== "@library")
83
+ assertSafeName(ws.workspace, "workspace"); // the account shelf's scope
83
84
  // The state head is a separate history in a subfolder of its own; the
84
85
  // workspace head's folder never lists it (seqs reads revs/ only).
85
86
  return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.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");
@@ -39,6 +39,9 @@ export interface BlobCache {
39
39
  put(tenant: string, sha: string, bytes: Buffer): Promise<void>;
40
40
  }
41
41
  export declare function setBlobCache(c: BlobCache | null): void;
42
+ /** The account's AGENTS.md or library changed outside the journal (a route
43
+ * that writes the file itself): publish it, as any other change of a scope. */
44
+ export declare function noteAccountFilesChanged(tenant: string): void;
42
45
  /** One file a step wrote back to the workspace (run-container.ts
43
46
  * applyContainerChanges): `base` is the sha of the folder's copy before the
44
47
  * write (null: new file), `after` the bytes now on the folder. */
@@ -36,7 +36,7 @@ import path from "node:path";
36
36
  import crypto from "node:crypto";
37
37
  import { pipeline } from "node:stream/promises";
38
38
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle } from "./history.js";
39
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.js";
39
+ import { workspaceDir, accountDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.js";
40
40
  import { dataRoot } from "./paths.js";
41
41
  import { processState } from "./process-state.js";
42
42
  import { opsError, opsLog } from "./ops-log.js";
@@ -88,7 +88,7 @@ const entryStore = () => S.primary ?? legacyFiles;
88
88
  export function setRevisionBackend(deps, opts = {}) {
89
89
  // Every commit asks, inside the store's workspace lock, whether the folder is
90
90
  // still there: a delete or rename on another pod removes it under that lock.
91
- S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
91
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
92
92
  S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
93
93
  S.primary = opts.journalStore ?? null;
94
94
  S.retention = opts.stateRetention ?? null;
@@ -139,6 +139,17 @@ const restoring = S.restoring;
139
139
  const key = (tenant, workspace) => `${tenant}\0${workspace}`;
140
140
  const split = (k) => k.split("\0");
141
141
  const journalRoot = () => path.join(dataRoot(), ".revision-journal");
142
+ /** Where a scope's files are: a workspace's folder, or for the account shelf
143
+ * ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
144
+ function folderOf(tenant, workspace) {
145
+ return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
146
+ }
147
+ /** The account's AGENTS.md or library changed outside the journal (a route
148
+ * that writes the file itself): publish it, as any other change of a scope. */
149
+ export function noteAccountFilesChanged(tenant) {
150
+ if (S.backend && journalOn())
151
+ requestReconcile(tenant, "@library");
152
+ }
142
153
  /** Write the entry down, atomically. A store that refuses leaves the entry in
143
154
  * memory only (said once per failure), as the journal always was. */
144
155
  function persist(tenant, workspace, e) {
@@ -164,8 +175,8 @@ function forget(tenant, workspace, e) {
164
175
  /** Called by history.recordRevision for every change set. Synchronous and
165
176
  * cheap; the commit happens in the background (flushRevisions waits for it). */
166
177
  function journalChange(tenant, scope, files, meta) {
167
- if (!S.backend || scope === "@library")
168
- return; // the account shelf is not a workspace
178
+ if (!S.backend)
179
+ return;
169
180
  const k = key(tenant, scope);
170
181
  if (!safe(S.gate.journal)) {
171
182
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
@@ -174,7 +185,9 @@ function journalChange(tenant, scope, files, meta) {
174
185
  }
175
186
  // Only what the head needs: the new content. The old text is the writer's
176
187
  // history record, not the journal's (it can be a quarter megabyte a file).
177
- const slim = files.map((f) => ({ path: f.path, before: null, after: f.after }));
188
+ // The account shelf's paths are `<kind>/<file>` in its own history and
189
+ // `library/<kind>/<file>` in its revisions (its folder is the account's).
190
+ const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
178
191
  enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
179
192
  }
180
193
  function enqueue(tenant, scope, entry) {
@@ -304,7 +317,7 @@ async function drainOne(k) {
304
317
  const entry = q[0];
305
318
  // The workspace was deleted while this waited (or retried): nothing to
306
319
  // publish, and nothing for a later boot to replay.
307
- if (!fs.existsSync(workspaceDir(tenant, workspace))) {
320
+ if (!fs.existsSync(folderOf(tenant, workspace))) {
308
321
  q.shift();
309
322
  forget(tenant, workspace, entry);
310
323
  continue;
@@ -354,7 +367,7 @@ async function drainOne(k) {
354
367
  // journal was off for a while, a run wrote the folder directly) is brought
355
368
  // to it. After the entries, never before: replaying an older change over a
356
369
  // reconciled head would write it backwards.
357
- if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
370
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
358
371
  verified.add(k);
359
372
  try {
360
373
  await reconcileNow(tenant, workspace, "reconcile");
@@ -860,7 +873,7 @@ export async function recoverJournal(opts = {}) {
860
873
  const k = key(tenant, workspace);
861
874
  const q = queues.get(k) ?? [];
862
875
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
863
- const gone = !fs.existsSync(workspaceDir(tenant, workspace));
876
+ const gone = !fs.existsSync(folderOf(tenant, workspace));
864
877
  const found = [];
865
878
  let names = [];
866
879
  try {
@@ -920,7 +933,9 @@ export async function reconcileAll(opts = {}) {
920
933
  if (S.orphanMarks)
921
934
  await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
922
935
  for (const tenant of opts.tenants ?? listTenants()) {
923
- for (const w of listWorkspaces(tenant)) {
936
+ // The account shelf too (account AGENTS.md + library/), as a scope of its own.
937
+ const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
938
+ for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
924
939
  const k = key(tenant, w.name);
925
940
  try {
926
941
  verified.add(k); // reconciled explicitly below, and counted
@@ -972,7 +987,7 @@ async function hashOf(abs, size) {
972
987
  * not be read. Null when the folder is not there.
973
988
  */
974
989
  async function scanFolder(tenant, workspace) {
975
- const dir = workspaceDir(tenant, workspace);
990
+ const dir = folderOf(tenant, workspace);
976
991
  if (!fs.existsSync(dir))
977
992
  return null;
978
993
  const found = [];
@@ -1074,7 +1089,7 @@ async function uploadLarge(deps, tenant, changes, onDisk, opId) {
1074
1089
  }
1075
1090
  function modeOf(tenant, workspace, rel) {
1076
1091
  try {
1077
- return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1092
+ return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1078
1093
  }
1079
1094
  catch {
1080
1095
  return MODE_FILE;
@@ -1309,7 +1324,7 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1309
1324
  // head alone is someone else's change not copied here yet, never undone.
1310
1325
  const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1311
1326
  if (base)
1312
- ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1327
+ ({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
1313
1328
  // A path the scan could not take (unreadable now, a name the manifest
1314
1329
  // refuses) but the folder still holds is neither added nor removed here;
1315
1330
  // one that is gone from the folder is gone from the head.
@@ -1368,7 +1383,7 @@ async function afterPublish(deps, ws, changes, r) {
1368
1383
  const { tenant, workspace } = ws;
1369
1384
  const base = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1370
1385
  const conflicted = new Set(r.conflicts.map((c) => c.path));
1371
- const dir = workspaceDir(tenant, workspace);
1386
+ const dir = folderOf(tenant, workspace);
1372
1387
  let head = null;
1373
1388
  for (const [p, c] of Object.entries(changes)) {
1374
1389
  if (!conflicted.has(p)) {
@@ -1484,7 +1499,7 @@ async function syncNow(tenant, workspace) {
1484
1499
  const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1485
1500
  if (busy())
1486
1501
  return "skipped";
1487
- const dir = workspaceDir(tenant, workspace);
1502
+ const dir = folderOf(tenant, workspace);
1488
1503
  // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1489
1504
  // from the heads: with the old record kept, every file would read as deleted
1490
1505
  // here and the reconcile would publish those deletes (Codex review).
@@ -1499,9 +1514,17 @@ async function syncNow(tenant, workspace) {
1499
1514
  return "absent";
1500
1515
  if (busy())
1501
1516
  return "skipped";
1502
- fs.rmSync(dir, { recursive: true, force: true });
1517
+ if (workspace === "@library") {
1518
+ // The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
1519
+ // never the account folder with every workspace in it (Codex review).
1520
+ fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
1521
+ fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
1522
+ }
1523
+ else
1524
+ fs.rmSync(dir, { recursive: true, force: true });
1503
1525
  dropMirrorBase(tenant, workspace);
1504
- notifyWorkspaceChanged(tenant, workspace, "delete");
1526
+ if (workspace !== "@library")
1527
+ notifyWorkspaceChanged(tenant, workspace, "delete");
1505
1528
  return "removed";
1506
1529
  }
1507
1530
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
@@ -1593,7 +1616,7 @@ async function syncNow(tenant, workspace) {
1593
1616
  return "skipped"; // a write landed meanwhile: next round
1594
1617
  const bytes = await blobBytes(deps, tenant, e.sha);
1595
1618
  if (!bytes)
1596
- 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
1597
1620
  const abs = path.join(dir, p);
1598
1621
  // Never through a link: a folder on the way that is a symlink could lead
1599
1622
  // outside the workspace (Codex review). Such a path is left as it is.
@@ -1642,7 +1665,7 @@ async function syncNow(tenant, workspace) {
1642
1665
  finished = true;
1643
1666
  if (ownChanges)
1644
1667
  requestReconcile(tenant, workspace);
1645
- if (wrote)
1668
+ if (wrote && workspace !== "@library")
1646
1669
  notifyWorkspaceChanged(tenant, workspace, "write");
1647
1670
  return "synced";
1648
1671
  }
@@ -1702,11 +1725,21 @@ export async function syncAllFromHeads() {
1702
1725
  }
1703
1726
  // ------------------------------------------------------------- reading
1704
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
+ };
1705
1738
  const hit = await S.cache?.get(tenant, sha);
1706
1739
  if (hit)
1707
- return hit;
1740
+ return checked(hit, "cache");
1708
1741
  try {
1709
- const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1742
+ const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
1710
1743
  void S.cache?.put(tenant, sha, b).catch(() => { });
1711
1744
  return b;
1712
1745
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "22.1.0",
3
+ "version": "22.3.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",
@@ -189,6 +189,28 @@ export async function readCapturedCallAsync(tenant: string, workspace: string, r
189
189
  return readCapturedCall(tenant, workspace, runId, callId);
190
190
  }
191
191
 
192
+ /**
193
+ * One call from a run's folder into the store, whatever the switch says
194
+ * (FOL-126: the one-time copy of the runs written before calls went to the
195
+ * store, before the shared volume goes). "stored", "present" (already in the
196
+ * store), or "unavailable": the store is not set up here — never mistaken for
197
+ * present (Codex review).
198
+ */
199
+ export async function backfillCall(tenant: string, workspace: string, runId: string, call: CapturedCall, opts: { dryRun?: boolean } = {}): Promise<"stored" | "present" | "unavailable"> {
200
+ const deps = CALLS.backend;
201
+ const port = portFor(tenant, workspace);
202
+ if (!deps || !port) return "unavailable";
203
+ if (!SAFE.test(runId) || !SAFE.test(call.id)) throw new Error(`not a call id: ${call.id}`);
204
+ if (await port.async!.stepGet!(tenant, workspace, runId, KIND, call.id)) return "present";
205
+ if (opts.dryRun) return "stored"; // would be
206
+ const bytes = Buffer.from(JSON.stringify(call));
207
+ const sha = sha256Hex(bytes);
208
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
209
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes, { contentType: "application/json" });
210
+ await port.async!.stepPut!(tenant, workspace, runId, KIND, call.id, { sha, size: bytes.length });
211
+ return "stored";
212
+ }
213
+
192
214
  // ---------------------------------------------------------------- lifecycle
193
215
 
194
216
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
package/src/manifest.ts CHANGED
@@ -89,7 +89,9 @@ export type ManifestId = string;
89
89
  // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
90
90
  // they differ — the failure is the prompt to decide which side the new folder
91
91
  // is on, and whether that needs manifest v2.
92
- export const AUTHORED_DIRS: readonly string[] = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
92
+ // "library": the account's shelf, kept as the scope "@library" whose folder is
93
+ // the account's (account AGENTS.md + library/**, FOL-126); no workspace has one.
94
+ export const AUTHORED_DIRS: readonly string[] = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks", "library"];
93
95
  export const STATE_DIRS: readonly string[] = ["state"];
94
96
  export const AUTHORED_ROOT_FILES: readonly string[] = ["AGENTS.md", "project.md"];
95
97
  /** A conflict copy of a root file (conflictPath) is a root file too. */
@@ -39,7 +39,7 @@ export function mirrorOn(): boolean {
39
39
  }
40
40
  }
41
41
 
42
- const SAFE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
42
+ const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
43
43
  export const mirrorBaseFile = (tenant: string, workspace: string): string | null =>
44
44
  SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
45
45
 
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. */
@@ -249,7 +249,7 @@ export function newRevisionId(): string {
249
249
  export function localRevisionStore(root: string = path.join(dataRoot(), ".revisions")): RevisionStore {
250
250
  const dirOf = (ws: WorkspaceRef) => {
251
251
  assertSafeName(ws.tenant, "tenant");
252
- assertSafeName(ws.workspace, "workspace");
252
+ if (ws.workspace !== "@library") assertSafeName(ws.workspace, "workspace"); // the account shelf's scope
253
253
  // The state head is a separate history in a subfolder of its own; the
254
254
  // workspace head's folder never lists it (seqs reads revs/ only).
255
255
  return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.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");
@@ -37,7 +37,7 @@ import path from "node:path";
37
37
  import crypto from "node:crypto";
38
38
  import { pipeline } from "node:stream/promises";
39
39
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle, type RevisionView, type RevisionFile, type RevisionSummary, type Revision as HistoryRevision } from "./history.ts";
40
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.ts";
40
+ import { workspaceDir, accountDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.ts";
41
41
  import { dataRoot } from "./paths.ts";
42
42
  import { processState } from "./process-state.ts";
43
43
  import { opsError, opsLog } from "./ops-log.ts";
@@ -134,7 +134,7 @@ const entryStore = (): JournalStore => S.primary ?? legacyFiles;
134
134
  export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {}): void {
135
135
  // Every commit asks, inside the store's workspace lock, whether the folder is
136
136
  // still there: a delete or rename on another pod removes it under that lock.
137
- S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
137
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
138
138
  S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
139
139
  S.primary = opts.journalStore ?? null;
140
140
  S.retention = opts.stateRetention ?? null;
@@ -237,6 +237,18 @@ const split = (k: string): [string, string] => k.split("\0") as [string, string]
237
237
 
238
238
  const journalRoot = () => path.join(dataRoot(), ".revision-journal");
239
239
 
240
+ /** Where a scope's files are: a workspace's folder, or for the account shelf
241
+ * ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
242
+ function folderOf(tenant: string, workspace: string): string {
243
+ return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
244
+ }
245
+
246
+ /** The account's AGENTS.md or library changed outside the journal (a route
247
+ * that writes the file itself): publish it, as any other change of a scope. */
248
+ export function noteAccountFilesChanged(tenant: string): void {
249
+ if (S.backend && journalOn()) requestReconcile(tenant, "@library");
250
+ }
251
+
240
252
  /** Write the entry down, atomically. A store that refuses leaves the entry in
241
253
  * memory only (said once per failure), as the journal always was. */
242
254
  function persist(tenant: string, workspace: string, e: Entry): void {
@@ -261,7 +273,7 @@ function forget(tenant: string, workspace: string, e: Entry): void {
261
273
  /** Called by history.recordRevision for every change set. Synchronous and
262
274
  * cheap; the commit happens in the background (flushRevisions waits for it). */
263
275
  function journalChange(tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }): void {
264
- if (!S.backend || scope === "@library") return; // the account shelf is not a workspace
276
+ if (!S.backend) return;
265
277
  const k = key(tenant, scope);
266
278
  if (!safe(S.gate.journal)) {
267
279
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
@@ -270,7 +282,9 @@ function journalChange(tenant: string, scope: string, files: RevisionFile[], met
270
282
  }
271
283
  // Only what the head needs: the new content. The old text is the writer's
272
284
  // history record, not the journal's (it can be a quarter megabyte a file).
273
- const slim = files.map((f) => ({ path: f.path, before: null, after: f.after }));
285
+ // The account shelf's paths are `<kind>/<file>` in its own history and
286
+ // `library/<kind>/<file>` in its revisions (its folder is the account's).
287
+ const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
274
288
  enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
275
289
  }
276
290
 
@@ -417,7 +431,7 @@ async function drainOne(k: string): Promise<void> {
417
431
  const entry = q[0];
418
432
  // The workspace was deleted while this waited (or retried): nothing to
419
433
  // publish, and nothing for a later boot to replay.
420
- if (!fs.existsSync(workspaceDir(tenant, workspace))) {
434
+ if (!fs.existsSync(folderOf(tenant, workspace))) {
421
435
  q.shift();
422
436
  forget(tenant, workspace, entry);
423
437
  continue;
@@ -463,7 +477,7 @@ async function drainOne(k: string): Promise<void> {
463
477
  // journal was off for a while, a run wrote the folder directly) is brought
464
478
  // to it. After the entries, never before: replaying an older change over a
465
479
  // reconciled head would write it backwards.
466
- if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
480
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
467
481
  verified.add(k);
468
482
  try {
469
483
  await reconcileNow(tenant, workspace, "reconcile");
@@ -954,7 +968,7 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
954
968
  const k = key(tenant, workspace);
955
969
  const q = queues.get(k) ?? [];
956
970
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
957
- const gone = !fs.existsSync(workspaceDir(tenant, workspace));
971
+ const gone = !fs.existsSync(folderOf(tenant, workspace));
958
972
  const found: Entry[] = [];
959
973
  let names: { handle: string; ageMs: number }[] = [];
960
974
  try {
@@ -1006,7 +1020,9 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
1006
1020
  // workspace of the same name.
1007
1021
  if (S.orphanMarks) await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
1008
1022
  for (const tenant of opts.tenants ?? listTenants()) {
1009
- for (const w of listWorkspaces(tenant)) {
1023
+ // The account shelf too (account AGENTS.md + library/), as a scope of its own.
1024
+ const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
1025
+ for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
1010
1026
  const k = key(tenant, w.name);
1011
1027
  try {
1012
1028
  verified.add(k); // reconciled explicitly below, and counted
@@ -1066,7 +1082,7 @@ async function hashOf(abs: string, size: number): Promise<string> {
1066
1082
  * not be read. Null when the folder is not there.
1067
1083
  */
1068
1084
  async function scanFolder(tenant: string, workspace: string): Promise<{ files: Map<string, FolderFile>; left: Set<string> } | null> {
1069
- const dir = workspaceDir(tenant, workspace);
1085
+ const dir = folderOf(tenant, workspace);
1070
1086
  if (!fs.existsSync(dir)) return null;
1071
1087
  const found: { rel: string; abs: string; st: fs.Stats }[] = [];
1072
1088
  const left = new Set<string>();
@@ -1151,7 +1167,7 @@ async function uploadLarge(deps: Deps, tenant: string, changes: Changes, onDisk:
1151
1167
 
1152
1168
  function modeOf(tenant: string, workspace: string, rel: string): number {
1153
1169
  try {
1154
- return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1170
+ return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1155
1171
  } catch {
1156
1172
  return MODE_FILE;
1157
1173
  }
@@ -1371,7 +1387,7 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1371
1387
  // differs from the last sync is this pod's change. A difference from the
1372
1388
  // head alone is someone else's change not copied here yet, never undone.
1373
1389
  const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1374
- if (base) ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1390
+ if (base) ({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
1375
1391
  // A path the scan could not take (unreadable now, a name the manifest
1376
1392
  // refuses) but the folder still holds is neither added nor removed here;
1377
1393
  // one that is gone from the folder is gone from the head.
@@ -1423,7 +1439,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1423
1439
  const { tenant, workspace } = ws;
1424
1440
  const base: MirrorBase = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1425
1441
  const conflicted = new Set(r.conflicts.map((c) => c.path));
1426
- const dir = workspaceDir(tenant, workspace);
1442
+ const dir = folderOf(tenant, workspace);
1427
1443
  let head: Record<string, ManifestEntry> | null = null;
1428
1444
  for (const [p, c] of Object.entries(changes)) {
1429
1445
  if (!conflicted.has(p)) {
@@ -1524,7 +1540,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1524
1540
  const k = key(tenant, workspace);
1525
1541
  const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1526
1542
  if (busy()) return "skipped";
1527
- const dir = workspaceDir(tenant, workspace);
1543
+ const dir = folderOf(tenant, workspace);
1528
1544
  // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1529
1545
  // from the heads: with the old record kept, every file would read as deleted
1530
1546
  // here and the reconcile would publish those deletes (Codex review).
@@ -1537,9 +1553,14 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1537
1553
  if (!heads.workspace && !heads.state) {
1538
1554
  if (!base) return "absent";
1539
1555
  if (busy()) return "skipped";
1540
- fs.rmSync(dir, { recursive: true, force: true });
1556
+ if (workspace === "@library") {
1557
+ // The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
1558
+ // never the account folder with every workspace in it (Codex review).
1559
+ fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
1560
+ fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
1561
+ } else fs.rmSync(dir, { recursive: true, force: true });
1541
1562
  dropMirrorBase(tenant, workspace);
1542
- notifyWorkspaceChanged(tenant, workspace, "delete");
1563
+ if (workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "delete");
1543
1564
  return "removed";
1544
1565
  }
1545
1566
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
@@ -1621,7 +1642,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1621
1642
  }
1622
1643
  if (busy()) return "skipped"; // a write landed meanwhile: next round
1623
1644
  const bytes = await blobBytes(deps, tenant, e.sha);
1624
- 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
1625
1646
  const abs = path.join(dir, p);
1626
1647
  // Never through a link: a folder on the way that is a symlink could lead
1627
1648
  // outside the workspace (Codex review). Such a path is left as it is.
@@ -1666,7 +1687,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1666
1687
  writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
1667
1688
  finished = true;
1668
1689
  if (ownChanges) requestReconcile(tenant, workspace);
1669
- if (wrote) notifyWorkspaceChanged(tenant, workspace, "write");
1690
+ if (wrote && workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "write");
1670
1691
  return "synced";
1671
1692
  } finally {
1672
1693
  if (!finished && touched) writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });
@@ -1721,10 +1742,20 @@ export async function syncAllFromHeads(): Promise<{ synced: number; removed: num
1721
1742
  // ------------------------------------------------------------- reading
1722
1743
 
1723
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
+ };
1724
1755
  const hit = await S.cache?.get(tenant, sha);
1725
- if (hit) return hit;
1756
+ if (hit) return checked(hit, "cache");
1726
1757
  try {
1727
- const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
1758
+ const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
1728
1759
  void S.cache?.put(tenant, sha, b).catch(() => {});
1729
1760
  return b;
1730
1761
  } catch (err) {