@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,182 @@
1
+ import type { Mock } from "bun:test";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { Mocks } from "./mock";
5
+ import { parseRoute, type RouteHandler } from "./routes";
6
+ import { type HttpRequest, shared } from "./state";
7
+
8
+ // biome-ignore lint/suspicious/noExplicitAny: a module's functions, of any signature.
9
+ type AnyFunction = (...args: any[]) => any;
10
+ // biome-ignore lint/suspicious/noExplicitAny: a class, faked only by name.
11
+ type AnyClass = abstract new (...args: any[]) => any;
12
+
13
+ /** The keys of `T` a fake may stand in for: its functions, and its classes by name. */
14
+ export type FakeableKeys<T> = {
15
+ [K in keyof T]-?: T[K] extends AnyFunction | AnyClass ? K : never;
16
+ }[keyof T] &
17
+ string;
18
+
19
+ /** A spy as `bun:test` makes it, typed as the function it stands in for. */
20
+ export type Spy<F> = F extends AnyFunction ? F & Mock<F> : F;
21
+
22
+ /** What `trial.mock` returns: each function's spy, by name. */
23
+ export type Spies<T> = { [K in FakeableKeys<T>]: Spy<T[K]> };
24
+
25
+ /** A stand-in typed as `T`, whose function members are spies. */
26
+ export type Faked<T> = T & { [K in FakeableKeys<T>]: Spy<T[K]> };
27
+
28
+ export type Routes = Record<string, RouteHandler>;
29
+
30
+ export type Trial<P extends Readonly<Record<string, string>> = Readonly<Record<string, string>>> = {
31
+ /** The case's `input.json`, typed where it is read: `const input: { today: string } = trial.input`. `{}` without one. */
32
+ // biome-ignore lint/suspicious/noExplicitAny: typed by the reader, as `JSON.parse` is.
33
+ readonly input: any;
34
+ /** The built case folder: the data folder's `shared/` and the case's `input/`, merged. */
35
+ readonly dir: string;
36
+ /** The trial's empty working folder, the run's `--cwd`. */
37
+ readonly scratch: string;
38
+ /** The code folder: your checkout, or the folder `--against` names. */
39
+ readonly root: string;
40
+ /**
41
+ * The trial's parameters: each one `trial.ts` declares, from its default, a dataset entry,
42
+ * `--param` or `--vary`. Turn them into argv or a module to load; a value is always a string.
43
+ */
44
+ readonly params: P;
45
+ /** A file of the case folder (`dir`), parsed as JSON. */
46
+ // biome-ignore lint/suspicious/noExplicitAny: typed by the reader, as `JSON.parse` is.
47
+ readJson<T = any>(name: string): T;
48
+ /** A file of the case folder (`dir`), as text. */
49
+ readText(name: string): string;
50
+ /**
51
+ * Replaces every function the module exports, as `jest.mock(path)` with no factory does, but a
52
+ * function not faked throws when called instead of returning `undefined`, unless named in
53
+ * `real`. Takes the imported module, not its path, so the fakes are typed. Classes stay real
54
+ * unless faked by name. `name` is where the trial record keeps the fakes' calls,
55
+ * `calls.{name}.{function}`; a name used twice is refused. Returns each function's `bun:test`
56
+ * mock.
57
+ */
58
+ mock<M extends object>(
59
+ name: string,
60
+ module: M,
61
+ fakes: { [K in FakeableKeys<M>]?: M[K] },
62
+ options?: { real?: readonly string[] },
63
+ ): Spies<M>;
64
+ /**
65
+ * A strict stand-in for an object a factory returns. `name` labels its refusals, and is where
66
+ * the trial record keeps its calls; `fake`, then `fake2` and on, unless given.
67
+ */
68
+ fake<T extends object>(fakes: Partial<T>, options?: { name?: string }): Faked<T>;
69
+ /** Answers the workflow's `fetch` from routes keyed `"{METHOD} {URL pattern}"`. */
70
+ mockFetch: ((routes: Routes) => void) & {
71
+ readonly requests: readonly HttpRequest[];
72
+ /**
73
+ * Lets this case's requests to one host, such as a live host its input names, through
74
+ * to the real `fetch`, as `sandbox.network.code` does for every case. A host no route names; under the
75
+ * lab's box, one the box's network reaches too, as it reaches only the dataset's.
76
+ */
77
+ allow(host: string): void;
78
+ };
79
+ /** Teardown, run after `evidence` even when the run fails, last given first. */
80
+ cleanup(fn: () => unknown): void;
81
+ /**
82
+ * A precondition, in `setup`: what must hold before the workflow runs (the site answers, a name
83
+ * is fresh). A falsy value or a throw errors the trial as the dataset's, code `precondition`, and
84
+ * the workflow never runs; two in a row stop the run. Gives back what `check` returned.
85
+ */
86
+ require<T>(what: string, check: () => T | Promise<T>): Promise<T>;
87
+ };
88
+
89
+ export type TrialFolders = {
90
+ dir: string;
91
+ scratch: string;
92
+ root: string;
93
+ params: Record<string, string>;
94
+ };
95
+
96
+ export function makeTrial(folders: TrialFolders, mocks: Mocks, cleanups: (() => unknown)[]): Trial {
97
+ const read = (name: string) => readFileSync(join(folders.dir, name), "utf8");
98
+ const inputFile = join(folders.dir, "input.json");
99
+ const input = existsSync(inputFile) ? JSON.parse(readFileSync(inputFile, "utf8")) : {};
100
+ const state = shared();
101
+
102
+ const http = (routes: Routes) => {
103
+ if (!state.realFetch) {
104
+ throw new Error("trial.mockFetch needs the lab's fetch preload: run the case with awf-lab");
105
+ }
106
+ const parsed = Object.entries(routes).map(([key, handler]) => parseRoute(key, handler));
107
+ for (const route of parsed) {
108
+ if (state.routes.some((each) => each.key === route.key)) {
109
+ throw new Error(`trial.mockFetch: "${route.key}" is routed twice`);
110
+ }
111
+ }
112
+ state.routes.push(...parsed);
113
+ };
114
+ Object.defineProperty(http, "requests", { get: () => state.requests });
115
+ const allow = (host: string) => {
116
+ if (!state.realFetch) {
117
+ throw new Error(
118
+ "trial.mockFetch.allow needs the lab's fetch preload: run the case with awf-lab",
119
+ );
120
+ }
121
+ if (typeof host !== "string" || !/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i.test(host)) {
122
+ throw new Error(
123
+ `trial.mockFetch.allow takes a host name, such as tenant.example.com: got ${JSON.stringify(host)}`,
124
+ );
125
+ }
126
+ if (state.routes.some((route) => route.hostname === host.toLowerCase())) {
127
+ throw new Error(
128
+ `trial.mockFetch.allow: ${host} has routes in this case, so it can't also go to the real fetch`,
129
+ );
130
+ }
131
+ state.allowed.push(host.toLowerCase());
132
+ };
133
+ Object.assign(http, { allow });
134
+
135
+ return {
136
+ input,
137
+ dir: folders.dir,
138
+ scratch: folders.scratch,
139
+ root: folders.root,
140
+ params: Object.freeze({ ...folders.params }),
141
+ readJson: (name) => JSON.parse(read(name)),
142
+ readText: read,
143
+ mock: (name, module, fakes, options) =>
144
+ mocks.module(name, module, fakes as Record<string, unknown>, options) as never,
145
+ fake: (fakes, options) => mocks.fake(fakes, options) as never,
146
+ mockFetch: http as Trial["mockFetch"],
147
+ cleanup: (fn) => {
148
+ cleanups.push(fn);
149
+ },
150
+ require: (what, check) => {
151
+ const checked = (async () => {
152
+ if (state.phase !== "setup") {
153
+ throw new CaseWiring(`trial.require("${what}") belongs in setup, not ${state.phase}`);
154
+ }
155
+ let value: Awaited<ReturnType<typeof check>>;
156
+ try {
157
+ value = await check();
158
+ } catch (error) {
159
+ throw failed(what, error instanceof Error ? error.message : String(error));
160
+ }
161
+ if (!value) throw failed(what);
162
+ return value;
163
+ })();
164
+ // One not awaited still errors the trial, through `state.precondition`: never as an
165
+ // unhandled rejection, which would end the process.
166
+ checked.catch(() => {});
167
+ return checked;
168
+ },
169
+ };
170
+
171
+ function failed(what: string, message?: string): PreconditionFailed {
172
+ const reason = `precondition "${what}" failed${message ? `: ${message}` : ""}`;
173
+ state.precondition ??= reason;
174
+ return new PreconditionFailed(reason);
175
+ }
176
+ }
177
+
178
+ /** A precondition `trial.require` found failed. */
179
+ export class PreconditionFailed extends Error {}
180
+
181
+ /** `trial` used where it can't be: the dataset's to fix. */
182
+ export class CaseWiring extends Error {}
@@ -0,0 +1,144 @@
1
+ import { isMap, isScalar, parseDocument } from "yaml";
2
+ import { type Checked, checkSchema, explainProblems, type Problem } from "../shared/validate";
3
+ import {
4
+ BoundSchema,
5
+ type Expected,
6
+ type Key,
7
+ KeySchema,
8
+ passProblem,
9
+ runFactNameProblem,
10
+ SETTINGS_PATTERNS,
11
+ } from "./settings";
12
+
13
+ /** A `key.md`: its frontmatter, checked, and the note below it. */
14
+ export type ReadKey = { key: Key; note: string };
15
+
16
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;
17
+
18
+ /** A fact name a key may not give: `error` is checked on every trial. `_` names are run facts. */
19
+ const RESERVED = (name: string) => name === "error";
20
+
21
+ /** Why an `expect` value is no bound or run fact's value, or undefined. */
22
+ function expectedProblem(name: string, value: Expected): string | undefined {
23
+ // The schema's pattern leaves a `_` name's value unchecked.
24
+ if (name.startsWith("_") && !checkSchema(BoundSchema, value).ok && typeof value !== "number") {
25
+ return `is a run fact, a number: give a number or a bound, such as { max: 3 }, not ${JSON.stringify(value)}`;
26
+ }
27
+ if (value !== null && typeof value === "object") {
28
+ const { min, max } = value;
29
+ if (min === undefined && max === undefined) {
30
+ return "is a bound with neither min nor max: give one, such as { max: 3 }";
31
+ }
32
+ if (min !== undefined && max !== undefined && min > max) {
33
+ return `is a bound whose min ${min} is past its max ${max}`;
34
+ }
35
+ return undefined;
36
+ }
37
+ return undefined;
38
+ }
39
+
40
+ /** A key field written as the wrong kind of value, in a line. */
41
+ const KINDS: Record<string, (value: unknown) => string> = {
42
+ must: () => 'must is a list: write each criterion on its own line, starting "- "',
43
+ "must-not": () => 'must-not is a list: write each criterion on its own line, starting "- "',
44
+ tags: () => "tags is a list, such as tags: [forms]",
45
+ expect: () => "expect maps fact names to values, such as expect: { answer: 42 }",
46
+ "known-failing": (value) => `known-failing is true or left out, not ${JSON.stringify(value)}`,
47
+ draft: (value) => `draft is true or left out, not ${JSON.stringify(value)}`,
48
+ };
49
+
50
+ /**
51
+ * Reads a key strictly: YAML 1.2's core schema, where only `true` and `false` are booleans, so an
52
+ * unquoted `no` is refused rather than read as a string or false; an unknown field is refused.
53
+ */
54
+ export function parseKey(text: string): Checked<ReadKey> {
55
+ const match = FRONTMATTER.exec(text);
56
+ if (!match) return fail("/", "a key starts with frontmatter between --- lines");
57
+ const document = parseDocument(match[1]!, {
58
+ schema: "core",
59
+ strict: true,
60
+ uniqueKeys: true,
61
+ prettyErrors: false,
62
+ });
63
+ const yamlProblems = [...document.errors, ...document.warnings];
64
+ if (yamlProblems.length > 0) {
65
+ // The frontmatter starts on the file's second line.
66
+ const lineOf = (offset: number) => {
67
+ const before = match[1]!.slice(0, offset);
68
+ return `line ${before.split("\n").length + 1}:${offset - before.lastIndexOf("\n")}`;
69
+ };
70
+ return {
71
+ ok: false,
72
+ problems: yamlProblems.map((e) => ({
73
+ path: "",
74
+ message: `${lineOf(e.pos[0])}: ${e.message}`,
75
+ })),
76
+ };
77
+ }
78
+ const raw: unknown = document.toJS();
79
+ const checked = checkSchema(KeySchema, raw);
80
+ if (!checked.ok) {
81
+ return {
82
+ ok: false,
83
+ problems: explainProblems(checked.problems, {
84
+ schema: KeySchema,
85
+ value: raw,
86
+ noun: "a key",
87
+ patterns: SETTINGS_PATTERNS,
88
+ hints: { marker: "case new writes one; copy one from another key, or remake the case" },
89
+ kinds: KINDS,
90
+ }),
91
+ };
92
+ }
93
+ const key = checked.value;
94
+ const problems: Problem[] = [];
95
+ const pass = passProblem(key.pass);
96
+ if (pass) problems.push({ path: "", message: pass });
97
+ for (const [name, value] of Object.entries(key.expect ?? {})) {
98
+ const problem = RESERVED(name)
99
+ ? "is reserved"
100
+ : ((name.startsWith("_") ? runFactNameProblem(name) : undefined) ??
101
+ expectedProblem(name, value));
102
+ if (problem) problems.push({ path: `/expect/${name}`, message: problem });
103
+ }
104
+ // Core schema reads `no` as a string; written unquoted it was almost surely meant as something
105
+ // else, so every string in `expect` is quoted, and an unquoted one is refused.
106
+ const expect = document.get("expect", true);
107
+ if (isMap(expect)) {
108
+ for (const item of expect.items) {
109
+ if (
110
+ isScalar(item.value) &&
111
+ typeof item.value.value === "string" &&
112
+ item.value.type === "PLAIN"
113
+ ) {
114
+ problems.push({
115
+ path: `/expect/${String((item.key as { value?: unknown })?.value)}`,
116
+ message: `quote "${item.value.value}": a string in expect is quoted`,
117
+ });
118
+ }
119
+ }
120
+ }
121
+ for (const field of ["must", "must-not"] as const) {
122
+ const list = key[field] ?? [];
123
+ const seen = new Set<string>();
124
+ list.forEach((criterion, index) => {
125
+ if (seen.has(criterion)) {
126
+ problems.push({ path: `/${field}/${index}`, message: "is given twice" });
127
+ }
128
+ seen.add(criterion);
129
+ });
130
+ }
131
+ if (problems.length > 0) return { ok: false, problems };
132
+ return { ok: true, value: { key, note: match[2]!.trim() } };
133
+ }
134
+
135
+ /** The criteria in the report's numbering: `must 1`, `must-not 2`. */
136
+ export function criteriaOf(key: Key): { name: string; field: "must" | "must-not"; text: string }[] {
137
+ return (["must", "must-not"] as const).flatMap((field) =>
138
+ (key[field] ?? []).map((text, index) => ({ name: `${field} ${index + 1}`, field, text })),
139
+ );
140
+ }
141
+
142
+ function fail(path: string, message: string): Checked<never> {
143
+ return { ok: false, problems: [{ path, message }] };
144
+ }
@@ -0,0 +1,178 @@
1
+ import Type from "typebox";
2
+
3
+ /**
4
+ * A loop's records under `{store}/loops/{id}/`, its id its name and when it started: `loop.json`,
5
+ * written once when it starts, with what its entry said then, and `brief.md`, the entry's brief;
6
+ * `tries/{n}/proposal.json`, the proposer's answer as soon as it is in, so a try cut short resumes
7
+ * with its code; `tries/{n}/try.json`, written once when the try is decided; and `finals/{k}.json`,
8
+ * each check of the kept code on the holdout; `spread.json`, the start run twice before the first
9
+ * try. The code itself is `start/` and `tries/{n}/code/`.
10
+ */
11
+
12
+ export const LOOP_KIND = "awf.case-loop/1";
13
+ export const TRY_KIND = "awf.case-try/1";
14
+ export const PROPOSAL_KIND = "awf.case-proposal/1";
15
+ export const FINAL_KIND = "awf.case-final/1";
16
+ export const SPREAD_KIND = "awf.case-spread/1";
17
+
18
+ /** The proposer a loop's entry gets when it names none. */
19
+ export const DEFAULT_PROPOSER = "claude/claude-sonnet-5-5";
20
+
21
+ const Text = Type.String({ minLength: 1 });
22
+ const Usd = Type.Number({ minimum: 0 });
23
+
24
+ /** What the proposer answers: the one change a try makes, and what the records must show. */
25
+ export const HypothesisSchema = Type.Object(
26
+ {
27
+ change: Type.String({ minLength: 1, description: "What changed, in a sentence." }),
28
+ hypothesis: Type.String({ minLength: 1, description: "Why it should do better." }),
29
+ predicted: Type.String({
30
+ minLength: 1,
31
+ description: "The effect expected on the comparison's numbers, and its cost.",
32
+ }),
33
+ mechanism: Type.String({
34
+ minLength: 1,
35
+ description: "What the trials must show if the hypothesis holds.",
36
+ }),
37
+ },
38
+ { additionalProperties: false },
39
+ );
40
+ export type Hypothesis = Type.Static<typeof HypothesisSchema>;
41
+
42
+ export const ProposalSchema = Type.Object(
43
+ {
44
+ kind: Type.Literal(PROPOSAL_KIND),
45
+ hypothesis: HypothesisSchema,
46
+ /** The proposer's run, its estimate, as the try counts it. */
47
+ spend: Usd,
48
+ /** The incumbent's run on the tuning cases the proposer read, its estimate. */
49
+ feedback: Usd,
50
+ runId: Type.Optional(Text),
51
+ },
52
+ { additionalProperties: false },
53
+ );
54
+ export type Proposal = Type.Static<typeof ProposalSchema>;
55
+
56
+ export const LoopSchema = Type.Object(
57
+ {
58
+ kind: Type.Literal(LOOP_KIND),
59
+ name: Text,
60
+ dataset: Text,
61
+ started: Text,
62
+ /** The checkout the start was copied from, and its git state then. */
63
+ from: Type.Object(
64
+ {
65
+ path: Text,
66
+ commit: Type.Union([Text, Type.Null()]),
67
+ dirty: Type.Boolean(),
68
+ },
69
+ { additionalProperties: false },
70
+ ),
71
+ /** The entry's brief, its digest: a resumed loop steers as it started. */
72
+ brief: Text,
73
+ /** The entry's `edit`: the globs a try's files are checked against. */
74
+ edit: Type.Object(
75
+ { allow: Type.Array(Text, { minItems: 1 }), deny: Type.Array(Text) },
76
+ { additionalProperties: false },
77
+ ),
78
+ proposer: Text,
79
+ trials: Type.Integer({ minimum: 1 }),
80
+ /** The entry's params, as `name=value`, sorted: every try and the final check run under them. */
81
+ params: Type.Array(Text),
82
+ /** The entry's `cases` and `tags`, when it names them: what picked the tuning cases. */
83
+ cases: Type.Optional(Type.Array(Text)),
84
+ tags: Type.Optional(Type.Array(Text)),
85
+ /** The entry's `spread`: whether the start runs twice before the first try. */
86
+ spread: Type.Boolean(),
87
+ /** The tuning cases in the seeded order every try runs them in. */
88
+ tuning: Type.Array(Text),
89
+ holdout: Type.Array(Text),
90
+ /** The dataset's `compare`, its version: a loop's tries are judged alike. */
91
+ comparison: Text,
92
+ },
93
+ { additionalProperties: false },
94
+ );
95
+ export type Loop = Type.Static<typeof LoopSchema>;
96
+
97
+ export const TrySchema = Type.Object(
98
+ {
99
+ kind: Type.Literal(TRY_KIND),
100
+ n: Type.Integer({ minimum: 1 }),
101
+ at: Text,
102
+ /** The try it changed: 0, the start. */
103
+ parent: Type.Integer({ minimum: 0 }),
104
+ decision: Type.Union([
105
+ Type.Literal("kept"),
106
+ Type.Literal("discarded"),
107
+ Type.Literal("refused"),
108
+ Type.Literal("failed"),
109
+ ]),
110
+ why: Text,
111
+ hypothesis: Type.Optional(HypothesisSchema),
112
+ /** The files it changed against its parent. */
113
+ changed: Type.Array(Text),
114
+ /** The run that compared it with its parent. */
115
+ runId: Type.Optional(Text),
116
+ verdict: Type.Optional(Type.Union([Text, Type.Null()])),
117
+ spend: Type.Object({ proposer: Usd, trials: Usd }, { additionalProperties: false }),
118
+ },
119
+ { additionalProperties: false },
120
+ );
121
+ export type Try = Type.Static<typeof TrySchema>;
122
+
123
+ export const FinalSchema = Type.Object(
124
+ {
125
+ kind: Type.Literal(FINAL_KIND),
126
+ k: Type.Integer({ minimum: 1 }),
127
+ at: Text,
128
+ /** The kept try checked against the start. */
129
+ incumbent: Type.Integer({ minimum: 1 }),
130
+ runId: Text,
131
+ verdict: Type.Union([Text, Type.Null()]),
132
+ why: Text,
133
+ spend: Usd,
134
+ },
135
+ { additionalProperties: false },
136
+ );
137
+ export type Final = Type.Static<typeof FinalSchema>;
138
+
139
+ /**
140
+ * `spread.json`: the start run twice on the tuning cases before the first try, as two columns of
141
+ * the same code, so a try's difference is read against how far the start moves on its own.
142
+ * Advisory: it stops nothing and sets no trials. `skipped` under the entry's `spread: false`.
143
+ */
144
+ export const SpreadSchema = Type.Union([
145
+ Type.Object(
146
+ {
147
+ kind: Type.Literal(SPREAD_KIND),
148
+ at: Text,
149
+ skipped: Type.Literal(true),
150
+ },
151
+ { additionalProperties: false },
152
+ ),
153
+ Type.Object(
154
+ {
155
+ kind: Type.Literal(SPREAD_KIND),
156
+ at: Text,
157
+ runId: Text,
158
+ trials: Type.Integer({ minimum: 1 }),
159
+ cases: Type.Integer({ minimum: 0 }),
160
+ /** The dataset's `compare`, the start against itself: `better` or `worse` is noise. */
161
+ verdict: Type.Union([Text, Type.Null()]),
162
+ /** The comparison's primary metric, the second run's minus the first's. */
163
+ primary: Type.Optional(
164
+ Type.Object(
165
+ { name: Text, difference: Type.Union([Type.Number(), Type.Null()]) },
166
+ { additionalProperties: false },
167
+ ),
168
+ ),
169
+ /** The cases that came out differently between the two runs, each run's passes. */
170
+ unsteady: Type.Array(
171
+ Type.Object({ case: Text, a: Text, b: Text }, { additionalProperties: false }),
172
+ ),
173
+ spend: Usd,
174
+ },
175
+ { additionalProperties: false },
176
+ ),
177
+ ]);
178
+ export type Spread = Type.Static<typeof SpreadSchema>;