@foldrun/core 21.0.0 → 21.2.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.
@@ -20,4 +20,10 @@ export declare function maskCall(text: string, redactSecrets: (text: string) =>
20
20
  };
21
21
  export declare function recordCallIo(workspaceRoot: string, runId: string, callId: string, tool: string, io: CallIo,
22
22
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
23
- redactSecrets: (text: string) => string): boolean;
23
+ 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;
@@ -97,7 +97,10 @@ export function maskCall(text, redactSecrets) {
97
97
  }
98
98
  export function recordCallIo(workspaceRoot, runId, callId, tool, io,
99
99
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
100
- redactSecrets) {
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
104
  try {
102
105
  const input = io.input === undefined ? null : maskCall(io.input, redactSecrets);
103
106
  const output = io.output === undefined ? null : maskCall(io.output, redactSecrets);
@@ -109,7 +112,7 @@ redactSecrets) {
109
112
  ...(input ? { input: input.text, ...(io.inputChars !== undefined ? { inputChars: io.inputChars } : {}), ...(input.cut || (io.inputChars ?? 0) > io.input.length ? { inputCut: true } : {}) } : {}),
110
113
  ...(output ? { output: output.text, ...(io.outputChars !== undefined ? { outputChars: io.outputChars } : {}), ...(output.cut || (io.outputChars ?? 0) > io.output.length ? { outputCut: true } : {}) } : {}),
111
114
  ...(io.truncated || input?.cut || output?.cut ? { truncated: true } : {}),
112
- });
115
+ }, scope);
113
116
  return true;
114
117
  }
115
118
  catch (err) {
@@ -22,6 +22,7 @@ import os from "node:os";
22
22
  import path from "node:path";
23
23
  import { saveWorkspace, keptOnDeploy, workspaceDir, listRunSummaries, listWorkspaceFiles, parseFlow, parseToolDef, WORKSPACE_DIRS, assertSafeName, accountDir, frontmatterErrorText, } from "./store.js";
24
24
  import { readAgentsMdKeys } from "./agents-md.js";
25
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
25
26
  import { libraryTools } from "./library.js";
26
27
  import { lintFlow, regexProblem } from "./flow-lint.js";
27
28
  import { parseEval } from "./evals.js";
@@ -773,15 +774,24 @@ export function deployWorkspace(tenant, workspace, files, opts = {}) {
773
774
  // see it in the file tree or be able to edit it.
774
775
  const commitFile = (tenant, workspace) => path.join(workspaceDir(tenant, workspace), "..", `.${workspace}.deployed`);
775
776
  export function writeDeployedCommit(tenant, workspace, commit) {
777
+ const store = docStore(tenant, workspace);
778
+ if (store)
779
+ return store.put(tenant, workspace, "deployed", "commit", { commit, at: new Date().toISOString() });
776
780
  const f = commitFile(tenant, workspace);
777
781
  fs.mkdirSync(path.dirname(f), { recursive: true });
778
782
  fs.writeFileSync(f, `${JSON.stringify({ commit, at: new Date().toISOString() })}\n`);
779
783
  }
780
784
  export function deployedCommit(tenant, workspace) {
785
+ let onFile = null;
781
786
  try {
782
- return JSON.parse(fs.readFileSync(commitFile(tenant, workspace), "utf8"));
787
+ onFile = JSON.parse(fs.readFileSync(commitFile(tenant, workspace), "utf8"));
783
788
  }
784
789
  catch {
785
- return null;
790
+ /* none */
786
791
  }
792
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, "deployed", "commit"), undefined) ?? null;
793
+ // Written either way over time: the later deploy is the one running.
794
+ if (row && onFile)
795
+ return String(row.at) >= String(onFile.at) ? row : onFile;
796
+ return row ?? onFile;
787
797
  }
@@ -216,6 +216,7 @@ export interface EvalHistoryEntry {
216
216
  failed: number;
217
217
  costUsd: number;
218
218
  }
219
+ /** Oldest first. Rows and the file both: the series may have been written either way. */
219
220
  export declare function readEvalHistory(tenant: string, workspace: string): EvalHistoryEntry[];
220
221
  export interface EvalTrend {
221
222
  eval: string;
package/dist/src/evals.js CHANGED
@@ -37,6 +37,7 @@ import fs from "node:fs";
37
37
  import crypto from "node:crypto";
38
38
  import path from "node:path";
39
39
  import { deployedCommit } from "./deploy.js";
40
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
40
41
  import { latestRevisionIdLocal as latestRevisionId } from "./history.js";
41
42
  import matter from "./matter.js";
42
43
  import { spawn } from "node:child_process";
@@ -740,9 +741,6 @@ export function writeEvalResult(tenant, workspace, result,
740
741
  // so a workspace that has never seen a git repository still gets a
741
742
  // series with ids in it, and the "this change made it worse" table works.
742
743
  commit = deployedCommit(tenant, workspace)?.commit ?? latestRevisionId(tenant, workspace)) {
743
- const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
744
- fs.mkdirSync(dir, { recursive: true });
745
- fs.writeFileSync(path.join(dir, `${result.eval}.json`), JSON.stringify(result, null, 2));
746
744
  const line = {
747
745
  eval: result.eval,
748
746
  at: result.finishedAt,
@@ -751,9 +749,31 @@ commit = deployedCommit(tenant, workspace)?.commit ?? latestRevisionId(tenant, w
751
749
  failed: result.failed,
752
750
  costUsd: result.costUsd,
753
751
  };
752
+ const store = docStore(tenant, workspace);
753
+ if (store) {
754
+ store.put(tenant, workspace, EVAL_RESULT_KIND, result.eval, result);
755
+ store.append(tenant, workspace, EVAL_HISTORY_KIND, line, KEEP_EVAL_HISTORY);
756
+ return;
757
+ }
758
+ const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
759
+ fs.mkdirSync(dir, { recursive: true });
760
+ fs.writeFileSync(path.join(dir, `${result.eval}.json`), JSON.stringify(result, null, 2));
754
761
  fs.appendFileSync(path.join(dir, "history.jsonl"), `${JSON.stringify(line)}\n`);
755
762
  }
763
+ const EVAL_RESULT_KIND = "eval-result";
764
+ const EVAL_HISTORY_KIND = "eval-history";
765
+ const EVAL_LOCK_KIND = "eval-lock";
766
+ /** Rows of history kept per workspace: years of deploys, and bounded. */
767
+ const KEEP_EVAL_HISTORY = 5000;
768
+ /** Oldest first. Rows and the file both: the series may have been written either way. */
756
769
  export function readEvalHistory(tenant, workspace) {
770
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, EVAL_HISTORY_KIND, KEEP_EVAL_HISTORY) ?? [], []).map((r) => r.data);
771
+ const lines = readEvalHistoryFile(tenant, workspace);
772
+ if (!rows.length)
773
+ return lines;
774
+ return [...lines, ...rows.reverse()].sort((a, b) => String(a.at).localeCompare(String(b.at)));
775
+ }
776
+ function readEvalHistoryFile(tenant, workspace) {
757
777
  const file = path.join(workspaceDir(tenant, workspace), "evals", ".results", "history.jsonl");
758
778
  if (!fs.existsSync(file))
759
779
  return [];
@@ -823,19 +843,38 @@ commit = null) {
823
843
  const evals = listEvals(tenant, workspace).filter((e) => e.trigger === "deploy" && !e.inputs);
824
844
  if (evals.length === 0)
825
845
  return { ran: 0, skipped: "no evals" };
846
+ // A lock older than an hour is a crash, not a run.
847
+ const store = docStore(tenant, workspace);
826
848
  const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
827
- fs.mkdirSync(dir, { recursive: true });
828
849
  const lock = path.join(dir, ".evaluating");
829
- // A lock older than an hour is a crash, not a run.
830
- try {
831
- if (Date.now() - fs.statSync(lock).mtimeMs < 60 * 60_000) {
832
- return { ran: 0, skipped: "evals already running for an earlier deploy" };
850
+ const HOUR = 60 * 60_000;
851
+ const busy = { ran: 0, skipped: "evals already running for an earlier deploy" };
852
+ // A lock taken in the OTHER place (the switch moved while evals ran) still holds.
853
+ const fileHeld = () => {
854
+ try {
855
+ return Date.now() - fs.statSync(lock).mtimeMs < HOUR;
856
+ }
857
+ catch {
858
+ return false;
833
859
  }
860
+ };
861
+ const rowHeld = () => {
862
+ const at = Date.parse(quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, EVAL_LOCK_KIND, "deploy"), undefined)?.at ?? "");
863
+ return Number.isFinite(at) && Date.now() - at < HOUR;
864
+ };
865
+ if (store) {
866
+ if (fileHeld())
867
+ return busy;
868
+ // One row, taken by exactly one caller however many pods race.
869
+ if (!store.claim(tenant, workspace, EVAL_LOCK_KIND, "deploy", { stamp, at: new Date().toISOString() }, HOUR))
870
+ return busy;
834
871
  }
835
- catch {
836
- // no lock
872
+ else {
873
+ if (rowHeld() || fileHeld())
874
+ return busy;
875
+ fs.mkdirSync(dir, { recursive: true });
876
+ fs.writeFileSync(lock, stamp);
837
877
  }
838
- fs.writeFileSync(lock, stamp);
839
878
  let ran = 0;
840
879
  try {
841
880
  for (const info of evals) {
@@ -863,7 +902,10 @@ commit = null) {
863
902
  }
864
903
  }
865
904
  finally {
866
- fs.rmSync(lock, { force: true });
905
+ if (store)
906
+ quietly(() => store.drop(tenant, workspace, EVAL_LOCK_KIND, "deploy"), undefined);
907
+ else
908
+ fs.rmSync(lock, { force: true });
867
909
  }
868
910
  return { ran, skipped: null };
869
911
  }
@@ -871,7 +913,12 @@ export function readEvalResult(tenant, workspace, name) {
871
913
  try {
872
914
  assertSafeName(name, "eval");
873
915
  const file = path.join(workspaceDir(tenant, workspace), "evals", ".results", `${name}.json`);
874
- return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
916
+ const onFile = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
917
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, EVAL_RESULT_KIND, name), undefined) ?? null;
918
+ // Written either way over time: the later run is the result.
919
+ if (row && onFile)
920
+ return String(row.finishedAt) >= String(onFile.finishedAt) ? row : onFile;
921
+ return row ?? onFile;
875
922
  }
876
923
  catch {
877
924
  return null;
@@ -49,6 +49,12 @@ import { workspaceDir, listRunSummaries, readRun, assertSafeName } from "./store
49
49
  import { listEvals, checkAssertion, judgeCall, judgeProcessEnv } from "./evals.js";
50
50
  import { accountModelEnv, withModelEnv } from "./model-env.js";
51
51
  import { judgeVerdict } from "./judge-verdict.js";
52
+ import { docRows, docStore } from "./workspace-docs.js";
53
+ /** Grades as rows: one log per grader. The cursor: one document per grader. */
54
+ const gradeKind = (name) => `grades:${name}`;
55
+ const GRADER_KIND = "grader";
56
+ /** More rows than pruneGrades ever leaves, so a read is the whole log. */
57
+ const ALL_GRADE_ROWS = 100_000;
52
58
  /** How far back the pass looks for runs to grade. */
53
59
  export const GRADE_WINDOW_MS = 3 * 86400_000;
54
60
  /** How long grades are kept, and how many per eval. */
@@ -211,11 +217,36 @@ export async function gradeRun(tenant, workspace, info, run, opts = {}) {
211
217
  /** Keep a grade: one line, appended. */
212
218
  export function recordGrade(tenant, workspace, grade) {
213
219
  const file = gradesFile(tenant, workspace, grade.eval);
220
+ const store = docStore(tenant, workspace);
221
+ if (store)
222
+ return store.append(tenant, workspace, gradeKind(grade.eval), grade, 0);
214
223
  fs.mkdirSync(path.dirname(file), { recursive: true });
215
224
  fs.appendFileSync(file, `${JSON.stringify(grade)}\n`);
216
225
  }
217
- /** Every line of a grader's file, oldest first; a torn line is skipped. */
226
+ /** The grader's rows, oldest first, each with its row id. Not quiet: a pass
227
+ * that cannot read what it graded must stop, not grade every run again. */
228
+ function rowLines(tenant, workspace, name) {
229
+ assertSafeName(name, "eval");
230
+ const rows = docRows(tenant, workspace)?.tail(tenant, workspace, gradeKind(name), ALL_GRADE_ROWS) ?? [];
231
+ const out = [];
232
+ for (const r of rows.reverse()) {
233
+ const g = r.data;
234
+ if (g && typeof g.runId === "string" && typeof g.at === "string")
235
+ out.push({ id: r.id, grade: g });
236
+ }
237
+ return out;
238
+ }
239
+ /** Every grade of a grader, oldest first: the file's lines and the rows (it
240
+ * may have been written either way over time). */
218
241
  function readLines(tenant, workspace, name) {
242
+ const rows = rowLines(tenant, workspace, name).map((r) => r.grade);
243
+ const lines = fileLines(tenant, workspace, name);
244
+ if (!rows.length)
245
+ return lines;
246
+ return [...lines, ...rows].sort((a, b) => a.at.localeCompare(b.at));
247
+ }
248
+ /** Every line of a grader's file, oldest first; a torn line is skipped. */
249
+ function fileLines(tenant, workspace, name) {
219
250
  let raw;
220
251
  try {
221
252
  raw = fs.readFileSync(gradesFile(tenant, workspace, name), "utf8");
@@ -297,14 +328,13 @@ export function summariseGrades(grades) {
297
328
  * never sampled, so a new grader starts from now rather than back-filling. */
298
329
  export function graderSince(tenant, workspace, name, now = Date.now()) {
299
330
  const file = stateFile(tenant, workspace, name);
300
- try {
301
- const s = JSON.parse(fs.readFileSync(file, "utf8"));
302
- const t = s.since ? Date.parse(s.since) : NaN;
303
- if (Number.isFinite(t))
304
- return t;
305
- }
306
- catch {
307
- /* first sight */
331
+ const t = Date.parse(graderState(tenant, workspace, name).since ?? "");
332
+ if (Number.isFinite(t))
333
+ return t;
334
+ const store = docStore(tenant, workspace);
335
+ if (store) {
336
+ store.merge(tenant, workspace, GRADER_KIND, name, { since: new Date(now).toISOString() });
337
+ return now;
308
338
  }
309
339
  fs.mkdirSync(path.dirname(file), { recursive: true });
310
340
  fs.writeFileSync(`${file}.tmp`, JSON.stringify({ since: new Date(now).toISOString() }));
@@ -314,17 +344,29 @@ export function graderSince(tenant, workspace, name, now = Date.now()) {
314
344
  /** When a grader last had a run graded by the pass (0: never) — the pass
315
345
  * serves the longest-waiting grader first, so fairness holds across passes. */
316
346
  export function graderLastServed(tenant, workspace, name) {
347
+ const t = Date.parse(graderState(tenant, workspace, name).lastServed ?? "");
348
+ return Number.isFinite(t) ? t : 0;
349
+ }
350
+ /** The grader's cursor from the file and the row together: the EARLIEST
351
+ * first sight (a grader is never made new again by a switch) and the LATEST
352
+ * serving. */
353
+ function graderState(tenant, workspace, name) {
354
+ let onFile = {};
317
355
  try {
318
- const s = JSON.parse(fs.readFileSync(stateFile(tenant, workspace, name), "utf8"));
319
- const t = s.lastServed ? Date.parse(s.lastServed) : NaN;
320
- return Number.isFinite(t) ? t : 0;
356
+ onFile = JSON.parse(fs.readFileSync(stateFile(tenant, workspace, name), "utf8"));
321
357
  }
322
358
  catch {
323
- return 0;
359
+ /* none */
324
360
  }
361
+ const row = docRows(tenant, workspace)?.get(tenant, workspace, GRADER_KIND, name) ?? {};
362
+ const pick = (a, b, later) => (!a ? b : !b ? a : (a > b) === later ? a : b);
363
+ return { since: pick(onFile.since, row.since, false), lastServed: pick(onFile.lastServed, row.lastServed, true) };
325
364
  }
326
365
  function markServed(tenant, workspace, name, now) {
327
366
  const file = stateFile(tenant, workspace, name);
367
+ const store = docStore(tenant, workspace);
368
+ if (store)
369
+ return store.merge(tenant, workspace, GRADER_KIND, name, { lastServed: new Date(now).toISOString() });
328
370
  let state = {};
329
371
  try {
330
372
  state = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -378,24 +420,36 @@ export function gradeCandidates(tenant, workspace, info, now = Date.now()) {
378
420
  /** Drop grades past the keeping window or the line cap. Rewritten whole
379
421
  * (temp, then rename); only the pass prunes. */
380
422
  export function pruneGrades(tenant, workspace, name, now = Date.now()) {
381
- const file = gradesFile(tenant, workspace, name);
382
- if (!fs.existsSync(file))
383
- return 0;
384
- // Read whatever its size: the 90 days hold for a quiet grader too.
385
- const lines = readLines(tenant, workspace, name);
386
423
  // The line cap never takes a grade from the last GRADE_WINDOW_MS (and a
387
424
  // day's margin): those are what keeps the pass from grading a run twice.
388
425
  const recent = (g) => now - Date.parse(g.at) < GRADE_WINDOW_MS + 86400_000;
389
- const old = lines.filter((g) => !recent(g) && now - Date.parse(g.at) < GRADE_KEEP_MS);
390
- const room = GRADE_KEEP_LINES - lines.filter(recent).length;
391
- const kept = [...(room > 0 ? old.slice(-room) : []), ...lines.filter(recent)]
392
- .sort((a, b) => a.at.localeCompare(b.at));
426
+ const keepers = (all, of) => {
427
+ const old = all.filter((x) => !recent(of(x)) && now - Date.parse(of(x).at) < GRADE_KEEP_MS);
428
+ const room = GRADE_KEEP_LINES - all.filter((x) => recent(of(x))).length;
429
+ return [...(room > 0 ? old.slice(-room) : []), ...all.filter((x) => recent(of(x)))];
430
+ };
431
+ // The rows, by the same rule (each place keeps its own window).
432
+ let droppedRows = 0;
433
+ const rows = rowLines(tenant, workspace, name);
434
+ if (rows.length) {
435
+ const keep = new Set(keepers(rows, (r) => r.grade).map((r) => r.id));
436
+ const gone = rows.filter((r) => !keep.has(r.id)).map((r) => r.id);
437
+ if (gone.length)
438
+ docRows(tenant, workspace)?.prune(tenant, workspace, gradeKind(name), gone);
439
+ droppedRows = gone.length;
440
+ }
441
+ const file = gradesFile(tenant, workspace, name);
442
+ if (!fs.existsSync(file))
443
+ return droppedRows;
444
+ // Read whatever its size: the 90 days hold for a quiet grader too.
445
+ const lines = fileLines(tenant, workspace, name);
446
+ const kept = keepers(lines, (g) => g).sort((a, b) => a.at.localeCompare(b.at));
393
447
  if (kept.length === lines.length)
394
- return 0;
448
+ return droppedRows;
395
449
  const tmp = `${file}.${process.pid}.tmp`;
396
450
  fs.writeFileSync(tmp, kept.map((g) => JSON.stringify(g)).join("\n") + (kept.length ? "\n" : ""));
397
451
  fs.renameSync(tmp, file);
398
- return lines.length - kept.length;
452
+ return droppedRows + lines.length - kept.length;
399
453
  }
400
454
  /**
401
455
  * Grade what is due in one workspace: for each grader, the sampled runs that
@@ -24,7 +24,48 @@ export interface RecordsPortAsync {
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
26
  }
27
+ /** Small per-workspace state that used to be files in the workspace's folder
28
+ * (FOL-126, the last files on the volume): webhook generations and the
29
+ * delivery log, eval results and their history, grades and grader cursors,
30
+ * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
31
+ * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
32
+ * the port; workspace-docs.ts is the only caller. */
33
+ export interface DocsPort {
34
+ get(tenant: string, workspace: string, kind: string, key: string): unknown | undefined;
35
+ put(tenant: string, workspace: string, kind: string, key: string, data: unknown): void;
36
+ /** Shallow-merge `patch` into the document, making it when absent — one statement, so two parts of one call never lose each other. */
37
+ merge(tenant: string, workspace: string, kind: string, key: string, patch: Record<string, unknown>): void;
38
+ /** Move a counter forward atomically: `field` becomes the greater of its
39
+ * value + 1 and `atLeast`, `patch` is merged in, and the new value comes back. */
40
+ raise(tenant: string, workspace: string, kind: string, key: string, field: string, atLeast: number, patch: Record<string, unknown>): number;
41
+ /** Take the key unless a document younger than `staleMs` holds it. True for the one caller that took it. */
42
+ claim(tenant: string, workspace: string, kind: string, key: string, data: unknown, staleMs: number): boolean;
43
+ /** `key` null: every document of the kind. */
44
+ drop(tenant: string, workspace: string, kind: string, key: string | null): void;
45
+ /** Every document of the kind whose key starts with `prefix`. */
46
+ dropPrefix(tenant: string, workspace: string, kind: string, prefix: string): void;
47
+ list(tenant: string, workspace: string, kind: string): {
48
+ key: string;
49
+ data: unknown;
50
+ }[];
51
+ /** Add one entry; `keep` > 0 drops all but the newest `keep`. */
52
+ append(tenant: string, workspace: string, kind: string, data: unknown, keep: number): void;
53
+ /** Newest first. */
54
+ tail(tenant: string, workspace: string, kind: string, limit: number): {
55
+ id: string;
56
+ data: unknown;
57
+ }[];
58
+ replace(tenant: string, workspace: string, kind: string, id: string, data: unknown): void;
59
+ prune(tenant: string, workspace: string, kind: string, ids: string[]): void;
60
+ }
27
61
  export interface RecordsPort {
62
+ /** The small per-workspace state (see DocsPort). Optional: a port without
63
+ * it keeps that state in the workspace's folder. */
64
+ docs?: DocsPort;
65
+ /** The `records.docs_store` setting, read per call: while false, that state
66
+ * is WRITTEN to the folder as before. It is read from both, so switching
67
+ * either way mid-flight loses nothing already written. */
68
+ docsOn?(): boolean;
28
69
  /** Async reads (see RecordsPortAsync). */
29
70
  async?: RecordsPortAsync;
30
71
  /** The `runs.step_state_store` setting, read per call: while false, step
@@ -65,7 +65,7 @@ import { buildScriptTools, parseScripts } from "./script-tools.js";
65
65
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.js";
66
66
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv } from "./runtime.js";
67
67
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
68
- import { dataRoot } from "./paths.js";
68
+ import { dataRoot, singleWorkspace } from "./paths.js";
69
69
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
70
70
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.js";
71
71
  import { chooseExecutor, ensureImage } from "./container.js";
@@ -2158,7 +2158,7 @@ conversation) {
2158
2158
  captureFull = true;
2159
2159
  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
2160
  }
2161
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact)) {
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, "..", "..")) })) {
2162
2162
  capturedChars += size;
2163
2163
  rest = { ...others, captured: true };
2164
2164
  }
@@ -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,7 +1691,10 @@ 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): void;
1694
+ export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: {
1695
+ tenant: string;
1696
+ workspace: string;
1697
+ }): void;
1695
1698
  /** One recorded call of a run, or null (not recorded, or not a call). */
1696
1699
  export declare function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null;
1697
1700
  export declare function runFilePath(tenant: string, workspace: string, runId: string): string;
package/dist/src/store.js CHANGED
@@ -29,6 +29,7 @@ import { processState } from "./process-state.js";
29
29
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.js";
30
30
  import { platform } from "./platform.js";
31
31
  import { records } from "./records.js";
32
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
32
33
  import { toLF, asRaw } from "./eol.js";
33
34
  import matter, { frontmatterErrorText, configMatter } from "./matter.js";
34
35
  import { readAgentsMdKeys, patchFrontmatter } from "./agents-md.js";
@@ -2924,6 +2925,7 @@ export function isSplicedRecord(step) {
2924
2925
  // and every page reads whole, and gone with the run (deleteRun removes
2925
2926
  // runs/<run>/). The runner writes them, secrets already masked.
2926
2927
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
2928
+ const CALL_KIND = "call";
2927
2929
  function capturedCallFile(workspaceRoot, runId, callId) {
2928
2930
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith("."))
2929
2931
  return null;
@@ -2931,10 +2933,16 @@ function capturedCallFile(workspaceRoot, runId, callId) {
2931
2933
  }
2932
2934
  /** Merge one part (the input, on the call; the output, on its completion)
2933
2935
  * into the call's file. */
2934
- export function writeCapturedCall(workspaceRoot, runId, part) {
2936
+ export function writeCapturedCall(workspaceRoot, runId, part, scope) {
2935
2937
  const file = capturedCallFile(workspaceRoot, runId, part.id);
2936
2938
  if (!file)
2937
2939
  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);
2938
2946
  let prev = {};
2939
2947
  try {
2940
2948
  prev = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -2955,12 +2963,22 @@ export function readCapturedCall(tenant, workspace, runId, callId) {
2955
2963
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
2956
2964
  if (!file)
2957
2965
  return null;
2966
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined);
2967
+ let onFile;
2958
2968
  try {
2959
- return JSON.parse(fs.readFileSync(file, "utf8"));
2969
+ onFile = JSON.parse(fs.readFileSync(file, "utf8"));
2960
2970
  }
2961
2971
  catch {
2962
- return null;
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;
2963
2980
  }
2981
+ return row ?? onFile ?? null;
2964
2982
  }
2965
2983
  export function runFilePath(tenant, workspace, runId) {
2966
2984
  assertSafeName(runId, "run id");
@@ -3000,6 +3018,9 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3000
3018
  // and finishes — the other order left the content with nothing pointing
3001
3019
  // at it (Codex review, FOL-124).
3002
3020
  fs.rmSync(dir, { recursive: true, force: true });
3021
+ // Its captured calls kept as rows go the same way, before the record.
3022
+ if (SAFE_ID.test(runId))
3023
+ docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
3003
3024
  if (port)
3004
3025
  port.runDelete(tenant, workspace, runId);
3005
3026
  else {
@@ -10,6 +10,11 @@
10
10
  * of them silently changed the first time a secret was stored.
11
11
  */
12
12
  export declare function installKey(): string;
13
+ /** The hook's generation: the greater of the row's and the file's, so a
14
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
15
+ * holds whichever way the switch stands now — an old URL never comes back.
16
+ * A database that cannot answer fails the call: guessing from the file could
17
+ * accept a token that was rotated away. */
13
18
  export declare function hookGeneration(tenant: string, workspace: string, flow: string): number;
14
19
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
15
20
  export declare function rotateWebhook(tenant: string, workspace: string, flow: string): string;