@foldrun/core 21.0.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.
- package/dist/src/capture.d.ts +7 -1
- package/dist/src/capture.js +5 -2
- package/dist/src/deploy.js +12 -2
- package/dist/src/evals.d.ts +1 -0
- package/dist/src/evals.js +60 -13
- package/dist/src/grades.js +78 -24
- package/dist/src/records.d.ts +41 -0
- package/dist/src/runner.js +2 -2
- package/dist/src/store.d.ts +4 -1
- package/dist/src/store.js +24 -3
- package/dist/src/webhook.d.ts +5 -0
- package/dist/src/webhook.js +61 -8
- package/dist/src/workspace-docs.d.ts +9 -0
- package/dist/src/workspace-docs.js +31 -0
- package/package.json +1 -1
- package/src/capture.ts +4 -1
- package/src/deploy.ts +10 -2
- package/src/evals.ts +54 -13
- package/src/grades.ts +75 -21
- package/src/records.ts +36 -0
- package/src/runner.ts +2 -2
- package/src/store.ts +21 -3
- package/src/webhook.ts +63 -8
- package/src/workspace-docs.ts +33 -0
|
@@ -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
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
|
-
|
|
836
|
+
onFile = JSON.parse(fs.readFileSync(commitFile(tenant, workspace), "utf8"));
|
|
833
837
|
} catch {
|
|
834
|
-
|
|
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
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
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
|
-
}
|
|
1040
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
.
|
|
449
|
-
|
|
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
|
}
|
package/src/store.ts
CHANGED
|
@@ -31,6 +31,7 @@ import { processState } from "./process-state.ts";
|
|
|
31
31
|
import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.ts";
|
|
32
32
|
import { platform } from "./platform.ts";
|
|
33
33
|
import { records } from "./records.ts";
|
|
34
|
+
import { docRows, docStore, quietly } from "./workspace-docs.ts";
|
|
34
35
|
import { toLF, asRaw } from "./eol.ts";
|
|
35
36
|
import type { TestEffect } from "./test-mode.ts";
|
|
36
37
|
import type { OperatorEvent } from "./operator.ts";
|
|
@@ -4065,6 +4066,7 @@ export interface RunRecord {
|
|
|
4065
4066
|
// runs/<run>/). The runner writes them, secrets already masked.
|
|
4066
4067
|
|
|
4067
4068
|
const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
4069
|
+
const CALL_KIND = "call";
|
|
4068
4070
|
|
|
4069
4071
|
function capturedCallFile(workspaceRoot: string, runId: string, callId: string): string | null {
|
|
4070
4072
|
if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
|
|
@@ -4073,9 +4075,14 @@ function capturedCallFile(workspaceRoot: string, runId: string, callId: string):
|
|
|
4073
4075
|
|
|
4074
4076
|
/** Merge one part (the input, on the call; the output, on its completion)
|
|
4075
4077
|
* into the call's file. */
|
|
4076
|
-
export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void {
|
|
4078
|
+
export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: { tenant: string; workspace: string }): void {
|
|
4077
4079
|
const file = capturedCallFile(workspaceRoot, runId, part.id);
|
|
4078
4080
|
if (!file) return;
|
|
4081
|
+
// A row when the platform keeps them (FOL-126): the two parts of a call
|
|
4082
|
+
// merge in one statement, and the web's copies read it wherever they run.
|
|
4083
|
+
// `truncated` is only ever sent true, so a merge keeps it once set.
|
|
4084
|
+
const store = scope ? docStore(scope.tenant, scope.workspace) : null;
|
|
4085
|
+
if (store && scope) return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part as unknown as Record<string, unknown>);
|
|
4079
4086
|
let prev: Partial<CapturedCall> = {};
|
|
4080
4087
|
try {
|
|
4081
4088
|
prev = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
|
|
@@ -4094,11 +4101,20 @@ export function writeCapturedCall(workspaceRoot: string, runId: string, part: Ca
|
|
|
4094
4101
|
export function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null {
|
|
4095
4102
|
const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
|
|
4096
4103
|
if (!file) return null;
|
|
4104
|
+
const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined) as CapturedCall | undefined;
|
|
4105
|
+
let onFile: CapturedCall | undefined;
|
|
4097
4106
|
try {
|
|
4098
|
-
|
|
4107
|
+
onFile = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
|
|
4099
4108
|
} catch {
|
|
4100
|
-
|
|
4109
|
+
/* none */
|
|
4110
|
+
}
|
|
4111
|
+
// A switch between a call's two parts leaves one part in each place: both, merged.
|
|
4112
|
+
if (row && onFile) {
|
|
4113
|
+
const merged: CapturedCall = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
|
|
4114
|
+
if (!merged.truncated) delete merged.truncated;
|
|
4115
|
+
return merged;
|
|
4101
4116
|
}
|
|
4117
|
+
return row ?? onFile ?? null;
|
|
4102
4118
|
}
|
|
4103
4119
|
|
|
4104
4120
|
export function runFilePath(tenant: string, workspace: string, runId: string) {
|
|
@@ -4138,6 +4154,8 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
|
|
|
4138
4154
|
// and finishes — the other order left the content with nothing pointing
|
|
4139
4155
|
// at it (Codex review, FOL-124).
|
|
4140
4156
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
4157
|
+
// Its captured calls kept as rows go the same way, before the record.
|
|
4158
|
+
if (SAFE_ID.test(runId)) docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
|
|
4141
4159
|
if (port) port.runDelete(tenant, workspace, runId);
|
|
4142
4160
|
else {
|
|
4143
4161
|
fs.rmSync(file, { force: true });
|
package/src/webhook.ts
CHANGED
|
@@ -8,6 +8,8 @@ import path from "node:path";
|
|
|
8
8
|
import { workspaceDir } from "./store.ts";
|
|
9
9
|
import { installKeyMaterial } from "./secrets.ts";
|
|
10
10
|
import crypto from "node:crypto";
|
|
11
|
+
import { docRows, docStore, quietly } from "./workspace-docs.ts";
|
|
12
|
+
import type { DocsPort } from "./records.ts";
|
|
11
13
|
|
|
12
14
|
/**
|
|
13
15
|
* The install's secret key. Every derived token — flow hooks, git secrets,
|
|
@@ -49,19 +51,37 @@ function readHooks(tenant: string, workspace: string): Record<string, HookState>
|
|
|
49
51
|
}
|
|
50
52
|
}
|
|
51
53
|
|
|
54
|
+
/** The hook's generation: the greater of the row's and the file's, so a
|
|
55
|
+
* rotation made while `records.docs_store` was on (a row) or off (the file)
|
|
56
|
+
* holds whichever way the switch stands now — an old URL never comes back.
|
|
57
|
+
* A database that cannot answer fails the call: guessing from the file could
|
|
58
|
+
* accept a token that was rotated away. */
|
|
52
59
|
export function hookGeneration(tenant: string, workspace: string, flow: string): number {
|
|
53
|
-
|
|
60
|
+
const file = readHooks(tenant, workspace)[flow]?.gen ?? 0;
|
|
61
|
+
const row = (docRows(tenant, workspace)?.get(tenant, workspace, HOOK_KIND, flow) as HookState | undefined)?.gen ?? 0;
|
|
62
|
+
return Math.max(file, row);
|
|
54
63
|
}
|
|
55
64
|
|
|
65
|
+
const HOOK_KIND = "hook";
|
|
66
|
+
const DELIVERY_KIND = "hook-delivery";
|
|
67
|
+
|
|
56
68
|
/** Invalidate a hook's URL and mint the next one. Returns the new path. */
|
|
57
69
|
export function rotateWebhook(tenant: string, workspace: string, flow: string): string {
|
|
58
70
|
const hooks = readHooks(tenant, workspace);
|
|
59
|
-
hooks[flow] = { gen: (hooks[flow]?.gen ?? 0) + 1, rotatedAt: new Date().toISOString() };
|
|
60
71
|
const file = hooksFile(tenant, workspace);
|
|
61
72
|
// Into a workspace that exists, never making one (30 Oct 2026): the mkdir
|
|
62
73
|
// here turned a rotate under a mistyped name into a workspace holding only
|
|
63
74
|
// hooks.json, past the plan's workspace count.
|
|
64
75
|
if (!fs.existsSync(path.dirname(file))) throw Object.assign(new Error(`workspace ${workspace} not found`), { status: 404 });
|
|
76
|
+
const rotatedAt = new Date().toISOString();
|
|
77
|
+
const store = docStore(tenant, workspace);
|
|
78
|
+
if (store) {
|
|
79
|
+
// One statement moves the row past both its own value and the file's.
|
|
80
|
+
store.raise(tenant, workspace, HOOK_KIND, flow, "gen", (hooks[flow]?.gen ?? 0) + 1, { rotatedAt });
|
|
81
|
+
return webhookPath(tenant, workspace, flow);
|
|
82
|
+
}
|
|
83
|
+
// On the file: still past whatever a row holds (hookGeneration reads both).
|
|
84
|
+
hooks[flow] = { gen: hookGeneration(tenant, workspace, flow) + 1, rotatedAt };
|
|
65
85
|
fs.writeFileSync(file, JSON.stringify(hooks, null, 2));
|
|
66
86
|
return webhookPath(tenant, workspace, flow);
|
|
67
87
|
}
|
|
@@ -184,6 +204,8 @@ const KEEP_DELIVERIES = 500;
|
|
|
184
204
|
export function recordDelivery(tenant: string, workspace: string, delivery: HookDelivery) {
|
|
185
205
|
const file = deliveriesFile(tenant, workspace);
|
|
186
206
|
if (!fs.existsSync(path.dirname(file))) return; // no workspace, nothing to log against
|
|
207
|
+
const store = docStore(tenant, workspace);
|
|
208
|
+
if (store) return recordDeliveryRow(store, tenant, workspace, delivery);
|
|
187
209
|
if (UNAUTHENTICATED.includes(delivery.outcome)) return recordRefusal(file, tenant, workspace, delivery);
|
|
188
210
|
fs.appendFileSync(file, JSON.stringify(delivery) + "\n");
|
|
189
211
|
// Bounded: compact to the newest KEEP when it doubles. Amortised cheap,
|
|
@@ -200,6 +222,34 @@ export function recordDelivery(tenant: string, workspace: string, delivery: Hook
|
|
|
200
222
|
}
|
|
201
223
|
}
|
|
202
224
|
|
|
225
|
+
/** The same log as rows: an append that keeps the newest KEEP, and a refusal
|
|
226
|
+
* folded into the newest entry when that is a refusal too (so a flood is one
|
|
227
|
+
* row). The fold is read-then-replace: two refusals at once may count one
|
|
228
|
+
* short, never push a real delivery out. */
|
|
229
|
+
function recordDeliveryRow(store: DocsPort, tenant: string, workspace: string, delivery: HookDelivery) {
|
|
230
|
+
if (UNAUTHENTICATED.includes(delivery.outcome)) {
|
|
231
|
+
const [last] = store.tail(tenant, workspace, DELIVERY_KIND, 1);
|
|
232
|
+
const prev = last?.data as HookDelivery | undefined;
|
|
233
|
+
if (last && prev && UNAUTHENTICATED.includes(prev.outcome)) {
|
|
234
|
+
store.replace(tenant, workspace, DELIVERY_KIND, last.id, foldRefusal(prev, delivery));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
store.append(tenant, workspace, DELIVERY_KIND, delivery, KEEP_DELIVERIES);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** A refusal folded into the refusal before it. The flow name is not part of
|
|
242
|
+
* the match: it comes from the URL, so a flood that varies it would
|
|
243
|
+
* otherwise never collapse. */
|
|
244
|
+
function foldRefusal(last: HookDelivery, delivery: HookDelivery): HookDelivery {
|
|
245
|
+
return {
|
|
246
|
+
...delivery,
|
|
247
|
+
count: (last.count ?? 1) + 1,
|
|
248
|
+
first: last.first ?? last.t,
|
|
249
|
+
...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
203
253
|
/**
|
|
204
254
|
* A refusal — anyone's to send — never changes the workspace's directory: no
|
|
205
255
|
* new file, no tmp file, no rename. The directory's mtime is the workspace's
|
|
@@ -252,12 +302,7 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
|
|
|
252
302
|
return false;
|
|
253
303
|
}
|
|
254
304
|
if (!UNAUTHENTICATED.includes(last.outcome)) return false;
|
|
255
|
-
const merged
|
|
256
|
-
...delivery,
|
|
257
|
-
count: (last.count ?? 1) + 1,
|
|
258
|
-
first: last.first ?? last.t,
|
|
259
|
-
...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
|
|
260
|
-
};
|
|
305
|
+
const merged = foldRefusal(last, delivery);
|
|
261
306
|
const line = Buffer.from(JSON.stringify(merged) + "\n");
|
|
262
307
|
const at = Buffer.byteLength(end.slice(0, cut));
|
|
263
308
|
const fd = fs.openSync(file, "r+");
|
|
@@ -271,6 +316,16 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
|
|
|
271
316
|
}
|
|
272
317
|
|
|
273
318
|
export function readDeliveries(tenant: string, workspace: string, limit = 20): HookDelivery[] {
|
|
319
|
+
// Rows and the file both: the log may have been written either way.
|
|
320
|
+
const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, DELIVERY_KIND, limit) ?? [], []).map((r) => r.data as HookDelivery);
|
|
321
|
+
const lines = readDeliveryLines(tenant, workspace, limit);
|
|
322
|
+
if (!rows.length) return lines;
|
|
323
|
+
if (!lines.length) return rows;
|
|
324
|
+
// Stable: equal times keep each source's own newest-first order.
|
|
325
|
+
return [...rows, ...lines].sort((a, b) => String(b.t).localeCompare(String(a.t))).slice(0, limit);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function readDeliveryLines(tenant: string, workspace: string, limit: number): HookDelivery[] {
|
|
274
329
|
const file = deliveriesFile(tenant, workspace);
|
|
275
330
|
if (!fs.existsSync(file)) return [];
|
|
276
331
|
return fs
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
|
|
10
|
+
import { records, type DocsPort } from "./records.ts";
|
|
11
|
+
|
|
12
|
+
/** Rows to read: the port's, whatever the switch says. Null on a laptop, the
|
|
13
|
+
* CLI, and for a workspace whose records are still files. */
|
|
14
|
+
export function docRows(tenant: string, workspace: string): DocsPort | null {
|
|
15
|
+
return records(tenant, workspace)?.docs ?? null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Rows to write to, or null: write the folder. */
|
|
19
|
+
export function docStore(tenant: string, workspace: string): DocsPort | null {
|
|
20
|
+
const port = records(tenant, workspace);
|
|
21
|
+
if (!port?.docs || !port.docsOn?.()) return null;
|
|
22
|
+
return port.docs;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A read that must not take the caller down with the database: these are
|
|
26
|
+
* logs and markers beside the work, never the work. */
|
|
27
|
+
export function quietly<T>(fn: () => T, fallback: T): T {
|
|
28
|
+
try {
|
|
29
|
+
return fn();
|
|
30
|
+
} catch {
|
|
31
|
+
return fallback;
|
|
32
|
+
}
|
|
33
|
+
}
|