@foldrun/core 21.1.0 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { type CapturedCall } from "./store.ts";
1
2
  import type { CallIo } from "./step-exec.ts";
2
3
  /** How much past the cap a step sends, so masking sees a secret whole
3
4
  * before the cut (a value longer than this is a file secret, which is also
@@ -21,9 +22,5 @@ export declare function maskCall(text: string, redactSecrets: (text: string) =>
21
22
  export declare function recordCallIo(workspaceRoot: string, runId: string, callId: string, tool: string, io: CallIo,
22
23
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
23
24
  redactSecrets: (text: string) => string,
24
- /** Whose run it is: with it the call is kept where the platform keeps a
25
- * workspace's small state (rows), without it beside the run as a file. */
26
- scope?: {
27
- tenant: string;
28
- workspace: string;
29
- }): boolean;
25
+ /** Where the part goes instead of the file beside the run (captured-calls.ts). */
26
+ sink?: (part: CapturedCall) => boolean): boolean;
@@ -98,13 +98,12 @@ export function maskCall(text, redactSecrets) {
98
98
  export function recordCallIo(workspaceRoot, runId, callId, tool, io,
99
99
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
100
100
  redactSecrets,
101
- /** Whose run it is: with it the call is kept where the platform keeps a
102
- * workspace's small state (rows), without it beside the run as a file. */
103
- scope) {
101
+ /** Where the part goes instead of the file beside the run (captured-calls.ts). */
102
+ sink) {
104
103
  try {
105
104
  const input = io.input === undefined ? null : maskCall(io.input, redactSecrets);
106
105
  const output = io.output === undefined ? null : maskCall(io.output, redactSecrets);
107
- writeCapturedCall(workspaceRoot, runId, {
106
+ const part = {
108
107
  id: callId,
109
108
  tool,
110
109
  // Which part was cut, each on its own: in the sandbox (the whole was
@@ -112,7 +111,10 @@ scope) {
112
111
  ...(input ? { input: input.text, ...(io.inputChars !== undefined ? { inputChars: io.inputChars } : {}), ...(input.cut || (io.inputChars ?? 0) > io.input.length ? { inputCut: true } : {}) } : {}),
113
112
  ...(output ? { output: output.text, ...(io.outputChars !== undefined ? { outputChars: io.outputChars } : {}), ...(output.cut || (io.outputChars ?? 0) > io.output.length ? { outputCut: true } : {}) } : {}),
114
113
  ...(io.truncated || input?.cut || output?.cut ? { truncated: true } : {}),
115
- }, scope);
114
+ };
115
+ if (sink)
116
+ return sink(part);
117
+ writeCapturedCall(workspaceRoot, runId, part);
116
118
  return true;
117
119
  }
118
120
  catch (err) {
@@ -0,0 +1,30 @@
1
+ import type { Deps } from "./publish.ts";
2
+ import { type CapturedCall } from "./store.ts";
3
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
4
+ export declare function setCallsBackend(deps: Deps | null): void;
5
+ /** The call could not be read back from where it was recorded. */
6
+ export declare class CapturedCallUnavailable extends Error {
7
+ constructor(callId: string, cause?: unknown);
8
+ }
9
+ interface Ctx {
10
+ tenant: string;
11
+ workspace: string;
12
+ runId: string;
13
+ workspaceRoot: string;
14
+ }
15
+ /**
16
+ * The runner's place to put a call's part (input on the call, output on its
17
+ * completion). Returns whether it was taken (the event says `captured`).
18
+ * `owner` is the step: flushCalls(owner) settles what it left.
19
+ */
20
+ export declare function callSink(owner: object, ctx: Ctx): (part: CapturedCall) => boolean;
21
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
22
+ export declare function flushCalls(owner: object): Promise<void>;
23
+ /** One recorded call, or null (not recorded). The row first, then the file. */
24
+ export declare function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null>;
25
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
26
+ export declare function settleCalls(): Promise<void>;
27
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
28
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
29
+ export declare function dropWorkspaceCalls(tenant: string, workspace: string): Promise<void>;
30
+ export {};
@@ -0,0 +1,219 @@
1
+ // Captured tool calls in the blob store (FOL-126 phase 7, step 2).
2
+ //
3
+ // A call's masked input and output used to be a file beside its run
4
+ // (runs/<run>/calls/<call>.json — store.ts writeCapturedCall), merged in place
5
+ // when the output arrived. With a database, a blob store and the setting
6
+ // `runs.calls_store` on, each call is ONE blob, written once when the call
7
+ // completes (the input waits in memory for its output: no read-merge-write),
8
+ // pinned by a run holder (`calls:<run>`, no lease — it lives until the run is
9
+ // deleted) before the upload, and indexed by a step-state row (kind "call",
10
+ // ref = the call id → {sha, size}). Masking is capture.ts's and is done before
11
+ // anything gets here; a part over the cap was cut and flagged there.
12
+ //
13
+ // Reads look at the row first, then at the file, so every run stays readable
14
+ // whichever way the switch is set. A row whose blob cannot be read is an error
15
+ // (CapturedCallUnavailable), never "nothing recorded".
16
+ //
17
+ // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
+ // (store down, database refuses) falls back to the volume file and logs
19
+ // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
+ // recorded, and the event says so".
21
+ import { records } from "./records.js";
22
+ import { blobObjectKey, sha256Hex } from "./manifest.js";
23
+ import { opsError } from "./ops-log.js";
24
+ import { BlobNotFound, readAll } from "./blob-store.js";
25
+ import { writeCapturedCall, readCapturedCall, registerRunRemovedHook } from "./store.js";
26
+ import { processState } from "./process-state.js";
27
+ const KIND = "call";
28
+ const SAFE = /^[A-Za-z0-9_.-]{1,128}$/;
29
+ const holderOf = (runId) => ({ kind: "run", id: `calls:${runId}` });
30
+ /** One per process (process-state.ts): the store the boot registered and the
31
+ * clean-ups in flight, whichever copy of this module a route handler holds. */
32
+ const CALLS = processState("captured-calls", () => ({ backend: null, background: new Set() }));
33
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
34
+ export function setCallsBackend(deps) {
35
+ CALLS.backend = deps;
36
+ registerRunRemovedHook(deps ? runGone : null, "captured-calls");
37
+ }
38
+ /** The call could not be read back from where it was recorded. */
39
+ export class CapturedCallUnavailable extends Error {
40
+ constructor(callId, cause) {
41
+ super(`captured call unavailable: the recorded content of call "${callId}" could not be read from storage`);
42
+ this.name = "CapturedCallUnavailable";
43
+ if (cause !== undefined)
44
+ this.cause = cause;
45
+ }
46
+ }
47
+ const portFor = (tenant, workspace) => {
48
+ const p = records(tenant, workspace);
49
+ // stepRuns too: without it a deleted workspace's calls could never be
50
+ // found again to release their pins (Codex review, 13 Nov 2026).
51
+ return p?.async?.stepPut && p.async.stepGet && p.async.stepRuns ? p : null;
52
+ };
53
+ const switchedOn = (p) => {
54
+ try {
55
+ return p.callsStoreOn?.() === true;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ };
61
+ /** Where a new call goes: the store (deps + port), or null (the volume). */
62
+ function active(tenant, workspace) {
63
+ const deps = CALLS.backend;
64
+ const port = portFor(tenant, workspace);
65
+ return deps && port && switchedOn(port) ? { deps, port } : null;
66
+ }
67
+ const merge = (prev, part) => {
68
+ const next = { ...prev, ...part, truncated: Boolean(prev?.truncated || part.truncated) || undefined };
69
+ if (!next.truncated)
70
+ delete next.truncated;
71
+ return next;
72
+ };
73
+ const sessions = new WeakMap();
74
+ /** One blob per call: pin, upload, then the row that names it. */
75
+ async function storeCall(ctx, call) {
76
+ const a = active(ctx.tenant, ctx.workspace);
77
+ const fall = (err) => {
78
+ // TEMPORARY (see the header): the volume copy, so the call is not lost.
79
+ opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
80
+ try {
81
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, call);
82
+ }
83
+ catch (e) {
84
+ opsError("capture.write_failed", e, { runId: ctx.runId });
85
+ }
86
+ };
87
+ if (!a)
88
+ return fall(new Error("the call store went away before the call was written"));
89
+ try {
90
+ const bytes = Buffer.from(JSON.stringify(call));
91
+ const sha = sha256Hex(bytes);
92
+ await a.deps.pins?.pinBlobs(ctx.tenant, [sha], holderOf(ctx.runId));
93
+ await a.deps.blobs.putIfAbsent(blobObjectKey(ctx.tenant, sha), bytes, { contentType: "application/json" });
94
+ await a.port.async.stepPut(ctx.tenant, ctx.workspace, ctx.runId, KIND, call.id, { sha, size: bytes.length });
95
+ }
96
+ catch (err) {
97
+ fall(err);
98
+ }
99
+ }
100
+ /**
101
+ * The runner's place to put a call's part (input on the call, output on its
102
+ * completion). Returns whether it was taken (the event says `captured`).
103
+ * `owner` is the step: flushCalls(owner) settles what it left.
104
+ */
105
+ export function callSink(owner, ctx) {
106
+ const s = { ctx, pending: new Map(), writes: new Set() };
107
+ sessions.set(owner, s);
108
+ return (part) => {
109
+ if (!SAFE.test(part.id) || !SAFE.test(ctx.runId))
110
+ return false;
111
+ const live = active(ctx.tenant, ctx.workspace);
112
+ const waiting = s.pending.get(part.id);
113
+ if (live && part.output === undefined) {
114
+ s.pending.set(part.id, merge(waiting, part));
115
+ return true;
116
+ }
117
+ s.pending.delete(part.id);
118
+ // A call whose input went to the volume before the switch flipped, or on another worker.
119
+ const prev = waiting ?? (live ? readCapturedCall(ctx.tenant, ctx.workspace, ctx.runId, part.id) ?? undefined : undefined);
120
+ const whole = merge(prev, part);
121
+ if (!live) {
122
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, whole);
123
+ return true;
124
+ }
125
+ const w = storeCall(ctx, whole).finally(() => s.writes.delete(w));
126
+ s.writes.add(w);
127
+ return true;
128
+ };
129
+ }
130
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
131
+ export async function flushCalls(owner) {
132
+ const s = sessions.get(owner);
133
+ if (!s)
134
+ return;
135
+ sessions.delete(owner);
136
+ for (const call of s.pending.values()) {
137
+ if (active(s.ctx.tenant, s.ctx.workspace))
138
+ s.writes.add(storeCall(s.ctx, call));
139
+ else {
140
+ try {
141
+ writeCapturedCall(s.ctx.workspaceRoot, s.ctx.runId, call);
142
+ }
143
+ catch (err) {
144
+ opsError("capture.write_failed", err, { runId: s.ctx.runId });
145
+ }
146
+ }
147
+ }
148
+ s.pending.clear();
149
+ await Promise.allSettled([...s.writes]);
150
+ }
151
+ /** One recorded call, or null (not recorded). The row first, then the file. */
152
+ export async function readCapturedCallAsync(tenant, workspace, runId, callId) {
153
+ if (!SAFE.test(runId) || !SAFE.test(callId) || callId.startsWith(".") || runId.startsWith("."))
154
+ return null;
155
+ const port = portFor(tenant, workspace);
156
+ if (port) {
157
+ let row;
158
+ try {
159
+ row = (await port.async.stepGet(tenant, workspace, runId, KIND, callId));
160
+ }
161
+ catch (err) {
162
+ throw new CapturedCallUnavailable(callId, err);
163
+ }
164
+ if (row) {
165
+ try {
166
+ if (!CALLS.backend || typeof row.sha !== "string")
167
+ throw new Error("the call store is not available here");
168
+ const call = JSON.parse((await readAll(CALLS.backend.blobs, blobObjectKey(tenant, row.sha))).toString("utf8"));
169
+ if (!call || typeof call !== "object" || call.id !== callId)
170
+ throw new Error("the stored object is not this call");
171
+ return call;
172
+ }
173
+ catch (err) {
174
+ if (!(err instanceof BlobNotFound))
175
+ opsError("captured_calls.read_failed", err, { tenant, workspace, runId, callId });
176
+ throw new CapturedCallUnavailable(callId, err);
177
+ }
178
+ }
179
+ }
180
+ return readCapturedCall(tenant, workspace, runId, callId);
181
+ }
182
+ // ---------------------------------------------------------------- lifecycle
183
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
184
+ export async function settleCalls() {
185
+ while (CALLS.background.size)
186
+ await Promise.allSettled([...CALLS.background]);
187
+ }
188
+ /** A run was deleted: its calls' pin goes (the rows went with it; the sweeper takes the blobs). */
189
+ function runGone(tenant, _workspace, runId) {
190
+ const deps = CALLS.backend;
191
+ if (!deps?.pins || !SAFE.test(runId))
192
+ return;
193
+ const p = (async () => {
194
+ for (let attempt = 0;; attempt++) {
195
+ try {
196
+ await deps.pins.release(tenant, holderOf(runId));
197
+ return;
198
+ }
199
+ catch (err) {
200
+ // A pin that cannot be released is kept: a leak is safe, a loss is not.
201
+ if (attempt >= 4)
202
+ return opsError("captured_calls.drop_failed", err, { tenant, runId });
203
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
204
+ }
205
+ }
206
+ })();
207
+ const q = p.finally(() => CALLS.background.delete(q));
208
+ CALLS.background.add(q);
209
+ }
210
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
211
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
212
+ export async function dropWorkspaceCalls(tenant, workspace) {
213
+ const deps = CALLS.backend;
214
+ const port = records(tenant, workspace);
215
+ if (!deps?.pins || !port?.async?.stepRuns)
216
+ return;
217
+ for (const runId of await port.async.stepRuns(tenant, workspace, KIND))
218
+ await deps.pins.release(tenant, holderOf(runId));
219
+ }
@@ -23,11 +23,13 @@ export interface RecordsPortAsync {
23
23
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
24
24
  /** `ref` null: every ref of the kind. */
25
25
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
26
+ /** The ids of the runs that have rows of this kind in the workspace. */
27
+ stepRuns?(tenant: string, workspace: string, kind: string): Promise<string[]>;
26
28
  }
27
29
  /** Small per-workspace state that used to be files in the workspace's folder
28
30
  * (FOL-126, the last files on the volume): webhook generations and the
29
31
  * delivery log, eval results and their history, grades and grader cursors,
30
- * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
32
+ * the deployed commit. Two shapes: a DOCUMENT per
31
33
  * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
32
34
  * the port; workspace-docs.ts is the only caller. */
33
35
  export interface DocsPort {
@@ -72,6 +74,9 @@ export interface RecordsPort {
72
74
  * state is written to the run's folder as before (it is still READ from
73
75
  * rows first, so switching off mid-run loses nothing). */
74
76
  stepStateOn?(): boolean;
77
+ /** The `runs.calls_store` setting, read per call: while false, a captured
78
+ * call is written to the run's folder as before (captured-calls.ts). */
79
+ callsStoreOn?(): boolean;
75
80
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
76
81
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
77
82
  runGet(tenant: string, workspace: string, id: string): RunRecord | null;
@@ -6,6 +6,7 @@ import { opsLog, opsError } from "./ops-log.js";
6
6
  import { globMatch } from "./bounded-match.js";
7
7
  import { latestRevisionId } from "./history.js";
8
8
  import { recordCallIo, redactionsFor } from "./capture.js";
9
+ import { callSink, flushCalls } from "./captured-calls.js";
9
10
  import { AUTH_REFUSAL, platformCause } from "./issues.js";
10
11
  import { hookNames } from "./hooks.js";
11
12
  import crypto from "node:crypto";
@@ -65,7 +66,7 @@ import { buildScriptTools, parseScripts } from "./script-tools.js";
65
66
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.js";
66
67
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv } from "./runtime.js";
67
68
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
68
- import { dataRoot, singleWorkspace } from "./paths.js";
69
+ import { dataRoot } from "./paths.js";
69
70
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
70
71
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.js";
71
72
  import { chooseExecutor, ensureImage } from "./container.js";
@@ -2014,7 +2015,16 @@ export function operatorBlock(step, workspaceRoot) {
2014
2015
  }
2015
2016
  return "";
2016
2017
  }
2017
- async function runStep(agentDir, tenant, step, context, save, modelOverride, tags = [], effortOverride, runId,
2018
+ /** A step, and then whatever its captured calls still hold (captured-calls.ts). */
2019
+ async function runStep(...args) {
2020
+ try {
2021
+ return await runStepBody(...args);
2022
+ }
2023
+ finally {
2024
+ await flushCalls(args[2]);
2025
+ }
2026
+ }
2027
+ async function runStepBody(agentDir, tenant, step, context, save, modelOverride, tags = [], effortOverride, runId,
2018
2028
  /** What the previous group returned as DATA (an `output: json` step's
2019
2029
  * value), beside the prose in `context`. Undefined when nothing did. */
2020
2030
  priorData,
@@ -2122,6 +2132,8 @@ conversation) {
2122
2132
  // calls keep their names, sizes and times (FOL-54 step 4).
2123
2133
  let capturedChars = 0;
2124
2134
  let captureFull = false;
2135
+ const callsRoot = path.resolve(agentDir, "..", "..");
2136
+ const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2125
2137
  const push = (type, text, extra) => {
2126
2138
  const t = new Date().toISOString();
2127
2139
  // The model has begun its first response: held only in memory, for
@@ -2158,7 +2170,7 @@ conversation) {
2158
2170
  captureFull = true;
2159
2171
  step.events.push({ t, type: "info", text: `capture: this step recorded ${Math.round(capturedChars / 1000)}k characters of tool content — the rest of its calls keep only their names, sizes and times` });
2160
2172
  }
2161
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact, singleWorkspace() ? undefined : { tenant, workspace: path.basename(path.resolve(agentDir, "..", "..")) })) {
2173
+ if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(callsRoot, runId, extra.call, text, io, redact, sink)) {
2162
2174
  capturedChars += size;
2163
2175
  rest = { ...others, captured: true };
2164
2176
  }
@@ -224,6 +224,15 @@ export declare function masterKeySource(): {
224
224
  source: "env" | "file";
225
225
  path: string | null;
226
226
  };
227
+ /** Every vault scope that has a FILE on this volume, across all accounts:
228
+ * what a fleet check or a move to a store starts from. Never opens one. */
229
+ export declare function vaultFileScopes(): {
230
+ tenant: string;
231
+ workspace?: string;
232
+ }[];
233
+ /** Does this stored record open for its place with this process's keys? True
234
+ * or false: the value is never handed out. */
235
+ export declare function vaultRecordOpens(tenant: string, workspace: string | undefined, name: string, rec: SecretsFile[string]): boolean;
227
236
  export interface RotationResult {
228
237
  /** Files rewritten, and how many values each held. */
229
238
  rewritten: {
@@ -403,6 +403,7 @@ export function setSecretSites(tenant, name, sites, workspace) {
403
403
  }
404
404
  let found = false;
405
405
  mutateVault(tenant, workspace, (all) => {
406
+ found = false; // a store may run this again against a newer read
406
407
  const rec = all[name];
407
408
  if (!rec)
408
409
  return null;
@@ -579,6 +580,7 @@ export function setSecretWorkspaces(tenant, name, workspaces, opts = {}) {
579
580
  const expected = opts.ifWorkspaces === undefined ? undefined : cleanWorkspaceList(opts.ifWorkspaces);
580
581
  let found = false;
581
582
  mutateVault(tenant, undefined, (all) => {
583
+ found = false; // a store may run this again against a newer read
582
584
  const rec = all[name];
583
585
  if (!rec)
584
586
  return null;
@@ -736,8 +738,9 @@ export function masterKeySource() {
736
738
  ? { source: "env", path: null }
737
739
  : { source: "file", path: keyFile() };
738
740
  }
739
- /** Every secrets.json under an account: the account's, then each workspace's. */
740
- function secretFiles(tenant) {
741
+ /** The secrets.json files that exist under an account: the account's (named
742
+ * even where there is none), then each workspace's. */
743
+ function diskSecretFiles(tenant) {
741
744
  const out = [{ file: secretsFile(tenant) }];
742
745
  for (const dirName of ["workspaces", "projects"]) {
743
746
  const dir = path.join(dataRoot(), tenant, dirName);
@@ -751,6 +754,37 @@ function secretFiles(tenant) {
751
754
  out.push({ file: f, workspace: entry.name });
752
755
  }
753
756
  }
757
+ return out;
758
+ }
759
+ /** Every vault scope that has a FILE on this volume, across all accounts:
760
+ * what a fleet check or a move to a store starts from. Never opens one. */
761
+ export function vaultFileScopes() {
762
+ const out = [];
763
+ if (!fs.existsSync(dataRoot()))
764
+ return out;
765
+ for (const e of fs.readdirSync(dataRoot(), { withFileTypes: true })) {
766
+ if (!e.isDirectory())
767
+ continue;
768
+ try {
769
+ assertSafeName(e.name, "tenant");
770
+ }
771
+ catch {
772
+ continue; // not an account's folder
773
+ }
774
+ for (const { file, workspace } of diskSecretFiles(e.name))
775
+ if (fs.existsSync(file))
776
+ out.push({ tenant: e.name, ...(workspace ? { workspace } : {}) });
777
+ }
778
+ return out;
779
+ }
780
+ /** Does this stored record open for its place with this process's keys? True
781
+ * or false: the value is never handed out. */
782
+ export function vaultRecordOpens(tenant, workspace, name, rec) {
783
+ return openRecord(tenant, workspace, name, rec) !== null;
784
+ }
785
+ /** Every secrets.json under an account: the account's, then each workspace's. */
786
+ function secretFiles(tenant) {
787
+ const out = diskSecretFiles(tenant);
754
788
  // Scopes in the platform's store have no file; they are named by where
755
789
  // the file would be (the result's `file` is a label, never opened).
756
790
  for (const workspace of VAULT.store?.workspaces(tenant) ?? []) {
@@ -782,7 +816,10 @@ export function rotateMasterKey(tenant, from, to) {
782
816
  const unreadable = [];
783
817
  for (const { file, workspace } of secretFiles(tenant)) {
784
818
  let count = 0;
819
+ const seen = unreadable.length;
785
820
  mutateVault(tenant, workspace, (all) => {
821
+ count = 0; // a store may run this again against a newer read
822
+ unreadable.length = seen;
786
823
  const next = {};
787
824
  for (const [name, rec] of Object.entries(all)) {
788
825
  // A record under the ACCOUNT's key is not under the install key, so
@@ -912,6 +949,7 @@ export function replaceOAuth2RefreshToken(tenant, name, workspace, usedValue, re
912
949
  for (const scope of workspace ? [workspace, undefined] : [undefined]) {
913
950
  let replaced = false;
914
951
  mutateVault(tenant, scope, (all) => {
952
+ replaced = false; // a store may run this again against a newer read
915
953
  const rec = all[name];
916
954
  if (rec && openRecord(tenant, scope, name, rec) === usedValue) {
917
955
  // Built whole, not spread over the old record: a spread kept a stale
@@ -1658,7 +1696,11 @@ export function sealVaultBindings(tenant) {
1658
1696
  let sealed = 0;
1659
1697
  const unreadable = [];
1660
1698
  for (const { workspace } of secretFiles(tenant)) {
1699
+ const [sealedBefore, seen] = [sealed, unreadable.length];
1661
1700
  mutateVault(tenant, workspace, (all) => {
1701
+ // a store may run this again against a newer read: count it once
1702
+ sealed = sealedBefore;
1703
+ unreadable.length = seen;
1662
1704
  const plain = new Map();
1663
1705
  const bad = [];
1664
1706
  for (const [name, rec] of Object.entries(all)) {
@@ -1703,7 +1745,11 @@ export function rewrapTenantSecrets(tenant) {
1703
1745
  for (const { workspace } of secretFiles(tenant)) {
1704
1746
  // Under the vault's lock: every pod runs this at boot, and a save made
1705
1747
  // between our read and our write must not be lost.
1748
+ const [movedBefore, seen] = [moved, unreadable.length];
1706
1749
  mutateVault(tenant, workspace, (all) => {
1750
+ // a store may run this again against a newer read: count it once
1751
+ moved = movedBefore;
1752
+ unreadable.length = seen;
1707
1753
  const plain = new Map();
1708
1754
  const unreadableHere = [];
1709
1755
  for (const [name, rec] of Object.entries(all)) {
@@ -1691,10 +1691,7 @@ export interface RunRecord {
1691
1691
  }
1692
1692
  /** Merge one part (the input, on the call; the output, on its completion)
1693
1693
  * into the call's file. */
1694
- export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: {
1695
- tenant: string;
1696
- workspace: string;
1697
- }): void;
1694
+ export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void;
1698
1695
  /** One recorded call of a run, or null (not recorded, or not a call). */
1699
1696
  export declare function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null;
1700
1697
  export declare function runFilePath(tenant: string, workspace: string, runId: string): string;
@@ -1716,9 +1713,11 @@ export declare function runFilePath(tenant: string, workspace: string, runId: st
1716
1713
  export declare function deleteRun(tenant: string, workspace: string, runId: string, opts?: {
1717
1714
  pruned?: boolean;
1718
1715
  }): boolean;
1719
- /** run-outputs.ts registers here (it imports this module). */
1716
+ /** run-outputs.ts and captured-calls.ts register here (they import this module). */
1720
1717
  type RunHook = (tenant: string, workspace: string, runId: string) => void;
1721
- export declare function registerRunRemovedHook(fn: RunHook | null): void;
1718
+ /** A run's content lives somewhere other than its folder: `name` says whose hook
1719
+ * this is, so one registering (or clearing, with null) never replaces another's. */
1720
+ export declare function registerRunRemovedHook(fn: RunHook | null, name?: string): void;
1722
1721
  /** ledger.ts registers here — store cannot import it without a cycle, and
1723
1722
  * money must not depend on one. */
1724
1723
  export declare function registerRunDeletionListener(fn: RunHook | undefined): void;
package/dist/src/store.js CHANGED
@@ -19,6 +19,7 @@
19
19
  // or an agent, and belongs in git.
20
20
  //
21
21
  // An account is a named directory (per OKF: tenancy is a hosting concern).
22
+ import { opsError } from "./ops-log.js";
22
23
  import { readCompute } from "./resources.js";
23
24
  import { expandPlatformVars } from "./host-env.js";
24
25
  import { FLOW_TRIGGERS } from "./frontmatter-fields.js";
@@ -29,7 +30,7 @@ import { processState } from "./process-state.js";
29
30
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.js";
30
31
  import { platform } from "./platform.js";
31
32
  import { records } from "./records.js";
32
- import { docRows, docStore, quietly } from "./workspace-docs.js";
33
+ import { docRows, quietly } from "./workspace-docs.js";
33
34
  import { toLF, asRaw } from "./eol.js";
34
35
  import matter, { frontmatterErrorText, configMatter } from "./matter.js";
35
36
  import { readAgentsMdKeys, patchFrontmatter } from "./agents-md.js";
@@ -2925,7 +2926,9 @@ export function isSplicedRecord(step) {
2925
2926
  // and every page reads whole, and gone with the run (deleteRun removes
2926
2927
  // runs/<run>/). The runner writes them, secrets already masked.
2927
2928
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
2928
- const CALL_KIND = "call";
2929
+ /** Captured calls kept as rows for one day on dev (13 Nov 2026); read and
2930
+ * dropped with their run, never written again. */
2931
+ const LEGACY_CALL_KIND = "call";
2929
2932
  function capturedCallFile(workspaceRoot, runId, callId) {
2930
2933
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith("."))
2931
2934
  return null;
@@ -2933,16 +2936,10 @@ function capturedCallFile(workspaceRoot, runId, callId) {
2933
2936
  }
2934
2937
  /** Merge one part (the input, on the call; the output, on its completion)
2935
2938
  * into the call's file. */
2936
- export function writeCapturedCall(workspaceRoot, runId, part, scope) {
2939
+ export function writeCapturedCall(workspaceRoot, runId, part) {
2937
2940
  const file = capturedCallFile(workspaceRoot, runId, part.id);
2938
2941
  if (!file)
2939
2942
  return;
2940
- // A row when the platform keeps them (FOL-126): the two parts of a call
2941
- // merge in one statement, and the web's copies read it wherever they run.
2942
- // `truncated` is only ever sent true, so a merge keeps it once set.
2943
- const store = scope ? docStore(scope.tenant, scope.workspace) : null;
2944
- if (store && scope)
2945
- return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part);
2946
2943
  let prev = {};
2947
2944
  try {
2948
2945
  prev = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -2963,22 +2960,17 @@ export function readCapturedCall(tenant, workspace, runId, callId) {
2963
2960
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
2964
2961
  if (!file)
2965
2962
  return null;
2966
- const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined);
2967
- let onFile;
2963
+ // A call kept as a workspace_docs row (records.docs_store, 13 Nov 2026,
2964
+ // before calls went to the blob store): still read until its run goes.
2965
+ const legacy = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, LEGACY_CALL_KIND, `${runId}/${callId}`), undefined);
2966
+ if (legacy)
2967
+ return legacy;
2968
2968
  try {
2969
- onFile = JSON.parse(fs.readFileSync(file, "utf8"));
2969
+ return JSON.parse(fs.readFileSync(file, "utf8"));
2970
2970
  }
2971
2971
  catch {
2972
- /* none */
2973
- }
2974
- // A switch between a call's two parts leaves one part in each place: both, merged.
2975
- if (row && onFile) {
2976
- const merged = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
2977
- if (!merged.truncated)
2978
- delete merged.truncated;
2979
- return merged;
2972
+ return null;
2980
2973
  }
2981
- return row ?? onFile ?? null;
2982
2974
  }
2983
2975
  export function runFilePath(tenant, workspace, runId) {
2984
2976
  assertSafeName(runId, "run id");
@@ -3018,9 +3010,8 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3018
3010
  // and finishes — the other order left the content with nothing pointing
3019
3011
  // at it (Codex review, FOL-124).
3020
3012
  fs.rmSync(dir, { recursive: true, force: true });
3021
- // Its captured calls kept as rows go the same way, before the record.
3022
3013
  if (SAFE_ID.test(runId))
3023
- docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
3014
+ quietly(() => docRows(tenant, workspace)?.dropPrefix(tenant, workspace, LEGACY_CALL_KIND, `${runId}/`), undefined);
3024
3015
  if (port)
3025
3016
  port.runDelete(tenant, workspace, runId);
3026
3017
  else {
@@ -3033,9 +3024,18 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3033
3024
  if (prior?.inputs?.length) {
3034
3025
  void import("./storage.js").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => { });
3035
3026
  }
3036
- // Outputs published to the blob store (run-outputs.ts) are records and pins,
3037
- // not files under dir: they go in the background, retried.
3038
- RUN_HOOKS.removed?.(tenant, workspace, runId);
3027
+ // Outputs and captured calls published to the blob store (run-outputs.ts,
3028
+ // captured-calls.ts) are records and pins, not files under dir: they go in
3029
+ // the background, retried.
3030
+ for (const [name, hook] of RUN_HOOKS.removed) {
3031
+ try {
3032
+ hook(tenant, workspace, runId);
3033
+ }
3034
+ catch (err) {
3035
+ // One store's clean-up failing must not stop the next one's.
3036
+ opsError("run_removed_hook.failed", err, { hook: name, tenant, runId });
3037
+ }
3038
+ }
3039
3039
  if (!had)
3040
3040
  return true;
3041
3041
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -3046,9 +3046,14 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3046
3046
  }
3047
3047
  /** One per process (process-state.ts): a run deleted from a route handler must
3048
3048
  * reach the hooks the boot registered. */
3049
- const RUN_HOOKS = processState("run-hooks", () => ({ removed: null, deleted: undefined }));
3050
- export function registerRunRemovedHook(fn) {
3051
- RUN_HOOKS.removed = fn;
3049
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: new Map(), deleted: undefined }));
3050
+ /** A run's content lives somewhere other than its folder: `name` says whose hook
3051
+ * this is, so one registering (or clearing, with null) never replaces another's. */
3052
+ export function registerRunRemovedHook(fn, name = "run-outputs") {
3053
+ if (fn)
3054
+ RUN_HOOKS.removed.set(name, fn);
3055
+ else
3056
+ RUN_HOOKS.removed.delete(name);
3052
3057
  }
3053
3058
  /** ledger.ts registers here — store cannot import it without a cycle, and
3054
3059
  * money must not depend on one. */