@agentswf/lab 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +15 -2
- package/package.json +46 -4
- package/schema/lab-check.schema.json +64 -0
- package/schema/lab-config.schema.json +187 -0
- package/schema/lab-final.schema.json +48 -0
- package/schema/lab-good-record.schema.json +70 -0
- package/schema/lab-grade.schema.json +49 -0
- package/schema/lab-key.schema.json +124 -0
- package/schema/lab-label.schema.json +32 -0
- package/schema/lab-loop-report.schema.json +221 -0
- package/schema/lab-loop.schema.json +141 -0
- package/schema/lab-plan.schema.json +128 -0
- package/schema/lab-previous.schema.json +70 -0
- package/schema/lab-proposal.schema.json +52 -0
- package/schema/lab-report.schema.json +1128 -0
- package/schema/lab-run.schema.json +253 -0
- package/schema/lab-runs.schema.json +132 -0
- package/schema/lab-score.schema.json +319 -0
- package/schema/lab-spread.schema.json +110 -0
- package/schema/lab-trial.schema.json +543 -0
- package/schema/lab-try.schema.json +113 -0
- package/schema/local.json +155 -0
- package/src/cli.ts +9 -0
- package/src/env/capture.ts +48 -0
- package/src/env/compare.ts +201 -0
- package/src/env/facts.ts +51 -0
- package/src/env/fetch.ts +57 -0
- package/src/env/files.ts +228 -0
- package/src/env/grade-case.ts +80 -0
- package/src/env/grade-helper.ts +352 -0
- package/src/env/grader.ts +131 -0
- package/src/env/index.ts +727 -0
- package/src/env/mock.ts +374 -0
- package/src/env/routes.ts +90 -0
- package/src/env/sources.ts +19 -0
- package/src/env/state.ts +79 -0
- package/src/env/trial.ts +185 -0
- package/src/format/key.ts +168 -0
- package/src/format/loop.ts +179 -0
- package/src/format/output.ts +542 -0
- package/src/format/records.ts +443 -0
- package/src/format/schema-files.ts +64 -0
- package/src/format/settings.ts +559 -0
- package/src/format/trial-env.ts +67 -0
- package/src/format/trial-file.ts +134 -0
- package/src/help/awf-lab.txt +29 -0
- package/src/help/case.txt +39 -0
- package/src/help/config.txt +14 -0
- package/src/help/label.txt +12 -0
- package/src/help/loop.txt +44 -0
- package/src/help/report.txt +20 -0
- package/src/help/run.txt +61 -0
- package/src/help/runs.txt +11 -0
- package/src/help/score.txt +28 -0
- package/src/judge/criteria.workflow.ts +237 -0
- package/src/judge/version.ts +6 -0
- package/src/lab/answer.ts +47 -0
- package/src/lab/blame.ts +204 -0
- package/src/lab/box.ts +251 -0
- package/src/lab/capture-command.ts +302 -0
- package/src/lab/capture.ts +234 -0
- package/src/lab/check-command.ts +187 -0
- package/src/lab/cli.ts +325 -0
- package/src/lab/code-graders.ts +108 -0
- package/src/lab/columns.ts +138 -0
- package/src/lab/command-context.ts +436 -0
- package/src/lab/compare.ts +123 -0
- package/src/lab/config-command.ts +283 -0
- package/src/lab/criteria.ts +69 -0
- package/src/lab/dataset.ts +375 -0
- package/src/lab/eval-files.ts +196 -0
- package/src/lab/expect.ts +79 -0
- package/src/lab/facts.ts +59 -0
- package/src/lab/families.ts +32 -0
- package/src/lab/folders.ts +172 -0
- package/src/lab/git.ts +128 -0
- package/src/lab/good.ts +224 -0
- package/src/lab/grading-stub.txt +8 -0
- package/src/lab/grading.ts +332 -0
- package/src/lab/inspect.ts +227 -0
- package/src/lab/labels.ts +211 -0
- package/src/lab/loop-code.ts +255 -0
- package/src/lab/loop-command.ts +774 -0
- package/src/lab/loop-records.ts +144 -0
- package/src/lab/loop.ts +864 -0
- package/src/lab/marker.ts +23 -0
- package/src/lab/outcome.ts +196 -0
- package/src/lab/pooled.ts +106 -0
- package/src/lab/project-env.ts +39 -0
- package/src/lab/rates.ts +155 -0
- package/src/lab/reach.ts +111 -0
- package/src/lab/record-copies.ts +202 -0
- package/src/lab/refusal.ts +2 -0
- package/src/lab/report-command.ts +157 -0
- package/src/lab/report.ts +936 -0
- package/src/lab/reuse.ts +134 -0
- package/src/lab/run-command.ts +958 -0
- package/src/lab/run-logs.ts +89 -0
- package/src/lab/run-report.ts +286 -0
- package/src/lab/runs-command.ts +171 -0
- package/src/lab/runs.ts +172 -0
- package/src/lab/scaffold.ts +94 -0
- package/src/lab/score-command.ts +197 -0
- package/src/lab/score.ts +396 -0
- package/src/lab/store.ts +383 -0
- package/src/lab/target-stub.txt +18 -0
- package/src/lab/text.ts +29 -0
- package/src/lab/trial-settings.ts +105 -0
- package/src/lab/trial.ts +439 -0
- package/src/lab/usage.ts +274 -0
- package/src/lab/verdict.ts +161 -0
- package/src/lab/workflow-graders.ts +164 -0
- package/src/lab/workspace.ts +496 -0
- package/src/loop/propose.workflow.ts +84 -0
- package/src/shared/allowance.ts +185 -0
- package/src/shared/compare/index.ts +3 -0
- package/src/shared/compare/paired.ts +397 -0
- package/src/shared/compare/stats.ts +139 -0
- package/src/shared/compare/types.ts +75 -0
- package/src/shared/config.ts +15 -0
- package/src/shared/runner.ts +321 -0
- package/src/shared/validate.ts +181 -0
- package/src/shared/version.ts +41 -0
- package/src/write-schemas.ts +10 -0
package/src/lab/facts.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import type { FactsProblem } from "../env/facts";
|
|
3
|
+
import type { TrialRecord } from "../format/records";
|
|
4
|
+
import type { Fact } from "../format/settings";
|
|
5
|
+
import type { Gathered } from "../format/trial-file";
|
|
6
|
+
import { runHelper } from "./code-graders";
|
|
7
|
+
import type { DatasetInfo } from "./dataset";
|
|
8
|
+
import { GRADING_FILE } from "./eval-files";
|
|
9
|
+
|
|
10
|
+
// `grading.ts`'s `facts`, run on a trial record outside the trial, in the checkout that ran the
|
|
11
|
+
// command. Facts are never kept with the trial: each grading reads them off its record again, so
|
|
12
|
+
// a `facts` fixed later grades old trials by the fix.
|
|
13
|
+
|
|
14
|
+
export type FactsRead = { facts: Record<string, Fact> } | { problem: FactsProblem };
|
|
15
|
+
|
|
16
|
+
/** Reads the facts of each record, in order; one helper process for them all. */
|
|
17
|
+
export type FactsReader = (records: readonly Gathered[], work: string) => Promise<FactsRead[]>;
|
|
18
|
+
|
|
19
|
+
/** The trial record as `facts` reads it: its own parts of the stored trial, and nothing else. */
|
|
20
|
+
export function recordOf(trial: TrialRecord): Gathered {
|
|
21
|
+
return {
|
|
22
|
+
...(trial.result !== undefined ? { result: trial.result } : {}),
|
|
23
|
+
stages: trial.stages ?? {},
|
|
24
|
+
stubbedStages: trial.stubbedStages ?? {},
|
|
25
|
+
...(trial.stoppedAfter !== undefined ? { stoppedAfter: trial.stoppedAfter } : {}),
|
|
26
|
+
calls: trial.calls ?? {},
|
|
27
|
+
requests: trial.requests ?? [],
|
|
28
|
+
...(trial.values !== undefined ? { values: trial.values } : {}),
|
|
29
|
+
files: trial.files,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A dataset's `facts`: none in its `grading.ts` gives every record no facts, and runs nothing. */
|
|
34
|
+
export function factsReader(
|
|
35
|
+
dataset: DatasetInfo,
|
|
36
|
+
root: string,
|
|
37
|
+
env: Record<string, string>,
|
|
38
|
+
timeoutMs: number,
|
|
39
|
+
): FactsReader {
|
|
40
|
+
const file = join(dataset.evalDir, GRADING_FILE);
|
|
41
|
+
return async (records, work) => {
|
|
42
|
+
if (records.length === 0) return [];
|
|
43
|
+
if (!dataset.grading.facts) return records.map(() => ({ facts: {} }));
|
|
44
|
+
let answer: { facts?: FactsRead[]; error?: string };
|
|
45
|
+
try {
|
|
46
|
+
answer = (await runHelper(
|
|
47
|
+
{ mode: "facts", file, records },
|
|
48
|
+
{ root, work, env, timeoutMs, name: "facts" },
|
|
49
|
+
)) as typeof answer;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
answer = { error: (error as Error).message };
|
|
52
|
+
}
|
|
53
|
+
if (answer.error !== undefined || !answer.facts) {
|
|
54
|
+
const reason = `${GRADING_FILE}'s facts didn't run: ${answer.error ?? "no answer"}`;
|
|
55
|
+
return records.map(() => ({ problem: { code: "facts-missing" as const, reason } }));
|
|
56
|
+
}
|
|
57
|
+
return answer.facts;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A model's provider, read from its id: a judge of one family may favour the answers of its own.
|
|
3
|
+
* Unknown ids are "family unknown". Kept small and by prefix; add a family when a model of it is
|
|
4
|
+
* judged or judges.
|
|
5
|
+
*/
|
|
6
|
+
const FAMILIES: [RegExp, string][] = [
|
|
7
|
+
[/^(anthropic\/)?claude/i, "anthropic"],
|
|
8
|
+
[/^(openai\/)?(gpt|o[0-9]|codex|chatgpt)/i, "openai"],
|
|
9
|
+
[/^(google\/)?(gemini|gemma)/i, "google"],
|
|
10
|
+
[/^(x-?ai\/)?grok/i, "xai"],
|
|
11
|
+
[/^(meta(-llama)?\/)?llama/i, "meta"],
|
|
12
|
+
[/^(mistral(ai)?\/)?(mistral|codestral|devstral|magistral)/i, "mistral"],
|
|
13
|
+
[/^(deepseek\/)?deepseek/i, "deepseek"],
|
|
14
|
+
[/^(qwen\/)?qwen/i, "qwen"],
|
|
15
|
+
[/^(moonshot(ai)?\/)?kimi/i, "moonshot"],
|
|
16
|
+
[/^(z-?ai\/)?glm/i, "zhipu"],
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
/** The harnesses that run one provider's models alone, for an alias such as claude's `sonnet`. */
|
|
20
|
+
const HARNESS_FAMILIES: Record<string, string> = { claude: "anthropic", codex: "openai" };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The provider family of a model id, the part after a harness's provider prefix included; with
|
|
24
|
+
* the harness, an alias it alone runs (`sonnet` on claude) too.
|
|
25
|
+
*/
|
|
26
|
+
export function familyOf(model: string, harness?: string): string | undefined {
|
|
27
|
+
const id = model.split("/").length > 2 ? model.split("/").slice(-2).join("/") : model;
|
|
28
|
+
const found = FAMILIES.find(
|
|
29
|
+
([pattern]) => pattern.test(id) || pattern.test(id.split("/").at(-1)!),
|
|
30
|
+
)?.[1];
|
|
31
|
+
return found ?? (harness ? HARNESS_FAMILIES[harness] : undefined);
|
|
32
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cpSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
mkdtempSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
realpathSync,
|
|
9
|
+
rmSync,
|
|
10
|
+
statSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from "node:fs";
|
|
13
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
14
|
+
import {
|
|
15
|
+
type CaseInfo,
|
|
16
|
+
filesUnder,
|
|
17
|
+
gitEntriesUnder,
|
|
18
|
+
INPUT_DIR,
|
|
19
|
+
type KeyFile,
|
|
20
|
+
refuseLinks,
|
|
21
|
+
SHARED_DIR,
|
|
22
|
+
sha256,
|
|
23
|
+
sharedOf,
|
|
24
|
+
} from "./dataset";
|
|
25
|
+
import { blobIdOf, blobIds, historyHolds } from "./git";
|
|
26
|
+
import { alive } from "./store";
|
|
27
|
+
|
|
28
|
+
const PREFIX = "awf-lab-case-";
|
|
29
|
+
/** A run's cases, built once as it starts, which its trials copy. */
|
|
30
|
+
const SNAPSHOT_PREFIX = "awf-lab-reuse-";
|
|
31
|
+
const OWNER = "owner.json";
|
|
32
|
+
|
|
33
|
+
export type TrialFolders = { parent: string; dir: string; scratch: string };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A trial's folders, outside every repository: a parent per trial holding its owner (the run's id
|
|
37
|
+
* and this process), the built case folder and the empty scratch folder.
|
|
38
|
+
*/
|
|
39
|
+
export function makeTrialFolders(tmp: string, run: string): TrialFolders {
|
|
40
|
+
const parent = realpathSync(mkdtempSync(join(tmp, PREFIX)));
|
|
41
|
+
writeFileSync(join(parent, OWNER), JSON.stringify({ run, pid: process.pid }));
|
|
42
|
+
const dir = join(parent, "case");
|
|
43
|
+
const scratch = join(parent, "scratch");
|
|
44
|
+
mkdirSync(dir);
|
|
45
|
+
mkdirSync(scratch);
|
|
46
|
+
return { parent, dir, scratch };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A folder for a run's built cases, owned by this process as a trial's folders are. */
|
|
50
|
+
export function makeSnapshotFolder(tmp: string): string {
|
|
51
|
+
const dir = realpathSync(mkdtempSync(join(tmp, SNAPSHOT_PREFIX)));
|
|
52
|
+
writeFileSync(join(dir, OWNER), JSON.stringify({ pid: process.pid }));
|
|
53
|
+
return dir;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Removes trial and snapshot folders whose process is gone; never one without an owner, or still
|
|
58
|
+
* owned.
|
|
59
|
+
*/
|
|
60
|
+
export function clearStale(tmp: string): number {
|
|
61
|
+
if (!existsSync(tmp)) return 0;
|
|
62
|
+
let removed = 0;
|
|
63
|
+
for (const name of readdirSync(tmp)) {
|
|
64
|
+
if (!name.startsWith(PREFIX) && !name.startsWith(SNAPSHOT_PREFIX)) continue;
|
|
65
|
+
const owner = join(tmp, name, OWNER);
|
|
66
|
+
try {
|
|
67
|
+
const { pid } = JSON.parse(readFileSync(owner, "utf8")) as { pid?: unknown };
|
|
68
|
+
if (typeof pid === "number" && !alive(pid)) {
|
|
69
|
+
rmSync(join(tmp, name), { recursive: true, force: true });
|
|
70
|
+
removed++;
|
|
71
|
+
}
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
return removed;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The built case folder: of the data folder's `shared/`, what the case's key names under `shared`,
|
|
79
|
+
* or all of it, at the same paths, and the case's `input/` merged over it at its root, the case's
|
|
80
|
+
* winning. Never `key.md` or `key/`.
|
|
81
|
+
*/
|
|
82
|
+
export function buildCase(dataDir: string, info: CaseInfo, target: string): void {
|
|
83
|
+
const shared = join(dataDir, SHARED_DIR);
|
|
84
|
+
refuseLinks(shared);
|
|
85
|
+
for (const path of sharedOf(dataDir, info)) {
|
|
86
|
+
mkdirSync(dirname(join(target, path)), { recursive: true });
|
|
87
|
+
cpSync(join(shared, path), join(target, path), { recursive: true, force: true });
|
|
88
|
+
}
|
|
89
|
+
const input = join(info.dir, INPUT_DIR);
|
|
90
|
+
refuseLinks(input);
|
|
91
|
+
if (existsSync(input)) cpSync(input, target, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type Needle = { marker: string; keyFiles: readonly KeyFile[] };
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Where the key turned up in a folder: a file holding the marker or a copy of a `key/` file, and
|
|
98
|
+
* in each git repository inside it, any commit holding the marker or a `key/` file's blob. A
|
|
99
|
+
* symlink is followed, as the workflow would read through it; a folder is walked once.
|
|
100
|
+
*/
|
|
101
|
+
export function searchFolder(dir: string, needle: Needle, label: string): string[] {
|
|
102
|
+
const found: string[] = [];
|
|
103
|
+
if (!existsSync(dir)) return found;
|
|
104
|
+
const marker = Buffer.from(needle.marker);
|
|
105
|
+
const sizes = new Set(needle.keyFiles.map((k) => k.size));
|
|
106
|
+
const digests = new Map(needle.keyFiles.map((k) => [k.digest, k]));
|
|
107
|
+
for (const file of filesUnder(dir, { skip: (name) => name === ".git", follow: true })) {
|
|
108
|
+
const size = statSync(file).size;
|
|
109
|
+
const bytes = readFileSync(file);
|
|
110
|
+
const where = `${label}/${relative(dir, file)}`;
|
|
111
|
+
if (bytes.includes(marker)) found.push(`the marker in ${where}`);
|
|
112
|
+
if (sizes.has(size)) {
|
|
113
|
+
const copy = digests.get(sha256(bytes));
|
|
114
|
+
if (copy) found.push(`a copy of key file ${basename(copy.path)} at ${where}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
for (const repository of gitEntriesUnder(dir).map((git) => dirname(git))) {
|
|
118
|
+
const where = `${label}/${relative(dir, repository) || "."}`;
|
|
119
|
+
if (historyHolds(repository, needle.marker)) found.push(`the marker in a commit of ${where}`);
|
|
120
|
+
if (needle.keyFiles.length > 0) {
|
|
121
|
+
const blobs = blobIds(repository);
|
|
122
|
+
for (const key of needle.keyFiles) {
|
|
123
|
+
if (blobs.has(blobIdOf(key.bytes))) found.push(`a key/ file in a commit of ${where}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return found;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Whether `text` holds the marker or a `key/` file's whole text. */
|
|
131
|
+
export function searchText(text: string, needle: Needle, label: string): string[] {
|
|
132
|
+
const found: string[] = [];
|
|
133
|
+
if (text.includes(needle.marker)) found.push(`the marker in ${label}`);
|
|
134
|
+
for (const key of needle.keyFiles) {
|
|
135
|
+
const content = Buffer.from(key.bytes).toString("utf8");
|
|
136
|
+
if (content.trim().length >= 16 && text.includes(content.trim())) {
|
|
137
|
+
found.push(`a key/ file's text in ${label}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return found;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Copies the scratch folder's files `evidence` names into `target`, a symlink as the file it names;
|
|
145
|
+
* returns their paths. A path outside the scratch folder is never kept.
|
|
146
|
+
*/
|
|
147
|
+
export function keepFiles(scratch: string, patterns: readonly string[], target: string): string[] {
|
|
148
|
+
const kept = new Set<string>();
|
|
149
|
+
for (const pattern of patterns) {
|
|
150
|
+
for (const path of new Bun.Glob(pattern).scanSync({
|
|
151
|
+
cwd: scratch,
|
|
152
|
+
dot: true,
|
|
153
|
+
onlyFiles: true,
|
|
154
|
+
followSymlinks: true,
|
|
155
|
+
})) {
|
|
156
|
+
const from = resolve(scratch, path);
|
|
157
|
+
const within = relative(scratch, from);
|
|
158
|
+
if (within === "" || within.startsWith("..") || isAbsolute(within)) continue;
|
|
159
|
+
try {
|
|
160
|
+
if (!statSync(from).isFile()) continue;
|
|
161
|
+
} catch {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
kept.add(within);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
for (const path of kept) {
|
|
168
|
+
mkdirSync(dirname(join(target, path)), { recursive: true });
|
|
169
|
+
cpSync(join(scratch, path), join(target, path), { dereference: true });
|
|
170
|
+
}
|
|
171
|
+
return [...kept].sort();
|
|
172
|
+
}
|
package/src/lab/git.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
function tryGit(dir: string, args: readonly string[]): { ok: boolean; out: string } {
|
|
4
|
+
const run = Bun.spawnSync(["git", "-C", dir, ...args], {
|
|
5
|
+
stdout: "pipe",
|
|
6
|
+
stderr: "ignore",
|
|
7
|
+
stdin: "ignore",
|
|
8
|
+
});
|
|
9
|
+
return { ok: run.exitCode === 0, out: run.stdout.toString() };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Git in `dir`, its stdout; throws with git's stderr when it fails. Commits are the lab's own, so
|
|
14
|
+
* they need no identity of the operator's.
|
|
15
|
+
*/
|
|
16
|
+
export function git(dir: string, args: readonly string[], stdin?: string): string {
|
|
17
|
+
const run = Bun.spawnSync(
|
|
18
|
+
["git", "-c", "user.name=awf-lab", "-c", "user.email=awf-lab@localhost", "-C", dir, ...args],
|
|
19
|
+
{
|
|
20
|
+
stdout: "pipe",
|
|
21
|
+
stderr: "pipe",
|
|
22
|
+
stdin: stdin === undefined ? "ignore" : new TextEncoder().encode(stdin),
|
|
23
|
+
},
|
|
24
|
+
);
|
|
25
|
+
if (run.exitCode !== 0) {
|
|
26
|
+
throw new Error(`git ${args.join(" ")} in ${dir}: ${run.stderr.toString().trim()}`);
|
|
27
|
+
}
|
|
28
|
+
return run.stdout.toString();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The top of the repository `dir` is in; undefined outside one. */
|
|
32
|
+
export function gitTop(dir: string): string | undefined {
|
|
33
|
+
const { ok, out } = tryGit(dir, ["rev-parse", "--show-toplevel"]);
|
|
34
|
+
return ok ? out.trim() || undefined : undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What names a project whatever checkout it is in: its first commit (the oldest root, when there
|
|
39
|
+
* are several) and the main checkout's folder name. Undefined outside a repository or before a
|
|
40
|
+
* first commit.
|
|
41
|
+
*/
|
|
42
|
+
export function projectOf(dir: string): { name: string; first: string } | undefined {
|
|
43
|
+
const roots = tryGit(dir, ["rev-list", "--max-parents=0", "HEAD"]);
|
|
44
|
+
const common = tryGit(dir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
45
|
+
if (!roots.ok || !common.ok) return undefined;
|
|
46
|
+
const first = roots.out.split("\n").filter(Boolean).sort()[0];
|
|
47
|
+
const gitDir = common.out.trim();
|
|
48
|
+
if (!first || !gitDir) return undefined;
|
|
49
|
+
const main = gitDir.endsWith("/.git") ? gitDir.slice(0, -"/.git".length) : gitDir;
|
|
50
|
+
return { name: main.split("/").at(-1) ?? "project", first: first.slice(0, 12) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Where a folder of code stands: its branch (null when detached), commit, and uncommitted changes. */
|
|
54
|
+
export function gitState(dir: string): {
|
|
55
|
+
branch: string | null;
|
|
56
|
+
commit: string | null;
|
|
57
|
+
dirty: boolean;
|
|
58
|
+
} {
|
|
59
|
+
const head = tryGit(dir, ["rev-parse", "HEAD"]);
|
|
60
|
+
const branch = tryGit(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
61
|
+
const status = tryGit(dir, ["status", "--porcelain"]);
|
|
62
|
+
return {
|
|
63
|
+
branch: branch.ok ? branch.out.trim() || null : null,
|
|
64
|
+
commit: head.ok ? head.out.trim() || null : null,
|
|
65
|
+
dirty: status.ok && status.out.trim() !== "",
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Whether any object of the repository at `dir` holds `text`: every commit, tree and blob read
|
|
71
|
+
* once, whether a ref reaches it or not. One pass, not a grep of each commit's tree, which took
|
|
72
|
+
* minutes on a long history.
|
|
73
|
+
*/
|
|
74
|
+
export function historyHolds(dir: string, text: string): boolean {
|
|
75
|
+
const run = Bun.spawnSync(
|
|
76
|
+
[
|
|
77
|
+
"sh",
|
|
78
|
+
"-c",
|
|
79
|
+
'git -C "$1" cat-file --batch-all-objects --batch --unordered | grep -aqF -e "$2"',
|
|
80
|
+
"sh",
|
|
81
|
+
dir,
|
|
82
|
+
text,
|
|
83
|
+
],
|
|
84
|
+
{ stdout: "ignore", stderr: "ignore", stdin: "ignore" },
|
|
85
|
+
);
|
|
86
|
+
return run.exitCode === 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Every blob id in the repository at `dir`, whether a ref reaches it or not. */
|
|
90
|
+
export function blobIds(dir: string): Set<string> {
|
|
91
|
+
const { ok, out } = tryGit(dir, [
|
|
92
|
+
"cat-file",
|
|
93
|
+
"--batch-all-objects",
|
|
94
|
+
"--unordered",
|
|
95
|
+
"--batch-check=%(objectname) %(objecttype)",
|
|
96
|
+
]);
|
|
97
|
+
if (!ok) return new Set();
|
|
98
|
+
return new Set(
|
|
99
|
+
out
|
|
100
|
+
.split("\n")
|
|
101
|
+
.filter((line) => line.endsWith(" blob"))
|
|
102
|
+
.map((line) => line.slice(0, line.indexOf(" "))),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The id git gives a file's bytes as a blob. */
|
|
107
|
+
export function blobIdOf(bytes: Uint8Array): string {
|
|
108
|
+
return createHash("sha1").update(`blob ${bytes.byteLength}\0`).update(bytes).digest("hex");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Which of these paths, relative to `dir`'s repository, its ignore rules match, whether git holds
|
|
113
|
+
* them or not.
|
|
114
|
+
*/
|
|
115
|
+
export function ignoredPaths(dir: string, paths: readonly string[]): Set<string> {
|
|
116
|
+
if (paths.length === 0) return new Set();
|
|
117
|
+
const run = Bun.spawnSync(["git", "-C", dir, "check-ignore", "--no-index", "-z", "--stdin"], {
|
|
118
|
+
stdout: "pipe",
|
|
119
|
+
stderr: "pipe",
|
|
120
|
+
stdin: new TextEncoder().encode(`${paths.join("\0")}\0`),
|
|
121
|
+
});
|
|
122
|
+
// 1: none of them is ignored.
|
|
123
|
+
if (run.exitCode === 1) return new Set();
|
|
124
|
+
if (run.exitCode !== 0) {
|
|
125
|
+
throw new Error(`git check-ignore in ${dir}: ${run.stderr.toString().trim()}`);
|
|
126
|
+
}
|
|
127
|
+
return new Set(run.stdout.toString().split("\0").filter(Boolean));
|
|
128
|
+
}
|
package/src/lab/good.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cpSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
mkdtempSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
} from "node:fs";
|
|
11
|
+
import { dirname, join, relative } from "node:path";
|
|
12
|
+
import { type GoodRecord, GoodRecordSchema } from "../format/records";
|
|
13
|
+
import type { Gathered } from "../format/trial-file";
|
|
14
|
+
import { checkSchema, describeProblems } from "../shared/validate";
|
|
15
|
+
import { type CaseInfo, type DatasetInfo, filesUnder, GOOD_DIR, GOOD_RECORD } from "./dataset";
|
|
16
|
+
import { type FactsReader, recordOf } from "./facts";
|
|
17
|
+
import { buildCase, makeTrialFolders } from "./folders";
|
|
18
|
+
import { decidersOf, failsIn, gradeTrial, type LabGrader } from "./grading";
|
|
19
|
+
import { Refusal } from "./refusal";
|
|
20
|
+
import type { StoredTrial } from "./store";
|
|
21
|
+
|
|
22
|
+
// A case's known good record, `key/good/record.json`, with the files its trial's `evidence` saved
|
|
23
|
+
// beside it: graded by `facts`, `expect` and the code graders with no `setup`, workflow or agent,
|
|
24
|
+
// so a key or grading that's wrong shows before anything is spent.
|
|
25
|
+
|
|
26
|
+
/** A known good record as read: the record, and the files saved beside it. */
|
|
27
|
+
type GoodRead = { record: Gathered; files: string[] } | { problem: string };
|
|
28
|
+
|
|
29
|
+
/** `key/good/record.json`, checked, with the files beside it; a problem when it doesn't read. */
|
|
30
|
+
export function readGood(info: CaseInfo): GoodRead | undefined {
|
|
31
|
+
if (!info.good) return undefined;
|
|
32
|
+
const file = join(info.good.dir, GOOD_RECORD);
|
|
33
|
+
if (!existsSync(file)) return { problem: `key/${GOOD_DIR}/ has no ${GOOD_RECORD}` };
|
|
34
|
+
let raw: unknown;
|
|
35
|
+
try {
|
|
36
|
+
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { problem: `key/${GOOD_DIR}/${GOOD_RECORD} is no JSON: ${(error as Error).message}` };
|
|
39
|
+
}
|
|
40
|
+
const checked = checkSchema(GoodRecordSchema, raw);
|
|
41
|
+
if (!checked.ok) {
|
|
42
|
+
return { problem: describeProblems(`key/${GOOD_DIR}/${GOOD_RECORD}`, checked.problems) };
|
|
43
|
+
}
|
|
44
|
+
const files = filesUnder(info.good.dir)
|
|
45
|
+
.map((path) => relative(info.good!.dir, path))
|
|
46
|
+
.filter((path) => path !== GOOD_RECORD);
|
|
47
|
+
return { record: gatheredOf(checked.value, files), files };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A partial record filled out as `facts` reads a trial's: what it leaves out is empty. */
|
|
51
|
+
function gatheredOf(record: GoodRecord, files: readonly string[]): Gathered {
|
|
52
|
+
return {
|
|
53
|
+
...(record.result !== undefined ? { result: record.result } : {}),
|
|
54
|
+
stages: record.stages ?? {},
|
|
55
|
+
stubbedStages: record.stubbedStages ?? {},
|
|
56
|
+
...(record.stoppedAfter !== undefined ? { stoppedAfter: record.stoppedAfter } : {}),
|
|
57
|
+
calls: record.calls ?? {},
|
|
58
|
+
requests: record.requests ?? [],
|
|
59
|
+
...(record.values !== undefined ? { values: record.values } : {}),
|
|
60
|
+
files: record.files ?? [...files],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type GoodCheck = {
|
|
65
|
+
case: string;
|
|
66
|
+
/** Whether the record passed: false when it failed, errored, or didn't read. */
|
|
67
|
+
passed: boolean;
|
|
68
|
+
/** A pass that left a grader out, or was graded by nothing: worth a line, as a failure is. */
|
|
69
|
+
partial?: true;
|
|
70
|
+
line: string;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Grades the known good records of these cases, those that have one: `facts` in one helper, then
|
|
75
|
+
* `expect` and the code graders, in `grading.ts`'s order. A grader that reads the trial is skipped
|
|
76
|
+
* when no file is saved beside the record, and said so. Agent and manual graders never run here.
|
|
77
|
+
*/
|
|
78
|
+
export async function checkGood(args: {
|
|
79
|
+
info: DatasetInfo;
|
|
80
|
+
cases: readonly CaseInfo[];
|
|
81
|
+
graders: readonly LabGrader[];
|
|
82
|
+
facts: FactsReader;
|
|
83
|
+
tmp: string;
|
|
84
|
+
env: Record<string, string>;
|
|
85
|
+
params: Record<string, string>;
|
|
86
|
+
}): Promise<GoodCheck[]> {
|
|
87
|
+
const graders = args.graders.filter((g) => !g.costly && !g.manual);
|
|
88
|
+
const read = args.cases.flatMap((info) => {
|
|
89
|
+
const good = readGood(info);
|
|
90
|
+
return good ? [{ info, good }] : [];
|
|
91
|
+
});
|
|
92
|
+
const readable = read.flatMap(({ info, good }) => ("record" in good ? [{ info, good }] : []));
|
|
93
|
+
const folders = makeTrialFolders(args.tmp, "case-check");
|
|
94
|
+
try {
|
|
95
|
+
const facts = await args.facts(
|
|
96
|
+
readable.map((r) => r.good.record),
|
|
97
|
+
folders.parent,
|
|
98
|
+
);
|
|
99
|
+
const checks: GoodCheck[] = [];
|
|
100
|
+
for (const { info, good } of read) {
|
|
101
|
+
const say = (passed: boolean, what: string, partial = false): GoodCheck => ({
|
|
102
|
+
case: info.name,
|
|
103
|
+
passed,
|
|
104
|
+
...(partial ? { partial: true as const } : {}),
|
|
105
|
+
line: `${info.name}: the known good record ${what}`,
|
|
106
|
+
});
|
|
107
|
+
if ("problem" in good) {
|
|
108
|
+
checks.push(say(false, `doesn't read: ${good.problem}`));
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const made = facts[readable.findIndex((r) => r.info === info)];
|
|
112
|
+
if (!made || "problem" in made) {
|
|
113
|
+
const problem = made?.problem ?? { code: "facts-missing", reason: "facts gave no answer" };
|
|
114
|
+
checks.push(say(false, `errored (${problem.code}): ${problem.reason}`));
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const noFiles = good.files.length === 0;
|
|
118
|
+
// A grader that reads the trial reads its saved files, and none were saved.
|
|
119
|
+
const skipped = noFiles ? graders.filter((g) => g.reads === "trial") : [];
|
|
120
|
+
const caseDir = join(folders.parent, `case-${checks.length}`);
|
|
121
|
+
mkdirSync(caseDir);
|
|
122
|
+
buildCase(args.info.dataDir, info, caseDir);
|
|
123
|
+
const kept = join(folders.parent, `kept-${checks.length}`);
|
|
124
|
+
mkdirSync(kept);
|
|
125
|
+
for (const file of good.files) {
|
|
126
|
+
mkdirSync(dirname(join(kept, file)), { recursive: true });
|
|
127
|
+
cpSync(join(info.good!.dir, file), join(kept, file));
|
|
128
|
+
}
|
|
129
|
+
const running = graders.filter((g) => !skipped.includes(g));
|
|
130
|
+
const work = join(folders.parent, `work-${checks.length}`);
|
|
131
|
+
mkdirSync(work);
|
|
132
|
+
const graded = await gradeTrial({
|
|
133
|
+
info,
|
|
134
|
+
facts: made.facts,
|
|
135
|
+
stages: good.record.stages,
|
|
136
|
+
result: good.record.result ?? null,
|
|
137
|
+
caseDir,
|
|
138
|
+
scratch: null,
|
|
139
|
+
kept,
|
|
140
|
+
work,
|
|
141
|
+
env: args.env,
|
|
142
|
+
params: args.params,
|
|
143
|
+
expect: Object.keys(info.key.expect ?? {}).length > 0,
|
|
144
|
+
good: true,
|
|
145
|
+
graders: running,
|
|
146
|
+
deciders: decidersOf(info.key, running),
|
|
147
|
+
});
|
|
148
|
+
const unread = skipped.filter((g) => g.appliesTo?.(info.key) ?? true).map((g) => g.name);
|
|
149
|
+
const without =
|
|
150
|
+
unread.length > 0
|
|
151
|
+
? `; not graded by ${unread.join(", ")}, which read${unread.length === 1 ? "s" : ""} the trial's files, and none is saved beside it`
|
|
152
|
+
: "";
|
|
153
|
+
if ("errored" in graded) {
|
|
154
|
+
const { code, reason } = graded.errored;
|
|
155
|
+
checks.push(say(false, `errored${code ? ` (${code})` : ""}: ${reason}`));
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const entries = graded.entries;
|
|
159
|
+
const erred = entries.find((e) => e.errored);
|
|
160
|
+
const deciders = decidersOf(info.key, running);
|
|
161
|
+
const undecided = entries.find((e) => deciders.has(e.grader) && e.verdict === "undecided");
|
|
162
|
+
if (erred) {
|
|
163
|
+
checks.push(say(false, `errored in ${erred.grader}: ${erred.errored!.reason}`));
|
|
164
|
+
} else if (failsIn(entries, deciders)) {
|
|
165
|
+
const failing = entries.find((e) => deciders.has(e.grader) && e.verdict === "failed")!;
|
|
166
|
+
const reason = failing.reasons[0]?.text;
|
|
167
|
+
checks.push(
|
|
168
|
+
say(false, `fails: ${failing.grader}${reason ? `: ${reason}` : ""}: the case's to fix`),
|
|
169
|
+
);
|
|
170
|
+
} else if (undecided) {
|
|
171
|
+
checks.push(say(false, `is undecided by ${undecided.grader}`));
|
|
172
|
+
} else if (entries.length === 0) {
|
|
173
|
+
checks.push(say(true, `is graded by nothing${without}`, true));
|
|
174
|
+
} else checks.push(say(true, `passes${without}`, without !== ""));
|
|
175
|
+
}
|
|
176
|
+
return checks;
|
|
177
|
+
} finally {
|
|
178
|
+
rmSync(folders.parent, { recursive: true, force: true });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Why a trial's record can't be vouched for, if it can't: it errored, leaked or threw. Grading's
|
|
184
|
+
* error on it, in `facts` or `expect`, is the key's or `grading.ts`'s, never the record's.
|
|
185
|
+
*/
|
|
186
|
+
export function unpinnable(trial: StoredTrial): string | undefined {
|
|
187
|
+
const { record } = trial;
|
|
188
|
+
if (record.leaked) return "it leaked: the key turned up where it ran";
|
|
189
|
+
if (record.errored && record.errored.phase !== "facts") {
|
|
190
|
+
return `it errored by ${record.errored.by}: ${record.errored.reason}`;
|
|
191
|
+
}
|
|
192
|
+
if (record.workflowError !== undefined) return `its workflow threw: ${record.workflowError}`;
|
|
193
|
+
if (record.stopped !== undefined) return `its workflow stopped itself: ${record.stopped}`;
|
|
194
|
+
if (record.stages === undefined) return "it kept no record";
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Writes a trial's record as a case's known good record, `{caseDir}/key/good/`, with the files
|
|
200
|
+
* its `evidence` saved beside it; built whole, then moved into place over any older one.
|
|
201
|
+
*/
|
|
202
|
+
export function writeGood(caseDir: string, trial: StoredTrial): string {
|
|
203
|
+
const keptDir = join(trial.dir, "kept");
|
|
204
|
+
if (existsSync(join(keptDir, GOOD_RECORD))) {
|
|
205
|
+
throw new Refusal(
|
|
206
|
+
`trial ${trial.record.trialId}'s evidence saved a file named ${GOOD_RECORD}, which the known good record's own name would hide`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
const target = join(caseDir, "key", GOOD_DIR);
|
|
210
|
+
mkdirSync(join(caseDir, "key"), { recursive: true });
|
|
211
|
+
const building = mkdtempSync(join(caseDir, "key", ".good-"));
|
|
212
|
+
try {
|
|
213
|
+
if (existsSync(keptDir)) cpSync(keptDir, building, { recursive: true });
|
|
214
|
+
writeFileSync(
|
|
215
|
+
join(building, GOOD_RECORD),
|
|
216
|
+
`${JSON.stringify(recordOf(trial.record), null, 2)}\n`,
|
|
217
|
+
);
|
|
218
|
+
rmSync(target, { recursive: true, force: true });
|
|
219
|
+
renameSync(building, target);
|
|
220
|
+
} finally {
|
|
221
|
+
rmSync(building, { recursive: true, force: true });
|
|
222
|
+
}
|
|
223
|
+
return join(target, GOOD_RECORD);
|
|
224
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { defineGrading } from "@agentswf/lab";
|
|
2
|
+
import type target from "./target";
|
|
3
|
+
|
|
4
|
+
// The key's expect checks the facts read off each trial record; list graders here for rules that
|
|
5
|
+
// hold for every case.
|
|
6
|
+
export default defineGrading<typeof target>({
|
|
7
|
+
facts: (record) => ({ done: record.result !== undefined }),
|
|
8
|
+
});
|