@foldrun/core 20.3.0 → 21.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/src/capture.d.ts +7 -1
  2. package/dist/src/capture.js +5 -2
  3. package/dist/src/deploy.js +12 -2
  4. package/dist/src/evals.d.ts +1 -0
  5. package/dist/src/evals.js +60 -13
  6. package/dist/src/grades.js +78 -24
  7. package/dist/src/history.d.ts +5 -1
  8. package/dist/src/history.js +41 -25
  9. package/dist/src/journal-store.d.ts +3 -1
  10. package/dist/src/library.js +1 -1
  11. package/dist/src/process-state.d.ts +2 -0
  12. package/dist/src/process-state.js +20 -0
  13. package/dist/src/records.d.ts +41 -0
  14. package/dist/src/run-outputs.js +22 -19
  15. package/dist/src/runner.js +2 -2
  16. package/dist/src/secret-health.js +8 -6
  17. package/dist/src/secrets.js +8 -6
  18. package/dist/src/store.d.ts +7 -5
  19. package/dist/src/store.js +33 -11
  20. package/dist/src/webhook.d.ts +5 -0
  21. package/dist/src/webhook.js +61 -8
  22. package/dist/src/workspace-docs.d.ts +9 -0
  23. package/dist/src/workspace-docs.js +31 -0
  24. package/dist/src/workspace-revisions.d.ts +10 -3
  25. package/dist/src/workspace-revisions.js +336 -146
  26. package/package.json +1 -1
  27. package/src/capture.ts +4 -1
  28. package/src/deploy.ts +10 -2
  29. package/src/evals.ts +54 -13
  30. package/src/grades.ts +75 -21
  31. package/src/history.ts +39 -24
  32. package/src/journal-store.ts +3 -2
  33. package/src/library.ts +1 -1
  34. package/src/process-state.ts +21 -0
  35. package/src/records.ts +36 -0
  36. package/src/run-outputs.ts +22 -19
  37. package/src/runner.ts +2 -2
  38. package/src/secret-health.ts +8 -6
  39. package/src/secrets.ts +8 -6
  40. package/src/store.ts +33 -12
  41. package/src/webhook.ts +63 -8
  42. package/src/workspace-docs.ts +33 -0
  43. package/src/workspace-revisions.ts +323 -132
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "20.3.0",
3
+ "version": "21.1.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/capture.ts CHANGED
@@ -100,6 +100,9 @@ export function recordCallIo(
100
100
  io: CallIo,
101
101
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
102
102
  redactSecrets: (text: string) => string,
103
+ /** Whose run it is: with it the call is kept where the platform keeps a
104
+ * workspace's small state (rows), without it beside the run as a file. */
105
+ scope?: { tenant: string; workspace: string },
103
106
  ): boolean {
104
107
  try {
105
108
  const input = io.input === undefined ? null : maskCall(io.input, redactSecrets);
@@ -112,7 +115,7 @@ export function recordCallIo(
112
115
  ...(input ? { input: input.text, ...(io.inputChars !== undefined ? { inputChars: io.inputChars } : {}), ...(input.cut || (io.inputChars ?? 0) > io.input!.length ? { inputCut: true } : {}) } : {}),
113
116
  ...(output ? { output: output.text, ...(io.outputChars !== undefined ? { outputChars: io.outputChars } : {}), ...(output.cut || (io.outputChars ?? 0) > io.output!.length ? { outputCut: true } : {}) } : {}),
114
117
  ...(io.truncated || input?.cut || output?.cut ? { truncated: true } : {}),
115
- });
118
+ }, scope);
116
119
  return true;
117
120
  } catch (err) {
118
121
  opsError("capture.write_failed", err, { tool, runId });
package/src/deploy.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  frontmatterErrorText,
37
37
  } from "./store.ts";
38
38
  import { readAgentsMdKeys } from "./agents-md.ts";
39
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
39
40
  import { libraryTools } from "./library.ts";
40
41
  import { lintFlow, regexProblem } from "./flow-lint.ts";
41
42
  import { parseEval } from "./evals.ts";
@@ -819,6 +820,8 @@ const commitFile = (tenant: string, workspace: string) =>
819
820
  path.join(workspaceDir(tenant, workspace), "..", `.${workspace}.deployed`);
820
821
 
821
822
  export function writeDeployedCommit(tenant: string, workspace: string, commit: string) {
823
+ const store = docStore(tenant, workspace);
824
+ if (store) return store.put(tenant, workspace, "deployed", "commit", { commit, at: new Date().toISOString() });
822
825
  const f = commitFile(tenant, workspace);
823
826
  fs.mkdirSync(path.dirname(f), { recursive: true });
824
827
  fs.writeFileSync(f, `${JSON.stringify({ commit, at: new Date().toISOString() })}\n`);
@@ -828,9 +831,14 @@ export function deployedCommit(
828
831
  tenant: string,
829
832
  workspace: string,
830
833
  ): { commit: string; at: string } | null {
834
+ let onFile: { commit: string; at: string } | null = null;
831
835
  try {
832
- return JSON.parse(fs.readFileSync(commitFile(tenant, workspace), "utf8"));
836
+ onFile = JSON.parse(fs.readFileSync(commitFile(tenant, workspace), "utf8"));
833
837
  } catch {
834
- return null;
838
+ /* none */
835
839
  }
840
+ const row = (quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, "deployed", "commit"), undefined) as { commit: string; at: string } | undefined) ?? null;
841
+ // Written either way over time: the later deploy is the one running.
842
+ if (row && onFile) return String(row.at) >= String(onFile.at) ? row : onFile;
843
+ return row ?? onFile;
836
844
  }
package/src/evals.ts CHANGED
@@ -39,6 +39,7 @@ import fs from "node:fs";
39
39
  import crypto from "node:crypto";
40
40
  import path from "node:path";
41
41
  import { deployedCommit } from "./deploy.ts";
42
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
42
43
  import { latestRevisionIdLocal as latestRevisionId } from "./history.ts";
43
44
  import matter from "./matter.ts";
44
45
  import { spawn } from "node:child_process";
@@ -922,9 +923,6 @@ export function writeEvalResult(
922
923
  // series with ids in it, and the "this change made it worse" table works.
923
924
  commit: string | null = deployedCommit(tenant, workspace)?.commit ?? latestRevisionId(tenant, workspace),
924
925
  ) {
925
- const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
926
- fs.mkdirSync(dir, { recursive: true });
927
- fs.writeFileSync(path.join(dir, `${result.eval}.json`), JSON.stringify(result, null, 2));
928
926
  const line: EvalHistoryEntry = {
929
927
  eval: result.eval,
930
928
  at: result.finishedAt,
@@ -933,9 +931,24 @@ export function writeEvalResult(
933
931
  failed: result.failed,
934
932
  costUsd: result.costUsd,
935
933
  };
934
+ const store = docStore(tenant, workspace);
935
+ if (store) {
936
+ store.put(tenant, workspace, EVAL_RESULT_KIND, result.eval, result);
937
+ store.append(tenant, workspace, EVAL_HISTORY_KIND, line, KEEP_EVAL_HISTORY);
938
+ return;
939
+ }
940
+ const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
941
+ fs.mkdirSync(dir, { recursive: true });
942
+ fs.writeFileSync(path.join(dir, `${result.eval}.json`), JSON.stringify(result, null, 2));
936
943
  fs.appendFileSync(path.join(dir, "history.jsonl"), `${JSON.stringify(line)}\n`);
937
944
  }
938
945
 
946
+ const EVAL_RESULT_KIND = "eval-result";
947
+ const EVAL_HISTORY_KIND = "eval-history";
948
+ const EVAL_LOCK_KIND = "eval-lock";
949
+ /** Rows of history kept per workspace: years of deploys, and bounded. */
950
+ const KEEP_EVAL_HISTORY = 5000;
951
+
939
952
  export interface EvalHistoryEntry {
940
953
  eval: string;
941
954
  at: string;
@@ -947,7 +960,15 @@ export interface EvalHistoryEntry {
947
960
  costUsd: number;
948
961
  }
949
962
 
963
+ /** Oldest first. Rows and the file both: the series may have been written either way. */
950
964
  export function readEvalHistory(tenant: string, workspace: string): EvalHistoryEntry[] {
965
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, EVAL_HISTORY_KIND, KEEP_EVAL_HISTORY) ?? [], []).map((r) => r.data as EvalHistoryEntry);
966
+ const lines = readEvalHistoryFile(tenant, workspace);
967
+ if (!rows.length) return lines;
968
+ return [...lines, ...rows.reverse()].sort((a, b) => String(a.at).localeCompare(String(b.at)));
969
+ }
970
+
971
+ function readEvalHistoryFile(tenant: string, workspace: string): EvalHistoryEntry[] {
951
972
  const file = path.join(workspaceDir(tenant, workspace), "evals", ".results", "history.jsonl");
952
973
  if (!fs.existsSync(file)) return [];
953
974
  return fs
@@ -1028,18 +1049,33 @@ export async function evaluateDeployed(
1028
1049
  // `trigger: runs` one grades real runs and has no cases to run.
1029
1050
  const evals = listEvals(tenant, workspace).filter((e) => e.trigger === "deploy" && !e.inputs);
1030
1051
  if (evals.length === 0) return { ran: 0, skipped: "no evals" };
1052
+ // A lock older than an hour is a crash, not a run.
1053
+ const store = docStore(tenant, workspace);
1031
1054
  const dir = path.join(workspaceDir(tenant, workspace), "evals", ".results");
1032
- fs.mkdirSync(dir, { recursive: true });
1033
1055
  const lock = path.join(dir, ".evaluating");
1034
- // A lock older than an hour is a crash, not a run.
1035
- try {
1036
- if (Date.now() - fs.statSync(lock).mtimeMs < 60 * 60_000) {
1037
- return { ran: 0, skipped: "evals already running for an earlier deploy" };
1056
+ const HOUR = 60 * 60_000;
1057
+ const busy = { ran: 0, skipped: "evals already running for an earlier deploy" };
1058
+ // A lock taken in the OTHER place (the switch moved while evals ran) still holds.
1059
+ const fileHeld = () => {
1060
+ try {
1061
+ return Date.now() - fs.statSync(lock).mtimeMs < HOUR;
1062
+ } catch {
1063
+ return false;
1038
1064
  }
1039
- } catch {
1040
- // no lock
1065
+ };
1066
+ const rowHeld = () => {
1067
+ const at = Date.parse((quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, EVAL_LOCK_KIND, "deploy"), undefined) as { at?: string } | undefined)?.at ?? "");
1068
+ return Number.isFinite(at) && Date.now() - at < HOUR;
1069
+ };
1070
+ if (store) {
1071
+ if (fileHeld()) return busy;
1072
+ // One row, taken by exactly one caller however many pods race.
1073
+ if (!store.claim(tenant, workspace, EVAL_LOCK_KIND, "deploy", { stamp, at: new Date().toISOString() }, HOUR)) return busy;
1074
+ } else {
1075
+ if (rowHeld() || fileHeld()) return busy;
1076
+ fs.mkdirSync(dir, { recursive: true });
1077
+ fs.writeFileSync(lock, stamp);
1041
1078
  }
1042
- fs.writeFileSync(lock, stamp);
1043
1079
  let ran = 0;
1044
1080
  try {
1045
1081
  for (const info of evals) {
@@ -1070,7 +1106,8 @@ export async function evaluateDeployed(
1070
1106
  }
1071
1107
  }
1072
1108
  } finally {
1073
- fs.rmSync(lock, { force: true });
1109
+ if (store) quietly(() => store.drop(tenant, workspace, EVAL_LOCK_KIND, "deploy"), undefined);
1110
+ else fs.rmSync(lock, { force: true });
1074
1111
  }
1075
1112
  return { ran, skipped: null };
1076
1113
  }
@@ -1079,7 +1116,11 @@ export function readEvalResult(tenant: string, workspace: string, name: string):
1079
1116
  try {
1080
1117
  assertSafeName(name, "eval");
1081
1118
  const file = path.join(workspaceDir(tenant, workspace), "evals", ".results", `${name}.json`);
1082
- return fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, "utf8")) as EvalResult) : null;
1119
+ const onFile = fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, "utf8")) as EvalResult) : null;
1120
+ const row = (quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, EVAL_RESULT_KIND, name), undefined) as EvalResult | undefined) ?? null;
1121
+ // Written either way over time: the later run is the result.
1122
+ if (row && onFile) return String(row.finishedAt) >= String(onFile.finishedAt) ? row : onFile;
1123
+ return row ?? onFile;
1083
1124
  } catch {
1084
1125
  return null;
1085
1126
  }
package/src/grades.ts CHANGED
@@ -50,6 +50,13 @@ import { workspaceDir, listRunSummaries, readRun, assertSafeName, type RunRecord
50
50
  import { listEvals, checkAssertion, judgeCall, judgeProcessEnv, type EvalInfo, type Assertion } from "./evals.ts";
51
51
  import { accountModelEnv, withModelEnv } from "./model-env.ts";
52
52
  import { judgeVerdict } from "./judge-verdict.ts";
53
+ import { docRows, docStore } from "./workspace-docs.ts";
54
+
55
+ /** Grades as rows: one log per grader. The cursor: one document per grader. */
56
+ const gradeKind = (name: string) => `grades:${name}`;
57
+ const GRADER_KIND = "grader";
58
+ /** More rows than pruneGrades ever leaves, so a read is the whole log. */
59
+ const ALL_GRADE_ROWS = 100_000;
53
60
 
54
61
  /** How far back the pass looks for runs to grade. */
55
62
  export const GRADE_WINDOW_MS = 3 * 86400_000;
@@ -260,12 +267,36 @@ export async function gradeRun(
260
267
  /** Keep a grade: one line, appended. */
261
268
  export function recordGrade(tenant: string, workspace: string, grade: Grade): void {
262
269
  const file = gradesFile(tenant, workspace, grade.eval);
270
+ const store = docStore(tenant, workspace);
271
+ if (store) return store.append(tenant, workspace, gradeKind(grade.eval), grade, 0);
263
272
  fs.mkdirSync(path.dirname(file), { recursive: true });
264
273
  fs.appendFileSync(file, `${JSON.stringify(grade)}\n`);
265
274
  }
266
275
 
267
- /** Every line of a grader's file, oldest first; a torn line is skipped. */
276
+ /** The grader's rows, oldest first, each with its row id. Not quiet: a pass
277
+ * that cannot read what it graded must stop, not grade every run again. */
278
+ function rowLines(tenant: string, workspace: string, name: string): { id: string; grade: Grade }[] {
279
+ assertSafeName(name, "eval");
280
+ const rows = docRows(tenant, workspace)?.tail(tenant, workspace, gradeKind(name), ALL_GRADE_ROWS) ?? [];
281
+ const out: { id: string; grade: Grade }[] = [];
282
+ for (const r of rows.reverse()) {
283
+ const g = r.data as Grade;
284
+ if (g && typeof g.runId === "string" && typeof g.at === "string") out.push({ id: r.id, grade: g });
285
+ }
286
+ return out;
287
+ }
288
+
289
+ /** Every grade of a grader, oldest first: the file's lines and the rows (it
290
+ * may have been written either way over time). */
268
291
  function readLines(tenant: string, workspace: string, name: string): Grade[] {
292
+ const rows = rowLines(tenant, workspace, name).map((r) => r.grade);
293
+ const lines = fileLines(tenant, workspace, name);
294
+ if (!rows.length) return lines;
295
+ return [...lines, ...rows].sort((a, b) => a.at.localeCompare(b.at));
296
+ }
297
+
298
+ /** Every line of a grader's file, oldest first; a torn line is skipped. */
299
+ function fileLines(tenant: string, workspace: string, name: string): Grade[] {
269
300
  let raw: string;
270
301
  try {
271
302
  raw = fs.readFileSync(gradesFile(tenant, workspace, name), "utf8");
@@ -352,12 +383,12 @@ export function summariseGrades(grades: Grade[]): GradeSummary {
352
383
  * never sampled, so a new grader starts from now rather than back-filling. */
353
384
  export function graderSince(tenant: string, workspace: string, name: string, now = Date.now()): number {
354
385
  const file = stateFile(tenant, workspace, name);
355
- try {
356
- const s = JSON.parse(fs.readFileSync(file, "utf8")) as { since?: string };
357
- const t = s.since ? Date.parse(s.since) : NaN;
358
- if (Number.isFinite(t)) return t;
359
- } catch {
360
- /* first sight */
386
+ const t = Date.parse(graderState(tenant, workspace, name).since ?? "");
387
+ if (Number.isFinite(t)) return t;
388
+ const store = docStore(tenant, workspace);
389
+ if (store) {
390
+ store.merge(tenant, workspace, GRADER_KIND, name, { since: new Date(now).toISOString() });
391
+ return now;
361
392
  }
362
393
  fs.mkdirSync(path.dirname(file), { recursive: true });
363
394
  fs.writeFileSync(`${file}.tmp`, JSON.stringify({ since: new Date(now).toISOString() }));
@@ -368,17 +399,29 @@ export function graderSince(tenant: string, workspace: string, name: string, now
368
399
  /** When a grader last had a run graded by the pass (0: never) — the pass
369
400
  * serves the longest-waiting grader first, so fairness holds across passes. */
370
401
  export function graderLastServed(tenant: string, workspace: string, name: string): number {
402
+ const t = Date.parse(graderState(tenant, workspace, name).lastServed ?? "");
403
+ return Number.isFinite(t) ? t : 0;
404
+ }
405
+
406
+ /** The grader's cursor from the file and the row together: the EARLIEST
407
+ * first sight (a grader is never made new again by a switch) and the LATEST
408
+ * serving. */
409
+ function graderState(tenant: string, workspace: string, name: string): { since?: string; lastServed?: string } {
410
+ let onFile: { since?: string; lastServed?: string } = {};
371
411
  try {
372
- const s = JSON.parse(fs.readFileSync(stateFile(tenant, workspace, name), "utf8")) as { lastServed?: string };
373
- const t = s.lastServed ? Date.parse(s.lastServed) : NaN;
374
- return Number.isFinite(t) ? t : 0;
412
+ onFile = JSON.parse(fs.readFileSync(stateFile(tenant, workspace, name), "utf8")) as typeof onFile;
375
413
  } catch {
376
- return 0;
414
+ /* none */
377
415
  }
416
+ const row = (docRows(tenant, workspace)?.get(tenant, workspace, GRADER_KIND, name) as typeof onFile | undefined) ?? {};
417
+ const pick = (a: string | undefined, b: string | undefined, later: boolean) => (!a ? b : !b ? a : (a > b) === later ? a : b);
418
+ return { since: pick(onFile.since, row.since, false), lastServed: pick(onFile.lastServed, row.lastServed, true) };
378
419
  }
379
420
 
380
421
  function markServed(tenant: string, workspace: string, name: string, now: number): void {
381
422
  const file = stateFile(tenant, workspace, name);
423
+ const store = docStore(tenant, workspace);
424
+ if (store) return store.merge(tenant, workspace, GRADER_KIND, name, { lastServed: new Date(now).toISOString() });
382
425
  let state: Record<string, unknown> = {};
383
426
  try {
384
427
  state = JSON.parse(fs.readFileSync(file, "utf8")) as Record<string, unknown>;
@@ -435,22 +478,33 @@ export function gradeCandidates(tenant: string, workspace: string, info: EvalInf
435
478
  /** Drop grades past the keeping window or the line cap. Rewritten whole
436
479
  * (temp, then rename); only the pass prunes. */
437
480
  export function pruneGrades(tenant: string, workspace: string, name: string, now = Date.now()): number {
438
- const file = gradesFile(tenant, workspace, name);
439
- if (!fs.existsSync(file)) return 0;
440
- // Read whatever its size: the 90 days hold for a quiet grader too.
441
- const lines = readLines(tenant, workspace, name);
442
481
  // The line cap never takes a grade from the last GRADE_WINDOW_MS (and a
443
482
  // day's margin): those are what keeps the pass from grading a run twice.
444
483
  const recent = (g: Grade) => now - Date.parse(g.at) < GRADE_WINDOW_MS + 86400_000;
445
- const old = lines.filter((g) => !recent(g) && now - Date.parse(g.at) < GRADE_KEEP_MS);
446
- const room = GRADE_KEEP_LINES - lines.filter(recent).length;
447
- const kept = [...(room > 0 ? old.slice(-room) : []), ...lines.filter(recent)]
448
- .sort((a, b) => a.at.localeCompare(b.at));
449
- if (kept.length === lines.length) return 0;
484
+ const keepers = <T>(all: T[], of: (x: T) => Grade): T[] => {
485
+ const old = all.filter((x) => !recent(of(x)) && now - Date.parse(of(x).at) < GRADE_KEEP_MS);
486
+ const room = GRADE_KEEP_LINES - all.filter((x) => recent(of(x))).length;
487
+ return [...(room > 0 ? old.slice(-room) : []), ...all.filter((x) => recent(of(x)))];
488
+ };
489
+ // The rows, by the same rule (each place keeps its own window).
490
+ let droppedRows = 0;
491
+ const rows = rowLines(tenant, workspace, name);
492
+ if (rows.length) {
493
+ const keep = new Set(keepers(rows, (r) => r.grade).map((r) => r.id));
494
+ const gone = rows.filter((r) => !keep.has(r.id)).map((r) => r.id);
495
+ if (gone.length) docRows(tenant, workspace)?.prune(tenant, workspace, gradeKind(name), gone);
496
+ droppedRows = gone.length;
497
+ }
498
+ const file = gradesFile(tenant, workspace, name);
499
+ if (!fs.existsSync(file)) return droppedRows;
500
+ // Read whatever its size: the 90 days hold for a quiet grader too.
501
+ const lines = fileLines(tenant, workspace, name);
502
+ const kept = keepers(lines, (g) => g).sort((a, b) => a.at.localeCompare(b.at));
503
+ if (kept.length === lines.length) return droppedRows;
450
504
  const tmp = `${file}.${process.pid}.tmp`;
451
505
  fs.writeFileSync(tmp, kept.map((g) => JSON.stringify(g)).join("\n") + (kept.length ? "\n" : ""));
452
506
  fs.renameSync(tmp, file);
453
- return lines.length - kept.length;
507
+ return droppedRows + lines.length - kept.length;
454
508
  }
455
509
 
456
510
  /**
package/src/history.ts CHANGED
@@ -35,6 +35,7 @@
35
35
  // per save.
36
36
 
37
37
  import fs from "node:fs";
38
+ import { processState } from "./process-state.ts";
38
39
  import path from "node:path";
39
40
  import crypto from "node:crypto";
40
41
  import { dataRoot } from "./paths.ts";
@@ -49,10 +50,28 @@ import { dataRoot } from "./paths.ts";
49
50
  * made a minute later has everything.
50
51
  */
51
52
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
52
- let readTree: TreeReader = () => null;
53
- export function registerTreeReader(fn: TreeReader) {
54
- const prev = readTree;
55
- readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
53
+ /** What is registered here is one per PROCESS (process-state.ts): the boot
54
+ * registers the journal and the view, and a route handler compiled apart from
55
+ * it must see them — until 13 Nov 2026 it did not, and a dashboard save was
56
+ * never journalled as a revision. */
57
+ const REG = processState("history", () => ({
58
+ readers: new Map<string, TreeReader>(),
59
+ journal: null as Journal | null,
60
+ onGone: null as ((tenant: string, workspace: string) => void) | null,
61
+ lifecycle: null as WorkspaceLifecycle | null,
62
+ view: null as RevisionView | null,
63
+ }));
64
+ /** `name` says which reader this is: every copy of a module registers its own,
65
+ * and the last one of a name replaces the others. */
66
+ export function registerTreeReader(fn: TreeReader, name = "default") {
67
+ REG.readers.set(name, fn);
68
+ }
69
+ function readTree(tenant: string, scope: string): RevisionFile[] | null {
70
+ for (const fn of REG.readers.values()) {
71
+ const tree = fn(tenant, scope);
72
+ if (tree) return tree;
73
+ }
74
+ return null;
56
75
  }
57
76
 
58
77
  /** The scope's tree as the registered readers see it (text files only), or null. */
@@ -66,20 +85,18 @@ export function currentTree(tenant: string, scope: string): RevisionFile[] | nul
66
85
  * Called after the legacy record is written; never throws into the writer.
67
86
  */
68
87
  type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }) => void;
69
- let journal: Journal | null = null;
70
88
  export function registerJournal(fn: Journal | null) {
71
- journal = fn;
89
+ REG.journal = fn;
72
90
  }
73
91
 
74
92
  /** A workspace was deleted: whatever a registered journal still holds for it
75
93
  * (queued changes, their files) goes too (FOL-126 phase 4). */
76
- let onGone: ((tenant: string, workspace: string) => void) | null = null;
77
94
  export function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null) {
78
- onGone = fn;
95
+ REG.onGone = fn;
79
96
  }
80
97
  export function workspaceGone(tenant: string, workspace: string): void {
81
98
  try {
82
- onGone?.(tenant, workspace);
99
+ REG.onGone?.(tenant, workspace);
83
100
  } catch {
84
101
  // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
85
102
  }
@@ -99,15 +116,14 @@ export interface WorkspaceLifecycle {
99
116
  move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
100
117
  moved(tenant: string, from: string, to: string): void;
101
118
  }
102
- let lifecycleHooks: WorkspaceLifecycle | null = null;
103
119
  export function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null) {
104
- lifecycleHooks = l;
120
+ REG.lifecycle = l;
105
121
  }
106
- export const workspaceLifecycle = (): WorkspaceLifecycle | null => lifecycleHooks;
122
+ export const workspaceLifecycle = (): WorkspaceLifecycle | null => REG.lifecycle;
107
123
  /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
108
124
  export function workspaceMoved(tenant: string, from: string, to: string): void {
109
125
  try {
110
- lifecycleHooks?.moved(tenant, from, to);
126
+ REG.lifecycle?.moved(tenant, from, to);
111
127
  } catch {
112
128
  // finished by the next reconcile
113
129
  }
@@ -225,7 +241,7 @@ export function recordRevision(
225
241
  snapshot(tenant, scope, rev.id);
226
242
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
227
243
  try {
228
- journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
244
+ REG.journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
229
245
  } catch {
230
246
  // the revision store is not allowed to break a save; workspace-revisions logs and retries
231
247
  }
@@ -556,9 +572,8 @@ export interface RevisionView {
556
572
  * the store has none. Optional: a view without it is asked through `list`. */
557
573
  get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
558
574
  }
559
- let view: RevisionView | null = null;
560
575
  export function registerRevisionView(v: RevisionView | null) {
561
- view = v;
576
+ REG.view = v;
562
577
  }
563
578
 
564
579
  /** Revisions first, then the local entries older than the oldest of them.
@@ -572,7 +587,7 @@ async function combinedRows(
572
587
  const limit = opts.limit ?? 200;
573
588
  // The whole of `limit`, every page of it: the store's first page is not all
574
589
  // of history (FOL-152).
575
- const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
590
+ const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
576
591
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
577
592
  if (restorableOnly) {
578
593
  const have = snapshotIds(tenant, scope);
@@ -603,24 +618,24 @@ export async function listRevisionsRestorable(tenant: string, scope: string, opt
603
618
 
604
619
  export async function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null> {
605
620
  assertSafeName(id, "revision id");
606
- const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
621
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
607
622
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
608
623
  }
609
624
 
610
625
  export async function snapshotAt(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null> {
611
626
  assertSafeName(id, "revision id");
612
- const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
627
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
613
628
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
614
629
  }
615
630
 
616
631
  export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
617
632
  assertSafeName(id, "revision id");
618
633
  if (hasSnapshotLocal(tenant, scope, id)) return true;
619
- if (!view || scope === "@library") return false;
634
+ if (!REG.view || scope === "@library") return false;
620
635
  // Looked up by id: a listing stops at a page, and a revision older than it
621
636
  // was "not restorable" until 9 Nov 2026 (FOL-152).
622
- if (view.get) return (await view.get(tenant, scope, id)) !== null;
623
- return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
637
+ if (REG.view.get) return (await REG.view.get(tenant, scope, id)) !== null;
638
+ return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
624
639
  }
625
640
 
626
641
  export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
@@ -632,8 +647,8 @@ export async function resolveRevision(tenant: string, scope: string, to: string,
632
647
  // An id in the store is one lookup; anything else (a date, a local id, a
633
648
  // commit) is answered from ALL of history — every page of the store, without
634
649
  // the changed paths, then the local entries.
635
- if ("id" in want && view?.get && scope !== "@library") {
636
- const hit = await view.get(tenant, scope, want.id);
650
+ if ("id" in want && REG.view?.get && scope !== "@library") {
651
+ const hit = await REG.view.get(tenant, scope, want.id);
637
652
  if (hit) return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
638
653
  }
639
654
  return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
@@ -20,11 +20,12 @@ import path from "node:path";
20
20
 
21
21
  /** What is stored: the whole entry (new content only, never the old text). */
22
22
  export interface JournalRecord {
23
- v: 1;
23
+ /** 2: some file is not text and rides as base64 (`enc`). */
24
+ v: 1 | 2;
24
25
  tenant: string;
25
26
  workspace: string;
26
27
  id: string;
27
- files: { path: string; before: null; after: string | null; base?: string | null; handed?: string | null }[];
28
+ files: { path: string; before: null; after: string | null; base?: string | null; handed?: string | null; enc?: "base64" }[];
28
29
  by: string;
29
30
  message: string;
30
31
  at: string;
package/src/library.ts CHANGED
@@ -437,7 +437,7 @@ registerTreeReader((tenant, scope) => {
437
437
  }
438
438
  }
439
439
  return out;
440
- });
440
+ }, "library");
441
441
 
442
442
 
443
443
 
@@ -0,0 +1,21 @@
1
+ // State that must be ONE per process, not one per copy of a module.
2
+ //
3
+ // A bundler that compiles the boot file and the route handlers apart (Next
4
+ // does) gives each bundle its own copy of every module they share. A
5
+ // registration made at boot — "revisions go to this store", "the vault is in
6
+ // the database" — then fills the boot bundle's copy, and a route handler reads
7
+ // its own, still empty: on dev (12 Nov 2026) a dashboard save was never
8
+ // journalled as a revision, and a run's outputs published to the object store
9
+ // answered "no such output" from the API, because only the worker (one bundle)
10
+ // saw the stores. platform.ts met this first, for its hooks.
11
+ //
12
+ // globalThis is the one thing every bundle in a process shares; a module keeps
13
+ // what it is told at boot (and the queues that go with it) in an object made
14
+ // here once.
15
+
16
+ /** The process's one object under `name`, made by `init` the first time. */
17
+ export function processState<T extends object>(name: string, init: () => T): T {
18
+ const g = globalThis as unknown as Record<symbol, object | undefined>;
19
+ const key = Symbol.for(`foldrun.state.${name}`);
20
+ return (g[key] ??= init()) as T;
21
+ }
package/src/records.ts CHANGED
@@ -43,7 +43,43 @@ export interface RecordsPortAsync {
43
43
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
44
44
  }
45
45
 
46
+ /** Small per-workspace state that used to be files in the workspace's folder
47
+ * (FOL-126, the last files on the volume): webhook generations and the
48
+ * delivery log, eval results and their history, grades and grader cursors,
49
+ * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
50
+ * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
51
+ * the port; workspace-docs.ts is the only caller. */
52
+ export interface DocsPort {
53
+ get(tenant: string, workspace: string, kind: string, key: string): unknown | undefined;
54
+ put(tenant: string, workspace: string, kind: string, key: string, data: unknown): void;
55
+ /** Shallow-merge `patch` into the document, making it when absent — one statement, so two parts of one call never lose each other. */
56
+ merge(tenant: string, workspace: string, kind: string, key: string, patch: Record<string, unknown>): void;
57
+ /** Move a counter forward atomically: `field` becomes the greater of its
58
+ * value + 1 and `atLeast`, `patch` is merged in, and the new value comes back. */
59
+ raise(tenant: string, workspace: string, kind: string, key: string, field: string, atLeast: number, patch: Record<string, unknown>): number;
60
+ /** Take the key unless a document younger than `staleMs` holds it. True for the one caller that took it. */
61
+ claim(tenant: string, workspace: string, kind: string, key: string, data: unknown, staleMs: number): boolean;
62
+ /** `key` null: every document of the kind. */
63
+ drop(tenant: string, workspace: string, kind: string, key: string | null): void;
64
+ /** Every document of the kind whose key starts with `prefix`. */
65
+ dropPrefix(tenant: string, workspace: string, kind: string, prefix: string): void;
66
+ list(tenant: string, workspace: string, kind: string): { key: string; data: unknown }[];
67
+ /** Add one entry; `keep` > 0 drops all but the newest `keep`. */
68
+ append(tenant: string, workspace: string, kind: string, data: unknown, keep: number): void;
69
+ /** Newest first. */
70
+ tail(tenant: string, workspace: string, kind: string, limit: number): { id: string; data: unknown }[];
71
+ replace(tenant: string, workspace: string, kind: string, id: string, data: unknown): void;
72
+ prune(tenant: string, workspace: string, kind: string, ids: string[]): void;
73
+ }
74
+
46
75
  export interface RecordsPort {
76
+ /** The small per-workspace state (see DocsPort). Optional: a port without
77
+ * it keeps that state in the workspace's folder. */
78
+ docs?: DocsPort;
79
+ /** The `records.docs_store` setting, read per call: while false, that state
80
+ * is WRITTEN to the folder as before. It is read from both, so switching
81
+ * either way mid-flight loses nothing already written. */
82
+ docsOn?(): boolean;
47
83
  /** Async reads (see RecordsPortAsync). */
48
84
  async?: RecordsPortAsync;
49
85
  /** The `runs.step_state_store` setting, read per call: while false, step