@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.
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { workspaceDir } from "./store.js";
8
8
  import { installKeyMaterial } from "./secrets.js";
9
9
  import crypto from "node:crypto";
10
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
10
11
  /**
11
12
  * The install's secret key. Every derived token — flow hooks, git secrets,
12
13
  * approval links — hangs off this one value, so rotating it invalidates all
@@ -35,19 +36,36 @@ function readHooks(tenant, workspace) {
35
36
  return {};
36
37
  }
37
38
  }
39
+ /** The hook's generation: the greater of the row's and the file's, so a
40
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
41
+ * holds whichever way the switch stands now — an old URL never comes back.
42
+ * A database that cannot answer fails the call: guessing from the file could
43
+ * accept a token that was rotated away. */
38
44
  export function hookGeneration(tenant, workspace, flow) {
39
- return readHooks(tenant, workspace)[flow]?.gen ?? 0;
45
+ const file = readHooks(tenant, workspace)[flow]?.gen ?? 0;
46
+ const row = docRows(tenant, workspace)?.get(tenant, workspace, HOOK_KIND, flow)?.gen ?? 0;
47
+ return Math.max(file, row);
40
48
  }
49
+ const HOOK_KIND = "hook";
50
+ const DELIVERY_KIND = "hook-delivery";
41
51
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
42
52
  export function rotateWebhook(tenant, workspace, flow) {
43
53
  const hooks = readHooks(tenant, workspace);
44
- hooks[flow] = { gen: (hooks[flow]?.gen ?? 0) + 1, rotatedAt: new Date().toISOString() };
45
54
  const file = hooksFile(tenant, workspace);
46
55
  // Into a workspace that exists, never making one (30 Oct 2026): the mkdir
47
56
  // here turned a rotate under a mistyped name into a workspace holding only
48
57
  // hooks.json, past the plan's workspace count.
49
58
  if (!fs.existsSync(path.dirname(file)))
50
59
  throw Object.assign(new Error(`workspace ${workspace} not found`), { status: 404 });
60
+ const rotatedAt = new Date().toISOString();
61
+ const store = docStore(tenant, workspace);
62
+ if (store) {
63
+ // One statement moves the row past both its own value and the file's.
64
+ store.raise(tenant, workspace, HOOK_KIND, flow, "gen", (hooks[flow]?.gen ?? 0) + 1, { rotatedAt });
65
+ return webhookPath(tenant, workspace, flow);
66
+ }
67
+ // On the file: still past whatever a row holds (hookGeneration reads both).
68
+ hooks[flow] = { gen: hookGeneration(tenant, workspace, flow) + 1, rotatedAt };
51
69
  fs.writeFileSync(file, JSON.stringify(hooks, null, 2));
52
70
  return webhookPath(tenant, workspace, flow);
53
71
  }
@@ -129,6 +147,9 @@ export function recordDelivery(tenant, workspace, delivery) {
129
147
  const file = deliveriesFile(tenant, workspace);
130
148
  if (!fs.existsSync(path.dirname(file)))
131
149
  return; // no workspace, nothing to log against
150
+ const store = docStore(tenant, workspace);
151
+ if (store)
152
+ return recordDeliveryRow(store, tenant, workspace, delivery);
132
153
  if (UNAUTHENTICATED.includes(delivery.outcome))
133
154
  return recordRefusal(file, tenant, workspace, delivery);
134
155
  fs.appendFileSync(file, JSON.stringify(delivery) + "\n");
@@ -146,6 +167,32 @@ export function recordDelivery(tenant, workspace, delivery) {
146
167
  // compaction is best-effort; the append already landed
147
168
  }
148
169
  }
170
+ /** The same log as rows: an append that keeps the newest KEEP, and a refusal
171
+ * folded into the newest entry when that is a refusal too (so a flood is one
172
+ * row). The fold is read-then-replace: two refusals at once may count one
173
+ * short, never push a real delivery out. */
174
+ function recordDeliveryRow(store, tenant, workspace, delivery) {
175
+ if (UNAUTHENTICATED.includes(delivery.outcome)) {
176
+ const [last] = store.tail(tenant, workspace, DELIVERY_KIND, 1);
177
+ const prev = last?.data;
178
+ if (last && prev && UNAUTHENTICATED.includes(prev.outcome)) {
179
+ store.replace(tenant, workspace, DELIVERY_KIND, last.id, foldRefusal(prev, delivery));
180
+ return;
181
+ }
182
+ }
183
+ store.append(tenant, workspace, DELIVERY_KIND, delivery, KEEP_DELIVERIES);
184
+ }
185
+ /** A refusal folded into the refusal before it. The flow name is not part of
186
+ * the match: it comes from the URL, so a flood that varies it would
187
+ * otherwise never collapse. */
188
+ function foldRefusal(last, delivery) {
189
+ return {
190
+ ...delivery,
191
+ count: (last.count ?? 1) + 1,
192
+ first: last.first ?? last.t,
193
+ ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
194
+ };
195
+ }
149
196
  /**
150
197
  * A refusal — anyone's to send — never changes the workspace's directory: no
151
198
  * new file, no tmp file, no rename. The directory's mtime is the workspace's
@@ -201,12 +248,7 @@ function collapseInto(file, delivery) {
201
248
  }
202
249
  if (!UNAUTHENTICATED.includes(last.outcome))
203
250
  return false;
204
- const merged = {
205
- ...delivery,
206
- count: (last.count ?? 1) + 1,
207
- first: last.first ?? last.t,
208
- ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
209
- };
251
+ const merged = foldRefusal(last, delivery);
210
252
  const line = Buffer.from(JSON.stringify(merged) + "\n");
211
253
  const at = Buffer.byteLength(end.slice(0, cut));
212
254
  const fd = fs.openSync(file, "r+");
@@ -220,6 +262,17 @@ function collapseInto(file, delivery) {
220
262
  return true;
221
263
  }
222
264
  export function readDeliveries(tenant, workspace, limit = 20) {
265
+ // Rows and the file both: the log may have been written either way.
266
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, DELIVERY_KIND, limit) ?? [], []).map((r) => r.data);
267
+ const lines = readDeliveryLines(tenant, workspace, limit);
268
+ if (!rows.length)
269
+ return lines;
270
+ if (!lines.length)
271
+ return rows;
272
+ // Stable: equal times keep each source's own newest-first order.
273
+ return [...rows, ...lines].sort((a, b) => String(b.t).localeCompare(String(a.t))).slice(0, limit);
274
+ }
275
+ function readDeliveryLines(tenant, workspace, limit) {
223
276
  const file = deliveriesFile(tenant, workspace);
224
277
  if (!fs.existsSync(file))
225
278
  return [];
@@ -0,0 +1,9 @@
1
+ import { type DocsPort } from "./records.ts";
2
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
3
+ * CLI, and for a workspace whose records are still files. */
4
+ export declare function docRows(tenant: string, workspace: string): DocsPort | null;
5
+ /** Rows to write to, or null: write the folder. */
6
+ export declare function docStore(tenant: string, workspace: string): DocsPort | null;
7
+ /** A read that must not take the caller down with the database: these are
8
+ * logs and markers beside the work, never the work. */
9
+ export declare function quietly<T>(fn: () => T, fallback: T): T;
@@ -0,0 +1,31 @@
1
+ // Where a workspace's small state lives (FOL-126): rows through the records
2
+ // port when the platform registered one that has them, the folder otherwise.
3
+ //
4
+ // Two answers, because a switch must never lose what is already written:
5
+ // `docStore` is where a WRITE goes (rows only while `records.docs_store` is
6
+ // on), `docRows` is what a READ also asks (rows whenever the port has them,
7
+ // on or off). Every caller reads both places and keeps the newer; nothing is
8
+ // copied between them.
9
+ import { records } from "./records.js";
10
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
11
+ * CLI, and for a workspace whose records are still files. */
12
+ export function docRows(tenant, workspace) {
13
+ return records(tenant, workspace)?.docs ?? null;
14
+ }
15
+ /** Rows to write to, or null: write the folder. */
16
+ export function docStore(tenant, workspace) {
17
+ const port = records(tenant, workspace);
18
+ if (!port?.docs || !port.docsOn?.())
19
+ return null;
20
+ return port.docs;
21
+ }
22
+ /** A read that must not take the caller down with the database: these are
23
+ * logs and markers beside the work, never the work. */
24
+ export function quietly(fn, fallback) {
25
+ try {
26
+ return fn();
27
+ }
28
+ catch {
29
+ return fallback;
30
+ }
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "21.0.0",
3
+ "version": "21.2.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/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
package/src/runner.ts CHANGED
@@ -118,7 +118,7 @@ import { buildScriptTools, parseScripts, type ExecutionContext, type ScriptSpec
118
118
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.ts";
119
119
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv, type PreparedRuntime, type RuntimeSpec } from "./runtime.ts";
120
120
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.ts";
121
- import { dataRoot } from "./paths.ts";
121
+ import { dataRoot, singleWorkspace } from "./paths.ts";
122
122
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.ts";
123
123
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.ts";
124
124
  import { chooseExecutor, ensureImage } from "./container.ts";
@@ -2346,7 +2346,7 @@ async function runStep(
2346
2346
  captureFull = true;
2347
2347
  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` });
2348
2348
  }
2349
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact)) {
2349
+ 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, "..", "..")) })) {
2350
2350
  capturedChars += size;
2351
2351
  rest = { ...others, captured: true };
2352
2352
  }