@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
@@ -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
@@ -8,7 +8,9 @@
8
8
  * made a minute later has everything.
9
9
  */
10
10
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
11
- export declare function registerTreeReader(fn: TreeReader): void;
11
+ /** `name` says which reader this is: every copy of a module registers its own,
12
+ * and the last one of a name replaces the others. */
13
+ export declare function registerTreeReader(fn: TreeReader, name?: string): void;
12
14
  /** The scope's tree as the registered readers see it (text files only), or null. */
13
15
  export declare function currentTree(tenant: string, scope: string): RevisionFile[] | null;
14
16
  /**
@@ -22,6 +24,8 @@ type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: {
22
24
  at: string;
23
25
  }) => void;
24
26
  export declare function registerJournal(fn: Journal | null): void;
27
+ /** A workspace was deleted: whatever a registered journal still holds for it
28
+ * (queued changes, their files) goes too (FOL-126 phase 4). */
25
29
  export declare function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null): void;
26
30
  export declare function workspaceGone(tenant: string, workspace: string): void;
27
31
  /**
@@ -34,45 +34,62 @@
34
34
  // change, and storing them again would be the whole tree
35
35
  // per save.
36
36
  import fs from "node:fs";
37
+ import { processState } from "./process-state.js";
37
38
  import path from "node:path";
38
39
  import crypto from "node:crypto";
39
40
  import { dataRoot } from "./paths.js";
40
- let readTree = () => null;
41
- export function registerTreeReader(fn) {
42
- const prev = readTree;
43
- readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
41
+ /** What is registered here is one per PROCESS (process-state.ts): the boot
42
+ * registers the journal and the view, and a route handler compiled apart from
43
+ * it must see them — until 13 Nov 2026 it did not, and a dashboard save was
44
+ * never journalled as a revision. */
45
+ const REG = processState("history", () => ({
46
+ readers: new Map(),
47
+ journal: null,
48
+ onGone: null,
49
+ lifecycle: null,
50
+ view: null,
51
+ }));
52
+ /** `name` says which reader this is: every copy of a module registers its own,
53
+ * and the last one of a name replaces the others. */
54
+ export function registerTreeReader(fn, name = "default") {
55
+ REG.readers.set(name, fn);
56
+ }
57
+ function readTree(tenant, scope) {
58
+ for (const fn of REG.readers.values()) {
59
+ const tree = fn(tenant, scope);
60
+ if (tree)
61
+ return tree;
62
+ }
63
+ return null;
44
64
  }
45
65
  /** The scope's tree as the registered readers see it (text files only), or null. */
46
66
  export function currentTree(tenant, scope) {
47
67
  return readTree(tenant, scope);
48
68
  }
49
- let journal = null;
50
69
  export function registerJournal(fn) {
51
- journal = fn;
70
+ REG.journal = fn;
52
71
  }
53
72
  /** A workspace was deleted: whatever a registered journal still holds for it
54
73
  * (queued changes, their files) goes too (FOL-126 phase 4). */
55
- let onGone = null;
56
74
  export function registerWorkspaceGone(fn) {
57
- onGone = fn;
75
+ REG.onGone = fn;
58
76
  }
59
77
  export function workspaceGone(tenant, workspace) {
60
78
  try {
61
- onGone?.(tenant, workspace);
79
+ REG.onGone?.(tenant, workspace);
62
80
  }
63
81
  catch {
64
82
  // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
65
83
  }
66
84
  }
67
- let lifecycleHooks = null;
68
85
  export function registerWorkspaceLifecycle(l) {
69
- lifecycleHooks = l;
86
+ REG.lifecycle = l;
70
87
  }
71
- export const workspaceLifecycle = () => lifecycleHooks;
88
+ export const workspaceLifecycle = () => REG.lifecycle;
72
89
  /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
73
90
  export function workspaceMoved(tenant, from, to) {
74
91
  try {
75
- lifecycleHooks?.moved(tenant, from, to);
92
+ REG.lifecycle?.moved(tenant, from, to);
76
93
  }
77
94
  catch {
78
95
  // finished by the next reconcile
@@ -154,7 +171,7 @@ export function recordRevision(tenant, scope, files, meta = {}) {
154
171
  snapshot(tenant, scope, rev.id);
155
172
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
156
173
  try {
157
- journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
174
+ REG.journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
158
175
  }
159
176
  catch {
160
177
  // the revision store is not allowed to break a save; workspace-revisions logs and retries
@@ -450,9 +467,8 @@ function changedIn(revs, from, to) {
450
467
  export function latestRevisionIdLocal(tenant, scope) {
451
468
  return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
452
469
  }
453
- let view = null;
454
470
  export function registerRevisionView(v) {
455
- view = v;
471
+ REG.view = v;
456
472
  }
457
473
  /** Revisions first, then the local entries older than the oldest of them.
458
474
  * `stored` is which rows came from the store (every one a restore point). */
@@ -460,7 +476,7 @@ async function combinedRows(tenant, scope, opts, restorableOnly = false) {
460
476
  const limit = opts.limit ?? 200;
461
477
  // The whole of `limit`, every page of it: the store's first page is not all
462
478
  // of history (FOL-152).
463
- const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
479
+ const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
464
480
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
465
481
  if (restorableOnly) {
466
482
  const have = snapshotIds(tenant, scope);
@@ -489,25 +505,25 @@ export async function listRevisionsRestorable(tenant, scope, opts = {}) {
489
505
  }
490
506
  export async function readRevision(tenant, scope, id, forPath) {
491
507
  assertSafeName(id, "revision id");
492
- const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
508
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
493
509
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
494
510
  }
495
511
  export async function snapshotAt(tenant, scope, id) {
496
512
  assertSafeName(id, "revision id");
497
- const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
513
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
498
514
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
499
515
  }
500
516
  export async function hasSnapshot(tenant, scope, id) {
501
517
  assertSafeName(id, "revision id");
502
518
  if (hasSnapshotLocal(tenant, scope, id))
503
519
  return true;
504
- if (!view || scope === "@library")
520
+ if (!REG.view || scope === "@library")
505
521
  return false;
506
522
  // Looked up by id: a listing stops at a page, and a revision older than it
507
523
  // was "not restorable" until 9 Nov 2026 (FOL-152).
508
- if (view.get)
509
- return (await view.get(tenant, scope, id)) !== null;
510
- return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
524
+ if (REG.view.get)
525
+ return (await REG.view.get(tenant, scope, id)) !== null;
526
+ return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
511
527
  }
512
528
  export async function headRevision(tenant, scope) {
513
529
  return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
@@ -517,8 +533,8 @@ export async function resolveRevision(tenant, scope, to, now = Date.now()) {
517
533
  // An id in the store is one lookup; anything else (a date, a local id, a
518
534
  // commit) is answered from ALL of history — every page of the store, without
519
535
  // the changed paths, then the local entries.
520
- if ("id" in want && view?.get && scope !== "@library") {
521
- const hit = await view.get(tenant, scope, want.id);
536
+ if ("id" in want && REG.view?.get && scope !== "@library") {
537
+ const hit = await REG.view.get(tenant, scope, want.id);
522
538
  if (hit)
523
539
  return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
524
540
  }
@@ -1,6 +1,7 @@
1
1
  /** What is stored: the whole entry (new content only, never the old text). */
2
2
  export interface JournalRecord {
3
- v: 1;
3
+ /** 2: some file is not text and rides as base64 (`enc`). */
4
+ v: 1 | 2;
4
5
  tenant: string;
5
6
  workspace: string;
6
7
  id: string;
@@ -10,6 +11,7 @@ export interface JournalRecord {
10
11
  after: string | null;
11
12
  base?: string | null;
12
13
  handed?: string | null;
14
+ enc?: "base64";
13
15
  }[];
14
16
  by: string;
15
17
  message: string;
@@ -347,7 +347,7 @@ registerTreeReader((tenant, scope) => {
347
347
  }
348
348
  }
349
349
  return out;
350
- });
350
+ }, "library");
351
351
  /** The workspace folders "Move to shared" applies to: the library's kinds
352
352
  * but hooks, whose run.mjs is code a shared hook is made for on purpose. */
353
353
  export const SHAREABLE_KINDS = ["skills", "tools", "scripts", "knowledge", "memory"];
@@ -0,0 +1,2 @@
1
+ /** The process's one object under `name`, made by `init` the first time. */
2
+ export declare function processState<T extends object>(name: string, init: () => T): T;
@@ -0,0 +1,20 @@
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
+ /** The process's one object under `name`, made by `init` the first time. */
16
+ export function processState(name, init) {
17
+ const g = globalThis;
18
+ const key = Symbol.for(`foldrun.state.${name}`);
19
+ return (g[key] ??= init());
20
+ }
@@ -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