@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,864 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ appendFileSync,
4
+ copyFileSync,
5
+ cpSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { join, relative } from "node:path";
14
+ import type { Room } from "../env/compare";
15
+ import {
16
+ FINAL_KIND,
17
+ type Final,
18
+ FinalSchema,
19
+ type Hypothesis,
20
+ LOOP_KIND,
21
+ type Loop,
22
+ LoopSchema,
23
+ PROPOSAL_KIND,
24
+ type Proposal,
25
+ ProposalSchema,
26
+ SPREAD_KIND,
27
+ type Spread,
28
+ SpreadSchema,
29
+ TRY_KIND,
30
+ type Try,
31
+ TrySchema,
32
+ } from "../format/loop";
33
+ import type { ComparedMetric } from "../shared/compare";
34
+ import { checkSchema, describeProblems } from "../shared/validate";
35
+ import type { CaseInfo } from "./dataset";
36
+ import {
37
+ ALWAYS_DENIED,
38
+ branchCode,
39
+ changedFiles,
40
+ changeOf,
41
+ commitTry,
42
+ copyStart,
43
+ outOfScope,
44
+ outsideGit,
45
+ } from "./loop-code";
46
+ import { PRECONDITION_STOP } from "./outcome";
47
+ import { Refusal } from "./refusal";
48
+ import { usd } from "./text";
49
+ import type { CaseWorkspace } from "./workspace";
50
+
51
+ // The loop: a proposer changes a copy of the best version so far, the copy runs against it on the
52
+ // tuning cases until the dataset's `compare` stops it, and it becomes the best version so far only
53
+ // on `better`. Its code and records live in the store, `loops/{id}/`.
54
+
55
+ /** The entry's brief as the loop started with it, beside `loop.json`. */
56
+ export const BRIEF_FILE = "brief.md";
57
+
58
+ /** A try's own change against its parent's code, beside its records. */
59
+ export const CHANGE_FILE = "change.patch";
60
+
61
+ /** The trials not the workflow's a try lists for a person, at most; the report has the rest. */
62
+ const OTHERS_SHOWN = 10;
63
+
64
+ /** The start run twice before the first try, beside `loop.json`. */
65
+ export const SPREAD_FILE = "spread.json";
66
+
67
+ /** How many tries in a row that kept nothing stop a loop's command: the stall a person should look at. */
68
+ export const STALL = 3;
69
+
70
+ /**
71
+ * A loop's id, as `runs` lists it and `report --loop` takes it: its name and when it started, as
72
+ * `desk-20261129-101112`.
73
+ */
74
+ export const loopIdOf = (loop: Pick<Loop, "name" | "started">) =>
75
+ `${loop.name}-${loop.started.replace(/[-:]/g, "").replace("T", "-").slice(0, 15)}`;
76
+
77
+ export type LoopFolder = { dir: string; loop: Loop } | { dir: string; unread: string };
78
+
79
+ /**
80
+ * Every loop folder of the store, oldest first: its loop, or why its `loop.json` doesn't read, as
81
+ * one from before the loop's entry doesn't.
82
+ */
83
+ export function readLoopFolders(store: string): LoopFolder[] {
84
+ const root = join(store, "loops");
85
+ if (!existsSync(root)) return [];
86
+ const found = readdirSync(root).flatMap((name): LoopFolder[] => {
87
+ const dir = join(root, name);
88
+ if (!existsSync(join(dir, "loop.json"))) return [];
89
+ try {
90
+ return [{ dir, loop: readLoop(dir)! }];
91
+ } catch (error) {
92
+ const first = (error as Error).message.split("\n")[1]?.trim();
93
+ return [{ dir, unread: `loop.json${first ? `: ${first}` : " doesn't read"}` }];
94
+ }
95
+ });
96
+ const at = (f: LoopFolder) => ("loop" in f ? f.loop.started : "");
97
+ return found.sort((a, b) => (at(a) < at(b) ? -1 : 1));
98
+ }
99
+
100
+ /** Every loop in the store that reads, oldest first. */
101
+ export const readLoops = (store: string): { dir: string; loop: Loop }[] =>
102
+ readLoopFolders(store).flatMap((f) => ("loop" in f ? [f] : []));
103
+
104
+ /** The newest loop of a name, which `loop run`, `final` and `patch` act on. */
105
+ export const newestLoop = (store: string, name: string) =>
106
+ readLoops(store)
107
+ .filter((l) => l.loop.name === name)
108
+ .at(-1);
109
+
110
+ export const loopDirOf = (store: string, id: string) => join(store, "loops", id);
111
+
112
+ /** The tuning cases in the loop's seeded order: by a digest of the loop's name and each case's. */
113
+ function seededOrder(name: string, cases: readonly string[]): string[] {
114
+ const rank = (c: string) => createHash("sha256").update(`${name}\0${c}`).digest("hex");
115
+ return [...cases].sort((a, b) => (rank(a) < rank(b) ? -1 : 1));
116
+ }
117
+
118
+ const writeJson = (file: string, value: unknown, flag = "w") =>
119
+ writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { flag });
120
+
121
+ function readChecked<T>(file: string, schema: Parameters<typeof checkSchema>[0]): T {
122
+ const value = JSON.parse(readFileSync(file, "utf8"));
123
+ const checked = checkSchema(schema, value);
124
+ if (!checked.ok) throw new Error(describeProblems(file, checked.problems));
125
+ return checked.value as T;
126
+ }
127
+
128
+ export function readLoop(dir: string): Loop | undefined {
129
+ const file = join(dir, "loop.json");
130
+ return existsSync(file) ? readChecked<Loop>(file, LoopSchema) : undefined;
131
+ }
132
+
133
+ export function readTries(dir: string): Try[] {
134
+ const root = join(dir, "tries");
135
+ if (!existsSync(root)) return [];
136
+ return readdirSync(root)
137
+ .filter((entry) => existsSync(join(root, entry, "try.json")))
138
+ .map((entry) => readChecked<Try>(join(root, entry, "try.json"), TrySchema))
139
+ .sort((a, b) => a.n - b.n);
140
+ }
141
+
142
+ /** The start run twice before the first try, if it ran or was skipped. */
143
+ export function readSpread(dir: string): Spread | undefined {
144
+ const file = join(dir, SPREAD_FILE);
145
+ return existsSync(file) ? readChecked<Spread>(file, SpreadSchema) : undefined;
146
+ }
147
+
148
+ export function readFinals(dir: string): Final[] {
149
+ const root = join(dir, "finals");
150
+ if (!existsSync(root)) return [];
151
+ return readdirSync(root)
152
+ .filter((f) => f.endsWith(".json"))
153
+ .map((f) => readChecked<Final>(join(root, f), FinalSchema))
154
+ .sort((a, b) => a.k - b.k);
155
+ }
156
+
157
+ /** The code of try `n`, or the start's for 0. */
158
+ export const codeOf = (dir: string, n: number) =>
159
+ n === 0 ? join(dir, "start") : join(dir, "tries", String(n), "code");
160
+
161
+ /**
162
+ * The version a loop's code runs under, in place of `target.ts`'s: the loop's own id of it, the
163
+ * start's from the loop's name and when it started, a try's with its number. A loop started again
164
+ * has another, so it shares no trial with the one before it.
165
+ */
166
+ export const loopVersionOf = (loop: Pick<Loop, "name" | "started">, n: number) =>
167
+ `loop ${loop.name} ${loop.started}${n === 0 ? "" : ` try ${n}`}`;
168
+
169
+ /** Try `n`'s code, or the start's for 0, as a column of a run. */
170
+ const columnOf = (loop: Loop, dir: string, n: number) => ({
171
+ dir: codeOf(dir, n),
172
+ version: loopVersionOf(loop, n),
173
+ });
174
+
175
+ /** The best version so far: the last kept try, or the start. */
176
+ export const bestSoFarOf = (tries: readonly Try[]) =>
177
+ tries.filter((t) => t.outcome === "kept").at(-1)?.n ?? 0;
178
+
179
+ /** What a try's run gave the loop: its run, how it ended, the decision on the second column. */
180
+ export type TryRun = {
181
+ labRun: string;
182
+ /**
183
+ * `budget`, the cap stopped it; `compare`, the comparison did; `precondition`, the environment;
184
+ * `stage`, a case named a stage its run never entered.
185
+ */
186
+ stopped?: "budget" | "compare" | "precondition" | "stage";
187
+ /** Under a precondition stop, the last trial's: `"{what}" failed: {message}`. */
188
+ precondition?: string;
189
+ /** Under a stage stop, the trial's reason. */
190
+ stage?: string;
191
+ decision?:
192
+ | {
193
+ decision: string;
194
+ stop: boolean;
195
+ reason: string;
196
+ /** The comparison's metrics, the second column's minus the first's. */
197
+ metrics?: readonly ComparedMetric[];
198
+ }
199
+ | { error: string };
200
+ /** The estimates of its own trials and grades, not those it reused. */
201
+ estimate: number;
202
+ };
203
+
204
+ /** A case that came out differently between a run's two columns, each one's passes. */
205
+ export type Differed = { case: string; a: string; b: string };
206
+
207
+ /** What the loop is given to run trials and its proposer: `loop-command.ts` binds these to `run`. */
208
+ export type LoopDeps = {
209
+ /** The cases in `order` on these folders, the reference first, under a cap; `stop` per case. */
210
+ runFolders(args: {
211
+ /** Each folder with the loop's id of its code, its version. */
212
+ folders: readonly { dir: string; version: string }[];
213
+ order: readonly string[];
214
+ budget: number;
215
+ stopOnDecision: boolean;
216
+ holdout?: boolean;
217
+ /** Called with the run's id as it starts, before any trial. */
218
+ started?: (runId: string) => void;
219
+ }): Promise<TryRun>;
220
+ /** What these runs' own trials and their grades are estimated at, from the store's records. */
221
+ estimatedIn(runIds: readonly string[]): number;
222
+ /**
223
+ * The known good records of these cases, those that have one, graded with no trial: the cases
224
+ * whose record failed, and a line each. Undefined when none has one.
225
+ */
226
+ checkGood(args: {
227
+ cases: readonly string[];
228
+ }): Promise<{ failing: string[]; lines: string[] } | undefined>;
229
+ /** The cases of a two-column run that came out differently between its columns. */
230
+ differed(runId: string): Differed[];
231
+ /**
232
+ * What the dataset's comparison says of a run of the start, every column of it the start's: how
233
+ * many cases a try could still win, and how many it must. Undefined when it can't tell.
234
+ */
235
+ room(runId: string): Promise<Room | undefined>;
236
+ /**
237
+ * The feedback of a run's column, for the proposer's bundle: the trials whose outcome is the
238
+ * workflow's. `others` are the rest, a line each, for a person.
239
+ */
240
+ feedback(runId: string, column: number): { trials: unknown[]; others: string[] };
241
+ /** The proposer, in the box: its answer and its estimate. */
242
+ propose(args: {
243
+ tryDir: string;
244
+ code: string;
245
+ bundle: string;
246
+ proposer: string;
247
+ }): Promise<{ hypothesis?: Hypothesis; why?: string; estimate: number; runId?: string }>;
248
+ /** Waits while a plan window the loop draws on is nearly used. */
249
+ waitForAllowance(): Promise<void>;
250
+ /** The comparison's version, from `grading.ts`, as a loop records it. */
251
+ comparison: string;
252
+ log(line: string): void;
253
+ now(): Date;
254
+ };
255
+
256
+ export type LoopRequest = {
257
+ name: string;
258
+ dir: string;
259
+ top: string;
260
+ workspace: CaseWorkspace;
261
+ /** The tuning cases: those the entry picks of the cases the dataset doesn't hold out. */
262
+ tuning: readonly CaseInfo[];
263
+ holdout: readonly string[];
264
+ tries: number;
265
+ /** This command's cap on its estimates: a loop keeps none of its own. */
266
+ budget: number;
267
+ /** What the entry says now; a new loop records it, and a resumed one was checked against it. */
268
+ definition: LoopDefinition;
269
+ /** The entry's brief, which a new loop copies. */
270
+ briefFile: string;
271
+ /** The project in a copy, the folder holding `evals/`, which `edit`'s globs are relative to. */
272
+ project: string;
273
+ from: { path: string; commit: string | null; dirty: boolean };
274
+ /** A new loop's start, which its id and folder are named by. */
275
+ started: string;
276
+ };
277
+
278
+ /** What a loop's entry said, as its record keeps it: a resume is refused one that differs. */
279
+ export type LoopDefinition = Pick<
280
+ Loop,
281
+ "dataset" | "brief" | "edit" | "proposer" | "trials" | "params" | "cases" | "tags" | "spread"
282
+ >;
283
+
284
+ /** The fields of the definition, in the order a refusal names them. */
285
+ const DEFINITION_FIELDS = [
286
+ "dataset",
287
+ "brief",
288
+ "edit",
289
+ "proposer",
290
+ "trials",
291
+ "params",
292
+ "cases",
293
+ "tags",
294
+ "spread",
295
+ ] as const satisfies readonly (keyof LoopDefinition)[];
296
+
297
+ /** The fields of a loop's entry that differ now from what its record kept, each said. */
298
+ export function changedDefinition(loop: Loop, now: LoopDefinition): string[] {
299
+ const said = (field: keyof LoopDefinition, value: unknown) =>
300
+ value === undefined
301
+ ? "none"
302
+ : field === "edit"
303
+ ? `allow ${(value as Loop["edit"]).allow.join(", ")}${(value as Loop["edit"]).deny.length > 0 ? ` · deny ${(value as Loop["edit"]).deny.join(", ")}` : ""}`
304
+ : Array.isArray(value)
305
+ ? value.join(", ") || "none"
306
+ : String(value);
307
+ return DEFINITION_FIELDS.flatMap((field) => {
308
+ if (JSON.stringify(loop[field]) === JSON.stringify(now[field])) return [];
309
+ if (field === "brief") return ["its brief"];
310
+ return [`${field} ${said(field, loop[field])}, now ${said(field, now[field])}`];
311
+ });
312
+ }
313
+
314
+ export type LoopOutcome = { exit: 0 | 1 | 3; why: string };
315
+
316
+ /**
317
+ * These cases' known good records: one that fails is the case's to fix, and a loop's cases are
318
+ * fixed, so the loop is refused. Free: no trial or agent runs, so nothing counts toward the cap.
319
+ */
320
+ async function checkGood(deps: LoopDeps, cases: readonly string[], which: string): Promise<void> {
321
+ const checked = await deps.checkGood({ cases });
322
+ if (!checked) return;
323
+ if (checked.failing.length > 0) {
324
+ for (const line of checked.lines) deps.log(` ${line}`);
325
+ throw new Refusal(
326
+ `the known good record of ${which} case ${checked.failing.join(", ")} fails: the case's to fix, and a loop's cases are fixed; awf-lab case check --cases ${checked.failing.join(",")} checks it again`,
327
+ );
328
+ }
329
+ deps.log(`the known good records: ${checked.lines.join("; ")}`);
330
+ }
331
+
332
+ /** The loop as it stands, made or resumed; a resumed loop is refused what would judge tries apart. */
333
+ function startOrResume(request: LoopRequest, deps: LoopDeps): Loop {
334
+ const { dir } = request;
335
+ const loop = readLoop(dir);
336
+ const tuning = seededOrder(
337
+ request.name,
338
+ request.tuning.map((c) => c.name),
339
+ );
340
+ if (loop) {
341
+ const now = {
342
+ holdout: JSON.stringify([...request.holdout].sort()),
343
+ comparison: deps.comparison,
344
+ };
345
+ const then = {
346
+ holdout: JSON.stringify(loop.holdout),
347
+ comparison: loop.comparison,
348
+ };
349
+ const moved = (Object.keys(now) as (keyof typeof now)[]).filter((k) => now[k] !== then[k]);
350
+ if (moved.length > 0) {
351
+ throw new Refusal(
352
+ `loop ${loop.name} was started with another ${moved.join(", ")}: a loop's tries are judged alike; loop run ${loop.name} --new starts another`,
353
+ );
354
+ }
355
+ const present = new Set(tuning);
356
+ const gone = loop.tuning.filter((name) => !present.has(name));
357
+ if (gone.length > 0) {
358
+ throw new Refusal(
359
+ `loop ${loop.name}'s tuning case${gone.length === 1 ? "" : "s"} ${gone.join(", ")} ${gone.length === 1 ? "is" : "are"} no longer in ${loop.dataset}: a loop's tuning cases are fixed; restore ${gone.length === 1 ? "it" : "them"}, or loop run ${loop.name} --new starts another`,
360
+ );
361
+ }
362
+ return loop;
363
+ }
364
+ if (existsSync(dir)) {
365
+ throw new Refusal(
366
+ `loop ${loopIdOf(request)} is already in the store: start it again in a second`,
367
+ );
368
+ }
369
+ mkdirSync(dir, { recursive: true });
370
+ copyFileSync(request.briefFile, join(dir, BRIEF_FILE));
371
+ copyStart(request.top, codeOf(dir, 0), request.workspace);
372
+ const made: Loop = {
373
+ kind: LOOP_KIND,
374
+ name: request.name,
375
+ started: request.started,
376
+ from: request.from,
377
+ ...request.definition,
378
+ tuning,
379
+ holdout: [...request.holdout].sort(),
380
+ comparison: deps.comparison,
381
+ };
382
+ writeJson(join(dir, "loop.json"), made, "wx");
383
+ return made;
384
+ }
385
+
386
+ /**
387
+ * What a loop's records are estimated at so far: its spread, every try decided and one cut short,
388
+ * and every final check. `report --loop` gives it; a command's `--budget` counts only its own.
389
+ */
390
+ export function loopEstimates(
391
+ dir: string,
392
+ estimatedIn: LoopDeps["estimatedIn"],
393
+ ): { spread: number; tries: number; pending?: { n: number; estimate: number }; finals: number } {
394
+ const deps = { estimatedIn } as Pick<LoopDeps, "estimatedIn">;
395
+ const file = join(dir, SPREAD_FILE);
396
+ const spread = existsSync(file) ? readChecked<Spread>(file, SpreadSchema) : undefined;
397
+ const tries = readTries(dir);
398
+ const n = tries.length + 1;
399
+ const pending = tryLedger(join(dir, "tries", String(n)), deps).total();
400
+ return {
401
+ spread:
402
+ spread && "estimate" in spread
403
+ ? spread.estimate
404
+ : tryLedger(join(dir, "spread"), deps).total(),
405
+ tries: tries.reduce((sum, t) => sum + t.estimate.proposer + t.estimate.trials, 0),
406
+ ...(pending > 0 ? { pending: { n, estimate: pending } } : {}),
407
+ finals: readFinals(dir).reduce((sum, f) => sum + f.estimate, 0),
408
+ };
409
+ }
410
+
411
+ /**
412
+ * What a try is estimated at, kept as it goes so a cut loses none of it: the runs it started, in
413
+ * `runs.json`, whose trials and grades the store's records price; and each proposer run's
414
+ * estimate, in `proposer.jsonl`. Both sit outside what the proposer's box may write.
415
+ */
416
+ function tryLedger(tryDir: string, deps: Pick<LoopDeps, "estimatedIn">) {
417
+ const runsFile = join(tryDir, "runs.json");
418
+ const proposerFile = join(tryDir, "proposer.jsonl");
419
+ const runs = (): string[] =>
420
+ existsSync(runsFile) ? (JSON.parse(readFileSync(runsFile, "utf8")) as string[]) : [];
421
+ const proposer = () =>
422
+ existsSync(proposerFile)
423
+ ? readFileSync(proposerFile, "utf8")
424
+ .split("\n")
425
+ .filter(Boolean)
426
+ .reduce((sum, line) => sum + (JSON.parse(line) as { usd: number }).usd, 0)
427
+ : 0;
428
+ const estimate = () => ({ proposer: proposer(), trials: deps.estimatedIn(runs()) });
429
+ return {
430
+ started(runId: string) {
431
+ mkdirSync(tryDir, { recursive: true });
432
+ writeJson(runsFile, [...new Set([...runs(), runId])]);
433
+ },
434
+ proposed(usd: number, runId?: string) {
435
+ appendFileSync(proposerFile, `${JSON.stringify({ usd, ...(runId ? { runId } : {}) })}\n`);
436
+ },
437
+ estimate,
438
+ total: () => {
439
+ const { proposer, trials } = estimate();
440
+ return proposer + trials;
441
+ },
442
+ };
443
+ }
444
+
445
+ export const digestOf = (bytes: Uint8Array) =>
446
+ `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
447
+
448
+ /**
449
+ * Tries until --tries, the cap or a stall. Each try: the best version so far runs on the tuning cases (its
450
+ * trials reused where nothing changed), the proposer changes a copy of it from that feedback, the
451
+ * change's scope is checked, and the copy runs against it case by case until `compare`
452
+ * stops it. Every try is written once, so a loop resumes where it stopped, its estimates summed
453
+ * from its own records.
454
+ */
455
+ export async function runLoop(request: LoopRequest, deps: LoopDeps): Promise<LoopOutcome> {
456
+ // A new loop's tuning cases are checked on their known good records before anything is written,
457
+ // so a refused start leaves nothing behind; a resumed loop's, before its next step.
458
+ const fresh = !readLoop(request.dir);
459
+ if (fresh) {
460
+ await checkGood(
461
+ deps,
462
+ request.tuning.map((c) => c.name),
463
+ "tuning",
464
+ );
465
+ }
466
+ const loop = startOrResume(request, deps);
467
+ if (!fresh) await checkGood(deps, loop.tuning, "tuning");
468
+ const { dir } = request;
469
+ const byName = new Map(request.tuning.map((c) => [c.name, c]));
470
+ // Every one is there: startOrResume refuses a loop whose tuning case is gone.
471
+ const tuning = loop.tuning.map((name) => byName.get(name)!);
472
+ const evals = relative(request.top, request.workspace.evals);
473
+ const tries = readTries(dir);
474
+ if (!fresh) deps.log(`loop ${loopIdOf(loop)} goes on`);
475
+ // The budget is this command's: what the loop's records already hold is counted under it, so
476
+ // the sums below run over the loop's whole history.
477
+ const earlier = loopEstimates(dir, deps.estimatedIn);
478
+ const cap = request.budget + earlier.spread + earlier.tries + (earlier.pending?.estimate ?? 0);
479
+ let estimated = tries.reduce((sum, t) => sum + t.estimate.proposer + t.estimate.trials, 0);
480
+ const capped = (what: string): LoopOutcome => ({
481
+ exit: 3,
482
+ why: `this command's estimates reach its --budget of ${usd(request.budget)}${what}: loop run ${loop.name} again goes on`,
483
+ });
484
+ const unready = (ran: TryRun, what: string): LoopOutcome => ({
485
+ exit: 3,
486
+ why: `${what} ${ran.labRun} stopped: ${PRECONDITION_STOP}: ${ran.precondition ?? "no trial says which"}; nothing decided: awf-lab loop run ${loop.name} again once it holds`,
487
+ });
488
+ // A stage never entered is the dataset's, and would be again in every run: nothing decided.
489
+ const misnamed = (ran: TryRun, what: string): LoopOutcome => ({
490
+ exit: 3,
491
+ why: `${what} ${ran.labRun} stopped: ${ran.stage ?? "a stage the case named was never entered"}; nothing decided`,
492
+ });
493
+ const spreadFile = join(dir, SPREAD_FILE);
494
+ const spreadLedger = tryLedger(join(dir, "spread"), deps);
495
+ let spread = existsSync(spreadFile) ? readChecked<Spread>(spreadFile, SpreadSchema) : undefined;
496
+ if (!spread && tries.length === 0) {
497
+ if (!loop.spread) {
498
+ spread = { kind: SPREAD_KIND, at: deps.now().toISOString(), skipped: true };
499
+ writeJson(spreadFile, spread, "wx");
500
+ } else {
501
+ const left = () => cap - estimated - spreadLedger.total();
502
+ if (left() <= 0) return capped(" by the start's spread");
503
+ await deps.waitForAllowance();
504
+ deps.log(`the start twice, on ${tuning.length} tuning cases`);
505
+ // Two columns of the same code: reuse gives each its own trials, and try 1's run of the
506
+ // start reuses them, so the spread costs one more run of the start, once.
507
+ const ran = await deps.runFolders({
508
+ folders: [columnOf(loop, dir, 0), columnOf(loop, dir, 0)],
509
+ order: loop.tuning,
510
+ budget: left(),
511
+ stopOnDecision: false,
512
+ started: spreadLedger.started,
513
+ });
514
+ if (ran.stopped === "budget" || left() <= 0) {
515
+ return capped(` by the start's spread, run ${ran.labRun}`);
516
+ }
517
+ if (ran.stopped === "precondition") return unready(ran, "the start's spread: its run");
518
+ if (ran.stopped === "stage") return misnamed(ran, "the start's spread: its run");
519
+ // A column with no trial of the workflow's measures nothing; unrecorded, a resume measures again.
520
+ if ([0, 1].some((column) => deps.feedback(ran.labRun, column).trials.length === 0)) {
521
+ return {
522
+ exit: 3,
523
+ why: `the start's spread: every trial of a column of run ${ran.labRun} was errored or leaked, so it measures nothing; nothing decided: awf-lab report ${ran.labRun}`,
524
+ };
525
+ }
526
+ const measured = spreadOf(ran, deps.differed(ran.labRun), {
527
+ at: deps.now().toISOString(),
528
+ trials: loop.trials,
529
+ cases: tuning.length,
530
+ estimate: spreadLedger.total(),
531
+ });
532
+ writeJson(spreadFile, measured, "wx");
533
+ deps.log(spreadLine(measured));
534
+ const warning = spreadWarning(measured, loop.name);
535
+ if (warning) deps.log(warning);
536
+ spread = measured;
537
+ }
538
+ }
539
+ // Before the first try: a try is kept only once it wins enough cases, and it can win only one the
540
+ // start doesn't always pass. Too few such, and no try could be kept, however good.
541
+ if (tries.length === 0 && spread && "labRun" in spread) {
542
+ const room = await deps.room(spread.labRun);
543
+ if (room && room.canWin < room.needed) {
544
+ return {
545
+ exit: 3,
546
+ why: `no try could be kept on these cases: ${room.what}; nothing decided: add cases the workflow fails, or lower minWon, then loop run ${loop.name} --new starts another`,
547
+ };
548
+ }
549
+ }
550
+ estimated += spread && "estimate" in spread ? spread.estimate : spreadLedger.total();
551
+ const unsteady = spread && "unsteady" in spread ? spread.unsteady : undefined;
552
+ /** What a try's why says of the start's spread: the cases it moved on that also moved alone. */
553
+ const againstSpread = (runId: string) => {
554
+ if (!unsteady) return " (the start's spread not measured)";
555
+ const moved = new Set(unsteady.map((d) => d.case));
556
+ const k = deps.differed(runId).filter((d) => moved.has(d.case)).length;
557
+ return k > 0
558
+ ? ` (${k} of the cases it won or lost also differed between two runs of the start)`
559
+ : " (none of them differed between two runs of the start)";
560
+ };
561
+
562
+ /** One try, decided; or why the loop stops before it is. */
563
+ const oneTry = async (): Promise<LoopOutcome | undefined> => {
564
+ const n = tries.length + 1;
565
+ const parent = bestSoFarOf(tries);
566
+ const tryDir = join(dir, "tries", String(n));
567
+ const code = codeOf(dir, n);
568
+ // What this try is estimated at, from records it keeps across a cut: the runs it started, read from
569
+ // the store, and what each proposer run was estimated at.
570
+ const ledger = tryLedger(tryDir, deps);
571
+ const left = () => cap - estimated - ledger.total();
572
+ if (left() <= 0) return capped("");
573
+ const decide = (fields: Omit<Try, "kind" | "n" | "at" | "parent" | "estimate">) => {
574
+ const record: Try = {
575
+ kind: TRY_KIND,
576
+ n,
577
+ at: deps.now().toISOString(),
578
+ parent,
579
+ ...fields,
580
+ estimate: ledger.estimate(),
581
+ };
582
+ writeJson(join(tryDir, "try.json"), record, "wx");
583
+ tries.push(record);
584
+ estimated += record.estimate.proposer + record.estimate.trials;
585
+ deps.log(`try ${n}: ${record.outcome}: ${record.why}`);
586
+ return record;
587
+ };
588
+
589
+ // A try cut short after its proposal resumes with it; before, it is proposed again.
590
+ const proposalFile = join(tryDir, "proposal.json");
591
+ let proposal: Proposal | undefined =
592
+ existsSync(proposalFile) && existsSync(code)
593
+ ? readChecked<Proposal>(proposalFile, ProposalSchema)
594
+ : undefined;
595
+ if (proposal) deps.log(`try ${n}: resumed against try ${parent}, ${usd(left())} left`);
596
+ else {
597
+ for (const part of ["code", "bundle"]) {
598
+ rmSync(join(tryDir, part), { recursive: true, force: true });
599
+ }
600
+ mkdirSync(tryDir, { recursive: true });
601
+ await deps.waitForAllowance();
602
+ deps.log(
603
+ `try ${n}: the best version so far, try ${parent}, on ${tuning.length} tuning cases`,
604
+ );
605
+ const fed = await deps.runFolders({
606
+ folders: [columnOf(loop, dir, parent)],
607
+ order: loop.tuning,
608
+ budget: left(),
609
+ stopOnDecision: false,
610
+ started: ledger.started,
611
+ });
612
+ if (fed.stopped === "budget" || left() <= 0)
613
+ return capped(` by the best version so far's run ${fed.labRun}`);
614
+ if (fed.stopped === "precondition")
615
+ return unready(fed, `try ${n}: the best version so far's run`);
616
+ if (fed.stopped === "stage") return misnamed(fed, `try ${n}: the best version so far's run`);
617
+ const feedback = deps.feedback(fed.labRun, 0);
618
+ const others = feedback.others;
619
+ if (others.length > 0) {
620
+ const shown = others.slice(0, OTHERS_SHOWN);
621
+ const more = others.length - shown.length;
622
+ deps.log(
623
+ `try ${n}: ${others.length} trial${others.length === 1 ? "" : "s"} not the workflow's, left out of the proposer's feedback:`,
624
+ );
625
+ for (const line of shown) deps.log(` ${line}`);
626
+ if (more > 0) deps.log(` and ${more} more: awf-lab report ${fed.labRun}`);
627
+ }
628
+ // Nothing of the workflow's to learn from: a proposal would be a guess, at the proposer's cost.
629
+ if (feedback.trials.length === 0) {
630
+ return {
631
+ exit: 3,
632
+ why: `try ${n}: every trial of the best version so far's run ${fed.labRun} was errored or leaked, so the proposer has nothing to read; nothing decided: awf-lab report ${fed.labRun}`,
633
+ };
634
+ }
635
+ branchCode(codeOf(dir, parent), code, request.top);
636
+ const bundle = join(tryDir, "bundle");
637
+ mkdirSync(bundle, { recursive: true });
638
+ copyFileSync(join(dir, BRIEF_FILE), join(bundle, BRIEF_FILE));
639
+ writeJson(join(bundle, "feedback.json"), feedback.trials);
640
+ writeJson(
641
+ join(bundle, "history.json"),
642
+ tries.map(({ n, parent, outcome, why, hypothesis, changed }) => ({
643
+ n,
644
+ parent,
645
+ outcome,
646
+ why,
647
+ ...(hypothesis ? { hypothesis } : {}),
648
+ changed,
649
+ })),
650
+ );
651
+ writeJson(join(bundle, "rules.json"), {
652
+ comparison: loop.comparison,
653
+ cases: tuning.length,
654
+ trials: loop.trials,
655
+ budgetLeft: Number(left().toFixed(2)),
656
+ // The files a try may edit, relative to `code/{root}`: `allow` and not `deny`, and never
657
+ // `alwaysDenied`'s.
658
+ edit: {
659
+ root: request.project,
660
+ allow: loop.edit.allow,
661
+ deny: loop.edit.deny,
662
+ alwaysDenied: [...ALWAYS_DENIED],
663
+ },
664
+ // The cases that came out differently between two runs of the start: noise, not signal.
665
+ ...(unsteady ? { unsteady } : {}),
666
+ });
667
+ await deps.waitForAllowance();
668
+ deps.log(`try ${n}: proposing against try ${parent}`);
669
+ const answer = await deps.propose({ tryDir, code, bundle, proposer: loop.proposer });
670
+ ledger.proposed(answer.estimate, answer.runId);
671
+ if (!answer.hypothesis) {
672
+ decide({
673
+ outcome: "failed",
674
+ why: answer.why ?? "the proposer gave no hypothesis",
675
+ changed: [],
676
+ });
677
+ return undefined;
678
+ }
679
+ commitTry(code, n);
680
+ writeFileSync(join(tryDir, CHANGE_FILE), changeOf(code));
681
+ proposal = {
682
+ kind: PROPOSAL_KIND,
683
+ hypothesis: answer.hypothesis,
684
+ estimate: answer.estimate,
685
+ feedback: fed.estimate,
686
+ ...(answer.runId ? { runId: answer.runId } : {}),
687
+ };
688
+ writeJson(proposalFile, proposal, "wx");
689
+ }
690
+ const { hypothesis } = proposal;
691
+ const changed = changedFiles(code);
692
+ const problems = [
693
+ ...outOfScope(
694
+ code,
695
+ changed,
696
+ { evals, project: request.project, top: request.top, edit: loop.edit },
697
+ tuning,
698
+ ),
699
+ ...outsideGit(code, request.top),
700
+ ];
701
+ if (problems.length > 0) {
702
+ decide({ outcome: "refused", why: problems.join("; "), hypothesis, changed });
703
+ return undefined;
704
+ }
705
+ if (left() <= 0) return capped(` by try ${n}'s proposer`);
706
+ await deps.waitForAllowance();
707
+ const ran = await deps.runFolders({
708
+ folders: [columnOf(loop, dir, parent), columnOf(loop, dir, n)],
709
+ order: loop.tuning,
710
+ budget: left(),
711
+ stopOnDecision: true,
712
+ started: ledger.started,
713
+ });
714
+ if (ran.stopped === "budget") return capped(` during try ${n}'s run ${ran.labRun}`);
715
+ if (ran.stopped === "precondition") return unready(ran, `try ${n}: its run`);
716
+ if (ran.stopped === "stage") return misnamed(ran, `try ${n}: its run`);
717
+ const decided = ran.decision && "decision" in ran.decision ? ran.decision : undefined;
718
+ decide({
719
+ outcome: !decided ? "failed" : decided.decision === "better" ? "kept" : "discarded",
720
+ why: decided
721
+ ? `${decided.decision}${decided.stop ? "" : ", not stopped"}: ${decided.reason}${againstSpread(ran.labRun)}`
722
+ : ran.decision && "error" in ran.decision
723
+ ? `the comparison failed: ${ran.decision.error}`
724
+ : "no comparison: the dataset has no compare",
725
+ hypothesis,
726
+ changed,
727
+ labRun: ran.labRun,
728
+ decision: decided?.decision ?? null,
729
+ });
730
+ return undefined;
731
+ };
732
+ // A stall stops this command, not the loop: run it again, after a look, and it goes on.
733
+ const before = tries.length;
734
+ for (let made = 0; made < request.tries; made++) {
735
+ const stopped = await oneTry();
736
+ if (stopped) return stopped;
737
+ const recent = tries.slice(before).slice(-STALL);
738
+ if (recent.length === STALL && recent.every((t) => t.outcome !== "kept")) {
739
+ return {
740
+ exit: 0,
741
+ why: `${STALL} tries in a row kept nothing: look at them before running more; run the loop again to go on`,
742
+ };
743
+ }
744
+ }
745
+ return { exit: 0, why: `${request.tries} ${request.tries === 1 ? "try" : "tries"} made` };
746
+ }
747
+
748
+ /**
749
+ * The final check: the kept code against the start, on the held-out cases no try saw. Each check
750
+ * is recorded; a second one says it was asked again.
751
+ */
752
+ export async function runFinal(
753
+ request: { dir: string; budget: number },
754
+ deps: LoopDeps,
755
+ ): Promise<LoopOutcome> {
756
+ const loop = readLoop(request.dir);
757
+ if (!loop) throw new Refusal(`no loop at ${request.dir}`);
758
+ if (loop.holdout.length === 0) {
759
+ throw new Refusal(`${loop.dataset} holds out no case: nothing for a final check`);
760
+ }
761
+ const kept = bestSoFarOf(readTries(request.dir));
762
+ if (kept === 0)
763
+ return { exit: 1, why: `loop ${loop.name} kept nothing: there is nothing to check` };
764
+ await checkGood(deps, loop.holdout, "held-out");
765
+ const ran = await deps.runFolders({
766
+ folders: [columnOf(loop, request.dir, 0), columnOf(loop, request.dir, kept)],
767
+ order: loop.holdout,
768
+ budget: request.budget,
769
+ stopOnDecision: false,
770
+ holdout: true,
771
+ });
772
+ // Not a check: nothing recorded, so the next is not counted as asked again.
773
+ if (ran.stopped === "precondition") {
774
+ return {
775
+ exit: 3,
776
+ why: `the final check's run ${ran.labRun} stopped: ${PRECONDITION_STOP}: ${ran.precondition ?? "no trial says which"}; run it again once it holds`,
777
+ };
778
+ }
779
+ if (ran.stopped === "stage") {
780
+ return {
781
+ exit: 3,
782
+ why: `the final check's run ${ran.labRun} stopped: ${ran.stage ?? "a stage the case named was never entered"}`,
783
+ };
784
+ }
785
+ const finals = join(request.dir, "finals");
786
+ mkdirSync(finals, { recursive: true });
787
+ const k = readFinals(request.dir).length + 1;
788
+ const decided = ran.decision && "decision" in ran.decision ? ran.decision : undefined;
789
+ const why = decided
790
+ ? `${decided.decision}: ${decided.reason}`
791
+ : ran.decision && "error" in ran.decision
792
+ ? `the comparison failed: ${ran.decision.error}`
793
+ : "no comparison";
794
+ const record: Final = {
795
+ kind: FINAL_KIND,
796
+ k,
797
+ at: deps.now().toISOString(),
798
+ kept,
799
+ labRun: ran.labRun,
800
+ decision: decided?.decision ?? null,
801
+ why,
802
+ estimate: ran.estimate,
803
+ };
804
+ writeJson(join(finals, `${k}.json`), record, "wx");
805
+ const again = k > 1 ? ` (checked ${k - 1} time${k > 2 ? "s" : ""} before)` : "";
806
+ return {
807
+ exit: ran.stopped === "budget" ? 3 : 0,
808
+ why: `final check ${k}${again}: try ${kept} against the start on ${loop.holdout.length} held-out cases: ${why}`,
809
+ };
810
+ }
811
+
812
+ type MeasuredSpread = Extract<Spread, { labRun: string }>;
813
+
814
+ /** The spread's record, from its run: the comparison of the start with itself. */
815
+ function spreadOf(
816
+ ran: TryRun,
817
+ unsteady: Differed[],
818
+ at: { at: string; trials: number; cases: number; estimate: number },
819
+ ): MeasuredSpread {
820
+ const decided = ran.decision && "decision" in ran.decision ? ran.decision : undefined;
821
+ const primary = decided?.metrics?.find((m) => m.role === "primary");
822
+ return {
823
+ kind: SPREAD_KIND,
824
+ at: at.at,
825
+ labRun: ran.labRun,
826
+ trials: at.trials,
827
+ cases: at.cases,
828
+ decision: decided?.decision ?? null,
829
+ ...(primary ? { primary: { name: primary.name, difference: primary.difference } } : {}),
830
+ unsteady,
831
+ estimate: at.estimate,
832
+ };
833
+ }
834
+
835
+ /** What the loop says of its spread, measured. */
836
+ function spreadLine(spread: MeasuredSpread): string {
837
+ const { primary, unsteady } = spread;
838
+ const by = primary
839
+ ? `${primary.name} ${primary.difference === null ? "no difference" : `${primary.difference >= 0 ? "+" : ""}${primary.difference.toFixed(2)}`}`
840
+ : (spread.decision ?? "no comparison");
841
+ const names = unsteady.length > 0 ? ` (${unsteady.map((d) => d.case).join(", ")})` : "";
842
+ return `the start twice: ${by}, ${unsteady.length} of ${spread.cases} cases differed${names}`;
843
+ }
844
+
845
+ /** The spread's warning, from the loop's record, for the command's closing block. */
846
+ export function spreadWarningOf(dir: string): string | undefined {
847
+ const file = join(dir, SPREAD_FILE);
848
+ const name = readLoop(dir)?.name ?? "";
849
+ return existsSync(file)
850
+ ? spreadWarning(readChecked<Spread>(file, SpreadSchema), name)
851
+ : undefined;
852
+ }
853
+
854
+ /** The warning when the comparison told the start from itself; a resume can't change trials. */
855
+ function spreadWarning(spread: Spread | undefined, name: string): string | undefined {
856
+ if (!spread || !("labRun" in spread)) return undefined;
857
+ if (spread.decision !== "better" && spread.decision !== "worse") return undefined;
858
+ return `the comparison told the start from itself (${spread.decision}): its decisions are noise-prone at ${spread.trials} trial${spread.trials === 1 ? "" : "s"}; raise the entry's trials, and loop run ${name} --new starts another`;
859
+ }
860
+
861
+ /** Copies a boxed run's records into the store's, where `awf logs` finds them. */
862
+ export function keepRuns(from: string, storeRuns: string): void {
863
+ if (existsSync(from)) cpSync(from, storeRuns, { recursive: true });
864
+ }