@agentswf/lab 0.0.0-stage → 0.3.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/case-check.schema.json +64 -0
  5. package/schema/case-config.schema.json +187 -0
  6. package/schema/case-final.schema.json +48 -0
  7. package/schema/case-good-record.schema.json +70 -0
  8. package/schema/case-grade.schema.json +49 -0
  9. package/schema/case-key.schema.json +117 -0
  10. package/schema/case-label.schema.json +32 -0
  11. package/schema/case-loop-report.schema.json +210 -0
  12. package/schema/case-loop.schema.json +141 -0
  13. package/schema/case-plan.schema.json +117 -0
  14. package/schema/case-previous.schema.json +70 -0
  15. package/schema/case-proposal.schema.json +52 -0
  16. package/schema/case-report.schema.json +892 -0
  17. package/schema/case-run.schema.json +253 -0
  18. package/schema/case-runs.schema.json +125 -0
  19. package/schema/case-score.schema.json +319 -0
  20. package/schema/case-spread.schema.json +110 -0
  21. package/schema/case-trial.schema.json +543 -0
  22. package/schema/case-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 +128 -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 +182 -0
  39. package/src/format/key.ts +144 -0
  40. package/src/format/loop.ts +178 -0
  41. package/src/format/output.ts +481 -0
  42. package/src/format/records.ts +440 -0
  43. package/src/format/schema-files.ts +64 -0
  44. package/src/format/settings.ts +552 -0
  45. package/src/format/trial-env.ts +64 -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 +38 -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 +60 -0
  54. package/src/help/runs.txt +10 -0
  55. package/src/help/score.txt +27 -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 +249 -0
  61. package/src/lab/capture-command.ts +298 -0
  62. package/src/lab/capture.ts +234 -0
  63. package/src/lab/check-command.ts +187 -0
  64. package/src/lab/cli.ts +324 -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 +278 -0
  70. package/src/lab/criteria.ts +69 -0
  71. package/src/lab/dataset.ts +356 -0
  72. package/src/lab/eval-files.ts +185 -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 +153 -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 +226 -0
  82. package/src/lab/labels.ts +206 -0
  83. package/src/lab/loop-code.ts +255 -0
  84. package/src/lab/loop-command.ts +770 -0
  85. package/src/lab/loop-records.ts +144 -0
  86. package/src/lab/loop.ts +859 -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 +150 -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 +156 -0
  96. package/src/lab/report.ts +838 -0
  97. package/src/lab/reuse.ts +126 -0
  98. package/src/lab/run-command.ts +853 -0
  99. package/src/lab/run-logs.ts +89 -0
  100. package/src/lab/run-report.ts +259 -0
  101. package/src/lab/runs-command.ts +163 -0
  102. package/src/lab/runs.ts +172 -0
  103. package/src/lab/scaffold.ts +91 -0
  104. package/src/lab/score-command.ts +189 -0
  105. package/src/lab/score.ts +396 -0
  106. package/src/lab/store.ts +383 -0
  107. package/src/lab/text.ts +29 -0
  108. package/src/lab/trial-settings.ts +100 -0
  109. package/src/lab/trial-stub.txt +18 -0
  110. package/src/lab/trial.ts +443 -0
  111. package/src/lab/usage.ts +273 -0
  112. package/src/lab/verdict.ts +161 -0
  113. package/src/lab/workflow-graders.ts +161 -0
  114. package/src/lab/workspace.ts +489 -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,770 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { HypothesisSchema } from "../format/loop";
4
+ import {
5
+ type CasePlan,
6
+ LOOP_REPORT_KIND,
7
+ type LoopReport,
8
+ LoopReportSchema,
9
+ PLAN_KIND,
10
+ } from "../format/output";
11
+ import { waitingOnAllowance } from "../shared/allowance";
12
+ import { checkSchema, describeProblems } from "../shared/validate";
13
+ import { boxSpec, heldOutOf, hiddenOf, writeBoxSpec } from "./box";
14
+ import { checkGoodRecords } from "./check-command";
15
+ import {
16
+ type Context,
17
+ countedGraders,
18
+ envOf,
19
+ externalsOf,
20
+ loadDataset,
21
+ type Options,
22
+ printPlan,
23
+ tmpOf,
24
+ workspaceOf,
25
+ } from "./command-context";
26
+ import { roomOf } from "./compare";
27
+ import { type CaseInfo, comparingFile, type DatasetInfo, fileDigest } from "./dataset";
28
+ import { gitState } from "./git";
29
+ import { checkTrialScript, inspectFolder } from "./inspect";
30
+ import {
31
+ changedDefinition,
32
+ codeOf,
33
+ digestOf,
34
+ incumbentOf,
35
+ keepRuns,
36
+ type LoopDefinition,
37
+ type LoopDeps,
38
+ loopDirOf,
39
+ loopIdOf,
40
+ loopSpend,
41
+ newestLoop,
42
+ readFinals,
43
+ readLoop,
44
+ readLoops,
45
+ readSpread,
46
+ readTries,
47
+ runFinal,
48
+ runLoop,
49
+ spreadWarningOf,
50
+ type TryRun,
51
+ } from "./loop";
52
+ import { patchOf } from "./loop-code";
53
+ import { readLoopRecords, writeLoopRecords } from "./loop-records";
54
+ import {
55
+ factsOf,
56
+ newestEntries,
57
+ preconditionFailure,
58
+ stageFailure,
59
+ trialOutcome,
60
+ trialSpend,
61
+ whyNot,
62
+ } from "./outcome";
63
+ import { Refusal } from "./refusal";
64
+ import { differingCases } from "./report";
65
+ import { earlierTrials, estimateOf, estimateText, type RunGiven, run } from "./run-command";
66
+ import { columnVerdicts } from "./run-report";
67
+ import { barsOf, type CaseBar, rowsOf } from "./runs";
68
+ import { awfRunsOf, newRunId, readRunRecord, readTrials, runSpan, type StoredTrial } from "./store";
69
+ import { plural, usd } from "./text";
70
+ import { afterMsOf } from "./trial-settings";
71
+ import {
72
+ type CaseWorkspace,
73
+ chooseLoop,
74
+ type LoopRef,
75
+ recordsFolders,
76
+ recordsOf,
77
+ } from "./workspace";
78
+
79
+ export const PROPOSER = join(import.meta.dir, "../loop/propose.workflow.ts");
80
+
81
+ const LOOP_VERBS = ["run", "final", "patch"] as const;
82
+ type LoopVerb = (typeof LOOP_VERBS)[number];
83
+
84
+ /** `loop run {name}`, `loop final {name}` and `loop patch {name}`. */
85
+ export async function loopCommand(context: Context, names: readonly string[]): Promise<number> {
86
+ const { options } = context;
87
+ const [verb, name, ...extra] = names;
88
+ if (!LOOP_VERBS.includes(verb as LoopVerb)) {
89
+ throw new Refusal(
90
+ `loop takes ${LOOP_VERBS.join(", ")}, then the loop's name${verb ? `, not ${verb}` : ""}: awf-lab loop run {name}`,
91
+ );
92
+ }
93
+ if (!name) throw new Refusal(`loop ${verb} needs the loop's name: loop ${verb} {name}`);
94
+ if (extra.length > 0) {
95
+ throw new Refusal(
96
+ `loop ${verb} takes one name; got ${names.length - 1} words: ${names.slice(1).join(" ")}`,
97
+ );
98
+ }
99
+ const workspace = workspaceOf(context);
100
+ const top = workspace.repository ?? workspace.root;
101
+ // A loop run elsewhere, as its committed records have it, goes on here.
102
+ for (const records of recordsFolders(workspace)) {
103
+ readLoopRecords(workspace.store, records, name, top, workspace);
104
+ }
105
+ const recorded = (dir: string) => {
106
+ const dataset = readLoop(dir)?.dataset;
107
+ const records = dataset === undefined ? undefined : recordsOf(workspace, dataset);
108
+ if (records) writeLoopRecords(dir, records);
109
+ };
110
+ // `final` and `patch` act on the newest loop of the name, which `--new` supersedes the one before.
111
+ const newest = newestLoop(workspace.store, name);
112
+ const none = () =>
113
+ new Refusal(`no loop ${name} in ${workspace.store}: awf-lab loop run ${name} starts one`);
114
+ if (verb === "patch") {
115
+ if (!newest) throw none();
116
+ const kept = incumbentOf(readTries(newest.dir));
117
+ if (kept === 0) {
118
+ context.stderr(`loop ${loopIdOf(newest.loop)} kept nothing: no patch`);
119
+ return 1;
120
+ }
121
+ context.stdout(patchOf(codeOf(newest.dir, kept)));
122
+ return 0;
123
+ }
124
+ // The cap is the person's answer, given up front: a loop runs unattended, so it never asks.
125
+ if (options.budget === undefined && !options.dryRun) {
126
+ throw new Refusal(
127
+ `loop ${verb} runs trials at a cost and never asks: --budget {usd} caps this command's estimates`,
128
+ );
129
+ }
130
+ const final = verb === "final";
131
+ if (final && !newest) throw none();
132
+ // `loop run` reads the entry once: a new loop records it, and a resume is refused one changed.
133
+ const fromEntry = final ? undefined : definitionOf(chooseLoop(workspace, name));
134
+ const resuming = final ? newest : options.new ? undefined : newest;
135
+ if (fromEntry && resuming) {
136
+ const changed = changedDefinition(resuming.loop, fromEntry.definition);
137
+ if (changed.length > 0) {
138
+ throw new Refusal(
139
+ `loop ${name}'s entry changed since ${loopIdOf(resuming.loop)} started: ${changed.join("; ")}: put it back to go on, or loop run ${name} --new starts a new loop from the entry as it is now`,
140
+ );
141
+ }
142
+ }
143
+ const definition: LoopDefinition = resuming?.loop ?? fromEntry!.definition;
144
+ const started = resuming
145
+ ? resuming.loop.started
146
+ : (context.environment.now ?? (() => new Date()))().toISOString();
147
+ const dir = resuming?.dir ?? loopDirOf(workspace.store, loopIdOf({ name, started }));
148
+ const { info, cases } = loadDataset(context, workspace, definition.dataset);
149
+ const { cases: held } = loadDataset(context, workspace, info.name, true);
150
+ if (info.trial.sandbox?.by === "workflow") {
151
+ throw new Refusal(
152
+ `a loop runs code no person wrote: ${info.name}'s trial.ts needs the lab's sandbox, sandbox.by "lab", the default`,
153
+ );
154
+ }
155
+ if (!info.grading.compare) {
156
+ throw new Refusal(
157
+ `a loop keeps a try only when better: ${info.name} needs compare in grading.ts`,
158
+ );
159
+ }
160
+ const bars = barsOf(info, [...cases, ...held], await countedGraders(context, workspace, info));
161
+ // Every run of the loop is under its own parameters and trials.
162
+ const scoped: Context = {
163
+ ...context,
164
+ options: { ...options, param: [...definition.params], trials: definition.trials },
165
+ };
166
+ const deps = loopDeps(scoped, {
167
+ workspace,
168
+ info,
169
+ bars,
170
+ top,
171
+ dir,
172
+ proposer: definition.proposer,
173
+ heldOut: held.map((c) => c.dir),
174
+ comparison: `grading.ts ${fileDigest(comparingFile(info)!).slice(0, 19)}`,
175
+ });
176
+ const reported = () => {
177
+ if (options.json) context.stdout(JSON.stringify(loopReportJson(workspace, dir), null, 2));
178
+ };
179
+
180
+ if (final) {
181
+ const loop = resuming!.loop;
182
+ const kept = incumbentOf(readTries(dir));
183
+ const plan: LoopPlan = {
184
+ command: "loop final",
185
+ dataset: info.name,
186
+ loop: name,
187
+ cases: loop.holdout,
188
+ trials: loop.trials,
189
+ columns: 2,
190
+ lines: [
191
+ `loop ${loopIdOf(loop)} final · ${info.name} · try ${kept} against the start on ${plural(loop.holdout.length, "held-out case")} · ${plural(loop.trials, "trial")} each`,
192
+ ],
193
+ newTrials: 2 * loop.holdout.length * loop.trials,
194
+ workspace,
195
+ };
196
+ if (options.dryRun) {
197
+ if (kept === 0) {
198
+ context.stderr(`loop ${loopIdOf(loop)} kept nothing: there is nothing to check`);
199
+ return 1;
200
+ }
201
+ showPlan(context, plan);
202
+ return 0;
203
+ }
204
+ if (kept > 0) context.stderr(planOf(context, plan).text);
205
+ const outcome = await runFinal({ dir, budget: options.budget! }, deps).finally(() =>
206
+ recorded(dir),
207
+ );
208
+ if (options.json) {
209
+ context.stderr(outcome.why);
210
+ reported();
211
+ } else context.stdout(outcome.why);
212
+ return outcome.exit;
213
+ }
214
+ const tuning = resuming
215
+ ? cases.filter((c) => resuming.loop.tuning.includes(c.name))
216
+ : tuningOf(name, info.name, cases, definition);
217
+ const rounds = options.rounds ?? 1;
218
+ const spreadFirst = definition.spread && !readSpread(dir) && readTries(dir).length === 0;
219
+ const plan: LoopPlan = {
220
+ command: "loop run",
221
+ dataset: info.name,
222
+ loop: name,
223
+ cases: tuning.map((c) => c.name),
224
+ trials: definition.trials,
225
+ columns: 2,
226
+ rounds,
227
+ spread: spreadFirst,
228
+ lines: [
229
+ `loop ${name} · ${info.name} · ${plural(tuning.length, "tuning case")} · ${plural(definition.trials, "trial")} each · up to ${rounds} ${rounds === 1 ? "try" : "tries"}${resuming ? `, going on with ${loopIdOf(resuming.loop)}` : ""}`,
230
+ ...(spreadFirst ? ["first: the start twice on the tuning cases"] : []),
231
+ "each try: the incumbent on the tuning cases, a proposal, then the try against the incumbent",
232
+ ],
233
+ // A try runs its own column anew, and the incumbent's reuses what it ran; the spread, two.
234
+ newTrials: tuning.length * definition.trials * (rounds + (spreadFirst ? 2 : 0)),
235
+ workspace,
236
+ };
237
+ if (options.dryRun) {
238
+ showPlan(context, plan);
239
+ return 0;
240
+ }
241
+ context.stderr(planOf(context, plan).text);
242
+ const state = gitState(workspace.root);
243
+ const outcome = await runLoop(
244
+ {
245
+ name,
246
+ dir,
247
+ top,
248
+ workspace,
249
+ tuning,
250
+ holdout: held.map((c) => c.name),
251
+ rounds,
252
+ budget: options.budget!,
253
+ definition,
254
+ briefFile: fromEntry!.brief,
255
+ project: relative(top, workspace.project),
256
+ from: { path: workspace.root, commit: state.commit, dirty: state.dirty },
257
+ started,
258
+ },
259
+ deps,
260
+ ).finally(() => recorded(dir));
261
+ const warning = spreadWarningOf(dir);
262
+ const said = `loop ${name}: ${outcome.why}${warning ? `\n${warning}` : ""}`;
263
+ if (options.json) {
264
+ context.stderr(said);
265
+ reported();
266
+ } else context.stdout(said);
267
+ return outcome.exit;
268
+ }
269
+
270
+ /**
271
+ * What a loop's entry says now, as its record would keep it, and its brief's file: refused when the
272
+ * brief is missing.
273
+ */
274
+ function definitionOf(entry: LoopRef): { definition: LoopDefinition; brief: string } {
275
+ const brief = entry.brief.value;
276
+ if (!existsSync(brief) || !statSync(brief).isFile()) {
277
+ throw new Refusal(`${entry.brief.from}: loop ${entry.name}'s brief ${brief} doesn't exist`);
278
+ }
279
+ return {
280
+ brief,
281
+ definition: {
282
+ dataset: entry.dataset.value,
283
+ brief: digestOf(readFileSync(brief)),
284
+ edit: { allow: [...entry.allow.value], deny: [...entry.deny.value] },
285
+ proposer: entry.proposer.value,
286
+ trials: entry.trials.value,
287
+ params: Object.entries(entry.params)
288
+ .map(([param, p]) => `${param}=${p.value}`)
289
+ .sort(),
290
+ ...(entry.cases ? { cases: [...entry.cases.value] } : {}),
291
+ ...(entry.tags ? { tags: [...entry.tags.value] } : {}),
292
+ spread: entry.spread.value,
293
+ },
294
+ };
295
+ }
296
+
297
+ /** The tuning cases a new loop's entry picks: of those not held out, its `cases`, then its `tags`. */
298
+ function tuningOf(
299
+ name: string,
300
+ dataset: string,
301
+ cases: readonly CaseInfo[],
302
+ definition: LoopDefinition,
303
+ ): CaseInfo[] {
304
+ let picked = [...cases];
305
+ if (definition.cases) {
306
+ const unknown = definition.cases.filter((n) => !cases.some((c) => c.name === n));
307
+ if (unknown.length > 0) {
308
+ throw new Refusal(
309
+ `loop ${name}'s cases: no tuning case ${unknown.join(", ")} in ${dataset}; known: ${cases.map((c) => c.name).join(", ")}`,
310
+ );
311
+ }
312
+ picked = picked.filter((c) => definition.cases!.includes(c.name));
313
+ }
314
+ if (definition.tags) {
315
+ const tags = definition.tags;
316
+ picked = picked.filter((c) => (c.key.tags ?? []).some((t) => tags.includes(t)));
317
+ if (picked.length === 0) {
318
+ throw new Refusal(
319
+ `loop ${name}'s tags: no tuning case of ${dataset}${definition.cases ? " its cases name" : ""} has ${tags.join(" or ")}`,
320
+ );
321
+ }
322
+ }
323
+ return picked;
324
+ }
325
+
326
+ type LoopPlan = {
327
+ command: "loop run" | "loop final";
328
+ dataset: string;
329
+ loop: string;
330
+ cases: readonly string[];
331
+ trials: number;
332
+ columns: number;
333
+ rounds?: number;
334
+ spread?: boolean;
335
+ lines: string[];
336
+ /** The trials it would run at most, none reused. */
337
+ newTrials: number;
338
+ workspace: CaseWorkspace;
339
+ };
340
+
341
+ /** A loop command's plan: what it runs, an estimate from earlier trials, and its budget. */
342
+ function planOf(context: Context, plan: LoopPlan): { text: string; json: CasePlan } {
343
+ const { workspace } = plan;
344
+ const { budget } = context.options;
345
+ const earlier = earlierTrials(workspace.store, plan.dataset, plan.cases);
346
+ const atOnce = workspace.concurrency;
347
+ const estimate = estimateOf(earlier, plan.newTrials, atOnce);
348
+ const json: CasePlan = {
349
+ kind: PLAN_KIND,
350
+ command: plan.command,
351
+ dataset: plan.dataset,
352
+ loop: plan.loop,
353
+ cases: plan.cases.map((c) => ({ case: c, trials: plan.trials })),
354
+ columns: plan.columns,
355
+ trials: plan.newTrials,
356
+ ...(plan.rounds !== undefined ? { rounds: plan.rounds } : {}),
357
+ ...(plan.spread !== undefined ? { spread: plan.spread } : {}),
358
+ ...(estimate ? { estimate } : {}),
359
+ ...(budget !== undefined ? { budget } : {}),
360
+ concurrency: atOnce,
361
+ };
362
+ const text = [
363
+ ...plan.lines,
364
+ ...(atOnce > 1 ? [`runs up to ${plural(atOnce, "trial")} at once`] : []),
365
+ `${estimateText(earlier, plan.newTrials, atOnce, "up to ")}; the proposer is not in it`,
366
+ ...(budget !== undefined
367
+ ? [`stops starting work once this command's estimates reach ${usd(budget)}`]
368
+ : []),
369
+ ].join("\n");
370
+ return { text, json };
371
+ }
372
+
373
+ function showPlan(context: Context, plan: LoopPlan): void {
374
+ const made = planOf(context, plan);
375
+ if (context.options.json) printPlan(context, made.json);
376
+ else context.stdout(made.text);
377
+ }
378
+
379
+ /** `report --loop {name or id}`: a loop's tries, checks and the total of its estimates so far. */
380
+ export function loopReport(context: Context, given: string): number {
381
+ const workspace = workspaceOf(context);
382
+ const loops = readLoops(workspace.store);
383
+ // A name means the newest loop of that name; an id from runs, that loop.
384
+ const found =
385
+ loops.filter((l) => l.loop.name === given).at(-1) ??
386
+ loops.find((l) => loopIdOf(l.loop) === given);
387
+ if (!found) {
388
+ throw new Refusal(
389
+ `no loop ${given} in ${workspace.store}${loops.length > 0 ? `; its loops: ${loops.map((l) => `${l.loop.name} (${loopIdOf(l.loop)})`).join(", ")}` : ""}`,
390
+ );
391
+ }
392
+ const json = loopReportJson(workspace, found.dir);
393
+ if (context.options.json) {
394
+ context.stdout(JSON.stringify(json, null, 2));
395
+ return 0;
396
+ }
397
+ const from = (parent: number) => (parent === 0 ? "the start" : `try ${parent}`);
398
+ const spread = json.spread;
399
+ const lines = [
400
+ `loop ${json.name} · ${json.id} · ${json.dataset}`,
401
+ `${plural(json.tuning.length, "tuning case")} · ${plural(json.holdout.length, "held-out case")} · ${plural(json.trials, "trial")} each · proposer ${json.proposer}${json.params.length > 0 ? ` · params ${json.params.join(" ")}` : ""}`,
402
+ spread === null
403
+ ? "the start twice: not yet"
404
+ : spread === "skipped"
405
+ ? "the start twice: skipped"
406
+ : `the start twice: ${spread.verdict ?? "no comparison"}, ${spread.unsteady.length} of ${json.tuning.length} cases differed · run ${spread.runId} · est. ${usd(spread.spend)}`,
407
+ ...json.tries.map(
408
+ (t) =>
409
+ `try ${t.n} against ${from(t.parent)}: ${t.decision}: ${t.why}${t.runId ? ` · run ${t.runId}` : ""} · est. ${usd(t.spend)}`,
410
+ ),
411
+ ...json.finals.map(
412
+ (f) =>
413
+ `final check ${f.k}: try ${f.incumbent} against the start: ${f.why} · est. ${usd(f.spend)}`,
414
+ ),
415
+ `keeps ${json.kept === 0 ? "the start: no try kept" : `try ${json.kept}`} · est. ${usd(json.estimate)} so far`,
416
+ ];
417
+ context.stdout(lines.join("\n"));
418
+ return 0;
419
+ }
420
+
421
+ function loopReportJson(workspace: CaseWorkspace, dir: string): LoopReport {
422
+ const loop = readLoop(dir)!;
423
+ const tries = readTries(dir);
424
+ const spread = readSpread(dir);
425
+ const finals = readFinals(dir);
426
+ const spend = loopSpend(dir, (ids) =>
427
+ ids.reduce((sum, id) => sum + spendOf(workspace.store, id), 0),
428
+ );
429
+ const report: LoopReport = {
430
+ kind: LOOP_REPORT_KIND,
431
+ id: loopIdOf(loop),
432
+ name: loop.name,
433
+ dataset: loop.dataset,
434
+ started: loop.started,
435
+ proposer: loop.proposer,
436
+ trials: loop.trials,
437
+ params: [...loop.params],
438
+ tuning: [...loop.tuning],
439
+ holdout: [...loop.holdout],
440
+ spread: !spread
441
+ ? null
442
+ : "runId" in spread
443
+ ? {
444
+ runId: spread.runId,
445
+ verdict: spread.verdict,
446
+ unsteady: spread.unsteady.map((d) => d.case),
447
+ spend: spread.spend,
448
+ }
449
+ : "skipped",
450
+ tries: tries.map((t) => ({
451
+ n: t.n,
452
+ parent: t.parent,
453
+ decision: t.decision,
454
+ why: t.why,
455
+ ...(t.hypothesis ? { change: t.hypothesis.change } : {}),
456
+ changed: [...t.changed],
457
+ ...(t.runId ? { runId: t.runId } : {}),
458
+ spend: t.spend.proposer + t.spend.trials,
459
+ })),
460
+ kept: incumbentOf(tries),
461
+ finals: finals.map((f) => ({
462
+ k: f.k,
463
+ incumbent: f.incumbent,
464
+ runId: f.runId,
465
+ verdict: f.verdict,
466
+ why: f.why,
467
+ spend: f.spend,
468
+ })),
469
+ estimate: spend.spread + spend.tries + (spend.pending?.spend ?? 0) + spend.finals,
470
+ };
471
+ const checked = checkSchema(LoopReportSchema, report);
472
+ if (!checked.ok) throw new Error(describeProblems("report --loop --json", checked.problems));
473
+ return report;
474
+ }
475
+
476
+ function loopDeps(
477
+ context: Context,
478
+ at: {
479
+ workspace: CaseWorkspace;
480
+ info: DatasetInfo;
481
+ bars: ReadonlyMap<string, CaseBar>;
482
+ top: string;
483
+ dir: string;
484
+ proposer: string;
485
+ /** The held-out cases' folders. */
486
+ heldOut: readonly string[];
487
+ comparison: string;
488
+ },
489
+ ): LoopDeps {
490
+ const { options, environment } = context;
491
+ const { workspace, info, bars } = at;
492
+ const { runner, estimate, allowance } = externalsOf(environment);
493
+ // The share of a plan window at which a loop waits: `--allowance`, the local file's, or 90.
494
+ const limit = options.allowance ?? workspace.allowance;
495
+ // The agents a loop draws on, as far as it can name them: the proposer, and any parameter
496
+ // value that is a harness/model.
497
+ const named = () => [at.proposer, ...options.param.map((p) => p.slice(p.indexOf("=") + 1))];
498
+ // The store is the loop's for each run of trials alone: busy at the first, the command is
499
+ // refused, as any is; at a later one, the loop waits for it.
500
+ let ranOnce = false;
501
+ const wait =
502
+ allowance && limit !== "off"
503
+ ? waitingOnAllowance(async () => undefined, allowance, { limit, log: context.stderr })
504
+ : undefined;
505
+ return {
506
+ comparison: at.comparison,
507
+ log: (line) => context.stderr(line),
508
+ now: environment.now ?? (() => new Date()),
509
+ async waitForAllowance() {
510
+ if (wait) await wait({ argv: named() });
511
+ },
512
+ estimatedIn(runIds) {
513
+ return runIds.reduce((sum, id) => sum + spendOf(workspace.store, id), 0);
514
+ },
515
+ async checkGood({ cases }) {
516
+ const all = loadDataset(context, workspace, info.name, "all").cases;
517
+ const checks = await checkGoodRecords(
518
+ context,
519
+ workspace,
520
+ info,
521
+ all.filter((c) => cases.includes(c.name)),
522
+ );
523
+ if (checks.length === 0) return undefined;
524
+ return {
525
+ failing: checks.filter((c) => !c.passed).map((c) => c.case),
526
+ lines: checks.map((c) => c.line),
527
+ };
528
+ },
529
+ async room(runId) {
530
+ const run = readRunRecord(workspace.store, runId);
531
+ if (!run) return undefined;
532
+ return roomOf({
533
+ trials: readTrials(workspace.store, runId),
534
+ bars,
535
+ planned: run.asked.length,
536
+ gradingFile: comparingFile(info),
537
+ root: workspace.root,
538
+ tmp: tmpOf(context),
539
+ env: envOf(context),
540
+ timeoutMs: afterMsOf(info),
541
+ });
542
+ },
543
+ differed(runId) {
544
+ const run = readRunRecord(workspace.store, runId);
545
+ if (!run || run.columns.length < 2) return [];
546
+ const trials = bothRan(readTrials(workspace.store, runId), run.columns.length);
547
+ const ran = new Set(trials.map((t) => t.record.case));
548
+ const asked = { ...run, asked: run.asked.filter((a) => ran.has(a.case)) };
549
+ return differingCases(
550
+ rowsOf(workspace.store, asked, trials, bars, 0),
551
+ rowsOf(workspace.store, asked, trials, bars, 1),
552
+ );
553
+ },
554
+ async runFolders({ folders, order, budget, stopOnVerdict, holdout, started }) {
555
+ const { budget: _, ...rest } = options;
556
+ const scoped: Context = {
557
+ ...context,
558
+ options: {
559
+ ...rest,
560
+ dataset: info.name,
561
+ yes: true,
562
+ fresh: false,
563
+ failed: false,
564
+ holdout: holdout ?? false,
565
+ against: [],
566
+ vary: [],
567
+ json: false,
568
+ dryRun: false,
569
+ ...(Number.isFinite(budget) ? { budget: Math.max(budget, 0.01) } : {}),
570
+ } satisfies Options,
571
+ };
572
+ const loop = readLoop(at.dir);
573
+ const given: RunGiven = {
574
+ folders,
575
+ order,
576
+ report: false,
577
+ ...(loop ? { loop: loopIdOf(loop) } : {}),
578
+ ...(ranOnce ? { waitForStore: true } : {}),
579
+ ...(started ? { started } : {}),
580
+ ...(stopOnVerdict
581
+ ? {
582
+ stop: async (run, trials) => {
583
+ const verdict = (
584
+ await columnVerdicts(scoped, {
585
+ workspace,
586
+ info,
587
+ run,
588
+ trials: bothRan(trials, folders.length),
589
+ bars,
590
+ })
591
+ )?.[0];
592
+ return verdict !== undefined && "verdict" in verdict && verdict.verdict.stop;
593
+ },
594
+ }
595
+ : {}),
596
+ };
597
+ ranOnce = true;
598
+ const done = await run(scoped, given);
599
+ const runId = done.id;
600
+ if (!runId) {
601
+ throw new Error(
602
+ `the try's run never started${done.unstarted ? `: ${done.unstarted}` : ""}`,
603
+ );
604
+ }
605
+ const record = readRunRecord(workspace.store, runId)!;
606
+ // Decided by nothing: the loop stops undecided, and resumes with this try.
607
+ if (record.broke) throw new Error(`the lab broke during run ${runId}: ${record.broke}`);
608
+ const trials = readTrials(workspace.store, runId);
609
+ const verdicts =
610
+ folders.length > 1
611
+ ? await columnVerdicts(scoped, {
612
+ workspace,
613
+ info,
614
+ run: record,
615
+ trials: bothRan(trials, folders.length),
616
+ bars,
617
+ })
618
+ : undefined;
619
+ const first = verdicts?.[0];
620
+ const result: TryRun = {
621
+ runId,
622
+ ...(record.stopped ? { stopped: record.stopped } : {}),
623
+ ...(record.stopped === "precondition"
624
+ ? { precondition: preconditionFailure(trials) ?? "no trial says which" }
625
+ : {}),
626
+ ...(record.stopped === "stage"
627
+ ? { stage: stageFailure(trials) ?? "no trial says which" }
628
+ : {}),
629
+ ...(first
630
+ ? {
631
+ verdict:
632
+ "verdict" in first
633
+ ? {
634
+ verdict: first.verdict.verdict,
635
+ stop: first.verdict.stop,
636
+ reason: first.verdict.reason,
637
+ metrics: first.verdict.metrics,
638
+ }
639
+ : { error: first.error },
640
+ }
641
+ : {}),
642
+ spend: spendOf(workspace.store, runId),
643
+ };
644
+ return result;
645
+ },
646
+ feedback(runId, column) {
647
+ const views = readTrials(workspace.store, runId)
648
+ .filter((t) => t.record.column === column)
649
+ .map((t) => ({ ...t, view: trialOutcome(t.record, t.scores) }));
650
+ // An errored or leaked trial's outcome is not the workflow's: no change to it fixes one.
651
+ const notOurs = (outcome: string) => outcome === "errored" || outcome === "leaked";
652
+ const others = views
653
+ .filter((t) => notOurs(t.view.outcome))
654
+ .map(
655
+ ({ record, scores }) =>
656
+ `${record.case} trial ${record.trial}: ${whyNot({ record, scores })}`,
657
+ );
658
+ const trials = views
659
+ .filter((t) => !notOurs(t.view.outcome))
660
+ .map(({ record, scores, view }) => ({
661
+ case: record.case,
662
+ trial: record.trial,
663
+ outcome: view.outcome,
664
+ ms: record.ms,
665
+ ...(factsOf(scores) ? { facts: factsOf(scores) } : {}),
666
+ ...(record.runFacts ? { runFacts: record.runFacts } : {}),
667
+ ...(record.stageMs ? { stageMs: record.stageMs } : {}),
668
+ ...(record.workflowError ? { workflowError: record.workflowError } : {}),
669
+ ...(record.stopped ? { stopped: record.stopped } : {}),
670
+ grades: newestEntries(scores).map((e) => ({
671
+ grader: e.grader,
672
+ ...(e.verdict ? { verdict: e.verdict } : {}),
673
+ ...(e.numbers ? { numbers: e.numbers } : {}),
674
+ ...(e.reasons ? { reasons: e.reasons } : {}),
675
+ ...(e.parts
676
+ ? { parts: e.parts.map((p) => ({ about: p.about, label: p.label, why: p.why })) }
677
+ : {}),
678
+ ...(e.errored ? { errored: e.errored } : {}),
679
+ })),
680
+ }));
681
+ return { trials, others };
682
+ },
683
+ async propose({ tryDir, code, bundle, proposer }) {
684
+ // The copy's own install, which its box reads, not your checkout's.
685
+ const copyRoot = join(code, relative(at.top, workspace.root));
686
+ const folder = await (environment.inspect ?? inspectFolder)(
687
+ copyRoot,
688
+ checkTrialScript(join(copyRoot, relative(workspace.root, info.evalDir))),
689
+ );
690
+ const id = newRunId((environment.now ?? (() => new Date()))());
691
+ const own = join(tryDir, "proposer");
692
+ const runRoot = join(own, "runs");
693
+ mkdirSync(runRoot, { recursive: true });
694
+ const path = [folder.bin, (environment.env ?? process.env).PATH].filter(Boolean).join(":");
695
+ const lab = realpathSync(join(import.meta.dir, "../.."));
696
+ // It works in the try's folder, writes the copy but its `evals/`, and reads its bundle.
697
+ const box = boxSpec({
698
+ read: [lab, bundle, join(code, relative(at.top, workspace.evals))],
699
+ write: [code, own],
700
+ // The store and the lab's home whole but this try's folder, where the proposer works.
701
+ hide: [
702
+ ...hiddenOf(code, workspace, { keep: [tryDir] }),
703
+ ...heldOutOf(at.heldOut, workspace, copyRoot),
704
+ ],
705
+ network: [],
706
+ });
707
+ const result = await runner({
708
+ workflow: PROPOSER,
709
+ cwd: tryDir,
710
+ timeout: "30m",
711
+ argv: ["--runtime", proposer],
712
+ runRoot,
713
+ id,
714
+ awf: { bin: folder.awf.bin, dir: folder.awf.dir },
715
+ quiet: true,
716
+ env: { ...envOf(context), PATH: path },
717
+ in: writeBoxSpec(box, join(tryDir, "box.json")),
718
+ });
719
+ keepRuns(runRoot, awfRunsOf(workspace.store));
720
+ const record = result.record;
721
+ // A proposer cut short prints no record; its folder still says what its agent is estimated at.
722
+ const unrecorded =
723
+ record || !estimate ? undefined : await estimate(folder.awf, runRoot, id, envOf(context));
724
+ const spend = record?.accounting.totals.estimate ?? unrecorded ?? 0;
725
+ if (record?.outcome !== "completed") {
726
+ return {
727
+ spend,
728
+ ...(record ? { runId: record.runId } : {}),
729
+ why: `the proposer's run ${record?.outcome ?? "printed no record"}: ${
730
+ (record && "reason" in record ? record.reason : undefined) ??
731
+ result.unread ??
732
+ result.stderr.trim().split("\n").at(-1) ??
733
+ ""
734
+ }`,
735
+ };
736
+ }
737
+ const checked = checkSchema(HypothesisSchema, record.value);
738
+ if (!checked.ok) {
739
+ return {
740
+ spend,
741
+ runId: record.runId,
742
+ why: describeProblems("the proposer's answer", checked.problems),
743
+ };
744
+ }
745
+ return { spend, runId: record.runId, hypothesis: checked.value };
746
+ },
747
+ };
748
+ }
749
+
750
+ /**
751
+ * The trials of the cases every column has run: a try's run holds the incumbent's reused trials of
752
+ * every case from its start, and a comparison weighs only what both have.
753
+ */
754
+ function bothRan(trials: readonly StoredTrial[], columns: number): StoredTrial[] {
755
+ const ran = new Map<string, Set<number>>();
756
+ for (const t of trials) {
757
+ const seen = ran.get(t.record.case) ?? new Set<number>();
758
+ seen.add(t.record.column);
759
+ ran.set(t.record.case, seen);
760
+ }
761
+ return trials.filter((t) => (ran.get(t.record.case)?.size ?? 0) === columns);
762
+ }
763
+
764
+ /** What a run's trials and their grades are estimated at, as its `--budget` counted them. */
765
+ function spendOf(store: string, id: string): number {
766
+ const run = readRunRecord(store, id);
767
+ if (!run) return 0;
768
+ const span = runSpan(store, run);
769
+ return readTrials(store, id).reduce((sum, t) => sum + trialSpend(t, span), 0);
770
+ }