@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,774 @@
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 LabPlan,
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 { checkTargetScript, inspectFolder } from "./inspect";
30
+ import {
31
+ bestSoFarOf,
32
+ changedDefinition,
33
+ codeOf,
34
+ digestOf,
35
+ keepRuns,
36
+ type LoopDefinition,
37
+ type LoopDeps,
38
+ loopDirOf,
39
+ loopEstimates,
40
+ loopIdOf,
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 { columnDecisions } 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 = bestSoFarOf(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.target.sandbox?.by === "workflow") {
151
+ throw new Refusal(
152
+ `a loop runs code no person wrote: ${info.name}'s target.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 = bestSoFarOf(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
+ const nothing = `loop ${loopIdOf(loop)} kept nothing: there is nothing to check`;
199
+ if (options.json) printPlan(context, { ...planOf(context, plan).json, trials: 0, nothing });
200
+ else context.stderr(nothing);
201
+ return 1;
202
+ }
203
+ showPlan(context, plan);
204
+ return 0;
205
+ }
206
+ if (kept > 0) context.stderr(planOf(context, plan).text);
207
+ const outcome = await runFinal({ dir, budget: options.budget! }, deps).finally(() =>
208
+ recorded(dir),
209
+ );
210
+ if (options.json) {
211
+ context.stderr(outcome.why);
212
+ reported();
213
+ } else context.stdout(outcome.why);
214
+ return outcome.exit;
215
+ }
216
+ const tuning = resuming
217
+ ? cases.filter((c) => resuming.loop.tuning.includes(c.name))
218
+ : tuningOf(name, info.name, cases, definition);
219
+ const tries = options.tries ?? 1;
220
+ const spreadFirst = definition.spread && !readSpread(dir) && readTries(dir).length === 0;
221
+ const plan: LoopPlan = {
222
+ command: "loop run",
223
+ dataset: info.name,
224
+ loop: name,
225
+ cases: tuning.map((c) => c.name),
226
+ trials: definition.trials,
227
+ columns: 2,
228
+ tries,
229
+ spread: spreadFirst,
230
+ lines: [
231
+ `loop ${name} · ${info.name} · ${plural(tuning.length, "tuning case")} · ${plural(definition.trials, "trial")} each · up to ${tries} ${tries === 1 ? "try" : "tries"}${resuming ? `, going on with ${loopIdOf(resuming.loop)}` : ""}`,
232
+ ...(spreadFirst ? ["first: the start twice on the tuning cases"] : []),
233
+ "each try: the best version so far on the tuning cases, a proposal, then the try against it",
234
+ ],
235
+ // A try runs its own column anew, and the best version so far reuses what it ran; the spread, two.
236
+ newTrials: tuning.length * definition.trials * (tries + (spreadFirst ? 2 : 0)),
237
+ workspace,
238
+ };
239
+ if (options.dryRun) {
240
+ showPlan(context, plan);
241
+ return 0;
242
+ }
243
+ context.stderr(planOf(context, plan).text);
244
+ const state = gitState(workspace.root);
245
+ const outcome = await runLoop(
246
+ {
247
+ name,
248
+ dir,
249
+ top,
250
+ workspace,
251
+ tuning,
252
+ holdout: held.map((c) => c.name),
253
+ tries,
254
+ budget: options.budget!,
255
+ definition,
256
+ briefFile: fromEntry!.brief,
257
+ project: relative(top, workspace.project),
258
+ from: { path: workspace.root, commit: state.commit, dirty: state.dirty },
259
+ started,
260
+ },
261
+ deps,
262
+ ).finally(() => recorded(dir));
263
+ const warning = spreadWarningOf(dir);
264
+ const said = `loop ${name}: ${outcome.why}${warning ? `\n${warning}` : ""}`;
265
+ if (options.json) {
266
+ context.stderr(said);
267
+ reported();
268
+ } else context.stdout(said);
269
+ return outcome.exit;
270
+ }
271
+
272
+ /**
273
+ * What a loop's entry says now, as its record would keep it, and its brief's file: refused when the
274
+ * brief is missing.
275
+ */
276
+ function definitionOf(entry: LoopRef): { definition: LoopDefinition; brief: string } {
277
+ const brief = entry.brief.value;
278
+ if (!existsSync(brief) || !statSync(brief).isFile()) {
279
+ throw new Refusal(`${entry.brief.from}: loop ${entry.name}'s brief ${brief} doesn't exist`);
280
+ }
281
+ return {
282
+ brief,
283
+ definition: {
284
+ dataset: entry.dataset.value,
285
+ brief: digestOf(readFileSync(brief)),
286
+ edit: { allow: [...entry.allow.value], deny: [...entry.deny.value] },
287
+ proposer: entry.proposer.value,
288
+ trials: entry.trials.value,
289
+ params: Object.entries(entry.params)
290
+ .map(([param, p]) => `${param}=${p.value}`)
291
+ .sort(),
292
+ ...(entry.cases ? { cases: [...entry.cases.value] } : {}),
293
+ ...(entry.tags ? { tags: [...entry.tags.value] } : {}),
294
+ spread: entry.spread.value,
295
+ },
296
+ };
297
+ }
298
+
299
+ /** The tuning cases a new loop's entry picks: of those not held out, its `cases`, then its `tags`. */
300
+ function tuningOf(
301
+ name: string,
302
+ dataset: string,
303
+ cases: readonly CaseInfo[],
304
+ definition: LoopDefinition,
305
+ ): CaseInfo[] {
306
+ let picked = [...cases];
307
+ if (definition.cases) {
308
+ const unknown = definition.cases.filter((n) => !cases.some((c) => c.name === n));
309
+ if (unknown.length > 0) {
310
+ throw new Refusal(
311
+ `loop ${name}'s cases: no tuning case ${unknown.join(", ")} in ${dataset}; known: ${cases.map((c) => c.name).join(", ")}`,
312
+ );
313
+ }
314
+ picked = picked.filter((c) => definition.cases!.includes(c.name));
315
+ }
316
+ if (definition.tags) {
317
+ const tags = definition.tags;
318
+ picked = picked.filter((c) => (c.key.tags ?? []).some((t) => tags.includes(t)));
319
+ if (picked.length === 0) {
320
+ throw new Refusal(
321
+ `loop ${name}'s tags: no tuning case of ${dataset}${definition.cases ? " its cases name" : ""} has ${tags.join(" or ")}`,
322
+ );
323
+ }
324
+ }
325
+ return picked;
326
+ }
327
+
328
+ type LoopPlan = {
329
+ command: "loop run" | "loop final";
330
+ dataset: string;
331
+ loop: string;
332
+ cases: readonly string[];
333
+ trials: number;
334
+ columns: number;
335
+ tries?: number;
336
+ spread?: boolean;
337
+ lines: string[];
338
+ /** The trials it would run at most, none reused. */
339
+ newTrials: number;
340
+ workspace: CaseWorkspace;
341
+ };
342
+
343
+ /** A loop command's plan: what it runs, an estimate from earlier trials, and its budget. */
344
+ function planOf(context: Context, plan: LoopPlan): { text: string; json: LabPlan } {
345
+ const { workspace } = plan;
346
+ const { budget } = context.options;
347
+ const earlier = earlierTrials(workspace.store, plan.dataset, plan.cases);
348
+ const atOnce = workspace.concurrency;
349
+ const estimate = estimateOf(earlier, plan.newTrials, atOnce);
350
+ const json: LabPlan = {
351
+ kind: PLAN_KIND,
352
+ command: plan.command,
353
+ dataset: plan.dataset,
354
+ loop: plan.loop,
355
+ cases: plan.cases.map((c) => ({ case: c, trials: plan.trials })),
356
+ columns: plan.columns,
357
+ trials: plan.newTrials,
358
+ ...(plan.tries !== undefined ? { tries: plan.tries } : {}),
359
+ ...(plan.spread !== undefined ? { spread: plan.spread } : {}),
360
+ ...(estimate ? { estimate } : {}),
361
+ ...(budget !== undefined ? { budget } : {}),
362
+ concurrency: atOnce,
363
+ };
364
+ const text = [
365
+ ...plan.lines,
366
+ ...(atOnce > 1 ? [`runs up to ${plural(atOnce, "trial")} at once`] : []),
367
+ `${estimateText(earlier, plan.newTrials, atOnce, "up to ")}; the proposer is not in it`,
368
+ ...(budget !== undefined
369
+ ? [`stops starting work once this command's estimates reach ${usd(budget)}`]
370
+ : []),
371
+ ].join("\n");
372
+ return { text, json };
373
+ }
374
+
375
+ function showPlan(context: Context, plan: LoopPlan): void {
376
+ const made = planOf(context, plan);
377
+ if (context.options.json) printPlan(context, made.json);
378
+ else context.stdout(made.text);
379
+ }
380
+
381
+ /** `report --loop {name or id}`: a loop's tries, checks and the total of its estimates so far. */
382
+ export function loopReport(context: Context, given: string): number {
383
+ const workspace = workspaceOf(context);
384
+ const loops = readLoops(workspace.store);
385
+ // A name means the newest loop of that name; an id from runs, that loop.
386
+ const found =
387
+ loops.filter((l) => l.loop.name === given).at(-1) ??
388
+ loops.find((l) => loopIdOf(l.loop) === given);
389
+ if (!found) {
390
+ throw new Refusal(
391
+ `no loop ${given} in ${workspace.store}${loops.length > 0 ? `; its loops: ${loops.map((l) => `${l.loop.name} (${loopIdOf(l.loop)})`).join(", ")}` : ""}`,
392
+ );
393
+ }
394
+ const json = loopReportJson(workspace, found.dir);
395
+ if (context.options.json) {
396
+ context.stdout(JSON.stringify(json, null, 2));
397
+ return 0;
398
+ }
399
+ const from = (parent: number) => (parent === 0 ? "the start" : `try ${parent}`);
400
+ const spread = json.spread;
401
+ const lines = [
402
+ `loop ${json.name} · ${json.id} · ${json.dataset}`,
403
+ `${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(" ")}` : ""}`,
404
+ spread === null
405
+ ? "the start twice: not yet"
406
+ : spread === "skipped"
407
+ ? "the start twice: skipped"
408
+ : `the start twice: ${spread.decision ?? "no comparison"}, ${spread.unsteady.length} of ${json.tuning.length} cases differed · run ${spread.labRun} · est. ${usd(spread.estimate)}`,
409
+ ...json.tries.map(
410
+ (t) =>
411
+ `try ${t.n} against ${from(t.parent)}: ${t.outcome}: ${t.why}${t.labRun ? ` · run ${t.labRun}` : ""} · est. ${usd(t.estimate)}`,
412
+ ),
413
+ ...json.finals.map(
414
+ (f) =>
415
+ `final check ${f.k}: try ${f.kept} against the start: ${f.why} · est. ${usd(f.estimate)}`,
416
+ ),
417
+ `keeps ${json.kept === 0 ? "the start: no try kept" : `try ${json.kept}`} · est. ${usd(json.estimate)} so far`,
418
+ ];
419
+ context.stdout(lines.join("\n"));
420
+ return 0;
421
+ }
422
+
423
+ function loopReportJson(workspace: CaseWorkspace, dir: string): LoopReport {
424
+ const loop = readLoop(dir)!;
425
+ const tries = readTries(dir);
426
+ const spread = readSpread(dir);
427
+ const finals = readFinals(dir);
428
+ const estimates = loopEstimates(dir, (ids) =>
429
+ ids.reduce((sum, id) => sum + estimatedIn(workspace.store, id), 0),
430
+ );
431
+ const report: LoopReport = {
432
+ kind: LOOP_REPORT_KIND,
433
+ id: loopIdOf(loop),
434
+ name: loop.name,
435
+ dataset: loop.dataset,
436
+ started: loop.started,
437
+ proposer: loop.proposer,
438
+ trials: loop.trials,
439
+ params: [...loop.params],
440
+ tuning: [...loop.tuning],
441
+ holdout: [...loop.holdout],
442
+ spread: !spread
443
+ ? null
444
+ : "labRun" in spread
445
+ ? {
446
+ labRun: spread.labRun,
447
+ decision: spread.decision,
448
+ unsteady: spread.unsteady.map((d) => d.case),
449
+ estimate: spread.estimate,
450
+ }
451
+ : "skipped",
452
+ tries: tries.map((t) => ({
453
+ n: t.n,
454
+ parent: t.parent,
455
+ outcome: t.outcome,
456
+ why: t.why,
457
+ ...(t.hypothesis ? { change: t.hypothesis.change } : {}),
458
+ changed: [...t.changed],
459
+ ...(t.labRun ? { labRun: t.labRun } : {}),
460
+ ...(t.decision !== undefined ? { decision: t.decision } : {}),
461
+ estimate: t.estimate.proposer + t.estimate.trials,
462
+ })),
463
+ kept: bestSoFarOf(tries),
464
+ finals: finals.map((f) => ({
465
+ k: f.k,
466
+ kept: f.kept,
467
+ labRun: f.labRun,
468
+ decision: f.decision,
469
+ why: f.why,
470
+ estimate: f.estimate,
471
+ })),
472
+ estimate:
473
+ estimates.spread + estimates.tries + (estimates.pending?.estimate ?? 0) + estimates.finals,
474
+ };
475
+ const checked = checkSchema(LoopReportSchema, report);
476
+ if (!checked.ok) throw new Error(describeProblems("report --loop --json", checked.problems));
477
+ return report;
478
+ }
479
+
480
+ function loopDeps(
481
+ context: Context,
482
+ at: {
483
+ workspace: CaseWorkspace;
484
+ info: DatasetInfo;
485
+ bars: ReadonlyMap<string, CaseBar>;
486
+ top: string;
487
+ dir: string;
488
+ proposer: string;
489
+ /** The held-out cases' folders. */
490
+ heldOut: readonly string[];
491
+ comparison: string;
492
+ },
493
+ ): LoopDeps {
494
+ const { options, environment } = context;
495
+ const { workspace, info, bars } = at;
496
+ const { runner, estimate, allowance } = externalsOf(environment);
497
+ // The share of a plan window at which a loop waits: `--allowance`, the local file's, or 90.
498
+ const limit = options.allowance ?? workspace.allowance;
499
+ // The agents a loop draws on, as far as it can name them: the proposer, and any parameter
500
+ // value that is a harness/model.
501
+ const named = () => [at.proposer, ...options.param.map((p) => p.slice(p.indexOf("=") + 1))];
502
+ // The store is the loop's for each run of trials alone: busy at the first, the command is
503
+ // refused, as any is; at a later one, the loop waits for it.
504
+ let ranOnce = false;
505
+ const wait =
506
+ allowance && limit !== "off"
507
+ ? waitingOnAllowance(async () => undefined, allowance, { limit, log: context.stderr })
508
+ : undefined;
509
+ return {
510
+ comparison: at.comparison,
511
+ log: (line) => context.stderr(line),
512
+ now: environment.now ?? (() => new Date()),
513
+ async waitForAllowance() {
514
+ if (wait) await wait({ argv: named() });
515
+ },
516
+ estimatedIn(runIds) {
517
+ return runIds.reduce((sum, id) => sum + estimatedIn(workspace.store, id), 0);
518
+ },
519
+ async checkGood({ cases }) {
520
+ const all = loadDataset(context, workspace, info.name, "all").cases;
521
+ const checks = await checkGoodRecords(
522
+ context,
523
+ workspace,
524
+ info,
525
+ all.filter((c) => cases.includes(c.name)),
526
+ );
527
+ if (checks.length === 0) return undefined;
528
+ return {
529
+ failing: checks.filter((c) => !c.passed).map((c) => c.case),
530
+ lines: checks.map((c) => c.line),
531
+ };
532
+ },
533
+ async room(runId) {
534
+ const run = readRunRecord(workspace.store, runId);
535
+ if (!run) return undefined;
536
+ return roomOf({
537
+ trials: readTrials(workspace.store, runId),
538
+ bars,
539
+ planned: run.asked.length,
540
+ gradingFile: comparingFile(info),
541
+ root: workspace.root,
542
+ tmp: tmpOf(context),
543
+ env: envOf(context),
544
+ timeoutMs: afterMsOf(info),
545
+ });
546
+ },
547
+ differed(runId) {
548
+ const run = readRunRecord(workspace.store, runId);
549
+ if (!run || run.columns.length < 2) return [];
550
+ const trials = bothRan(readTrials(workspace.store, runId), run.columns.length);
551
+ const ran = new Set(trials.map((t) => t.record.case));
552
+ const asked = { ...run, asked: run.asked.filter((a) => ran.has(a.case)) };
553
+ return differingCases(
554
+ rowsOf(workspace.store, asked, trials, bars, 0),
555
+ rowsOf(workspace.store, asked, trials, bars, 1),
556
+ );
557
+ },
558
+ async runFolders({ folders, order, budget, stopOnDecision, holdout, started }) {
559
+ const { budget: _, ...rest } = options;
560
+ const scoped: Context = {
561
+ ...context,
562
+ options: {
563
+ ...rest,
564
+ dataset: info.name,
565
+ yes: true,
566
+ fresh: false,
567
+ failed: false,
568
+ holdout: holdout ?? false,
569
+ against: [],
570
+ vary: [],
571
+ json: false,
572
+ dryRun: false,
573
+ ...(Number.isFinite(budget) ? { budget: Math.max(budget, 0.01) } : {}),
574
+ } satisfies Options,
575
+ };
576
+ const loop = readLoop(at.dir);
577
+ const given: RunGiven = {
578
+ folders,
579
+ order,
580
+ report: false,
581
+ ...(loop ? { loop: loopIdOf(loop) } : {}),
582
+ ...(ranOnce ? { waitForStore: true } : {}),
583
+ ...(started ? { started } : {}),
584
+ ...(stopOnDecision
585
+ ? {
586
+ stop: async (run, trials) => {
587
+ const said = (
588
+ await columnDecisions(scoped, {
589
+ workspace,
590
+ info,
591
+ run,
592
+ trials: bothRan(trials, folders.length),
593
+ bars,
594
+ })
595
+ )?.[0];
596
+ return said !== undefined && !("error" in said) && said.stop;
597
+ },
598
+ }
599
+ : {}),
600
+ };
601
+ ranOnce = true;
602
+ const done = await run(scoped, given);
603
+ const runId = done.id;
604
+ if (!runId) {
605
+ throw new Error(
606
+ `the try's run never started${done.unstarted ? `: ${done.unstarted}` : ""}`,
607
+ );
608
+ }
609
+ const record = readRunRecord(workspace.store, runId)!;
610
+ // Decided by nothing: the loop stops undecided, and resumes with this try.
611
+ if (record.broke) throw new Error(`the lab broke during run ${runId}: ${record.broke}`);
612
+ const trials = readTrials(workspace.store, runId);
613
+ const verdicts =
614
+ folders.length > 1
615
+ ? await columnDecisions(scoped, {
616
+ workspace,
617
+ info,
618
+ run: record,
619
+ trials: bothRan(trials, folders.length),
620
+ bars,
621
+ })
622
+ : undefined;
623
+ const first = verdicts?.[0];
624
+ const result: TryRun = {
625
+ labRun: runId,
626
+ ...(record.stopped ? { stopped: record.stopped } : {}),
627
+ ...(record.stopped === "precondition"
628
+ ? { precondition: preconditionFailure(trials) ?? "no trial says which" }
629
+ : {}),
630
+ ...(record.stopped === "stage"
631
+ ? { stage: stageFailure(trials) ?? "no trial says which" }
632
+ : {}),
633
+ ...(first
634
+ ? {
635
+ decision:
636
+ "error" in first
637
+ ? { error: first.error }
638
+ : {
639
+ decision: first.decision,
640
+ stop: first.stop,
641
+ reason: first.reason,
642
+ metrics: first.metrics,
643
+ },
644
+ }
645
+ : {}),
646
+ estimate: estimatedIn(workspace.store, runId),
647
+ };
648
+ return result;
649
+ },
650
+ feedback(runId, column) {
651
+ const views = readTrials(workspace.store, runId)
652
+ .filter((t) => t.record.column === column)
653
+ .map((t) => ({ ...t, view: trialOutcome(t.record, t.scores) }));
654
+ // An errored or leaked trial's outcome is not the workflow's: no change to it fixes one.
655
+ const notOurs = (outcome: string) => outcome === "errored" || outcome === "leaked";
656
+ const others = views
657
+ .filter((t) => notOurs(t.view.outcome))
658
+ .map(
659
+ ({ record, scores }) =>
660
+ `${record.case} trial ${record.trial}: ${whyNot({ record, scores })}`,
661
+ );
662
+ const trials = views
663
+ .filter((t) => !notOurs(t.view.outcome))
664
+ .map(({ record, scores, view }) => ({
665
+ case: record.case,
666
+ trial: record.trial,
667
+ outcome: view.outcome,
668
+ ms: record.ms,
669
+ ...(factsOf(scores) ? { facts: factsOf(scores) } : {}),
670
+ ...(record.runFacts ? { runFacts: record.runFacts } : {}),
671
+ ...(record.stageMs ? { stageMs: record.stageMs } : {}),
672
+ ...(record.workflowError ? { workflowError: record.workflowError } : {}),
673
+ ...(record.stopped ? { stopped: record.stopped } : {}),
674
+ grades: newestEntries(scores).map((e) => ({
675
+ grader: e.grader,
676
+ ...(e.verdict ? { verdict: e.verdict } : {}),
677
+ ...(e.numbers ? { numbers: e.numbers } : {}),
678
+ ...(e.reasons ? { reasons: e.reasons } : {}),
679
+ ...(e.parts
680
+ ? { parts: e.parts.map((p) => ({ about: p.about, label: p.label, why: p.why })) }
681
+ : {}),
682
+ ...(e.errored ? { errored: e.errored } : {}),
683
+ })),
684
+ }));
685
+ return { trials, others };
686
+ },
687
+ async propose({ tryDir, code, bundle, proposer }) {
688
+ // The copy's own install, which its box reads, not your checkout's.
689
+ const copyRoot = join(code, relative(at.top, workspace.root));
690
+ const folder = await (environment.inspect ?? inspectFolder)(
691
+ copyRoot,
692
+ checkTargetScript(join(copyRoot, relative(workspace.root, info.evalDir))),
693
+ );
694
+ const id = newRunId((environment.now ?? (() => new Date()))());
695
+ const own = join(tryDir, "proposer");
696
+ const runRoot = join(own, "runs");
697
+ mkdirSync(runRoot, { recursive: true });
698
+ const path = [folder.bin, (environment.env ?? process.env).PATH].filter(Boolean).join(":");
699
+ const lab = realpathSync(join(import.meta.dir, "../.."));
700
+ // It works in the try's folder, writes the copy but its `evals/`, and reads its bundle.
701
+ const box = boxSpec({
702
+ read: [lab, bundle, join(code, relative(at.top, workspace.evals))],
703
+ write: [code, own],
704
+ // The store and the lab's home whole but this try's folder, where the proposer works.
705
+ hide: [
706
+ ...hiddenOf(code, workspace, { keep: [tryDir] }),
707
+ ...heldOutOf(at.heldOut, workspace, copyRoot),
708
+ ],
709
+ network: [],
710
+ });
711
+ const result = await runner({
712
+ workflow: PROPOSER,
713
+ cwd: tryDir,
714
+ timeout: "30m",
715
+ argv: ["--runtime", proposer],
716
+ runRoot,
717
+ id,
718
+ awf: { bin: folder.awf.bin, dir: folder.awf.dir },
719
+ quiet: true,
720
+ env: { ...envOf(context), PATH: path },
721
+ in: writeBoxSpec(box, join(tryDir, "box.json")),
722
+ });
723
+ keepRuns(runRoot, awfRunsOf(workspace.store));
724
+ const record = result.record;
725
+ // A proposer cut short prints no record; its folder still says what its agent is estimated at.
726
+ const unrecorded =
727
+ record || !estimate ? undefined : await estimate(folder.awf, runRoot, id, envOf(context));
728
+ const estimated = record?.accounting.totals.estimate ?? unrecorded ?? 0;
729
+ if (record?.outcome !== "completed") {
730
+ return {
731
+ estimate: estimated,
732
+ ...(record ? { runId: record.runId } : {}),
733
+ why: `the proposer's run ${record?.outcome ?? "printed no record"}: ${
734
+ (record && "reason" in record ? record.reason : undefined) ??
735
+ result.unread ??
736
+ result.stderr.trim().split("\n").at(-1) ??
737
+ ""
738
+ }`,
739
+ };
740
+ }
741
+ const checked = checkSchema(HypothesisSchema, record.value);
742
+ if (!checked.ok) {
743
+ return {
744
+ estimate: estimated,
745
+ runId: record.runId,
746
+ why: describeProblems("the proposer's answer", checked.problems),
747
+ };
748
+ }
749
+ return { estimate: estimated, runId: record.runId, hypothesis: checked.value };
750
+ },
751
+ };
752
+ }
753
+
754
+ /**
755
+ * The trials of the cases every column has run: a try's run holds the best version so far's reused trials of
756
+ * every case from its start, and a comparison weighs only what both have.
757
+ */
758
+ function bothRan(trials: readonly StoredTrial[], columns: number): StoredTrial[] {
759
+ const ran = new Map<string, Set<number>>();
760
+ for (const t of trials) {
761
+ const seen = ran.get(t.record.case) ?? new Set<number>();
762
+ seen.add(t.record.column);
763
+ ran.set(t.record.case, seen);
764
+ }
765
+ return trials.filter((t) => (ran.get(t.record.case)?.size ?? 0) === columns);
766
+ }
767
+
768
+ /** What a run's trials and their grades are estimated at, as its `--budget` counted them. */
769
+ function estimatedIn(store: string, id: string): number {
770
+ const run = readRunRecord(store, id);
771
+ if (!run) return 0;
772
+ const span = runSpan(store, run);
773
+ return readTrials(store, id).reduce((sum, t) => sum + trialSpend(t, span), 0);
774
+ }