@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,489 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
4
+ import { DEFAULT_PROPOSER } from "../format/loop";
5
+ import type { DatasetEntry, LabConfig, LocalFile, LoopEntry } from "../format/settings";
6
+ import {
7
+ CONFIG_FILE,
8
+ checkLabConfig,
9
+ describeFiles,
10
+ type HelperPlace,
11
+ LOCAL_FILE,
12
+ readLocalFile,
13
+ TRIAL_FILE,
14
+ } from "./eval-files";
15
+ import { gitTop, projectOf } from "./git";
16
+ import { Refusal } from "./refusal";
17
+
18
+ /** A value and where it came from: a file, or the lab's default. */
19
+ export type Traced<T> = { value: T; from: string };
20
+
21
+ /** Where a value is when no file sets it. */
22
+ export const DEFAULT = "default";
23
+
24
+ /** A dataset as the project names it: an eval folder and a data folder, and its own values. */
25
+ export type DatasetRef = {
26
+ name: string;
27
+ /** The eval folder: `trial.ts`, `grading.ts`, `graders/`, `capture.ts`. */
28
+ eval: Traced<string>;
29
+ /** The data folder: `cases/`, and optionally `shared/`. */
30
+ data: Traced<string>;
31
+ /** Values over `trial.ts`'s defaults, by parameter. */
32
+ params: Record<string, Traced<string>>;
33
+ /** Where a copy of the dataset's records is kept: `{records}/{first commit}`. */
34
+ records?: Traced<string>;
35
+ /** The files that define it: its folder, the config, the local file. */
36
+ definedIn: string[];
37
+ };
38
+
39
+ /** A loop as its entry names it, merged from the config and the local file, each value traced. */
40
+ export type LoopRef = {
41
+ name: string;
42
+ dataset: Traced<string>;
43
+ /** The brief's path, resolved from `evals/`. */
44
+ brief: Traced<string>;
45
+ /** `edit`'s globs, relative to the project. */
46
+ allow: Traced<string[]>;
47
+ deny: Traced<string[]>;
48
+ proposer: Traced<string>;
49
+ trials: Traced<number>;
50
+ /** Values over the dataset's, by parameter. */
51
+ params: Record<string, Traced<string>>;
52
+ cases?: Traced<string[]>;
53
+ tags?: Traced<string[]>;
54
+ spread: Traced<boolean>;
55
+ /** The files that define it: the config, the local file. */
56
+ definedIn: string[];
57
+ };
58
+
59
+ export type CaseWorkspace = {
60
+ /** The project's `evals/`: the eval folders, the config and the local file. */
61
+ evals: string;
62
+ /** The project: the folder holding `evals/`, which `ignore`'s and `edit`'s globs are relative to. */
63
+ project: string;
64
+ /**
65
+ * Your checkout: the code folder, the first column. The nearest folder at or above `evals/`'s
66
+ * parent holding `node_modules/agentswf`, so a package of a monorepo is its own.
67
+ */
68
+ root: string;
69
+ /** The repository the code folder is in, for its git state; undefined outside one. */
70
+ repository?: string;
71
+ /** `evals/awf-lab.config.ts`, when the project has one. */
72
+ configFile?: string;
73
+ /** `evals/awf-lab.local.json`, when this machine has one. */
74
+ localFile?: string;
75
+ /**
76
+ * Where runs are kept: one store per project, `~/.awf/lab/{main checkout's folder}-{first commit}`, shared by every checkout
77
+ * of it.
78
+ */
79
+ store: string;
80
+ /** Globs relative to the project of files that aren't code under test. */
81
+ ignore: string[];
82
+ reuseDays: number;
83
+ concurrency: number;
84
+ /** How full the plan's usage window may get before a loop pauses, in percent. */
85
+ allowance: number;
86
+ /** The file each setting above came from, or `default`. */
87
+ from: Record<"store" | "ignore" | "reuseDays" | "concurrency" | "allowance", string>;
88
+ datasets: DatasetRef[];
89
+ loops: LoopRef[];
90
+ /** `~/.awf/lab`: where the default store and the trial files live, whatever `store` says. */
91
+ labHome: string;
92
+ };
93
+
94
+ export const REUSE_DAYS = 14;
95
+ const ALLOWANCE = 90;
96
+
97
+ function labHomeOf(home: string): string {
98
+ return join(home, ".awf", "lab");
99
+ }
100
+
101
+ export function inside(dir: string, target: string): boolean {
102
+ const path = relative(dir, target);
103
+ return path === "" || (path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path));
104
+ }
105
+
106
+ /** The project's `evals/`: the nearest here or above, as git finds its repository. */
107
+ export function findEvals(cwd: string): string | undefined {
108
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
109
+ const evals = join(dir, "evals");
110
+ if (existsSync(evals) && statSync(evals).isDirectory()) return evals;
111
+ if (basename(dir) === "evals") return dir;
112
+ if (dirname(dir) === dir) return undefined;
113
+ }
114
+ }
115
+
116
+ /** `~/x` from the home folder, anything else from `evals/`. */
117
+ const pathOf = (evals: string, home: string, path: string) =>
118
+ path === "~" || path.startsWith("~/") ? join(home, path.slice(1)) : resolve(evals, path);
119
+
120
+ function folders(dir: string): string[] {
121
+ if (!existsSync(dir)) return [];
122
+ return readdirSync(dir, { withFileTypes: true })
123
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
124
+ .map((entry) => entry.name)
125
+ .sort();
126
+ }
127
+
128
+ /**
129
+ * The folders of `evals/` that are datasets of their own: each with a `trial.ts` and `cases/`. A
130
+ * folder still holding the files they replaced is refused, saying so.
131
+ */
132
+ export function folderDatasets(evals: string): { name: string; dir: string }[] {
133
+ if (existsSync(join(evals, "awf-lab.json"))) {
134
+ throw new Refusal(
135
+ `${join(evals, "awf-lab.json")}: awf-lab.json is replaced by evals/${CONFIG_FILE} (defineLab) and the git-ignored evals/${LOCAL_FILE}`,
136
+ );
137
+ }
138
+ return folders(evals).flatMap((name) => {
139
+ const dir = join(evals, name);
140
+ if (!existsSync(join(dir, TRIAL_FILE))) {
141
+ for (const old of ["dataset.json", "env.ts", "graders.ts"]) {
142
+ if (existsSync(join(dir, old))) {
143
+ throw new Refusal(
144
+ `${join(dir, old)}: dataset.json, env.ts and graders.ts are replaced by trial.ts (defineTrial) and grading.ts (defineGrading)`,
145
+ );
146
+ }
147
+ }
148
+ return [];
149
+ }
150
+ return existsSync(join(dir, "cases")) ? [{ name, dir }] : [];
151
+ });
152
+ }
153
+
154
+ /**
155
+ * The project's names: in the store, `{main checkout}-{first commit}`; in a records folder, its
156
+ * first commit alone, which every clone shares whatever its folder is called.
157
+ */
158
+ function projectNames(root: string): { store: string; records: string } {
159
+ const project = projectOf(root);
160
+ if (project) return { store: `${project.name}-${project.first}`, records: project.first };
161
+ const hash = createHash("sha256").update(root).digest("hex").slice(0, 10);
162
+ return { store: `${basename(root)}-${hash}`, records: hash };
163
+ }
164
+
165
+ /** A glob that names nothing inside the project: absolute, or climbing out of it. */
166
+ function outsideProject(glob: string): boolean {
167
+ const clean = normalize(glob).replace(/\/+$/, "");
168
+ return isAbsolute(clean) || clean.split(/[\\/]/).includes("..") || clean === ".";
169
+ }
170
+
171
+ function checkIgnore(project: string, evals: string, file: string, globs: readonly string[]): void {
172
+ for (const glob of globs) {
173
+ const clean = normalize(glob).replace(/\/+$/, "");
174
+ if (outsideProject(glob)) {
175
+ throw new Refusal(
176
+ `${file}: ignore ${glob} must be a glob inside the project, relative to it`,
177
+ );
178
+ }
179
+ const trial = folders(evals)
180
+ .map((name) => relative(project, join(evals, name, TRIAL_FILE)))
181
+ .find((path) => new Bun.Glob(clean).match(path) || path.startsWith(`${clean}/`));
182
+ if (trial) {
183
+ throw new Refusal(`${file}: ignore ${glob} takes in ${trial}, which shapes every trial`);
184
+ }
185
+ }
186
+ }
187
+
188
+ /** Whether a path relative to the project is one of the globs': matched, or under a folder named. */
189
+ export function ignored(globs: readonly string[], path: string): boolean {
190
+ return globs.some((glob) => {
191
+ const clean = normalize(glob).replace(/\/+$/, "");
192
+ return new Bun.Glob(clean).match(path) || path.startsWith(`${clean}/`);
193
+ });
194
+ }
195
+
196
+ /**
197
+ * The project the lab runs in: its `evals/`, the config read in the helper, the local file read
198
+ * while git ignores it, and every dataset either names, merged with the folders' own.
199
+ */
200
+ export function openCaseWorkspace(
201
+ evals: string,
202
+ home: string,
203
+ place: Omit<HelperPlace, "root">,
204
+ ): CaseWorkspace {
205
+ evals = realpathSync(evals);
206
+ const repository = gitTop(evals);
207
+ const root = codeFolderOf(dirname(evals));
208
+ const labHome = labHomeOf(home);
209
+ const configFile = join(evals, CONFIG_FILE);
210
+ const localFile = join(evals, LOCAL_FILE);
211
+ let config: LabConfig = {};
212
+ if (existsSync(configFile)) {
213
+ config = checkLabConfig(configFile, describeFiles({ lab: configFile }, { ...place, root }).lab);
214
+ }
215
+ const local: LocalFile = existsSync(localFile) ? readLocalFile(localFile) : {};
216
+ const pick = <T>(fromLocal: T | undefined, fromConfig: T | undefined, otherwise: T): Traced<T> =>
217
+ fromLocal !== undefined
218
+ ? { value: fromLocal, from: localFile }
219
+ : fromConfig !== undefined
220
+ ? { value: fromConfig, from: configFile }
221
+ : { value: otherwise, from: DEFAULT };
222
+ const project = projectNames(root);
223
+ const store = pick(local.store, config.store, join(labHome, project.store));
224
+ if (store.from !== DEFAULT) {
225
+ store.value = pathOf(evals, home, store.value);
226
+ if (inside(repository ?? root, store.value)) {
227
+ throw new Refusal(
228
+ `${store.from}: store ${store.value} is inside the repository; keep runs outside it`,
229
+ );
230
+ }
231
+ }
232
+ const ignore = pick(undefined, config.ignore, [] as string[]);
233
+ checkIgnore(dirname(evals), evals, configFile, ignore.value);
234
+ const reuseDays = pick(undefined, config.reuse?.days, REUSE_DAYS);
235
+ const datasets = datasetRefs({
236
+ evals,
237
+ home,
238
+ root,
239
+ project: project.records,
240
+ config: { file: configFile, datasets: config.datasets ?? {} },
241
+ local: { file: localFile, datasets: local.datasets ?? {} },
242
+ });
243
+ const loops = loopRefs({
244
+ evals,
245
+ home,
246
+ datasets: datasets.map((d) => d.name),
247
+ config: { file: configFile, loops: config.loops ?? {} },
248
+ local: { file: localFile, loops: local.loops ?? {} },
249
+ });
250
+ const concurrency = pick(local.concurrency, undefined, 1);
251
+ const allowance = pick(local.allowance, undefined, ALLOWANCE);
252
+ return {
253
+ evals,
254
+ project: dirname(evals),
255
+ root,
256
+ ...(repository ? { repository } : {}),
257
+ ...(existsSync(configFile) ? { configFile } : {}),
258
+ ...(existsSync(localFile) ? { localFile } : {}),
259
+ store: store.value,
260
+ ignore: ignore.value,
261
+ reuseDays: reuseDays.value,
262
+ concurrency: concurrency.value,
263
+ allowance: allowance.value,
264
+ from: {
265
+ store: store.from,
266
+ ignore: ignore.from,
267
+ reuseDays: reuseDays.from,
268
+ concurrency: concurrency.from,
269
+ allowance: allowance.from,
270
+ },
271
+ datasets,
272
+ loops,
273
+ labHome,
274
+ };
275
+ }
276
+
277
+ function datasetRefs(args: {
278
+ evals: string;
279
+ home: string;
280
+ root: string;
281
+ project: string;
282
+ config: { file: string; datasets: Record<string, DatasetEntry> };
283
+ local: { file: string; datasets: Record<string, DatasetEntry> };
284
+ }): DatasetRef[] {
285
+ const { evals, home, root, config, local } = args;
286
+ const own = new Map(folderDatasets(evals).map((d) => [d.name, d.dir]));
287
+ const names = [
288
+ ...new Set([...own.keys(), ...Object.keys(config.datasets), ...Object.keys(local.datasets)]),
289
+ ].sort();
290
+ return names.map((name): DatasetRef => {
291
+ const fromConfig = config.datasets[name];
292
+ const fromLocal = local.datasets[name];
293
+ const folder = own.get(name);
294
+ const definedIn = [
295
+ ...(folder ? [folder] : []),
296
+ ...(fromConfig ? [config.file] : []),
297
+ ...(fromLocal ? [local.file] : []),
298
+ ];
299
+ // The local file over the config, field by field; a folder dataset's own folder under both.
300
+ const given = <K extends "eval" | "data" | "records">(field: K) =>
301
+ fromLocal?.[field] !== undefined
302
+ ? { value: fromLocal[field]!, from: local.file }
303
+ : fromConfig?.[field] !== undefined
304
+ ? { value: fromConfig[field]!, from: config.file }
305
+ : undefined;
306
+ const place = (field: "eval" | "data"): Traced<string> => {
307
+ const named = given(field);
308
+ if (named) return { value: pathOf(evals, home, named.value), from: named.from };
309
+ if (folder) return { value: folder, from: folder };
310
+ throw new Refusal(
311
+ `${definedIn.at(-1)}: dataset ${name} names no ${field} folder: give "${field}", relative to evals/`,
312
+ );
313
+ };
314
+ const evalDir = place("eval");
315
+ const dataDir = place("data");
316
+ if (!existsSync(join(evalDir.value, TRIAL_FILE))) {
317
+ throw new Refusal(
318
+ `${evalDir.from}: dataset ${name}'s eval folder ${evalDir.value} has no ${TRIAL_FILE}`,
319
+ );
320
+ }
321
+ if (!inside(root, evalDir.value)) {
322
+ throw new Refusal(
323
+ `${evalDir.from}: dataset ${name}'s eval folder ${evalDir.value} is outside the code folder ${root}: it is code, kept with the code`,
324
+ );
325
+ }
326
+ if (!existsSync(dataDir.value) || !statSync(dataDir.value).isDirectory()) {
327
+ throw new Refusal(
328
+ `${dataDir.from}: dataset ${name}'s data folder ${dataDir.value} doesn't exist`,
329
+ );
330
+ }
331
+ const params: Record<string, Traced<string>> = {};
332
+ for (const [entry, file] of [
333
+ [fromConfig, config.file],
334
+ [fromLocal, local.file],
335
+ ] as const) {
336
+ for (const [param, value] of Object.entries(entry?.params ?? {})) {
337
+ params[param] = { value, from: file };
338
+ }
339
+ }
340
+ const records = given("records");
341
+ return {
342
+ name,
343
+ eval: evalDir,
344
+ data: dataDir,
345
+ params,
346
+ ...(records
347
+ ? {
348
+ records: {
349
+ value: join(pathOf(evals, home, records.value), args.project),
350
+ from: records.from,
351
+ },
352
+ }
353
+ : {}),
354
+ definedIn,
355
+ };
356
+ });
357
+ }
358
+
359
+ /**
360
+ * Every loop the config or the local file names: the local entry over the config's of its name,
361
+ * field by field, `params` by parameter, as datasets merge.
362
+ */
363
+ function loopRefs(args: {
364
+ evals: string;
365
+ home: string;
366
+ datasets: readonly string[];
367
+ config: { file: string; loops: Record<string, LoopEntry> };
368
+ local: { file: string; loops: Record<string, LoopEntry> };
369
+ }): LoopRef[] {
370
+ const { evals, home, config, local } = args;
371
+ const names = [...new Set([...Object.keys(config.loops), ...Object.keys(local.loops)])].sort();
372
+ return names.map((name): LoopRef => {
373
+ const fromConfig = Object.hasOwn(config.loops, name) ? config.loops[name] : undefined;
374
+ const fromLocal = Object.hasOwn(local.loops, name) ? local.loops[name] : undefined;
375
+ const definedIn = [...(fromConfig ? [config.file] : []), ...(fromLocal ? [local.file] : [])];
376
+ const where = definedIn.at(-1)!;
377
+ const given = <T>(read: (entry: LoopEntry) => T | undefined): Traced<T> | undefined => {
378
+ const mine = fromLocal ? read(fromLocal) : undefined;
379
+ if (mine !== undefined) return { value: mine, from: local.file };
380
+ const theirs = fromConfig ? read(fromConfig) : undefined;
381
+ return theirs !== undefined ? { value: theirs, from: config.file } : undefined;
382
+ };
383
+ const needed = <T>(field: string, read: (entry: LoopEntry) => T | undefined): Traced<T> => {
384
+ const found = given(read);
385
+ if (!found) throw new Refusal(`${where}: loop ${name} needs ${field}`);
386
+ return found;
387
+ };
388
+ const dataset = needed("dataset, the dataset it tunes on", (e) => e.dataset);
389
+ if (!args.datasets.includes(dataset.value)) {
390
+ throw new Refusal(
391
+ `${dataset.from}: loop ${name}'s dataset ${dataset.value} is no dataset; known: ${args.datasets.join(", ") || "none"}`,
392
+ );
393
+ }
394
+ const brief = needed("brief, a file relative to evals/ the proposer reads", (e) => e.brief);
395
+ const allow = needed('edit.allow, the files a try may edit; ["**"] for anything', (e) =>
396
+ e.edit?.allow ? [...e.edit.allow] : undefined,
397
+ );
398
+ const deny = given((e) => (e.edit?.deny ? [...e.edit.deny] : undefined)) ?? {
399
+ value: [],
400
+ from: DEFAULT,
401
+ };
402
+ for (const [field, list] of [
403
+ ["allow", allow],
404
+ ["deny", deny],
405
+ ] as const) {
406
+ const bad = list.value.find(outsideProject);
407
+ if (bad !== undefined) {
408
+ throw new Refusal(
409
+ `${list.from}: loop ${name}'s edit.${field} ${bad} must be a glob inside the project, relative to it`,
410
+ );
411
+ }
412
+ }
413
+ const params: Record<string, Traced<string>> = {};
414
+ for (const [entry, file] of [
415
+ [fromConfig, config.file],
416
+ [fromLocal, local.file],
417
+ ] as const) {
418
+ for (const [param, value] of Object.entries(entry?.params ?? {})) {
419
+ params[param] = { value, from: file };
420
+ }
421
+ }
422
+ const cases = given((e) => e.cases && [...e.cases]);
423
+ const tags = given((e) => e.tags && [...e.tags]);
424
+ return {
425
+ name,
426
+ dataset,
427
+ brief: { value: pathOf(evals, home, brief.value), from: brief.from },
428
+ allow,
429
+ deny,
430
+ proposer: given((e) => e.proposer) ?? { value: DEFAULT_PROPOSER, from: DEFAULT },
431
+ trials: given((e) => e.trials) ?? { value: 1, from: DEFAULT },
432
+ params,
433
+ ...(cases ? { cases } : {}),
434
+ ...(tags ? { tags } : {}),
435
+ spread: given((e) => e.spread) ?? { value: true, from: DEFAULT },
436
+ definedIn,
437
+ };
438
+ });
439
+ }
440
+
441
+ /** The loop a command is for, by its entry's name. */
442
+ export function chooseLoop(workspace: CaseWorkspace, name: string): LoopRef {
443
+ const found = workspace.loops.find((l) => l.name === name);
444
+ if (found) return found;
445
+ const known = workspace.loops.map((l) => l.name);
446
+ throw new Refusal(
447
+ `no loop ${name}: a loop is an entry of loops in evals/${CONFIG_FILE} or evals/${LOCAL_FILE}${known.length > 0 ? `; known: ${known.join(", ")}` : ""}`,
448
+ );
449
+ }
450
+
451
+ /** The nearest folder at or above `from` holding `node_modules/agentswf`; `from` when none does. */
452
+ export function codeFolderOf(from: string): string {
453
+ for (let at = from; ; at = dirname(at)) {
454
+ if (existsSync(join(at, "node_modules", "agentswf"))) return at;
455
+ if (dirname(at) === at) return from;
456
+ }
457
+ }
458
+
459
+ /** The dataset a command is for: `--dataset`, or the only one. */
460
+ export function chooseDataset(workspace: CaseWorkspace, name?: string): DatasetRef {
461
+ const found = workspace.datasets;
462
+ if (name !== undefined) {
463
+ const named = found.find((d) => d.name === name);
464
+ if (!named) {
465
+ throw new Refusal(
466
+ `no dataset ${name} in ${workspace.evals}; known: ${found.map((d) => d.name).join(", ") || "none"}`,
467
+ );
468
+ }
469
+ return named;
470
+ }
471
+ if (found.length === 1) return found[0]!;
472
+ if (found.length === 0) {
473
+ throw new Refusal(
474
+ `no dataset in ${workspace.evals}; awf-lab case new {dataset}/{case} makes one`,
475
+ );
476
+ }
477
+ throw new Refusal(
478
+ `more than one dataset: name one with --dataset (${found.map((d) => d.name).join(", ")})`,
479
+ );
480
+ }
481
+
482
+ /** The records folders of every dataset that keeps one. */
483
+ export const recordsFolders = (workspace: CaseWorkspace) => [
484
+ ...new Set(workspace.datasets.flatMap((d) => (d.records ? [d.records.value] : []))),
485
+ ];
486
+
487
+ /** The records folder of a dataset, by its name, when it keeps one. */
488
+ export const recordsOf = (workspace: CaseWorkspace, dataset: string) =>
489
+ workspace.datasets.find((d) => d.name === dataset)?.records?.value;
@@ -0,0 +1,84 @@
1
+ // awf run packages/lab/src/loop/propose.workflow.ts --cwd {try} -- [--runtime harness/model]
2
+ //
3
+ // A loop's proposer: one agent reads `bundle/`, which awf-lab built from the tuning cases alone,
4
+ // changes the copy of the code in `code/`, and answers with its hypothesis.
5
+ // `bundle/brief.md`, the loop entry's, steers it; the rules of a try are here. It runs in the lab's
6
+ // box, which lets it write `code/` but not `code/evals/`, and awf-lab checks the files it changed
7
+ // against the entry's `edit` before anything runs them.
8
+ import { defineWorkflow, type ExecutionConfig, type WorkflowInvocation } from "agentswf/workflow";
9
+ import { DEFAULT_PROPOSER, type Hypothesis, HypothesisSchema } from "../format/loop";
10
+
11
+ export { DEFAULT_PROPOSER };
12
+
13
+ type Args = { runtime: string };
14
+
15
+ const PROMPT = `You are the proposer in a loop that improves a workflow against cases with known answers. Your working directory holds:
16
+
17
+ - \`bundle/brief.md\`: the operator's brief: what to improve, and what is known about the problem. Read it first and follow it.
18
+ - \`bundle/feedback.json\`: how the current code did on each tuning case and trial: its facts; its run facts, from the run's own record (\`_turns\`, \`_turns_{outcome}\`, \`_turns_by_{agent}\`), and its time and each stage's in ms, which say where a slow or stopped trial spent its time; its outcome; and every grader's verdict, numbers, reasons and parts.
19
+ - \`bundle/history.json\`: every earlier try, its change, its prediction and what the comparison decided. Do not repeat a discarded idea unchanged.
20
+ - \`bundle/rules.json\`: how a try is judged, the spend left, and \`edit\`: the files you may change, globs relative to \`code/{edit.root}\`. A file may change only when \`allow\` matches it and \`deny\` doesn't, and never one \`alwaysDenied\` names; a try that changes any other is refused before it runs. \`unsteady\`, when given, lists the cases that came out differently between two runs of the unchanged start, so their outcome moves on its own: weigh what they show as noise.
21
+ - \`code/\`: a copy of the project's code, the best so far. \`code/evals/\` holds how the dataset is measured and is read-only.
22
+
23
+ Change only files \`edit\` allows in \`code/\`, and nothing else anywhere. Your shell is your only tool: read and write files with it.
24
+
25
+ The rules of a try:
26
+
27
+ 1. One hypothesis: change one thing about how the workflow works, such as a prompt, its steps, or the model per stage, and say why it should do better on what the feedback shows it doing badly.
28
+ 2. Aim at a gain the comparison can see; a change too small to show is wasted.
29
+ 3. Describe failures in general terms. Never copy case content into the code: no names, values, text or files from the feedback. It runs on cases you have not seen.
30
+ 4. Keep the workflow's arguments and its result's shape; do not touch \`code/evals/\` or any \`node_modules\`.
31
+
32
+ Answer with the change, the hypothesis, the predicted effect and its cost, and what the trials must show if it holds.`;
33
+
34
+ /** Every harness's effort levels: the lab may not import the harness package, so it repeats them. */
35
+ export const LEVELS: readonly string[] = [
36
+ "off",
37
+ "minimal",
38
+ "low",
39
+ "medium",
40
+ "high",
41
+ "xhigh",
42
+ "max",
43
+ "ultra",
44
+ ];
45
+
46
+ /** `harness/model[:effort]`, headless: the box has no terminal to put an agent in. */
47
+ function proposerRuntime(name: string): ExecutionConfig {
48
+ const slash = name.indexOf("/");
49
+ if (slash <= 0 || slash === name.length - 1) {
50
+ throw new Error(`the proposer is harness/model, not ${name}`);
51
+ }
52
+ const colon = name.lastIndexOf(":");
53
+ const level = colon > slash ? name.slice(colon + 1) : undefined;
54
+ const effort = level && LEVELS.includes(level) ? level : undefined;
55
+ const harness = name.slice(0, slash);
56
+ return {
57
+ harness,
58
+ model: name.slice(slash + 1, effort ? colon : undefined),
59
+ ...(effort ? { effort } : {}),
60
+ placement: "headless",
61
+ } as ExecutionConfig;
62
+ }
63
+
64
+ export default defineWorkflow<Args, Hypothesis>({
65
+ meta: {
66
+ name: "loop-proposer",
67
+ description: "Change a copy of a workflow's code from the tuning cases' feedback.",
68
+ },
69
+ async run(wf, args) {
70
+ const agent = await wf.agents.open({ key: "proposer", runtime: proposerRuntime(args.runtime) });
71
+ const { outcome } = await agent.run({ prompt: PROMPT, schema: HypothesisSchema });
72
+ if (!outcome.answered) throw new Error(`no proposal: ${outcome.kind}: ${outcome.reason}`);
73
+ return outcome.value as Hypothesis;
74
+ },
75
+ prepare: (invocation: WorkflowInvocation) => {
76
+ const [flag, value, ...rest] = invocation.argv;
77
+ if (flag === undefined) return { runtime: DEFAULT_PROPOSER };
78
+ if (flag !== "--runtime" || !value || rest.length > 0) {
79
+ throw new Error("the proposer takes --runtime harness/model, or nothing");
80
+ }
81
+ return { runtime: value };
82
+ },
83
+ present: (hypothesis) => `${hypothesis.change}\n${hypothesis.predicted}`,
84
+ });