@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,113 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "awf-lab loop's try.json",
4
+ "type": "object",
5
+ "required": ["kind", "n", "at", "parent", "outcome", "why", "changed", "estimate"],
6
+ "properties": {
7
+ "kind": {
8
+ "type": "string",
9
+ "const": "awf.lab-try/1"
10
+ },
11
+ "n": {
12
+ "type": "integer",
13
+ "minimum": 1
14
+ },
15
+ "at": {
16
+ "type": "string",
17
+ "minLength": 1
18
+ },
19
+ "parent": {
20
+ "type": "integer",
21
+ "minimum": 0
22
+ },
23
+ "outcome": {
24
+ "anyOf": [
25
+ {
26
+ "type": "string",
27
+ "const": "kept"
28
+ },
29
+ {
30
+ "type": "string",
31
+ "const": "discarded"
32
+ },
33
+ {
34
+ "type": "string",
35
+ "const": "refused"
36
+ },
37
+ {
38
+ "type": "string",
39
+ "const": "failed"
40
+ }
41
+ ]
42
+ },
43
+ "why": {
44
+ "type": "string",
45
+ "minLength": 1
46
+ },
47
+ "hypothesis": {
48
+ "type": "object",
49
+ "required": ["change", "hypothesis", "predicted", "mechanism"],
50
+ "properties": {
51
+ "change": {
52
+ "type": "string",
53
+ "minLength": 1,
54
+ "description": "What changed, in a sentence."
55
+ },
56
+ "hypothesis": {
57
+ "type": "string",
58
+ "minLength": 1,
59
+ "description": "Why it should do better."
60
+ },
61
+ "predicted": {
62
+ "type": "string",
63
+ "minLength": 1,
64
+ "description": "The effect expected on the comparison's numbers, and its cost."
65
+ },
66
+ "mechanism": {
67
+ "type": "string",
68
+ "minLength": 1,
69
+ "description": "What the trials must show if the hypothesis holds."
70
+ }
71
+ },
72
+ "additionalProperties": false
73
+ },
74
+ "changed": {
75
+ "type": "array",
76
+ "items": {
77
+ "type": "string",
78
+ "minLength": 1
79
+ }
80
+ },
81
+ "labRun": {
82
+ "type": "string",
83
+ "minLength": 1
84
+ },
85
+ "decision": {
86
+ "anyOf": [
87
+ {
88
+ "type": "string",
89
+ "minLength": 1
90
+ },
91
+ {
92
+ "type": "null"
93
+ }
94
+ ]
95
+ },
96
+ "estimate": {
97
+ "type": "object",
98
+ "required": ["proposer", "trials"],
99
+ "properties": {
100
+ "proposer": {
101
+ "type": "number",
102
+ "minimum": 0
103
+ },
104
+ "trials": {
105
+ "type": "number",
106
+ "minimum": 0
107
+ }
108
+ },
109
+ "additionalProperties": false
110
+ }
111
+ },
112
+ "additionalProperties": false
113
+ }
@@ -0,0 +1,155 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "awf-lab's evals/awf-lab.local.json",
4
+ "type": "object",
5
+ "properties": {
6
+ "$schema": {
7
+ "type": "string"
8
+ },
9
+ "store": {
10
+ "type": "string",
11
+ "minLength": 1,
12
+ "description": "Where every run, trial, label and loop of the project is kept, in place of ~/.awf/lab/{main checkout's folder}-{first commit}; never inside the repository."
13
+ },
14
+ "concurrency": {
15
+ "type": "integer",
16
+ "minimum": 1,
17
+ "description": "How many trials of a run may run at once, across its cases and columns; 1 when absent."
18
+ },
19
+ "allowance": {
20
+ "type": "integer",
21
+ "minimum": 1,
22
+ "maximum": 100,
23
+ "description": "How full the plan's usage window may get, in percent, before a loop pauses; 90 when absent."
24
+ },
25
+ "datasets": {
26
+ "type": "object",
27
+ "patternProperties": {
28
+ "^[A-Za-z0-9][A-Za-z0-9._-]*$": {
29
+ "type": "object",
30
+ "properties": {
31
+ "eval": {
32
+ "type": "string",
33
+ "minLength": 1,
34
+ "description": "The eval folder, holding target.ts and grading.ts, relative to evals/; the folder of the dataset's name when absent."
35
+ },
36
+ "data": {
37
+ "type": "string",
38
+ "minLength": 1,
39
+ "description": "The data folder, holding cases/ and optionally shared/, relative to evals/; the folder of the dataset's name when absent."
40
+ },
41
+ "params": {
42
+ "type": "object",
43
+ "patternProperties": {
44
+ "^[A-Za-z][A-Za-z0-9_-]*$": {
45
+ "type": "string",
46
+ "minLength": 1
47
+ }
48
+ },
49
+ "description": "Values over target.ts's defaults, each a parameter it declares."
50
+ },
51
+ "records": {
52
+ "type": "string",
53
+ "minLength": 1,
54
+ "description": "A folder, usually in the data's repository, holding a copy of the dataset's records under {records}/{the project's first commit}/, so another clone reuses its trials."
55
+ }
56
+ },
57
+ "additionalProperties": false
58
+ }
59
+ }
60
+ },
61
+ "loops": {
62
+ "type": "object",
63
+ "patternProperties": {
64
+ "^[A-Za-z0-9][A-Za-z0-9_-]*$": {
65
+ "type": "object",
66
+ "properties": {
67
+ "dataset": {
68
+ "type": "string",
69
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$",
70
+ "description": "The dataset the loop tunes on."
71
+ },
72
+ "brief": {
73
+ "type": "string",
74
+ "minLength": 1,
75
+ "description": "Plain prose for the proposer, relative to evals/: what to improve, and what is known about the problem."
76
+ },
77
+ "edit": {
78
+ "type": "object",
79
+ "properties": {
80
+ "allow": {
81
+ "type": "array",
82
+ "items": {
83
+ "type": "string",
84
+ "minLength": 1
85
+ },
86
+ "minItems": 1,
87
+ "uniqueItems": true,
88
+ "description": "Globs of the files a try may edit, relative to the project, as git shows paths; [\"**\"] for anything."
89
+ },
90
+ "deny": {
91
+ "type": "array",
92
+ "items": {
93
+ "type": "string",
94
+ "minLength": 1
95
+ },
96
+ "uniqueItems": true,
97
+ "description": "Globs of files a try may not edit though allow matches them, relative to the project, as git shows paths."
98
+ }
99
+ },
100
+ "additionalProperties": false,
101
+ "description": "Which files a try may edit: those allow matches and deny doesn't. evals/, node_modules, files git ignores and a key's text copied into code are always denied."
102
+ },
103
+ "proposer": {
104
+ "type": "string",
105
+ "pattern": "^[^/\\s]+/[^/\\s]+$",
106
+ "description": "{harness}/{model} of the loop's proposer; claude/claude-sonnet-5-5 when absent."
107
+ },
108
+ "trials": {
109
+ "type": "integer",
110
+ "minimum": 1,
111
+ "description": "Trials per case in each try's run; 1 when absent."
112
+ },
113
+ "params": {
114
+ "type": "object",
115
+ "patternProperties": {
116
+ "^[A-Za-z][A-Za-z0-9_-]*$": {
117
+ "type": "string",
118
+ "minLength": 1
119
+ }
120
+ },
121
+ "description": "Values over target.ts's and the dataset entry's, for every trial of the loop."
122
+ },
123
+ "cases": {
124
+ "type": "array",
125
+ "items": {
126
+ "type": "string",
127
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"
128
+ },
129
+ "minItems": 1,
130
+ "uniqueItems": true,
131
+ "description": "Tune on these cases only; every case the dataset doesn't hold out when absent."
132
+ },
133
+ "tags": {
134
+ "type": "array",
135
+ "items": {
136
+ "type": "string",
137
+ "pattern": "^[a-z0-9][a-z0-9-]*$"
138
+ },
139
+ "minItems": 1,
140
+ "uniqueItems": true,
141
+ "description": "Tune only on the cases with one of these tags."
142
+ },
143
+ "spread": {
144
+ "type": "boolean",
145
+ "description": "Whether the start runs twice on the tuning cases before the first try, to show its noise; true when absent."
146
+ }
147
+ },
148
+ "additionalProperties": false
149
+ }
150
+ }
151
+ }
152
+ },
153
+ "additionalProperties": false,
154
+ "description": "This machine's awf-lab settings, datasets and loops included; git-ignored."
155
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ import { runCases } from "./lab/cli";
3
+ import { envFolder, loadProjectEnv } from "./lab/project-env";
4
+
5
+ if (import.meta.main) {
6
+ const argv = Bun.argv.slice(2);
7
+ loadProjectEnv(envFolder(process.cwd(), argv));
8
+ process.exit(await runCases(argv));
9
+ }
@@ -0,0 +1,48 @@
1
+ import type { Fact } from "./index";
2
+
3
+ /** What a dataset's `capture.ts` default export carries, checked by the helper that loads it. */
4
+ export const CAPTURE_KIND = "awf.lab-capture/0";
5
+
6
+ /** A real run of the workflow, as `capture` is given it: its record, read from its folder. */
7
+ export type CapturedRun = {
8
+ id: string;
9
+ /** The workflow's `meta.name`. */
10
+ workflow: string;
11
+ /** Its arguments, as given. */
12
+ argv: string[];
13
+ /** The args a program started it with, as JSON; absent for a run started from argv. */
14
+ args?: unknown;
15
+ /** How its last attempt ended: `completed`, `failed`, …, or `running` while it hasn't. */
16
+ outcome: string;
17
+ /** Its value when it completed; null otherwise. */
18
+ result: unknown;
19
+ /** The run's folder: its logs and records. */
20
+ dir: string;
21
+ };
22
+
23
+ /** One case a run gives: its folder's name, its input, and what it did. */
24
+ export type CapturedCase = {
25
+ name: string;
26
+ /** Written as `input/input.json`, which `trial.input` reads. */
27
+ input?: unknown;
28
+ /** Paths inside the case's `input/`, each to its contents. */
29
+ files?: Record<string, string>;
30
+ /** What `facts` would have returned, read off this case's share of the result. */
31
+ facts?: Record<string, Fact>;
32
+ };
33
+
34
+ export type Capture = {
35
+ readonly kind: typeof CAPTURE_KIND;
36
+ capture(input: { run: CapturedRun; root: string }): CapturedCase[] | Promise<CapturedCase[]>;
37
+ };
38
+
39
+ /**
40
+ * The default export of a dataset's `capture.ts`: turns a real run of the workflow into cases,
41
+ * one per thing it handled (a mail run that read five emails gives five). `awf-lab capture {run}`
42
+ * calls it in your checkout and writes each case with a draft key.
43
+ */
44
+ export function defineCapture(
45
+ capture: (input: { run: CapturedRun; root: string }) => CapturedCase[] | Promise<CapturedCase[]>,
46
+ ): Capture {
47
+ return { kind: CAPTURE_KIND, capture };
48
+ }
@@ -0,0 +1,201 @@
1
+ import {
2
+ type CaseScore,
3
+ type Decision,
4
+ type MetricSpec,
5
+ type PairedOptions,
6
+ pairedComparison,
7
+ } from "../shared/compare";
8
+
9
+ // What "better" means for a dataset: `compare` in its grading.ts. The lab gives
10
+ // it every trial of the reference column and of one other, and it says whether the other is
11
+ // better, worse, a tie or undecided, with a reason and whether more trials could change that.
12
+
13
+ /** What a comparison export carries, checked by the helper that loads `grading.ts`. */
14
+ export const COMPARISON_KIND = "awf.lab-comparison/0";
15
+
16
+ /** One trial, as a comparison sees it. */
17
+ export type ComparedTrial = {
18
+ case: string;
19
+ trial: number;
20
+ /** The lab's verdict on it: true passed, false failed, null neither (undecided, numbers only). */
21
+ passed: boolean | null;
22
+ /** The workflow erred: its body failed, timed out or stopped. Its numbers are what `onFailure` says. */
23
+ workflowFailed: boolean;
24
+ /** Each deciding grader's numbers, as `{grader}.{number}`: a count as its fraction, or a value. */
25
+ numbers: Readonly<Record<string, number>>;
26
+ /** The workflow's estimated cost, in dollars, when it was priced. */
27
+ cost: number | null;
28
+ /** The trial's time, in seconds. */
29
+ seconds: number;
30
+ };
31
+
32
+ export type ComparisonCall = {
33
+ reference: readonly ComparedTrial[];
34
+ column: readonly ComparedTrial[];
35
+ /** The cases the run asked for: a sequential rule's last look. */
36
+ planned: number;
37
+ };
38
+
39
+ /** The start's trials, before any try: what `room` reads. */
40
+ export type RoomCall = {
41
+ reference: readonly ComparedTrial[];
42
+ /** The cases a try would run. */
43
+ planned: number;
44
+ };
45
+
46
+ /**
47
+ * Whether any column could be called better than the reference on these cases: how many it could
48
+ * still win, and how many it must. A loop stops before its first try when `canWin < needed`.
49
+ */
50
+ export type Room = { canWin: number; needed: number; what: string };
51
+
52
+ export type CaseComparison = {
53
+ readonly kind: typeof COMPARISON_KIND;
54
+ compare(call: ComparisonCall): Decision;
55
+ /** Optional: undefined, or no `room`, when the rule can't tell from the start alone. */
56
+ room?(call: RoomCall): Room | undefined;
57
+ };
58
+
59
+ export type { Decision };
60
+
61
+ /** A comparison of your own: `compare` gets both columns' trials and returns the verdict. */
62
+ export function defineComparison(options: {
63
+ compare(call: ComparisonCall): Decision;
64
+ /** How many cases a column could still win against the start, and how many it must. */
65
+ room?(call: RoomCall): Room | undefined;
66
+ }): CaseComparison {
67
+ return {
68
+ kind: COMPARISON_KIND,
69
+ compare: options.compare,
70
+ ...(options.room ? { room: options.room } : {}),
71
+ };
72
+ }
73
+
74
+ /** How a metric is read: which way is better, and what a trial whose workflow failed scores. */
75
+ export type MetricOptions = {
76
+ direction?: "higher" | "lower";
77
+ /** A failed workflow's value, such as 0 recall; "missing" leaves the trial out. */
78
+ onFailure?: number | "missing";
79
+ };
80
+
81
+ /**
82
+ * A metric's name: `passed` (1 or 0), `cost`, `seconds`, or a grader's number,
83
+ * `{grader}.{number}`. `cost` and `seconds` are better lower; the rest higher, unless told.
84
+ */
85
+ export type MetricName = string;
86
+
87
+ const LOWER = new Set(["cost", "seconds"]);
88
+
89
+ function metricOf(trial: ComparedTrial, name: MetricName): number | null {
90
+ if (name === "passed") return trial.passed === null ? null : trial.passed ? 1 : 0;
91
+ if (name === "cost") return trial.cost;
92
+ if (name === "seconds") return trial.seconds;
93
+ return trial.numbers[name] ?? null;
94
+ }
95
+
96
+ function scoresOf(trials: readonly ComparedTrial[], names: readonly MetricName[]): CaseScore[] {
97
+ return trials.map((t) => ({
98
+ case: t.case,
99
+ trial: t.trial,
100
+ // A failed workflow's `passed` is a result, 0: only its other numbers go by `onFailure`.
101
+ outcome: t.workflowFailed ? "workflow-failed" : "scored",
102
+ metrics: Object.fromEntries(names.map((name) => [name, metricOf(t, name)])),
103
+ }));
104
+ }
105
+
106
+ function specOf(name: MetricName, options: MetricOptions | undefined): MetricSpec {
107
+ return {
108
+ name,
109
+ direction: options?.direction ?? (LOWER.has(name) ? "lower" : "higher"),
110
+ onFailure: name === "passed" ? 0 : (options?.onFailure ?? "missing"),
111
+ };
112
+ }
113
+
114
+ type Paired = Omit<PairedOptions, "primary" | "guards" | "tiebreak"> & {
115
+ /** The metric that decides. */
116
+ primary: MetricName;
117
+ /** Metrics that may not get worse by more than `margin`. */
118
+ guards?: readonly { metric: MetricName; margin: number }[];
119
+ /** Metrics that decide, in order, when the primary is shown equal. */
120
+ tiebreak?: readonly { metric: MetricName; margin: number }[];
121
+ /** How each metric named is read, by name. */
122
+ metrics?: Readonly<Record<MetricName, MetricOptions>>;
123
+ };
124
+
125
+ export const better = {
126
+ /**
127
+ * A sequential paired rule: per-case differences on the same cases, "better"
128
+ * claimed only past an O'Brien–Fleming bound at the planned looks, so it can stop as soon as it
129
+ * can tell; guards that may not get worse; tie-breakers.
130
+ */
131
+ paired(options: Paired): CaseComparison {
132
+ const { metrics, ...rule } = options;
133
+ const names = [
134
+ ...new Set([
135
+ rule.primary,
136
+ ...(rule.guards ?? []).map((g) => g.metric),
137
+ ...(rule.tiebreak ?? []).map((t) => t.metric),
138
+ ]),
139
+ ];
140
+ const specs = names.map((name) => specOf(name, metrics?.[name]));
141
+ const comparison = pairedComparison(rule);
142
+ const needed = rule.minWon ?? 6;
143
+ return defineComparison({
144
+ // Only on `passed` can the start alone say a case can't be won: one it passed in every trial.
145
+ // A number's best is the grader's to know, so another primary says nothing.
146
+ room:
147
+ rule.primary === "passed"
148
+ ? ({ reference }) => {
149
+ const cases = new Set(reference.map((t) => t.case));
150
+ const canWin = [...cases].filter((name) =>
151
+ reference.some((t) => t.case === name && t.passed !== true),
152
+ ).length;
153
+ return {
154
+ canWin,
155
+ needed,
156
+ what: `${canWin} of ${cases.size} cases the start didn't pass in every trial; better needs ${needed} won (minWon)`,
157
+ };
158
+ }
159
+ : undefined,
160
+ compare: ({ reference, column, planned }) =>
161
+ comparison.compare({
162
+ reference: scoresOf(reference, names),
163
+ column: scoresOf(column, names),
164
+ metrics: specs,
165
+ planned,
166
+ }),
167
+ });
168
+ },
169
+
170
+ /**
171
+ * Better on the mean of one number of your own per trial, paired by case; `onFailure` is what a
172
+ * trial whose workflow failed scores, `missing` leaving it out.
173
+ */
174
+ mean(
175
+ value: (trial: ComparedTrial) => number | null,
176
+ options: MetricOptions = {},
177
+ ): CaseComparison {
178
+ const spec: MetricSpec = {
179
+ name: "value",
180
+ direction: options.direction ?? "higher",
181
+ onFailure: options.onFailure ?? "missing",
182
+ };
183
+ const comparison = pairedComparison({ primary: "value" });
184
+ const scores = (trials: readonly ComparedTrial[]): CaseScore[] =>
185
+ trials.map((t) => ({
186
+ case: t.case,
187
+ trial: t.trial,
188
+ outcome: t.workflowFailed ? "workflow-failed" : "scored",
189
+ metrics: { value: t.workflowFailed ? null : value(t) },
190
+ }));
191
+ return defineComparison({
192
+ compare: ({ reference, column, planned }) =>
193
+ comparison.compare({
194
+ reference: scores(reference),
195
+ column: scores(column),
196
+ metrics: [spec],
197
+ planned,
198
+ }),
199
+ });
200
+ },
201
+ };
@@ -0,0 +1,51 @@
1
+ import type { DatasetError } from "../format/trial-file";
2
+
3
+ /** Why what `grading.ts`'s `facts` returned is no facts: the dataset's to fix, by its code. */
4
+ export type FactsProblem = {
5
+ code: Extract<DatasetError, "facts-missing" | "fact-type">;
6
+ reason: string;
7
+ };
8
+
9
+ /**
10
+ * What is wrong with what `facts` returned, if anything: no object, a fact `undefined`, a name the
11
+ * lab's run facts take, or a value that isn't flat.
12
+ */
13
+ export function factsProblem(facts: unknown): FactsProblem | undefined {
14
+ if (typeof facts !== "object" || facts === null || Array.isArray(facts)) {
15
+ return { code: "fact-type", reason: "facts returned no object of facts" };
16
+ }
17
+ const entries = Object.entries(facts);
18
+ const missing = entries.filter(([, value]) => value === undefined).map(([name]) => name);
19
+ if (missing.length > 0) {
20
+ return {
21
+ code: "facts-missing",
22
+ reason: `fact ${missing.join(", ")} is undefined: return null where the workflow gave nothing`,
23
+ };
24
+ }
25
+ const reserved = entries.find(([name]) => name.startsWith("_"));
26
+ if (reserved) {
27
+ return {
28
+ code: "fact-type",
29
+ reason: `fact ${reserved[0]} starts with _, which names a run fact: the lab reads those from the run's record, so give the fact another name`,
30
+ };
31
+ }
32
+ for (const [name, value] of entries) {
33
+ const flat =
34
+ value === null ||
35
+ typeof value === "string" ||
36
+ typeof value === "boolean" ||
37
+ (typeof value === "number" && Number.isFinite(value));
38
+ if (!flat) {
39
+ const kind = Array.isArray(value)
40
+ ? "an array"
41
+ : value instanceof Date
42
+ ? "a Date"
43
+ : typeof value;
44
+ return {
45
+ code: "fact-type",
46
+ reason: `fact ${name} is ${kind}: a fact is a string, a number, a boolean or null`,
47
+ };
48
+ }
49
+ }
50
+ return undefined;
51
+ }
@@ -0,0 +1,57 @@
1
+ import { TRIAL_ENV } from "../format/trial-env";
2
+ import { hostListed, routeFor } from "./routes";
3
+ import { type HttpRequest, refuse, shared, trialSettings } from "./state";
4
+
5
+ // The preload a trial's process starts with (`bun --preload`), so the lab's `fetch` is in place
6
+ // before the engine, `env.ts` or anything they import keeps a reference to `globalThis.fetch`.
7
+
8
+ /** Replaces `globalThis.fetch` with the lab's, once. */
9
+ export function installFetch(codeHosts: readonly string[] = []): void {
10
+ const state = shared();
11
+ if (state.realFetch) return;
12
+ const real = globalThis.fetch;
13
+ state.realFetch = real;
14
+
15
+ const labFetch = async (
16
+ input: string | URL | Request,
17
+ init?: RequestInit & { unix?: string },
18
+ ): Promise<Response> => {
19
+ const unix = init?.unix;
20
+ const request = new Request(input, init);
21
+ const seen: HttpRequest = { method: request.method, url: request.url };
22
+ if (unix !== undefined) seen.unix = unix;
23
+ if (request.body) seen.body = await request.clone().text();
24
+ state.requests.push(seen);
25
+
26
+ const url = new URL(request.url);
27
+ // The built request goes on, its body whole: `input` and `init` again would read a stream twice.
28
+ const onward = () => real(request, unix !== undefined ? ({ unix } as RequestInit) : undefined);
29
+ // A socket names no host, nor does a scheme other than HTTP's: they go to the real `fetch`.
30
+ if (unix !== undefined || (url.protocol !== "http:" && url.protocol !== "https:")) {
31
+ return onward();
32
+ }
33
+ const found = routeFor(state.routes, request.method, url);
34
+ if (found === "missing") {
35
+ throw refuse(
36
+ `${request.method} ${request.url}`,
37
+ "host",
38
+ `no route for ${request.method} ${request.url} in this case: add one to trial.mockFetch`,
39
+ );
40
+ }
41
+ if (found === "unrouted") {
42
+ if (hostListed(codeHosts, url.hostname) || hostListed(state.allowed, url.hostname)) {
43
+ return onward();
44
+ }
45
+ throw refuse(
46
+ `${request.method} ${request.url}`,
47
+ "host",
48
+ `reached ${url.hostname}: add a route, list it in target.ts's sandbox.network.code, or trial.mockFetch.allow it`,
49
+ );
50
+ }
51
+ found.route.calls += 1;
52
+ return found.route.handler(request, { params: found.params });
53
+ };
54
+ globalThis.fetch = Object.assign(labFetch, { preconnect: real.preconnect }) as typeof fetch;
55
+ }
56
+
57
+ if (process.env[TRIAL_ENV.case]) installFetch(trialSettings()?.codeHosts ?? []);