@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,228 @@
1
+ import type { DatasetEntry, LoopEntry } from "../format/settings";
2
+ import { checkVersion } from "../shared/version";
3
+ import type { CaseComparison } from "./compare";
4
+ import type { CodeGrader, Reads } from "./grader";
5
+ import type { Facts, RecordOf, TargetDefinition } from "./index";
6
+
7
+ // What `grading.ts` and `evals/awf-lab.config.ts` export, and what marks each value the lab's
8
+ // helper hands over. The marks live in code, never in the files a person writes.
9
+
10
+ /** The spec `defineTarget` was given, on what it returns: what the lab reads of `target.ts`. */
11
+ export const TARGET_SPEC = Symbol.for("agentswf.lab.target");
12
+ const REQUIRED = Symbol.for("agentswf.lab.required");
13
+ const DESCRIBING = Symbol.for("agentswf.lab.describing");
14
+
15
+ export const GRADING_KIND = "awf.lab-grading/0";
16
+ export const LAB_KIND = "awf.lab-settings/0";
17
+ export const WORKFLOW_GRADER_KIND = "awf.lab-workflow-grader/0";
18
+ export const SENTENCES_KIND = "awf.lab-sentences/0";
19
+
20
+ /**
21
+ * Whether these files are being read by the lab's helper, rather than run: `defineTarget` then
22
+ * makes no workflow, and loads no engine.
23
+ */
24
+ export function describing(): boolean {
25
+ return (globalThis as { [DESCRIBING]?: boolean })[DESCRIBING] === true;
26
+ }
27
+
28
+ export function startDescribing(): void {
29
+ (globalThis as { [DESCRIBING]?: boolean })[DESCRIBING] = true;
30
+ }
31
+
32
+ /** A parameter `target.ts` declares with no default: a run is refused until it is given a value. */
33
+ export type RequiredParam<T extends string = string> = {
34
+ readonly [REQUIRED]: true;
35
+ /** Never set: carries the value's type. */
36
+ readonly value?: T;
37
+ };
38
+
39
+ /** A parameter with no default, in `defineTarget`'s `params`. */
40
+ export function required<T extends string = string>(): RequiredParam<T> {
41
+ return { [REQUIRED]: true };
42
+ }
43
+
44
+ export const isRequired = (value: unknown): value is RequiredParam =>
45
+ typeof value === "object" && value !== null && (value as RequiredParam)[REQUIRED] === true;
46
+
47
+ /** Refuses a field a spec doesn't take: an unknown field is a mistake, never ignored. */
48
+ export function refuseUnknown(what: string, spec: object, fields: readonly string[]): void {
49
+ const unknown = Object.keys(spec).filter((field) => !fields.includes(field));
50
+ if (unknown.length > 0) {
51
+ throw new Error(`${what}: unknown field ${unknown.join(", ")}; it takes ${fields.join(", ")}`);
52
+ }
53
+ }
54
+
55
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
56
+
57
+ /** Checks a grader's name, which `score --grader` and a metric's `{grader}.{name}` use. */
58
+ export function checkGraderName(what: string, name: unknown): string {
59
+ if (typeof name !== "string" || !NAME.test(name)) {
60
+ throw new Error(
61
+ `${what}: name ${JSON.stringify(name)} is letters, digits, _ and -, starting with a letter or digit`,
62
+ );
63
+ }
64
+ if (name === "expect") {
65
+ throw new Error(`${what}: ${name} is the lab's own; name your grader otherwise`);
66
+ }
67
+ return name;
68
+ }
69
+
70
+ /** Checks a grader's `reads`: what it grades from. */
71
+ export function readsOf(what: string, reads: unknown): Reads {
72
+ if (reads !== "facts" && reads !== "trial") {
73
+ throw new Error(
74
+ `${what}: reads is "facts", for a grader of the facts alone, or "trial", for one that also reads the record and the files evidence saved`,
75
+ );
76
+ }
77
+ return reads;
78
+ }
79
+
80
+ /** A grader workflow: a workflow whose agents decide what code can't. */
81
+ export type WorkflowGrader = {
82
+ readonly kind: typeof WORKFLOW_GRADER_KIND;
83
+ readonly name: string;
84
+ readonly version: string;
85
+ /** Loads the workflow; its file is read from the import, so write it as `() => import("./graders/x")`. */
86
+ readonly load: () => Promise<unknown>;
87
+ readonly reads: Reads;
88
+ readonly manual: boolean;
89
+ readonly timeout?: string;
90
+ };
91
+
92
+ /** A grader's version, checked where it is made. */
93
+ function versionOf(what: string, version: unknown): string {
94
+ const bad = checkVersion(version);
95
+ if (bad) throw new Error(`${what}: ${bad}`);
96
+ return version as string;
97
+ }
98
+
99
+ /**
100
+ * A grader workflow of the eval folder, run with `awf run`: `load` is `() => import("./graders/x")`,
101
+ * a literal path, which the lab reads to find the file. `version`, semver, is the grader's: its
102
+ * grades are kept while its major, minor and pre-release tag stay the same. `reads: "facts"` gives
103
+ * it the facts alone, `"trial"` also the result, the stages' values and the files `evidence` saved;
104
+ * `manual` runs it only under `score --grader`, and it never decides a verdict.
105
+ */
106
+ export function workflowGrader(
107
+ load: () => Promise<unknown>,
108
+ options: {
109
+ name: string;
110
+ version: string;
111
+ reads: Reads;
112
+ manual?: boolean;
113
+ timeout?: string;
114
+ },
115
+ ): WorkflowGrader {
116
+ refuseUnknown("workflowGrader", options, ["name", "version", "reads", "manual", "timeout"]);
117
+ if (typeof load !== "function") {
118
+ throw new Error('workflowGrader takes its workflow as () => import("./graders/x")');
119
+ }
120
+ const name = checkGraderName("workflowGrader", options.name);
121
+ return {
122
+ kind: WORKFLOW_GRADER_KIND,
123
+ name,
124
+ version: versionOf(`workflowGrader ${name}`, options.version),
125
+ load,
126
+ reads: readsOf(`workflowGrader ${name}`, options.reads),
127
+ manual: options.manual === true,
128
+ ...(options.timeout !== undefined ? { timeout: options.timeout } : {}),
129
+ };
130
+ }
131
+
132
+ /** The lab's grader for a key's `must` and `must-not` sentences. */
133
+ export type SentencesGrader = {
134
+ readonly kind: typeof SENTENCES_KIND;
135
+ readonly name: string;
136
+ readonly version: string;
137
+ /** `{harness}/{model}`. */
138
+ readonly agent: string;
139
+ readonly voters?: number;
140
+ readonly manual: boolean;
141
+ };
142
+
143
+ /**
144
+ * The key's `must` and `must-not` sentences, each put to `voters` agents (3 unless set, odd), the
145
+ * majority deciding. A key with sentences needs one that isn't `manual`. `version`, semver, is the
146
+ * grader's, as on any other; another `agent` or `voters` grades again without a bump. Named
147
+ * `sentences` unless given a `name`; a second one needs its own. Its voters read the trial: the
148
+ * result, the facts, the stages' values and the files `evidence` saved.
149
+ */
150
+ export function sentences(options: {
151
+ agent: string;
152
+ version: string;
153
+ voters?: number;
154
+ name?: string;
155
+ manual?: boolean;
156
+ }): SentencesGrader {
157
+ refuseUnknown("sentences", options, ["agent", "version", "voters", "name", "manual"]);
158
+ return {
159
+ kind: SENTENCES_KIND,
160
+ name: options.name === undefined ? "sentences" : checkGraderName("sentences", options.name),
161
+ version: versionOf("sentences", options.version),
162
+ agent: options.agent,
163
+ ...(options.voters !== undefined ? { voters: options.voters } : {}),
164
+ manual: options.manual === true,
165
+ };
166
+ }
167
+
168
+ export type Grader = CodeGrader | WorkflowGrader | SentencesGrader;
169
+
170
+ export type GradingSpec<T = TargetDefinition> = {
171
+ /**
172
+ * Turns a trial record into flat facts: strings, numbers, booleans or `null`. The key's `expect`
173
+ * checks them, and graders read them. A plain function of the record, run outside the trial in
174
+ * your checkout, so it can be fixed and run again on kept records. A fact that comes out
175
+ * `undefined`, or a `facts` that throws, errors the trial as the dataset's (`facts-missing`).
176
+ */
177
+ facts?: (record: RecordOf<T>) => Facts | Promise<Facts>;
178
+ /**
179
+ * Graders, run in this order after the key's `expect`, stopping at the first that fails the
180
+ * trial: list the cheap ones first.
181
+ */
182
+ graders?: readonly Grader[];
183
+ /** The bar for every case: `"all"` unless set, or a fraction such as `"2/3"`; a key's wins. */
184
+ pass?: string;
185
+ /** What "better" means when two versions are compared. */
186
+ compare?: CaseComparison;
187
+ };
188
+
189
+ export type Grading = GradingSpec<never> & { readonly kind: typeof GRADING_KIND };
190
+
191
+ /**
192
+ * `grading.ts`'s default export: everything that decides a grade. `defineGrading<typeof target>`,
193
+ * with `import type target from "./target"`, types the record `facts` reads.
194
+ */
195
+ export function defineGrading<T = TargetDefinition>(spec: GradingSpec<T>): Grading {
196
+ return { ...(spec as GradingSpec<never>), kind: GRADING_KIND };
197
+ }
198
+
199
+ export type LabSpec = {
200
+ /** Where every run of the project is kept, in place of `~/.awf/lab/{main checkout's folder}-{first commit}`. */
201
+ store?: string;
202
+ reuse?: { days: number };
203
+ /** Globs of files that aren't code under test, relative to the project. */
204
+ ignore?: readonly string[];
205
+ /** Datasets whose data is elsewhere, or settings over a folder's, by name. */
206
+ datasets?: Record<string, DatasetEntry>;
207
+ /** Loops by name: everything that defines each. The local file may add to one, field by field. */
208
+ loops?: Record<string, LoopSpec>;
209
+ };
210
+
211
+ /**
212
+ * A loop: its dataset, its brief, and the files a try may edit, those `allow` matches and `deny`
213
+ * doesn't; `evals/`, `node_modules`, files git ignores and a key's text copied into code never.
214
+ */
215
+ export type LoopSpec = Omit<LoopEntry, "dataset" | "brief" | "edit"> & {
216
+ dataset: string;
217
+ /** Relative to `evals/`. */
218
+ brief: string;
219
+ /** Globs relative to the project, as git shows paths; `["**"]` allows anything. */
220
+ edit: { allow: readonly string[]; deny?: readonly string[] };
221
+ };
222
+
223
+ export type Lab = LabSpec & { readonly kind: typeof LAB_KIND };
224
+
225
+ /** `evals/awf-lab.config.ts`'s default export: the project's settings and datasets. */
226
+ export function defineLab(spec: LabSpec): Lab {
227
+ return { ...spec, kind: LAB_KIND };
228
+ }
@@ -0,0 +1,80 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { GRADE_KIND, type Previous } from "../format/records";
4
+ import { GRADE_FILES, TRIAL_ENV } from "../format/trial-env";
5
+ import type { GradeInput, Reads, TrialInput } from "./grader";
6
+ import type { Fact } from "./index";
7
+
8
+ /**
9
+ * What a grader workflow is given: a code grader's input and its earlier parts. `result`,
10
+ * `stages`, `scratch` and `kept` are there when it `reads: "trial"`.
11
+ */
12
+ export type GradeCase<R = unknown> = GradeInput &
13
+ Partial<TrialInput<R>> & {
14
+ /**
15
+ * This grader's parts from its newest grade of the trial, and the key digest they were graded
16
+ * on, when that grade did not error and has this grader's `{major}.{minor}`: judge only what
17
+ * the key's change touched. Absent otherwise.
18
+ */
19
+ previous?: Previous;
20
+ };
21
+
22
+ function readJson(file: string): unknown {
23
+ return JSON.parse(readFileSync(file, "utf8"));
24
+ }
25
+
26
+ /**
27
+ * Reads the grade folder the lab names in `AWF_LAB_GRADE`: a grader workflow calls it in its
28
+ * `run`, and returns a grade (`verdict`, `numbers`, `reasons`, `parts` or `notApplies`) as its
29
+ * result. Typed as `R`, the workflow's result.
30
+ */
31
+ export function gradeCase<R = unknown>(): GradeCase<R> {
32
+ const dir = process.env[TRIAL_ENV.grade];
33
+ if (!dir) {
34
+ throw new Error(
35
+ `gradeCase() reads the grade folder awf-lab names in ${TRIAL_ENV.grade}: run this grader through awf-lab run or score`,
36
+ );
37
+ }
38
+ const grade = readJson(join(dir, GRADE_FILES.grade)) as {
39
+ kind?: unknown;
40
+ case: string;
41
+ scratch: string | null;
42
+ params: Record<string, string>;
43
+ reads: Reads;
44
+ };
45
+ if (grade.kind !== GRADE_KIND) {
46
+ throw new Error(
47
+ `${join(dir, GRADE_FILES.grade)} is ${String(grade.kind)}, not ${GRADE_KIND}: this grader's @agentswf/lab is another version than the lab's`,
48
+ );
49
+ }
50
+ const caseDir = join(dir, GRADE_FILES.case);
51
+ const inputFile = join(caseDir, "input.json");
52
+ const keyDir = join(dir, GRADE_FILES.keyDir);
53
+ const previousFile = join(dir, GRADE_FILES.previous);
54
+ const { facts, stages } = readJson(join(dir, GRADE_FILES.facts)) as {
55
+ facts: Record<string, Fact>;
56
+ stages?: Record<string, unknown>;
57
+ };
58
+ const trial =
59
+ grade.reads === "trial"
60
+ ? {
61
+ result: readJson(join(dir, GRADE_FILES.result)) as R,
62
+ stages: stages ?? {},
63
+ scratch: grade.scratch,
64
+ kept: join(dir, GRADE_FILES.kept),
65
+ }
66
+ : {};
67
+ return {
68
+ case: {
69
+ name: grade.case,
70
+ dir: caseDir,
71
+ input: existsSync(inputFile) ? readJson(inputFile) : {},
72
+ key: readJson(join(dir, GRADE_FILES.key)) as GradeInput["case"]["key"],
73
+ ...(existsSync(keyDir) ? { keyDir } : {}),
74
+ },
75
+ facts,
76
+ params: grade.params,
77
+ ...trial,
78
+ ...(existsSync(previousFile) ? { previous: readJson(previousFile) as Previous } : {}),
79
+ };
80
+ }
@@ -0,0 +1,352 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { CAPTURE_KIND, type Capture } from "./capture";
4
+ import {
5
+ type CaseComparison,
6
+ COMPARISON_KIND,
7
+ type ComparisonCall,
8
+ type RoomCall,
9
+ } from "./compare";
10
+ import { factsProblem } from "./facts";
11
+ import {
12
+ GRADING_KIND,
13
+ type Grading,
14
+ isRequired,
15
+ LAB_KIND,
16
+ SENTENCES_KIND,
17
+ type SentencesGrader,
18
+ startDescribing,
19
+ TARGET_SPEC,
20
+ WORKFLOW_GRADER_KIND,
21
+ type WorkflowGrader,
22
+ } from "./files";
23
+ import { type CodeGrader, GRADER_KIND } from "./grader";
24
+
25
+ /**
26
+ * Runs in a Bun process of its own the lab starts in your checkout, so dataset code never loads
27
+ * into the lab's process. Reads a request file and writes its answer to the file it names:
28
+ *
29
+ * - `describe`: reads `target.ts`, `grading.ts` and `awf-lab.config.ts`, running nothing they
30
+ * define; answers each as JSON, or `{ error }` naming the first that doesn't load.
31
+ * - `facts`: runs `grading.ts`'s `facts` on each trial record; answers `{ facts: [...] }`, each
32
+ * `{ facts }` or `{ problem: { code, reason } }`, or `{ error }` when the file doesn't load.
33
+ * - `grade`: runs one code grader of `grading.ts`; answers `{ grade, version }` or
34
+ * `{ error, version? }`.
35
+ * - `capture`: runs the dataset's `capture.ts` on a real run; answers `{ cases }` or `{ error }`.
36
+ * - `compare`: runs `grading.ts`'s `compare` on two columns' trials; answers `{ decision }`,
37
+ * `{ none: true }` when it has none, or `{ error }`.
38
+ * - `room`: runs its `room` on the start's trials; answers `{ room }`, `{ none: true }` when it has
39
+ * none or can't tell, or `{ error }`.
40
+ */
41
+ type Request =
42
+ | {
43
+ mode: "describe";
44
+ files: { target?: string; grading?: string; lab?: string };
45
+ out: string;
46
+ }
47
+ | {
48
+ mode: "grade";
49
+ /** `grading.ts`. */
50
+ file: string;
51
+ name: string;
52
+ /** The case, facts and params; with `result`, `stages`, `scratch` and `kept`, for a grader that reads the trial. */
53
+ input: Record<string, unknown>;
54
+ out: string;
55
+ }
56
+ | {
57
+ mode: "facts";
58
+ /** `grading.ts`. */
59
+ file: string;
60
+ records: unknown[];
61
+ out: string;
62
+ }
63
+ | {
64
+ mode: "capture";
65
+ /** The dataset's `capture.ts`. */
66
+ file: string;
67
+ input: { run: unknown; root: string };
68
+ out: string;
69
+ }
70
+ | {
71
+ mode: "compare";
72
+ /** `grading.ts`. */
73
+ file: string;
74
+ input: ComparisonCall;
75
+ out: string;
76
+ }
77
+ | {
78
+ mode: "room";
79
+ /** `grading.ts`. */
80
+ file: string;
81
+ input: RoomCall;
82
+ out: string;
83
+ };
84
+
85
+ const request = JSON.parse(readFileSync(process.argv[2]!, "utf8")) as Request;
86
+ const answer = (value: object) => writeFileSync(request.out, JSON.stringify(value));
87
+
88
+ const isGrader = (value: unknown): value is CodeGrader =>
89
+ (value as CodeGrader | undefined)?.kind === GRADER_KIND &&
90
+ typeof (value as CodeGrader).grade === "function";
91
+
92
+ /** An error's message; a build's, each of its errors, which say where the file is wrong. */
93
+ const messageOf = (error: unknown): string => {
94
+ const inner = (error as { errors?: unknown })?.errors;
95
+ if (Array.isArray(inner) && inner.length > 0) return inner.map(messageOf).join("; ");
96
+ return error instanceof Error ? error.message : String(error);
97
+ };
98
+
99
+ /** `grading.ts`'s default export, or why it isn't one. */
100
+ async function gradingOf(file: string): Promise<Grading> {
101
+ const module = (await import(file)) as { default?: Partial<Grading> };
102
+ if (module.default?.kind !== GRADING_KIND) {
103
+ throw new Error(
104
+ `${file} has no grading as its default export: export default defineGrading({ … })`,
105
+ );
106
+ }
107
+ return module.default as Grading;
108
+ }
109
+
110
+ const noGrader = (file: string, name: string) =>
111
+ `${file} lists no code grader ${name}: graders: [defineGrader({ name: "${name}", grade })]`;
112
+
113
+ async function codeGrader(file: string, name: string): Promise<CodeGrader> {
114
+ const grader = ((await gradingOf(file)).graders ?? []).find(
115
+ (each) => isGrader(each) && each.name === name,
116
+ );
117
+ if (!grader) throw new Error(noGrader(file, name));
118
+ return grader as CodeGrader;
119
+ }
120
+
121
+ async function comparisonOf(file: string): Promise<Partial<CaseComparison> | undefined> {
122
+ return (await gradingOf(file)).compare as Partial<CaseComparison> | undefined;
123
+ }
124
+
125
+ /** A value of a file as JSON: a function as `{ $function: true }`, `required()` as `{ $required: true }`. */
126
+ function asJson(value: unknown, at: string): unknown {
127
+ if (typeof value === "function") return { $function: true };
128
+ if (isRequired(value)) return { $required: true };
129
+ if (Array.isArray(value)) return value.map((each, i) => asJson(each, `${at}[${i}]`));
130
+ if (typeof value === "object" && value !== null) {
131
+ if (
132
+ Object.getPrototypeOf(value) !== Object.prototype &&
133
+ Object.getPrototypeOf(value) !== null
134
+ ) {
135
+ throw new Error(`${at} is a ${value.constructor?.name ?? "class instance"}, not plain data`);
136
+ }
137
+ return Object.fromEntries(
138
+ Object.entries(value)
139
+ .filter(([, each]) => each !== undefined)
140
+ .map(([key, each]) => [key, asJson(each, `${at}.${key}`)]),
141
+ );
142
+ }
143
+ if (typeof value === "symbol" || typeof value === "bigint") {
144
+ throw new Error(`${at} is a ${typeof value}, not plain data`);
145
+ }
146
+ return value;
147
+ }
148
+
149
+ /** The file a grader workflow's `() => import("…")` names, resolved from `grading.ts`. */
150
+ function workflowFile(grader: WorkflowGrader, grading: string): string {
151
+ const spec = /^(?:async\s*)?\(\s*\)\s*=>\s*import\(\s*(["'`])([^"'`]+)\1\s*\)\s*;?\s*$/.exec(
152
+ grader.load.toString().trim(),
153
+ )?.[2];
154
+ if (!spec) {
155
+ throw new Error(
156
+ `grader ${grader.name}: workflowGrader takes its workflow as () => import("./graders/x"), a literal path the lab reads to find the file`,
157
+ );
158
+ }
159
+ try {
160
+ return Bun.resolveSync(spec, dirname(grading));
161
+ } catch (error) {
162
+ throw new Error(`grader ${grader.name}: ${spec} does not resolve: ${messageOf(error)}`);
163
+ }
164
+ }
165
+
166
+ /** `grading.ts` as JSON: each grader as what made it. */
167
+ async function describeGrading(file: string): Promise<unknown> {
168
+ const grading = await gradingOf(file);
169
+ const { kind: _, graders, compare, ...rest } = grading as Grading & Record<string, unknown>;
170
+ const described: Record<string, unknown> = asJson(rest, "grading") as Record<string, unknown>;
171
+ if (graders !== undefined) {
172
+ if (!Array.isArray(graders)) throw new Error(`${file}: graders is a list`);
173
+ described.graders = graders.map((grader: unknown, i: number) => {
174
+ if (isGrader(grader)) {
175
+ return {
176
+ grader: "code",
177
+ name: grader.name,
178
+ version: grader.version,
179
+ reads: grader.reads,
180
+ manual: grader.manual === true,
181
+ };
182
+ }
183
+ const kind = (grader as { kind?: unknown } | null)?.kind;
184
+ if (kind === WORKFLOW_GRADER_KIND) {
185
+ const each = grader as WorkflowGrader;
186
+ return {
187
+ grader: "workflow",
188
+ name: each.name,
189
+ version: each.version,
190
+ file: workflowFile(each, file),
191
+ reads: each.reads,
192
+ manual: each.manual,
193
+ ...(each.timeout !== undefined ? { timeout: each.timeout } : {}),
194
+ };
195
+ }
196
+ if (kind === SENTENCES_KIND) {
197
+ const each = grader as SentencesGrader;
198
+ return {
199
+ grader: "sentences",
200
+ name: each.name,
201
+ version: each.version,
202
+ agent: each.agent,
203
+ ...(each.voters !== undefined ? { voters: each.voters } : {}),
204
+ manual: each.manual === true,
205
+ };
206
+ }
207
+ throw new Error(
208
+ `${file}: graders[${i}] is no grader: give defineGrader({ … }), workflowGrader(() => import("…"), { … }) or sentences({ … })`,
209
+ );
210
+ });
211
+ }
212
+ if (compare !== undefined) {
213
+ const comparison = compare as Partial<CaseComparison>;
214
+ if (comparison.kind !== COMPARISON_KIND || typeof comparison.compare !== "function") {
215
+ throw new Error(
216
+ `${file}: compare is not a comparison: compare: better.paired({ primary: "passed" })`,
217
+ );
218
+ }
219
+ described.compare = {};
220
+ }
221
+ return described;
222
+ }
223
+
224
+ async function describeTarget(file: string): Promise<unknown> {
225
+ const module = (await import(file)) as { default?: Record<symbol, unknown> };
226
+ const spec = module.default?.[TARGET_SPEC];
227
+ if (typeof spec !== "object" || spec === null) {
228
+ throw new Error(
229
+ `${file} has no target as its default export: export default defineTarget({ … })`,
230
+ );
231
+ }
232
+ const { version, ...rest } = spec as { version?: unknown };
233
+ // A version function is the one thing of `target.ts` the lab runs: once, in this checkout.
234
+ let declared: unknown = version;
235
+ if (typeof version === "function") {
236
+ try {
237
+ declared = await version();
238
+ } catch (error) {
239
+ throw new Error(`target: version() threw: ${messageOf(error)}`);
240
+ }
241
+ }
242
+ return {
243
+ ...(asJson(rest, "target") as object),
244
+ ...(declared !== undefined ? { version: declared } : {}),
245
+ };
246
+ }
247
+
248
+ async function describeLab(file: string): Promise<unknown> {
249
+ const module = (await import(file)) as { default?: { kind?: unknown } };
250
+ if (module.default?.kind !== LAB_KIND) {
251
+ throw new Error(`${file} has no lab as its default export: export default defineLab({ … })`);
252
+ }
253
+ const { kind: _, ...spec } = module.default as Record<string, unknown>;
254
+ return asJson(spec, "lab");
255
+ }
256
+
257
+ if (request.mode === "describe") {
258
+ startDescribing();
259
+ const answered: Record<string, unknown> = {};
260
+ let at = "";
261
+ try {
262
+ const { target, grading, lab } = request.files;
263
+ if (lab) {
264
+ at = lab;
265
+ answered.lab = await describeLab(lab);
266
+ }
267
+ if (target) {
268
+ at = target;
269
+ answered.target = await describeTarget(target);
270
+ }
271
+ if (grading) {
272
+ at = grading;
273
+ answered.grading = await describeGrading(grading);
274
+ }
275
+ answer(answered);
276
+ } catch (error) {
277
+ const message = messageOf(error);
278
+ answer({ error: message.startsWith(at) ? message : `${at}: ${message}` });
279
+ }
280
+ } else if (request.mode === "compare") {
281
+ try {
282
+ const comparison = await comparisonOf(request.file);
283
+ if (comparison === undefined) answer({ none: true });
284
+ else if (comparison.kind !== COMPARISON_KIND || typeof comparison.compare !== "function") {
285
+ answer({
286
+ error: `${request.file}'s compare is not a comparison: compare: better.paired({ primary: "passed" })`,
287
+ });
288
+ } else {
289
+ answer({ decision: comparison.compare(request.input) });
290
+ }
291
+ } catch (error) {
292
+ answer({ error: error instanceof Error ? error.message : String(error) });
293
+ }
294
+ } else if (request.mode === "room") {
295
+ try {
296
+ const comparison = await comparisonOf(request.file);
297
+ const room =
298
+ comparison?.kind === COMPARISON_KIND && typeof comparison.room === "function"
299
+ ? comparison.room(request.input)
300
+ : undefined;
301
+ answer(room ? { room } : { none: true });
302
+ } catch (error) {
303
+ answer({ error: error instanceof Error ? error.message : String(error) });
304
+ }
305
+ } else if (request.mode === "facts") {
306
+ try {
307
+ const { facts } = await gradingOf(request.file);
308
+ if (typeof facts !== "function") throw new Error(`${request.file} has no facts function`);
309
+ const answers: unknown[] = [];
310
+ for (const record of request.records) {
311
+ try {
312
+ const made = await facts(record as never);
313
+ const problem = factsProblem(made);
314
+ answers.push(problem ? { problem } : { facts: made });
315
+ } catch (error) {
316
+ answers.push({
317
+ problem: { code: "facts-missing", reason: `facts threw: ${messageOf(error)}` },
318
+ });
319
+ }
320
+ }
321
+ answer({ facts: answers });
322
+ } catch (error) {
323
+ answer({ error: messageOf(error) });
324
+ }
325
+ } else if (request.mode === "capture") {
326
+ try {
327
+ const module = (await import(request.file)) as { default?: Partial<Capture> };
328
+ const capture = module.default;
329
+ if (capture?.kind !== CAPTURE_KIND || typeof capture.capture !== "function") {
330
+ answer({
331
+ error: `${request.file} has no capture as its default export: export default defineCapture(({ run, root }) => [...])`,
332
+ });
333
+ } else {
334
+ answer({ cases: (await capture.capture(request.input as never)) ?? null });
335
+ }
336
+ } catch (error) {
337
+ answer({ error: error instanceof Error ? error.message : String(error) });
338
+ }
339
+ } else {
340
+ let version: string | undefined;
341
+ try {
342
+ const grader = await codeGrader(request.file, request.name);
343
+ version = grader.version;
344
+ // A grader of the facts alone is given nothing of the record but them.
345
+ const { result: _, stages: __, scratch: ___, kept: ____, ...facts } = request.input;
346
+ const input = grader.reads === "trial" ? request.input : facts;
347
+ answer({ grade: (await grader.grade(input as never)) ?? null, version });
348
+ } catch (error) {
349
+ answer({ error: messageOf(error), version });
350
+ }
351
+ }
352
+ process.exit(0);