@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.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -2
  3. package/package.json +46 -4
  4. package/schema/lab-check.schema.json +64 -0
  5. package/schema/lab-config.schema.json +187 -0
  6. package/schema/lab-final.schema.json +48 -0
  7. package/schema/lab-good-record.schema.json +70 -0
  8. package/schema/lab-grade.schema.json +49 -0
  9. package/schema/lab-key.schema.json +124 -0
  10. package/schema/lab-label.schema.json +32 -0
  11. package/schema/lab-loop-report.schema.json +221 -0
  12. package/schema/lab-loop.schema.json +141 -0
  13. package/schema/lab-plan.schema.json +128 -0
  14. package/schema/lab-previous.schema.json +70 -0
  15. package/schema/lab-proposal.schema.json +52 -0
  16. package/schema/lab-report.schema.json +1128 -0
  17. package/schema/lab-run.schema.json +253 -0
  18. package/schema/lab-runs.schema.json +132 -0
  19. package/schema/lab-score.schema.json +319 -0
  20. package/schema/lab-spread.schema.json +110 -0
  21. package/schema/lab-trial.schema.json +543 -0
  22. package/schema/lab-try.schema.json +113 -0
  23. package/schema/local.json +155 -0
  24. package/src/cli.ts +9 -0
  25. package/src/env/capture.ts +48 -0
  26. package/src/env/compare.ts +201 -0
  27. package/src/env/facts.ts +51 -0
  28. package/src/env/fetch.ts +57 -0
  29. package/src/env/files.ts +228 -0
  30. package/src/env/grade-case.ts +80 -0
  31. package/src/env/grade-helper.ts +352 -0
  32. package/src/env/grader.ts +131 -0
  33. package/src/env/index.ts +727 -0
  34. package/src/env/mock.ts +374 -0
  35. package/src/env/routes.ts +90 -0
  36. package/src/env/sources.ts +19 -0
  37. package/src/env/state.ts +79 -0
  38. package/src/env/trial.ts +185 -0
  39. package/src/format/key.ts +168 -0
  40. package/src/format/loop.ts +179 -0
  41. package/src/format/output.ts +542 -0
  42. package/src/format/records.ts +443 -0
  43. package/src/format/schema-files.ts +64 -0
  44. package/src/format/settings.ts +559 -0
  45. package/src/format/trial-env.ts +67 -0
  46. package/src/format/trial-file.ts +134 -0
  47. package/src/help/awf-lab.txt +29 -0
  48. package/src/help/case.txt +39 -0
  49. package/src/help/config.txt +14 -0
  50. package/src/help/label.txt +12 -0
  51. package/src/help/loop.txt +44 -0
  52. package/src/help/report.txt +20 -0
  53. package/src/help/run.txt +61 -0
  54. package/src/help/runs.txt +11 -0
  55. package/src/help/score.txt +28 -0
  56. package/src/judge/criteria.workflow.ts +237 -0
  57. package/src/judge/version.ts +6 -0
  58. package/src/lab/answer.ts +47 -0
  59. package/src/lab/blame.ts +204 -0
  60. package/src/lab/box.ts +251 -0
  61. package/src/lab/capture-command.ts +302 -0
  62. package/src/lab/capture.ts +234 -0
  63. package/src/lab/check-command.ts +187 -0
  64. package/src/lab/cli.ts +325 -0
  65. package/src/lab/code-graders.ts +108 -0
  66. package/src/lab/columns.ts +138 -0
  67. package/src/lab/command-context.ts +436 -0
  68. package/src/lab/compare.ts +123 -0
  69. package/src/lab/config-command.ts +283 -0
  70. package/src/lab/criteria.ts +69 -0
  71. package/src/lab/dataset.ts +375 -0
  72. package/src/lab/eval-files.ts +196 -0
  73. package/src/lab/expect.ts +79 -0
  74. package/src/lab/facts.ts +59 -0
  75. package/src/lab/families.ts +32 -0
  76. package/src/lab/folders.ts +172 -0
  77. package/src/lab/git.ts +128 -0
  78. package/src/lab/good.ts +224 -0
  79. package/src/lab/grading-stub.txt +8 -0
  80. package/src/lab/grading.ts +332 -0
  81. package/src/lab/inspect.ts +227 -0
  82. package/src/lab/labels.ts +211 -0
  83. package/src/lab/loop-code.ts +255 -0
  84. package/src/lab/loop-command.ts +774 -0
  85. package/src/lab/loop-records.ts +144 -0
  86. package/src/lab/loop.ts +864 -0
  87. package/src/lab/marker.ts +23 -0
  88. package/src/lab/outcome.ts +196 -0
  89. package/src/lab/pooled.ts +106 -0
  90. package/src/lab/project-env.ts +39 -0
  91. package/src/lab/rates.ts +155 -0
  92. package/src/lab/reach.ts +111 -0
  93. package/src/lab/record-copies.ts +202 -0
  94. package/src/lab/refusal.ts +2 -0
  95. package/src/lab/report-command.ts +157 -0
  96. package/src/lab/report.ts +936 -0
  97. package/src/lab/reuse.ts +134 -0
  98. package/src/lab/run-command.ts +958 -0
  99. package/src/lab/run-logs.ts +89 -0
  100. package/src/lab/run-report.ts +286 -0
  101. package/src/lab/runs-command.ts +171 -0
  102. package/src/lab/runs.ts +172 -0
  103. package/src/lab/scaffold.ts +94 -0
  104. package/src/lab/score-command.ts +197 -0
  105. package/src/lab/score.ts +396 -0
  106. package/src/lab/store.ts +383 -0
  107. package/src/lab/target-stub.txt +18 -0
  108. package/src/lab/text.ts +29 -0
  109. package/src/lab/trial-settings.ts +105 -0
  110. package/src/lab/trial.ts +439 -0
  111. package/src/lab/usage.ts +274 -0
  112. package/src/lab/verdict.ts +161 -0
  113. package/src/lab/workflow-graders.ts +164 -0
  114. package/src/lab/workspace.ts +496 -0
  115. package/src/loop/propose.workflow.ts +84 -0
  116. package/src/shared/allowance.ts +185 -0
  117. package/src/shared/compare/index.ts +3 -0
  118. package/src/shared/compare/paired.ts +397 -0
  119. package/src/shared/compare/stats.ts +139 -0
  120. package/src/shared/compare/types.ts +75 -0
  121. package/src/shared/config.ts +15 -0
  122. package/src/shared/runner.ts +321 -0
  123. package/src/shared/validate.ts +181 -0
  124. package/src/shared/version.ts +41 -0
  125. package/src/write-schemas.ts +10 -0
@@ -0,0 +1,274 @@
1
+ import top from "../help/awf-lab.txt" with { type: "text" };
2
+ import caseHelp from "../help/case.txt" with { type: "text" };
3
+ import configHelp from "../help/config.txt" with { type: "text" };
4
+ import label from "../help/label.txt" with { type: "text" };
5
+ import loop from "../help/loop.txt" with { type: "text" };
6
+ import report from "../help/report.txt" with { type: "text" };
7
+ import run from "../help/run.txt" with { type: "text" };
8
+ import runs from "../help/runs.txt" with { type: "text" };
9
+ import score from "../help/score.txt" with { type: "text" };
10
+ import { Refusal } from "./refusal";
11
+
12
+ // Each command's help is its file in help/, and the flags a command takes are read from its
13
+ // usage lines there, so the help can't drift from what the command accepts.
14
+
15
+ export type CommandName =
16
+ | "case"
17
+ | "run"
18
+ | "report"
19
+ | "score"
20
+ | "label"
21
+ | "loop"
22
+ | "runs"
23
+ | "config";
24
+
25
+ type Synopsis = {
26
+ /** After `awf-lab [-C {folder}] `, as `loop final {name} --budget {usd}`. */
27
+ line: string;
28
+ /** The flag that picks this synopsis over the command's others: its first one not in brackets, as `report --loop`. */
29
+ mode?: string;
30
+ /** The word after the command that picks this synopsis, as `case pin`'s `pin`. */
31
+ verb?: string;
32
+ };
33
+
34
+ type Command = { name: CommandName; help: string; synopses: Synopsis[] };
35
+
36
+ const HELP: Record<CommandName, string> = {
37
+ case: caseHelp,
38
+ run,
39
+ report,
40
+ score,
41
+ label,
42
+ loop,
43
+ runs,
44
+ config: configHelp,
45
+ };
46
+
47
+ const PREFIX = /^(usage: | {7})awf-lab \[-C \{folder\}\] /;
48
+
49
+ /** The synopses of a command's help: its lines up to the first blank, each from `awf-lab`. */
50
+ export function synopsesOf(help: string): Synopsis[] {
51
+ const lines: string[] = [];
52
+ for (const raw of help.split("\n")) {
53
+ if (raw.trim() === "") break;
54
+ if (PREFIX.test(raw)) lines.push(raw.replace(PREFIX, ""));
55
+ else lines[lines.length - 1] += ` ${raw.trim()}`;
56
+ }
57
+ return lines.map((line) => {
58
+ const words = synopsisWords(line);
59
+ const verb = /^[a-z]+$/.test(words[1] ?? "") ? words[1] : undefined;
60
+ // A verb picks its synopsis; a flag it requires is no mode.
61
+ const mode = verb ? undefined : words.find((word) => word.startsWith("--"));
62
+ return { line, ...(mode ? { mode } : {}), ...(verb ? { verb } : {}) };
63
+ });
64
+ }
65
+
66
+ /** A synopsis's words, a bracketed group kept whole. */
67
+ function synopsisWords(line: string): string[] {
68
+ const words: string[] = [];
69
+ let depth = 0;
70
+ let word = "";
71
+ for (const ch of line) {
72
+ if (ch === " " && depth === 0) {
73
+ if (word) words.push(word);
74
+ word = "";
75
+ continue;
76
+ }
77
+ if (ch === "[" || ch === "(") depth++;
78
+ if (ch === "]" || ch === ")") depth--;
79
+ word += ch;
80
+ }
81
+ if (word) words.push(word);
82
+ return words;
83
+ }
84
+
85
+ const COMMANDS: Command[] = (Object.keys(HELP) as CommandName[]).map((name) => ({
86
+ name,
87
+ help: HELP[name],
88
+ synopses: synopsesOf(HELP[name]),
89
+ }));
90
+
91
+ /** Words that read as a command but are not one, and what to run instead. */
92
+ const NOT_COMMANDS: Record<string, string> = {
93
+ capture:
94
+ 'capture is case capture now: awf-lab case capture {id} (--good | --needs-work "{note}")',
95
+ compare:
96
+ "compare is grading.ts's, not a command: run --against {folder} or --vary {name}={a,b} makes the columns it compares",
97
+ };
98
+
99
+ /** Flags that are another flag's near miss, each naming the other. */
100
+ const NEAR: Record<string, string> = { "--case": "--cases", "--cases": "--case" };
101
+
102
+ const flagsOf = (line: string): string[] => line.match(/--[a-z-]+/g) ?? [];
103
+
104
+ /** Every flag the command takes, in any of its synopses. */
105
+ const flagsIn = (command: Command) =>
106
+ new Set(command.synopses.flatMap(({ line }) => flagsOf(line)));
107
+
108
+ /** Flags every command takes. */
109
+ const EVERYWHERE = new Set(["-C", "--help"]);
110
+
111
+ /** Flags no command takes any more, and what took their place. */
112
+ const GONE: Record<string, string> = {
113
+ "--config": "--config is gone: -C {folder} runs as if started in {folder}, as git -C does",
114
+ "--final": "loop --final is loop final {name} now",
115
+ "--patch": "loop --patch is loop patch {name} now",
116
+ "--program":
117
+ "--program is gone: a loop's brief is its entry's brief, in loops of evals/awf-lab.config.ts or the local file",
118
+ "--proposer":
119
+ "--proposer is gone: a loop's proposer is its entry's proposer, in loops of evals/awf-lab.config.ts or the local file",
120
+ "--no-spread":
121
+ "--no-spread is gone: spread: false in the loop's entry, in loops of evals/awf-lab.config.ts or the local file",
122
+ "--rounds": "--rounds is now --tries: loop run {name} --tries {n}",
123
+ };
124
+
125
+ /** The loop's flags that are its entry's fields now, each with the field. */
126
+ const LOOP_ENTRY_FIELDS: Record<string, string> = {
127
+ "--dataset": "dataset",
128
+ "--cases": "cases",
129
+ "--tags": "tags",
130
+ "--trials": "trials",
131
+ "--param": "params",
132
+ };
133
+
134
+ /** `awf-lab --help`. */
135
+ export const fullUsage = (): string => top.trimEnd();
136
+
137
+ /** `awf-lab {command} --help`; undefined if unknown. */
138
+ export const commandUsage = (name: string): string | undefined =>
139
+ COMMANDS.find((c) => c.name === name)?.help.trimEnd();
140
+
141
+ /** The commands that take a flag, as `run's`, `run's and score's`. */
142
+ function owners(flag: string): string | undefined {
143
+ const names = COMMANDS.flatMap((c) => {
144
+ const verbs = c.synopses.filter((s) => s.verb && flagsOf(s.line).includes(flag));
145
+ if (verbs.length > 0) return verbs.map((s) => `${c.name} ${s.verb}'s`);
146
+ return flagsIn(c).has(flag) ? [`${c.name}'s`] : [];
147
+ });
148
+ if (names.length === 0) return undefined;
149
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
150
+ }
151
+
152
+ /** How a flag is written in a synopsis: `--cases {a,b}`. */
153
+ const written = (flag: string) => {
154
+ for (const { line } of COMMANDS.flatMap((c) => c.synopses)) {
155
+ const found = line.match(new RegExp(`${flag} \\{[^}]*\\}`));
156
+ if (found) return found[0];
157
+ }
158
+ return flag;
159
+ };
160
+
161
+ /**
162
+ * Refuses a flag the command doesn't take where it is given, saying whose it is and, for a near
163
+ * miss, the other. A command of several synopses takes the flags of the one its mode picks.
164
+ */
165
+ export function refuseForeignFlags(name: string, given: readonly string[], verb?: string): void {
166
+ const command = COMMANDS.find((c) => c.name === name);
167
+ if (!command) return;
168
+ if (name === "loop") {
169
+ const field = given.find((flag) => Object.hasOwn(LOOP_ENTRY_FIELDS, flag));
170
+ if (field) {
171
+ throw new Refusal(
172
+ `${field} is not an option of ${verb ? `loop ${verb}` : "loop"}: a loop's ${LOOP_ENTRY_FIELDS[field]} is its entry's, in loops of evals/awf-lab.config.ts or the local file`,
173
+ );
174
+ }
175
+ }
176
+ // A command of verbs takes the flags of its verb's synopsis; an unknown verb is its to refuse.
177
+ const verbed = command.synopses.some((s) => s.verb !== undefined);
178
+ const pool = verbed ? command.synopses.filter((s) => s.verb === verb) : command.synopses;
179
+ if (pool.length === 0) return;
180
+ const modes = pool.filter((s) => s.mode !== undefined && given.includes(s.mode));
181
+ if (modes.length > 1) {
182
+ throw new Refusal(`${modes.map((s) => s.mode).join(" and ")} do not go together`);
183
+ }
184
+ const synopsis = modes[0] ?? pool.find((s) => s.mode === undefined)!;
185
+ const own = new Set(flagsOf(synopsis.line));
186
+ const where = verbed ? `${name} ${verb}` : synopsis.mode ? `${name} ${synopsis.mode}` : name;
187
+ for (const flag of given) {
188
+ if (EVERYWHERE.has(flag) || own.has(flag)) continue;
189
+ const otherVerb = verbed
190
+ ? command.synopses.find((s) => flagsOf(s.line).includes(flag))?.verb
191
+ : undefined;
192
+ if (otherVerb) {
193
+ throw new Refusal(
194
+ `${flag} is not an option of ${where}: it is ${name} ${otherVerb}'s; ${where} is ${synopsis.line}`,
195
+ );
196
+ }
197
+ if (flagsIn(command).has(flag)) {
198
+ const other = command.synopses.find((s) => flagsOf(s.line).includes(flag))!;
199
+ throw new Refusal(
200
+ `${flag} is not an option of ${where}: it is ${name}'s ${other.mode ? `with ${other.mode}` : `without ${synopsis.mode}`}; ${where} is ${synopsis.line}`,
201
+ );
202
+ }
203
+ const near = NEAR[flag];
204
+ const whose = owners(flag);
205
+ const hint =
206
+ near && own.has(near)
207
+ ? `${whose ? `${flag} is ${whose}; ` : ""}${name} takes ${written(near)}`
208
+ : whose
209
+ ? `it is ${whose}`
210
+ : undefined;
211
+ throw new Refusal(`${flag} is not an option of ${where}${hint ? `: ${hint}` : ""}`);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Refuses a flag no command takes, with the command's flag it is nearest, two edits or fewer
217
+ * away.
218
+ */
219
+ export function refuseUnknownFlag(flag: string, name: string | undefined): never {
220
+ if (Object.hasOwn(GONE, flag)) throw new Refusal(GONE[flag]!);
221
+ const command = name === undefined ? undefined : COMMANDS.find((c) => c.name === name);
222
+ if (!command) throw new Refusal(`unknown option ${flag}; awf-lab --help lists the options`);
223
+ const near = [...flagsIn(command), ...EVERYWHERE]
224
+ .map((f) => [f, distance(flag, f)] as const)
225
+ .filter(([, d]) => d <= 2)
226
+ .sort((a, b) => a[1] - b[1])[0]?.[0];
227
+ throw new Refusal(
228
+ `unknown option ${flag} for ${name}${near ? `; did you mean ${near}?` : ";"} awf-lab ${name} --help lists its options`,
229
+ );
230
+ }
231
+
232
+ /** The edits, inserting, removing or changing a character, that make `a` into `b`. */
233
+ function distance(a: string, b: string): number {
234
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
235
+ for (let i = 1; i <= a.length; i++) {
236
+ const next = [i];
237
+ for (let j = 1; j <= b.length; j++) {
238
+ next[j] = Math.min(
239
+ row[j]! + 1,
240
+ next[j - 1]! + 1,
241
+ row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
242
+ );
243
+ }
244
+ row = next;
245
+ }
246
+ return row[b.length]!;
247
+ }
248
+
249
+ /** Whether a word is one of the commands. */
250
+ export const isCommand = (name: string): name is CommandName =>
251
+ COMMANDS.some((c) => c.name === name);
252
+
253
+ /** Refuses a word that is not a command, with what to run instead when there is something. */
254
+ export function refuseNotCommand(name: string): void {
255
+ if (Object.hasOwn(NOT_COMMANDS, name)) throw new Refusal(NOT_COMMANDS[name]!);
256
+ }
257
+
258
+ /**
259
+ * What a command's help leaves out: a line for each flag its synopses name, and its exit codes.
260
+ * `exits` is each command's, as the code means them.
261
+ */
262
+ export function usageProblems(exits: (name: CommandName) => string[]): string[] {
263
+ return COMMANDS.flatMap((command) => {
264
+ const flat = command.help.replace(/\s+/g, " ");
265
+ return [
266
+ ...[...flagsIn(command), "-C"]
267
+ .filter((flag) => !new RegExp(`^ ${flag}( |$)`, "m").test(command.help))
268
+ .map((flag) => `${command.name}'s help has no line for ${flag}`),
269
+ ...exits(command.name)
270
+ .filter((exit) => !flat.includes(exit))
271
+ .map((exit) => `${command.name}'s help leaves out exit ${exit}`),
272
+ ];
273
+ });
274
+ }
@@ -0,0 +1,161 @@
1
+ import type { Errored, Outcome, Verdict } from "../format/records";
2
+
3
+ /** What one trial came to, before the order below picks its outcome. */
4
+ export type TrialFacts = {
5
+ leaked: boolean;
6
+ errored?: Pick<Errored, "by">;
7
+ /** The workflow erred: its body failed or timed out. */
8
+ workflowErred: boolean;
9
+ /** Its body called `wf.stop` before any `stopAfterStage`. */
10
+ stopped: boolean;
11
+ /** Each grader that gave a verdict; empty when none did. */
12
+ verdicts: readonly Verdict[];
13
+ /** Some grader gave numbers. */
14
+ numbers: boolean;
15
+ /** No grader applies, or the key is a draft. */
16
+ notGraded: boolean;
17
+ };
18
+
19
+ /** When several apply, the first in this order counts. */
20
+ export function outcomeOf(trial: TrialFacts): Outcome {
21
+ if (trial.leaked) return "leaked";
22
+ if (trial.errored) return "errored";
23
+ if (trial.stopped) return "stopped";
24
+ if (trial.workflowErred || trial.verdicts.includes("failed")) return "failed";
25
+ if (trial.notGraded) return "not graded";
26
+ if (trial.verdicts.length === 0) return trial.numbers ? "graded by numbers" : "not graded";
27
+ if (trial.verdicts.includes("undecided")) return "undecided";
28
+ return "passed";
29
+ }
30
+
31
+ export type CaseVerdict = "passed" | "failed" | "flaky" | "unclear";
32
+
33
+ /** `"all"` or `"{n}/{d}"`: the share of trials that must pass. */
34
+ export function needOf(pass: string, trials: number): number {
35
+ if (pass === "all") return trials;
36
+ const [n, d] = pass.split("/").map(Number) as [number, number];
37
+ return Math.min(trials, Math.ceil((n / d) * trials - 1e-9));
38
+ }
39
+
40
+ export type CaseTally = {
41
+ verdict?: CaseVerdict;
42
+ /** Set when the case has no verdict: all its trials not graded, or graded by numbers only. */
43
+ none?: "not graded" | "graded by numbers";
44
+ passed: number;
45
+ failed: number;
46
+ trials: number;
47
+ need: number;
48
+ /** Why an unclear case is unclear, or why a passing bar was rounded up. */
49
+ note?: string;
50
+ };
51
+
52
+ /**
53
+ * A case's verdict from its trials' outcomes, with `trials` the count asked for. A stopped trial is
54
+ * a failed one: the workflow erred. `said` is an outcome the case's row already names for its one
55
+ * trial, which an unclear note leaves out.
56
+ */
57
+ export function caseVerdict(
58
+ outcomes: readonly Outcome[],
59
+ trials: number,
60
+ pass: string,
61
+ said?: Outcome,
62
+ ): CaseTally {
63
+ const need = needOf(pass, trials);
64
+ const passed = outcomes.filter((o) => o === "passed").length;
65
+ const failed = outcomes.filter((o) => o === "failed" || o === "stopped").length;
66
+ const tally = { passed, failed, trials, need };
67
+ if (outcomes.length > 0 && outcomes.every((o) => o === "not graded")) {
68
+ return { ...tally, none: "not graded" };
69
+ }
70
+ if (
71
+ outcomes.length > 0 &&
72
+ outcomes.every((o) => o === "graded by numbers" || o === "not graded")
73
+ ) {
74
+ return { ...tally, none: "graded by numbers" };
75
+ }
76
+ const rounded =
77
+ pass !== "all" && need === trials && trials > 0 && needOf(pass, 3 * trials) < 3 * trials
78
+ ? `the ${pass} bar at ${trials} trial${trials === 1 ? "" : "s"} asks every one`
79
+ : undefined;
80
+ const withNote = (verdict: CaseVerdict, note?: string): CaseTally => ({
81
+ ...tally,
82
+ verdict,
83
+ ...((note ?? rounded) ? { note: note ?? rounded } : {}),
84
+ });
85
+ if (passed >= need) return withNote("passed");
86
+ if (failed > trials / 2) return withNote("failed");
87
+ if (passed >= 1 && failed >= 1) return withNote("flaky");
88
+ const counts = (["errored", "undecided", "leaked"] as const)
89
+ .map((o) => [o, outcomes.filter((x) => x === o).length] as const)
90
+ .filter(([o, n]) => n > 0 && !(n === 1 && o === said))
91
+ .map(([o, n]) => `${n} ${o}`);
92
+ const missing = trials - outcomes.length;
93
+ if (missing > 0) counts.push(`${missing} not run`);
94
+ return withNote("unclear", counts.length > 0 ? counts.join(", ") : undefined);
95
+ }
96
+
97
+ export type ExitInputs = {
98
+ cases: readonly {
99
+ tally: CaseTally;
100
+ knownFailing: boolean;
101
+ /** A trial of it errored by the dataset, by grading or by the harness, or leaked. */
102
+ brokenTrial: boolean;
103
+ /** Every broken trial of it failed a precondition. */
104
+ onlyPreconditions?: boolean;
105
+ /** A trial of it errored by the lab, or was cancelled. */
106
+ labTrial?: boolean;
107
+ }[];
108
+ partial: boolean;
109
+ /**
110
+ * The run stopped on two precondition failures in a row: the environment wasn't ready, so the
111
+ * run is a pause, 3, though the trials that failed one errored by the dataset. Any other broken
112
+ * trial keeps 5.
113
+ */
114
+ preconditionStop?: boolean;
115
+ };
116
+
117
+ export type ExitCode = 0 | 1 | 3 | 4 | 5;
118
+
119
+ /** What each exit of `run`, `report` and `score` means: the help lists them, a report ends with one. */
120
+ export const EXITS: Readonly<Record<ExitCode | 2, string>> = {
121
+ 0: "every case that must pass passed",
122
+ 1: "a case that must pass failed",
123
+ 2: "refused before any work",
124
+ 3: "a case flaky or unclear, a partial run, a budget stop, a stop on preconditions with no other trial broken, or nothing graded",
125
+ 4: "the lab broke, or a trial errored by the lab or was cancelled: its result says nothing of the workflow",
126
+ 5: "a trial errored by the dataset, by grading or by the harness, or leaked",
127
+ };
128
+
129
+ /**
130
+ * The exit code of `run`, `report` and `score`, from your checkout's column alone. A trial the lab
131
+ * broke says nothing of the workflow, so it outranks every verdict, as the lab breaking mid-run
132
+ * does.
133
+ */
134
+ export function exitCodeOf({ cases, partial, preconditionStop }: ExitInputs): ExitCode {
135
+ if (cases.some((c) => c.labTrial)) return 4;
136
+ const counted = cases.filter((c) => !c.knownFailing);
137
+ if (counted.some((c) => c.tally.verdict === "failed")) return 1;
138
+ if (preconditionStop && cases.every((c) => !c.brokenTrial || c.onlyPreconditions)) return 3;
139
+ if (cases.some((c) => c.brokenTrial)) return 5;
140
+ const graded = cases.some((c) => c.tally.verdict || c.tally.none === "graded by numbers");
141
+ if (
142
+ partial ||
143
+ !graded ||
144
+ counted.some((c) => c.tally.verdict === "flaky" || c.tally.verdict === "unclear")
145
+ ) {
146
+ return 3;
147
+ }
148
+ return 0;
149
+ }
150
+
151
+ /**
152
+ * Whether a trial errored so a CI must not pass it: by the dataset, by grading or by the harness,
153
+ * or leaked.
154
+ */
155
+ export function isBroken(outcome: Outcome, errored?: Pick<Errored, "by">): boolean {
156
+ return (
157
+ outcome === "leaked" ||
158
+ (outcome === "errored" &&
159
+ (errored?.by === "dataset" || errored?.by === "grading" || errored?.by === "harness"))
160
+ );
161
+ }
@@ -0,0 +1,164 @@
1
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import type { Reads } from "../env/grader";
4
+ import { GRADE_KIND, type GradeFile, GradeFileSchema, PreviousSchema } from "../format/records";
5
+ import { GRADE_FILES, TRIAL_ENV } from "../format/trial-env";
6
+ import type { AwfBin, Runner } from "../shared/runner";
7
+ import { checkSchema, describeProblems } from "../shared/validate";
8
+ import { checkAnswer } from "./answer";
9
+ import type { DatasetInfo, GraderSpec } from "./dataset";
10
+ import type { GradeCall, LabGrader } from "./grading";
11
+ import { newRunId } from "./store";
12
+ import { LIMIT_DEFAULTS } from "./trial-settings";
13
+
14
+ type WorkflowSpec = Extract<GraderSpec, { kind: "workflow" }>;
15
+
16
+ /**
17
+ * Writes a grade folder: what `gradeCase()` reads. The key in it has no marker; the record's
18
+ * values and the saved files are there only for a grader that reads the trial.
19
+ */
20
+ export function writeGradeFolder(dir: string, call: GradeCall, reads: Reads): void {
21
+ mkdirSync(dir, { recursive: true });
22
+ const file: GradeFile = {
23
+ kind: GRADE_KIND,
24
+ case: call.case.name,
25
+ scratch: call.scratch,
26
+ params: call.params,
27
+ reads,
28
+ };
29
+ const checked = checkSchema(GradeFileSchema, file);
30
+ if (!checked.ok) throw new Error(describeProblems(GRADE_FILES.grade, checked.problems));
31
+ writeFileSync(join(dir, GRADE_FILES.grade), JSON.stringify(file, null, 2));
32
+ cpSync(call.case.dir, join(dir, GRADE_FILES.case), { recursive: true });
33
+ writeFileSync(join(dir, GRADE_FILES.key), JSON.stringify(call.case.key, null, 2));
34
+ if (call.case.keyDir)
35
+ cpSync(call.case.keyDir, join(dir, GRADE_FILES.keyDir), { recursive: true });
36
+ if (reads === "trial") {
37
+ writeFileSync(join(dir, GRADE_FILES.result), JSON.stringify(call.result ?? null));
38
+ writeFileSync(
39
+ join(dir, GRADE_FILES.facts),
40
+ JSON.stringify({ facts: call.facts, stages: call.stages }),
41
+ );
42
+ if (existsSync(call.kept)) cpSync(call.kept, join(dir, GRADE_FILES.kept), { recursive: true });
43
+ else mkdirSync(join(dir, GRADE_FILES.kept));
44
+ } else writeFileSync(join(dir, GRADE_FILES.facts), JSON.stringify({ facts: call.facts }));
45
+ if (call.previous) {
46
+ const previous = checkSchema(PreviousSchema, call.previous);
47
+ if (!previous.ok) throw new Error(describeProblems(GRADE_FILES.previous, previous.problems));
48
+ writeFileSync(join(dir, GRADE_FILES.previous), JSON.stringify(call.previous));
49
+ }
50
+ }
51
+
52
+ export type WorkflowGraderLab = {
53
+ dataset: DatasetInfo;
54
+ /**
55
+ * Your checkout's `awf`, which runs every grader workflow; never with the trials' preload. Asked
56
+ * for when the first grade needs it.
57
+ */
58
+ awf: () => Promise<AwfBin>;
59
+ runner: Runner;
60
+ runRoot: string;
61
+ now: () => Date;
62
+ };
63
+
64
+ /**
65
+ * The dataset's grader workflows: each graded by its own `awf run`, in an empty working folder,
66
+ * with `AWF_LAB_GRADE` naming a grade folder made beside it and deleted after.
67
+ */
68
+ export function workflowGraders(lab: WorkflowGraderLab, specs: readonly GraderSpec[]): LabGrader[] {
69
+ return specs
70
+ .filter((spec): spec is WorkflowSpec => spec.kind === "workflow")
71
+ .map((spec) => workflowGrader(lab, spec));
72
+ }
73
+
74
+ /** A grader workflow as the lab runs it: a dataset's, or the lab's own criteria judge. */
75
+ export type GraderRun = Pick<WorkflowSpec, "name" | "file" | "reads" | "manual"> & {
76
+ timeout: string;
77
+ /** The workflow's own arguments. */
78
+ argv?: readonly string[];
79
+ /** Added to the run's environment, over the trial's. */
80
+ env?: Record<string, string>;
81
+ };
82
+
83
+ function workflowGrader(lab: WorkflowGraderLab, spec: WorkflowSpec): LabGrader {
84
+ return {
85
+ ...graderWorkflow(
86
+ { runner: lab.runner, runRoot: lab.runRoot, now: lab.now, awf: lab.awf },
87
+ {
88
+ ...spec,
89
+ timeout: spec.timeout ?? lab.dataset.target.limits?.workflow ?? LIMIT_DEFAULTS.workflow,
90
+ },
91
+ ),
92
+ version: spec.version,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * A grader that runs `spec.file` in an `awf run` of its own. `awf` gives the folder's `awf`, or
98
+ * undefined for this checkout's own, which the lab's criteria judge runs on.
99
+ */
100
+ export function graderWorkflow(
101
+ lab: Pick<WorkflowGraderLab, "runner" | "runRoot" | "now"> & {
102
+ awf: () => Promise<AwfBin | undefined>;
103
+ },
104
+ spec: GraderRun,
105
+ ): LabGrader {
106
+ const { timeout } = spec;
107
+ return {
108
+ name: spec.name,
109
+ costly: true,
110
+ reads: spec.reads,
111
+ ...(spec.manual ? { manual: true } : {}),
112
+ async grade(call) {
113
+ // Each its own, whatever the grader's name: `a/b` and `a_b` never share one.
114
+ const dir = join(mkdtempSync(join(call.work, "grade-")), "grade");
115
+ const cwd = join(dirname(dir), "cwd");
116
+ mkdirSync(cwd);
117
+ const fail = (reason: string, more: object = {}) => Object.assign(new Error(reason), more);
118
+ try {
119
+ writeGradeFolder(dir, call, spec.reads);
120
+ const folder = await lab.awf();
121
+ const ran = await lab.runner({
122
+ workflow: spec.file,
123
+ cwd,
124
+ timeout,
125
+ argv: spec.argv ?? [],
126
+ runRoot: lab.runRoot,
127
+ id: newRunId(lab.now()),
128
+ ...(folder ? { awf: { bin: folder.bin, dir: folder.dir } } : {}),
129
+ quiet: true,
130
+ env: { ...call.env, ...spec.env, [TRIAL_ENV.grade]: dir },
131
+ });
132
+ const run = ran.record;
133
+ if (!run) {
134
+ const last = ran.unread ?? ran.stderr.trim().split("\n").at(-1);
135
+ throw fail(`grader ${spec.name}'s run printed no record${last ? `: ${last}` : ""}`);
136
+ }
137
+ const spent = {
138
+ runId: run.runId,
139
+ ...(run.accounting.totals.estimate !== undefined
140
+ ? { estimate: run.accounting.totals.estimate }
141
+ : {}),
142
+ };
143
+ if (run.outcome !== "completed") {
144
+ throw fail(`grader ${spec.name}'s run ${run.outcome}: ${run.reason}`, spent);
145
+ }
146
+ let answer: ReturnType<typeof checkAnswer>;
147
+ try {
148
+ answer = checkAnswer(spec.name, run.value);
149
+ } catch (error) {
150
+ throw fail((error as Error).message, spent);
151
+ }
152
+ const models = run.accounting.byModel.map((m) => m.model);
153
+ return {
154
+ ...answer,
155
+ ...spent,
156
+ ...(models.length > 0 ? { models } : {}),
157
+ ms: run.accounting.wallMs,
158
+ };
159
+ } finally {
160
+ rmSync(dirname(dir), { recursive: true, force: true });
161
+ }
162
+ },
163
+ };
164
+ }