@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,187 @@
1
+ import { CHECK_KIND, type LabCheck, LabCheckSchema } from "../format/output";
2
+ import { checkSchema, describeProblems } from "../shared/validate";
3
+ import {
4
+ type Context,
5
+ countedGraders,
6
+ datasetFacts,
7
+ envOf,
8
+ helperPlace,
9
+ tagged,
10
+ tmpOf,
11
+ workspaceOf,
12
+ } from "./command-context";
13
+ import {
14
+ type CaseInfo,
15
+ type DatasetInfo,
16
+ judgesSentences,
17
+ readDataset,
18
+ readEachCase,
19
+ } from "./dataset";
20
+ import { checkGood, type GoodCheck } from "./good";
21
+ import { Refusal } from "./refusal";
22
+ import { plural } from "./text";
23
+ import { type CaseWorkspace, chooseDataset } from "./workspace";
24
+
25
+ // `case check`: the cases, not the workflow. Every case, held out and drafts too: its key reads
26
+ // and carries its marker, its sentences have a grader, and its known good record passes `facts`,
27
+ // `expect` and the code graders. No `setup`, workflow or agent runs, so it spends nothing.
28
+
29
+ export type CasesChecked = {
30
+ dataset: string;
31
+ /** The cases that failed a check, by name. */
32
+ failing: string[];
33
+ /** Each case that failed a check or has a known good record: whether it passed, and a line. */
34
+ cases: { case: string; passed: boolean; partial?: true; line: string }[];
35
+ /** How many cases have a known good record. */
36
+ good: number;
37
+ /** How many cases were checked. */
38
+ checked: number;
39
+ };
40
+
41
+ /** The known good records of these cases, graded: what the loop checks before it runs a try. */
42
+ export async function checkGoodRecords(
43
+ context: Context,
44
+ workspace: CaseWorkspace,
45
+ info: DatasetInfo,
46
+ cases: readonly CaseInfo[],
47
+ ): Promise<GoodCheck[]> {
48
+ const params = Object.fromEntries(
49
+ Object.entries(info.params).flatMap(([name, { value }]) =>
50
+ value === undefined ? [] : [[name, value]],
51
+ ),
52
+ );
53
+ return checkGood({
54
+ info,
55
+ cases,
56
+ graders: await countedGraders(context, workspace, info),
57
+ facts: datasetFacts(context, workspace, info),
58
+ tmp: tmpOf(context),
59
+ env: envOf(context),
60
+ params,
61
+ });
62
+ }
63
+
64
+ /** Each dataset's cases checked: `--dataset`'s, or every dataset's; those `--cases` and `--tags` pick. */
65
+ export async function checkCases(context: Context): Promise<CasesChecked[]> {
66
+ const { options } = context;
67
+ const workspace = workspaceOf(context);
68
+ const refs =
69
+ options.dataset !== undefined || workspace.datasets.length <= 1
70
+ ? [chooseDataset(workspace, options.dataset)]
71
+ : workspace.datasets;
72
+ const datasets = refs.map((ref) => {
73
+ const info = readDataset(ref, helperPlace(context, workspace));
74
+ return { info, read: readEachCase(info) };
75
+ });
76
+ for (const name of options.cases ?? []) {
77
+ if (!datasets.some(({ read }) => read.some((c) => c.name === name))) {
78
+ const where = datasets.length === 1 ? datasets[0]!.info.name : "any dataset";
79
+ const known = datasets.flatMap(({ read }) => read.map((c) => c.name));
80
+ throw new Refusal(`no case ${name} in ${where}; known: ${[...new Set(known)].join(", ")}`);
81
+ }
82
+ }
83
+ const checked: CasesChecked[] = [];
84
+ for (const { info, read } of datasets) {
85
+ checked.push(await checkDataset(context, workspace, info, read));
86
+ }
87
+ // Across datasets, one that `--cases` or `--tags` picks nothing of isn't checked.
88
+ const picking = options.cases !== undefined || options.tags !== undefined;
89
+ return datasets.length > 1 && picking ? checked.filter((d) => d.checked > 0) : checked;
90
+ }
91
+
92
+ async function checkDataset(
93
+ context: Context,
94
+ workspace: CaseWorkspace,
95
+ info: DatasetInfo,
96
+ all: ReturnType<typeof readEachCase>,
97
+ ): Promise<CasesChecked> {
98
+ const { options } = context;
99
+ let read = all;
100
+ if (options.cases) read = read.filter((c) => options.cases!.includes(c.name));
101
+ if (options.tags) {
102
+ // A key that doesn't read has no tags to pick by: it is checked whatever the tags.
103
+ read = read.filter((c) => !("info" in c) || tagged(c.info, options.tags!));
104
+ }
105
+ const lines: CasesChecked["cases"] = [];
106
+ const failing = new Set<string>();
107
+ const fail = (name: string, line: string) => {
108
+ failing.add(name);
109
+ lines.push({ case: name, passed: false, line: `${name}: ${line}` });
110
+ };
111
+ const cases: CaseInfo[] = [];
112
+ const judged = judgesSentences(info);
113
+ for (const each of read) {
114
+ if ("problem" in each) {
115
+ fail(each.name, each.problem);
116
+ continue;
117
+ }
118
+ const { key } = each.info;
119
+ if ((key.must || key["must-not"]) && !judged) {
120
+ fail(
121
+ each.name,
122
+ `its key has must or must-not, and ${info.name}'s grading.ts lists no sentences grader to judge them, other than a manual one`,
123
+ );
124
+ }
125
+ cases.push(each.info);
126
+ }
127
+ const checks = await checkGoodRecords(context, workspace, info, cases);
128
+ for (const check of checks) {
129
+ lines.push({
130
+ case: check.case,
131
+ passed: check.passed,
132
+ ...(check.partial ? { partial: true as const } : {}),
133
+ line: check.line,
134
+ });
135
+ if (!check.passed) failing.add(check.case);
136
+ }
137
+ return {
138
+ dataset: info.name,
139
+ failing: [...failing],
140
+ cases: lines,
141
+ good: checks.length,
142
+ checked: read.length,
143
+ };
144
+ }
145
+
146
+ /**
147
+ * `case check`, printed: a line for each check that failed or left a grader out, under its
148
+ * dataset's name when it checked more than one, then the count; with `--json`, each dataset's
149
+ * cases that failed or have a known good record.
150
+ */
151
+ export async function caseCheck(context: Context, names: readonly string[]): Promise<number> {
152
+ if (names.length > 0) {
153
+ throw new Refusal(
154
+ `case check takes no words, only flags; got ${names.join(" ")}: --cases {a,b} picks cases`,
155
+ );
156
+ }
157
+ const checked = await checkCases(context);
158
+ const failed = checked.reduce((n, d) => n + d.failing.length, 0);
159
+ if (context.options.json) {
160
+ const json: LabCheck = {
161
+ kind: CHECK_KIND,
162
+ datasets: checked.map((d) => ({
163
+ dataset: d.dataset,
164
+ checked: d.checked,
165
+ good: d.good,
166
+ failing: d.failing,
167
+ cases: d.cases.map((c) => ({ case: c.case, passed: c.passed, said: c.line })),
168
+ })),
169
+ };
170
+ const valid = checkSchema(LabCheckSchema, json);
171
+ if (!valid.ok) throw new Error(describeProblems("case check --json", valid.problems));
172
+ context.stdout(JSON.stringify(json, null, 2));
173
+ } else {
174
+ const n = checked.reduce((sum, d) => sum + d.checked, 0);
175
+ const good = checked.reduce((sum, d) => sum + d.good, 0);
176
+ const several = checked.length > 1;
177
+ const shown = checked.flatMap((d) => {
178
+ const lines = d.cases.filter((c) => !c.passed || c.partial).map((c) => c.line);
179
+ if (!several || lines.length === 0) return lines;
180
+ return [d.dataset, ...lines.map((line) => ` ${line}`)];
181
+ });
182
+ const across = several ? ` in ${checked.length} datasets` : "";
183
+ const closing = `checked ${plural(n, "case")}${across}, ${good} with a known good record: ${failed === 0 ? "every one passed" : `${failed} failed`}`;
184
+ context.stdout([...shown, closing].join("\n"));
185
+ }
186
+ return failed > 0 ? 1 : 0;
187
+ }
package/src/lab/cli.ts ADDED
@@ -0,0 +1,325 @@
1
+ import { existsSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, join, relative, resolve } from "node:path";
4
+ import { captureCommand, casePin, label } from "./capture-command";
5
+ import { caseCheck } from "./check-command";
6
+ import {
7
+ type CasesEnvironment,
8
+ type Context,
9
+ type Options,
10
+ relativePaths,
11
+ workspaceOf,
12
+ } from "./command-context";
13
+ import { config } from "./config-command";
14
+ import { TARGET_FILE } from "./eval-files";
15
+ import { gitTop } from "./git";
16
+ import { loopCommand, loopReport } from "./loop-command";
17
+ import { Refusal } from "./refusal";
18
+ import { report } from "./report-command";
19
+ import { run } from "./run-command";
20
+ import { runs } from "./runs-command";
21
+ import { newCase } from "./scaffold";
22
+ import { score } from "./score-command";
23
+ import {
24
+ commandUsage,
25
+ fullUsage,
26
+ isCommand,
27
+ refuseForeignFlags,
28
+ refuseNotCommand,
29
+ refuseUnknownFlag,
30
+ } from "./usage";
31
+ import { findEvals } from "./workspace";
32
+
33
+ function parse(argv: readonly string[]): {
34
+ command?: string;
35
+ names: string[];
36
+ options: Options;
37
+ /** The flags given, each once, as written; `-h` as `--help`. */
38
+ flags: string[];
39
+ /** Flags no command takes, in the order given. */
40
+ unknown: string[];
41
+ } {
42
+ const options: Options = {
43
+ failed: false,
44
+ yes: false,
45
+ dryRun: false,
46
+ json: false,
47
+ help: false,
48
+ against: [],
49
+ param: [],
50
+ limit: [],
51
+ vary: [],
52
+ fresh: false,
53
+ holdout: false,
54
+ clear: false,
55
+ md: false,
56
+ good: false,
57
+ replace: false,
58
+ new: false,
59
+ };
60
+ const positional: string[] = [];
61
+ const flags = new Set<string>();
62
+ const unknown: string[] = [];
63
+ const rest = [...argv];
64
+ const value = (flag: string) => {
65
+ const next = rest.shift();
66
+ if (next === undefined || next.startsWith("--") || next === "-C" || next === "-h") {
67
+ throw new Refusal(`${flag} needs a value`);
68
+ }
69
+ return next;
70
+ };
71
+ while (rest.length > 0) {
72
+ const arg = rest.shift()!;
73
+ if (arg.startsWith("-")) flags.add(arg === "-h" ? "--help" : arg);
74
+ switch (arg) {
75
+ case "-C":
76
+ options.folder = value(arg);
77
+ break;
78
+ case "--dataset":
79
+ options.dataset = value(arg);
80
+ break;
81
+ case "--cases":
82
+ options.cases = value(arg)
83
+ .split(",")
84
+ .map((c) => c.trim())
85
+ .filter(Boolean);
86
+ break;
87
+ case "--failed":
88
+ options.failed = true;
89
+ break;
90
+ case "--trials": {
91
+ const text = value(arg);
92
+ if (!/^[1-9][0-9]*$/.test(text)) throw new Refusal("--trials is a whole number from 1");
93
+ options.trials = Number(text);
94
+ break;
95
+ }
96
+ case "--against":
97
+ options.against.push(value(arg));
98
+ break;
99
+ case "--tags":
100
+ options.tags = value(arg)
101
+ .split(",")
102
+ .map((t) => t.trim())
103
+ .filter(Boolean);
104
+ break;
105
+ case "--md":
106
+ options.md = true;
107
+ break;
108
+ case "--holdout":
109
+ options.holdout = true;
110
+ break;
111
+ case "--clear":
112
+ options.clear = true;
113
+ break;
114
+ case "--fresh":
115
+ options.fresh = true;
116
+ break;
117
+ case "--param":
118
+ options.param.push(value(arg));
119
+ break;
120
+ case "--vary":
121
+ options.vary.push(value(arg));
122
+ break;
123
+ case "--limit":
124
+ options.limit.push(value(arg));
125
+ break;
126
+ case "--case":
127
+ options.case = value(arg);
128
+ break;
129
+ case "--yes":
130
+ options.yes = true;
131
+ break;
132
+ case "--good":
133
+ options.good = true;
134
+ break;
135
+ case "--needs-work":
136
+ options.needsWork = value(arg);
137
+ break;
138
+ case "--grader":
139
+ options.grader = value(arg);
140
+ break;
141
+ case "--dry-run":
142
+ options.dryRun = true;
143
+ break;
144
+ case "--json":
145
+ options.json = true;
146
+ break;
147
+ case "--budget": {
148
+ const text = value(arg);
149
+ const usd = Number(text);
150
+ if (!/^[0-9]+(\.[0-9]+)?$/.test(text) || !(usd > 0)) {
151
+ throw new Refusal("--budget is US dollars, more than 0, such as 5 or 2.50");
152
+ }
153
+ options.budget = usd;
154
+ break;
155
+ }
156
+ case "--tries": {
157
+ const text = value(arg);
158
+ if (!/^[1-9][0-9]*$/.test(text)) throw new Refusal("--tries is a whole number from 1");
159
+ options.tries = Number(text);
160
+ break;
161
+ }
162
+ case "--allowance": {
163
+ const text = value(arg);
164
+ if (text === "off") options.allowance = "off";
165
+ else if (/^[0-9]+$/.test(text) && Number(text) >= 1 && Number(text) <= 100) {
166
+ options.allowance = Number(text);
167
+ } else throw new Refusal("--allowance is a percent from 1 to 100, or off");
168
+ break;
169
+ }
170
+ case "--concurrency": {
171
+ const text = value(arg);
172
+ if (!/^[1-9][0-9]*$/.test(text)) {
173
+ throw new Refusal("--concurrency is a whole number from 1");
174
+ }
175
+ options.concurrency = Number(text);
176
+ break;
177
+ }
178
+ case "--loop":
179
+ options.loop = value(arg);
180
+ break;
181
+ case "--replace":
182
+ options.replace = true;
183
+ break;
184
+ case "--new":
185
+ options.new = true;
186
+ break;
187
+ case "--help":
188
+ case "-h":
189
+ options.help = true;
190
+ break;
191
+ default:
192
+ if (arg.startsWith("-")) unknown.push(arg);
193
+ else positional.push(arg);
194
+ }
195
+ }
196
+ const [command, ...names] = positional;
197
+ return { ...(command ? { command } : {}), names, options, flags: [...flags], unknown };
198
+ }
199
+
200
+ /** The command line: the commands in `usage.ts`. */
201
+ export async function runCases(
202
+ argv: readonly string[],
203
+ environment: CasesEnvironment = {},
204
+ ): Promise<number> {
205
+ const stdout = environment.stdout ?? ((text) => console.log(text));
206
+ const stderr = environment.stderr ?? ((text) => void process.stderr.write(`${text}\n`));
207
+ try {
208
+ const { command, names, options, flags, unknown } = parse(argv);
209
+ if (command === "help" || (!command && options.help && unknown.length === 0)) {
210
+ stdout(fullUsage());
211
+ return 0;
212
+ }
213
+ if (!command) {
214
+ if (unknown.length > 0) refuseUnknownFlag(unknown[0]!, undefined);
215
+ stderr(`awf-lab needs a command:\n${fullUsage()}`);
216
+ return 2;
217
+ }
218
+ refuseNotCommand(command);
219
+ if (!isCommand(command)) {
220
+ throw new Refusal(`unknown command ${command}; awf-lab --help lists them`);
221
+ }
222
+ if (unknown.length > 0) refuseUnknownFlag(unknown[0]!, command);
223
+ if (options.help) {
224
+ stdout(commandUsage(command)!);
225
+ return 0;
226
+ }
227
+ refuseForeignFlags(
228
+ command,
229
+ flags,
230
+ command === "case" || command === "loop" ? names[0] : undefined,
231
+ );
232
+ const verbs = command === "loop" ? 2 : command === "case" ? 1 : 0;
233
+ const context: Context = {
234
+ command: [command, ...names.slice(0, verbs)].join(" "),
235
+ cwd: folderOf(environment.cwd ?? process.cwd(), options.folder),
236
+ home: environment.home ?? homedir(),
237
+ options,
238
+ environment,
239
+ stdout,
240
+ stderr,
241
+ };
242
+ switch (command) {
243
+ case "case":
244
+ return await caseCommand(context, names);
245
+ case "run":
246
+ if (names.length > 0) {
247
+ throw new Refusal(
248
+ `run takes no words, only flags; got ${names.join(" ")}: --cases {a,b} picks cases, --dataset {name} a dataset`,
249
+ );
250
+ }
251
+ return (await run(context)).exit;
252
+ case "report":
253
+ if (options.loop !== undefined) {
254
+ if (names.length > 0) {
255
+ throw new Refusal(`report --loop takes no run; got ${names.join(" ")}`);
256
+ }
257
+ return loopReport(context, options.loop);
258
+ }
259
+ return await report(context, names);
260
+ case "score":
261
+ return await score(context, names);
262
+ case "runs":
263
+ if (names.length > 0) throw new Refusal(`runs takes no words; got ${names.join(" ")}`);
264
+ return runs(context);
265
+ case "label":
266
+ return label(context, names);
267
+ case "loop":
268
+ return await loopCommand(context, names);
269
+ case "config":
270
+ if (names.length > 0) throw new Refusal(`config takes no words; got ${names.join(" ")}`);
271
+ return config(context);
272
+ }
273
+ } catch (error) {
274
+ if (error instanceof Refusal) {
275
+ stderr(`awf-lab: ${relativePaths(environment.cwd ?? process.cwd(), error.message)}`);
276
+ return 2;
277
+ }
278
+ stderr(`awf-lab: ${(error as Error).message}`);
279
+ return 4;
280
+ }
281
+ }
282
+
283
+ const CASE_VERBS = ["new", "capture", "pin", "check"];
284
+
285
+ /** `-C {folder}`: the folder the command runs as if started in, as `git -C` does. */
286
+ function folderOf(cwd: string, given: string | undefined): string {
287
+ if (given === undefined) return cwd;
288
+ const folder = resolve(cwd, given);
289
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) {
290
+ throw new Refusal(`-C ${given}: no such folder`);
291
+ }
292
+ return realpathSync(folder);
293
+ }
294
+
295
+ async function caseCommand(context: Context, names: readonly string[]): Promise<number> {
296
+ const [verb, ...rest] = names;
297
+ if (verb === "capture") return await captureCommand(context, rest);
298
+ if (verb === "pin") return await casePin(context, rest);
299
+ if (verb === "check") return await caseCheck(context, rest);
300
+ if (verb !== "new") {
301
+ throw new Refusal(
302
+ `case takes ${CASE_VERBS.join(", ")}${verb ? `, not ${verb}` : ""}: awf-lab case --help lists them`,
303
+ );
304
+ }
305
+ const [address, ...extra] = rest;
306
+ if (!address) throw new Refusal("case new needs a {dataset}/{case}");
307
+ if (extra.length > 0) {
308
+ throw new Refusal(
309
+ `case new takes one {dataset}/{case}; got ${extra.length + 1} words: ${[address, ...extra].join(" ")}`,
310
+ );
311
+ }
312
+ const found = findEvals(context.cwd);
313
+ const evals = found ?? join(gitTop(context.cwd) ?? context.cwd, "evals");
314
+ const made = newCase(evals, address, found ? workspaceOf(context) : undefined);
315
+ const shown = (file: string) => relative(context.cwd, file) || file;
316
+ for (const file of made.written) context.stdout(`wrote ${shown(file)}`);
317
+ for (const dir of made.made) context.stdout(`made ${shown(dir)}/`);
318
+ const targetScript = made.written.find((file) => basename(file) === TARGET_FILE);
319
+ context.stdout(
320
+ targetScript
321
+ ? `next: fill ${shown(targetScript)} and delete its first line, then the case's input/ and its key's expect, and remove the key's draft: true`
322
+ : `case ${shown(made.caseDir)}: fill its input/ and key.md, then remove the key's draft: true`,
323
+ );
324
+ return 0;
325
+ }
@@ -0,0 +1,108 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { checkVersion } from "../shared/version";
4
+ import { checkAnswer } from "./answer";
5
+ import { type DatasetInfo, graderSpecs } from "./dataset";
6
+ import { GRADING_FILE } from "./eval-files";
7
+ import type { LabGrader } from "./grading";
8
+
9
+ const HELPER = join(import.meta.dir, "../env/grade-helper.ts");
10
+
11
+ let requests = 0;
12
+
13
+ /**
14
+ * Starts the grade helper in `root` on a request and reads its answer. Its output goes to a file,
15
+ * never a pipe: a process the grader left running would hold a pipe open, and the lab would wait
16
+ * on it after the kill.
17
+ */
18
+ export async function runHelper(
19
+ request: Record<string, unknown>,
20
+ options: {
21
+ root: string;
22
+ work: string;
23
+ env: Record<string, string>;
24
+ timeoutMs: number;
25
+ name: string;
26
+ },
27
+ ): Promise<Record<string, unknown>> {
28
+ mkdirSync(options.work, { recursive: true });
29
+ const stem = join(options.work, `helper-${options.name}-${process.pid}-${++requests}`);
30
+ const file = `${stem}.json`;
31
+ const out = `${stem}.out.json`;
32
+ const said = `${stem}.err.txt`;
33
+ writeFileSync(file, JSON.stringify({ ...request, out }));
34
+ try {
35
+ const child = Bun.spawn([process.execPath, HELPER, file], {
36
+ cwd: options.root,
37
+ stdin: "ignore",
38
+ stdout: "ignore",
39
+ stderr: Bun.file(said),
40
+ env: options.env,
41
+ });
42
+ const timer = setTimeout(() => child.kill("SIGKILL"), options.timeoutMs);
43
+ await child.exited;
44
+ clearTimeout(timer);
45
+ if (!existsSync(out)) {
46
+ const last = existsSync(said)
47
+ ? readFileSync(said, "utf8").trim().split("\n").at(-1)
48
+ : undefined;
49
+ throw new Error(
50
+ child.signalCode
51
+ ? `grader ${options.name} took longer than ${Math.round(options.timeoutMs / 1000)}s`
52
+ : `grader ${options.name} exited ${child.exitCode}${last ? `: ${last}` : ""}`,
53
+ );
54
+ }
55
+ return JSON.parse(readFileSync(out, "utf8")) as Record<string, unknown>;
56
+ } finally {
57
+ for (const each of [file, out, said]) rmSync(each, { force: true });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * The dataset's own code graders, each run in a Bun process started in `root`, your checkout, so
63
+ * `grading.ts` resolves its imports there and never loads into the lab's process.
64
+ */
65
+ export function codeGraders(dataset: DatasetInfo, root: string, timeoutMs: number): LabGrader[] {
66
+ const file = join(dataset.evalDir, GRADING_FILE);
67
+ return graderSpecs(dataset)
68
+ .filter((spec) => spec.kind === "code")
69
+ .map(({ name, version, reads, manual }) => ({
70
+ name,
71
+ version,
72
+ reads,
73
+ ...(manual ? { manual: true } : {}),
74
+ async grade(input) {
75
+ const answer = (await runHelper(
76
+ {
77
+ mode: "grade",
78
+ file,
79
+ name,
80
+ input: {
81
+ case: input.case,
82
+ facts: input.facts,
83
+ params: input.params,
84
+ result: input.result ?? null,
85
+ stages: input.stages,
86
+ scratch: input.scratch,
87
+ kept: input.kept,
88
+ },
89
+ },
90
+ { root, work: input.work, env: input.env, timeoutMs, name },
91
+ )) as { grade?: unknown; error?: string; version?: string };
92
+ if (answer.version !== undefined && checkVersion(answer.version)) {
93
+ throw new Error(`grader ${name}: ${checkVersion(answer.version)}`);
94
+ }
95
+ const withVersion = (error: Error) =>
96
+ Object.assign(error, answer.version ? { version: answer.version } : {});
97
+ if (answer.error !== undefined) throw withVersion(new Error(answer.error));
98
+ try {
99
+ return {
100
+ ...checkAnswer(name, answer.grade),
101
+ ...(answer.version ? { version: answer.version } : {}),
102
+ };
103
+ } catch (error) {
104
+ throw withVersion(error as Error);
105
+ }
106
+ },
107
+ }));
108
+ }