@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,89 @@
1
+ import type { LogEventJson, LogsJson, TurnRecord } from "@agentswf/contract/records";
2
+ import { runFactName, TURN_OUTCOMES } from "../format/settings";
3
+
4
+ /** A turn or compaction of a trial's run, as `awf logs --json` printed it once it settled. */
5
+ export type RunTurn = Pick<
6
+ TurnRecord,
7
+ "kind" | "attempt" | "agent" | "outcome" | "stage" | "label" | "deliveredAt" | "settledAt"
8
+ > & {
9
+ /** A message to the agent started it, not the workflow: the line's `cause`. */
10
+ caused?: true;
11
+ };
12
+
13
+ /**
14
+ * The turns and compactions in `awf logs --json`'s page, in the order the page holds them;
15
+ * undefined when the text is no page. An event of a kind or shape this lab doesn't know is
16
+ * skipped, as every reader of the run's logs skips one.
17
+ */
18
+ export function turnsOf(text: string): RunTurn[] | undefined {
19
+ const events = eventsOf(text);
20
+ if (!events) return undefined;
21
+ return events.flatMap((event: LogEventJson) => {
22
+ if (!event || typeof event !== "object") return [];
23
+ if (event.kind !== "turn" && event.kind !== "compact") return [];
24
+ const line = event as Partial<RunTurn>;
25
+ if (typeof line.agent !== "string" || typeof line.outcome !== "string") return [];
26
+ if (typeof line.attempt !== "number") return [];
27
+ return [
28
+ {
29
+ kind: event.kind,
30
+ attempt: line.attempt,
31
+ agent: line.agent,
32
+ outcome: line.outcome,
33
+ ...(typeof line.stage === "string" ? { stage: line.stage } : {}),
34
+ ...(typeof line.label === "string" ? { label: line.label } : {}),
35
+ ...(typeof line.deliveredAt === "string" ? { deliveredAt: line.deliveredAt } : {}),
36
+ ...(typeof line.settledAt === "string" ? { settledAt: line.settledAt } : {}),
37
+ ...((line as { cause?: unknown }).cause ? { caused: true as const } : {}),
38
+ },
39
+ ];
40
+ });
41
+ }
42
+
43
+ /** The agents the run opened, by name, the calling session's left out; undefined for no page. */
44
+ export function agentsOpenedOf(text: string): string[] | undefined {
45
+ const events = eventsOf(text);
46
+ if (!events) return undefined;
47
+ const names = events.flatMap((event) => {
48
+ if (!event || typeof event !== "object" || event.kind !== "agent-opened") return [];
49
+ const line = event as { agent?: unknown; caller?: unknown };
50
+ return typeof line.agent === "string" && !line.caller ? [line.agent] : [];
51
+ });
52
+ return [...new Set(names)];
53
+ }
54
+
55
+ function eventsOf(text: string): LogEventJson[] | undefined {
56
+ let page: Partial<LogsJson>;
57
+ try {
58
+ page = JSON.parse(text);
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ if (!page || typeof page !== "object" || !Array.isArray(page.events)) return undefined;
63
+ return page.events;
64
+ }
65
+
66
+ /**
67
+ * The run facts: what the run's own record says of its path, beside `grading.ts`'s facts and under
68
+ * reserved `_` names. Turns only; compactions are left out, and a nudge is part of its turn.
69
+ * `_turns` and each outcome's count every turn; an agent's, the turns the workflow started (not a
70
+ * message's), by its name over every call path and attempt, 0 for an agent opened that took none.
71
+ */
72
+ export function runFactsOf(
73
+ turns: readonly RunTurn[],
74
+ opened: readonly string[],
75
+ ): Record<string, number> {
76
+ const facts: Record<string, number> = { _turns: 0 };
77
+ for (const outcome of TURN_OUTCOMES) facts[runFactName.outcome(outcome)] = 0;
78
+ for (const agent of opened) facts[runFactName.agent(agent)] = 0;
79
+ const add = (name: string) => {
80
+ facts[name] = (facts[name] ?? 0) + 1;
81
+ };
82
+ for (const turn of turns) {
83
+ if (turn.kind !== "turn") continue;
84
+ add("_turns");
85
+ add(runFactName.outcome(turn.outcome));
86
+ if (!turn.caused) add(runFactName.agent(turn.agent));
87
+ }
88
+ return facts;
89
+ }
@@ -0,0 +1,286 @@
1
+ import { type LabReport, LabReportSchema, REPORT_KIND } from "../format/output";
2
+ import type { RunRecord } from "../format/records";
3
+ import { checkSchema, describeProblems } from "../shared/validate";
4
+ import { versionKey } from "../shared/version";
5
+ import { columnLabel } from "./columns";
6
+ import { type Context, envOf, tmpOf } from "./command-context";
7
+ import { type ColumnDecision, compareColumns } from "./compare";
8
+ import { comparingFile, type DatasetInfo } from "./dataset";
9
+ import type { LabGrader } from "./grading";
10
+ import { agreementOf, judgeLabeled, type PersonAgreement, readLabels } from "./labels";
11
+ import { type CaseRow, newestEntries } from "./outcome";
12
+ import { agreements, poolNumbers } from "./pooled";
13
+ import { pairedDifference, ratesOf } from "./rates";
14
+ import { notRunOf, type RunReport, renderRun, tagRows, trialSums } from "./report";
15
+ import { type CaseBar, rowsOf } from "./runs";
16
+ import { readableRuns, type StoredTrial } from "./store";
17
+ import { afterMsOf } from "./trial-settings";
18
+ import type { CaseWorkspace } from "./workspace";
19
+
20
+ // The report a run ends with: its rows, the other columns, compare's decisions and the person's
21
+ // agreement.
22
+
23
+ /** `compare`'s verdict on each column but the reference; undefined when the dataset has none. */
24
+ export async function columnDecisions(
25
+ context: Context,
26
+ {
27
+ workspace,
28
+ info,
29
+ run,
30
+ trials,
31
+ bars,
32
+ }: {
33
+ workspace: CaseWorkspace;
34
+ info: DatasetInfo;
35
+ run: RunRecord;
36
+ trials: readonly StoredTrial[];
37
+ bars: ReadonlyMap<string, CaseBar>;
38
+ },
39
+ ): Promise<ColumnDecision[] | undefined> {
40
+ return compareColumns({
41
+ run,
42
+ trials,
43
+ bars,
44
+ gradingFile: comparingFile(info),
45
+ root: workspace.root,
46
+ tmp: tmpOf(context),
47
+ env: envOf(context),
48
+ timeoutMs: afterMsOf(info),
49
+ });
50
+ }
51
+
52
+ /**
53
+ * The person's labels on a run's trials and how the lab agrees with them, and how many labeled
54
+ * trials the current judge graded across the dataset's runs, for its "checked" mark.
55
+ */
56
+ function personOf({
57
+ workspace,
58
+ dataset,
59
+ trials,
60
+ bars,
61
+ graders,
62
+ }: {
63
+ workspace: CaseWorkspace;
64
+ dataset: string;
65
+ trials: readonly StoredTrial[];
66
+ bars: ReadonlyMap<string, CaseBar>;
67
+ graders: readonly LabGrader[] | undefined;
68
+ }): Pick<RunReport, "person" | "judgeLabeled" | "manual" | "judges"> {
69
+ const labels = readLabels(workspace.store, dataset);
70
+ const manual = new Set((graders ?? []).filter((g) => g.manual).map((g) => g.name));
71
+ const person = agreementOf(trials, labels, (name) => bars.get(name)?.deciders, manual);
72
+ const judges = graders
73
+ ? new Set(graders.filter((g) => g.agent && !g.manual).map((g) => g.name))
74
+ : undefined;
75
+ const shown = { ...(manual.size > 0 ? { manual } : {}), ...(judges ? { judges } : {}) };
76
+ // The judge whose "checked" mark the report gives: the first `sentences` that decides.
77
+ const listed = graders?.find((g) => g.agent && !g.manual);
78
+ const graded = listed
79
+ ? undefined
80
+ : trials.flatMap((t) => newestEntries(t.scores)).find((e) => e.agent && !manual.has(e.grader));
81
+ const agent = listed?.agent ?? graded?.agent;
82
+ const name = listed?.name ?? graded?.grader;
83
+ if (!agent || !name) return { ...(person ? { person } : {}), ...shown };
84
+ const runs = [...readableRuns(workspace.store, { dataset })].map((r) => r.trials);
85
+ return {
86
+ ...(person ? { person } : {}),
87
+ ...shown,
88
+ judgeLabeled: judgeLabeled(runs, labels, {
89
+ grader: name,
90
+ ...agent,
91
+ minor: versionKey(listed?.version ?? graded?.version) ?? "",
92
+ }),
93
+ };
94
+ }
95
+
96
+ /** The rows of each column but yours, from the second on. */
97
+ function otherColumns(
98
+ store: string,
99
+ run: RunRecord,
100
+ trials: readonly StoredTrial[],
101
+ bars: ReadonlyMap<string, CaseBar>,
102
+ ): CaseRow[][] {
103
+ return run.columns.slice(1).map((_, i) => rowsOf(store, run, trials, bars, i + 1));
104
+ }
105
+
106
+ /**
107
+ * How a run, report or score ends: the run's rows and the other columns', the person's agreement
108
+ * and `compare`'s decisions, rendered, and as `--json` for an exit the caller settles.
109
+ */
110
+ export async function runReport(
111
+ context: Context,
112
+ workspace: CaseWorkspace,
113
+ args: {
114
+ /** The dataset as it is now; undefined when it no longer reads. */
115
+ info: DatasetInfo | undefined;
116
+ run: RunRecord;
117
+ trials: readonly StoredTrial[];
118
+ bars: ReadonlyMap<string, CaseBar>;
119
+ graders: readonly LabGrader[] | undefined;
120
+ criteria: number;
121
+ stale?: LabReport["stale"];
122
+ /** The run's plan was printed just before. */
123
+ followsPlan?: boolean;
124
+ },
125
+ ) {
126
+ const { info, run, trials, bars, stale } = args;
127
+ const rows = rowsOf(workspace.store, run, trials, bars);
128
+ const others = otherColumns(workspace.store, run, trials, bars);
129
+ const personal = personOf({
130
+ workspace,
131
+ dataset: run.dataset,
132
+ trials,
133
+ bars,
134
+ graders: args.graders,
135
+ });
136
+ const decisions = info
137
+ ? await columnDecisions(context, { workspace, info, run, trials, bars })
138
+ : undefined;
139
+ const { text, exit } = renderRun({
140
+ run,
141
+ rows,
142
+ others,
143
+ trials: [...trials],
144
+ criteria: args.criteria,
145
+ ...(stale !== undefined ? { stale } : {}),
146
+ decidersOf: (name) => bars.get(name)?.deciders,
147
+ tagsOf: (name) => bars.get(name)?.tags ?? [],
148
+ ungradedOf: (name) => bars.get(name)?.ungraded,
149
+ ...(args.followsPlan ? { followsPlan: true } : {}),
150
+ ...(decisions ? { decisions } : {}),
151
+ ...personal,
152
+ });
153
+ return {
154
+ rows,
155
+ others,
156
+ person: personal.person,
157
+ decisions,
158
+ text,
159
+ exit,
160
+ json: (exit: number, scored?: LabReport["scored"]) =>
161
+ reportJson({
162
+ ...(scored ? { scored } : {}),
163
+ run,
164
+ rows,
165
+ trials,
166
+ exit,
167
+ bars,
168
+ others,
169
+ ...(stale !== undefined ? { stale } : {}),
170
+ ...(personal.person ? { person: personal.person } : {}),
171
+ ...(decisions ? { decisions } : {}),
172
+ }),
173
+ };
174
+ }
175
+
176
+ /** `report --json`: a run's cases, pooled numbers and agreement, checked against its schema. */
177
+ export function reportJson(args: {
178
+ run: RunRecord;
179
+ rows: readonly CaseRow[];
180
+ trials: readonly StoredTrial[];
181
+ exit: number;
182
+ bars: ReadonlyMap<string, CaseBar>;
183
+ stale?: LabReport["stale"];
184
+ withTrials?: boolean;
185
+ others?: readonly CaseRow[][];
186
+ person?: PersonAgreement;
187
+ decisions?: readonly ColumnDecision[];
188
+ scored?: LabReport["scored"];
189
+ }): LabReport {
190
+ const { run, rows, trials, exit, bars } = args;
191
+ const own = trials.filter((t) => t.record.column === 0);
192
+ const pooled = poolNumbers(own);
193
+ const decidersOf = (name: string) => bars.get(name)?.deciders;
194
+ const sumsOf = (column: number) => {
195
+ const sums = trialSums(
196
+ trials.filter((t) => t.record.column === column),
197
+ decidersOf,
198
+ );
199
+ return {
200
+ ...(sums.msMedian !== undefined ? { msMedian: sums.msMedian } : {}),
201
+ ...(sums.estimateMedian !== undefined ? { estimateMedian: sums.estimateMedian } : {}),
202
+ estimate: sums.estimate,
203
+ reusedEstimate: sums.reused,
204
+ gradingEstimate: sums.grading,
205
+ unpriced: sums.unpriced,
206
+ };
207
+ };
208
+ const idsOf = (name: string, column: number) =>
209
+ trials.flatMap((t) =>
210
+ t.record.case === name && t.record.column === column && t.record.trialId
211
+ ? [t.record.trialId]
212
+ : [],
213
+ );
214
+ const report: LabReport = {
215
+ kind: REPORT_KIND,
216
+ labRun: run.id,
217
+ dataset: run.dataset,
218
+ partial: run.finished === undefined || run.broke !== undefined,
219
+ ...(run.stopped ? { stop: { why: run.stopped, notRun: notRunOf(run, trials) } } : {}),
220
+ exit,
221
+ params: run.columns[0]!.params,
222
+ code: run.folders[run.columns[0]!.folder]!,
223
+ sums: sumsOf(0),
224
+ reused: trials.filter((t) => t.record.reused).length,
225
+ rates: ratesOf(rows),
226
+ tags: tagRows(rows, (name) => bars.get(name)?.tags ?? []),
227
+ cases: rows.map((row) => ({
228
+ name: row.name,
229
+ verdict: row.tally.verdict ?? null,
230
+ ...(row.tally.none ? { none: row.tally.none } : {}),
231
+ passed: row.tally.passed,
232
+ trials: row.tally.trials,
233
+ trialIds: idsOf(row.name, 0),
234
+ knownFailing: row.knownFailing,
235
+ outcomes: row.outcomes,
236
+ ...(row.why ? { why: row.why } : {}),
237
+ notes: row.notes,
238
+ history: row.history,
239
+ })),
240
+ numbers: Object.fromEntries(
241
+ [...pooled.graders].map(([grader, numbers]) => [grader, Object.fromEntries(numbers)]),
242
+ ),
243
+ numbersLeftOut: pooled.left,
244
+ agreement: agreements(own, (name) => bars.get(name)?.deciders),
245
+ ...(args.person ? { labels: args.person } : {}),
246
+ ...(args.stale !== undefined ? { stale: args.stale } : {}),
247
+ ...(args.others && args.others.length > 0
248
+ ? {
249
+ columns: args.others.map((column, i) => {
250
+ const { folder: at, params } = run.columns[i + 1]!;
251
+ const folder = run.folders[at]!;
252
+ const theirs = poolNumbers(trials.filter((t) => t.record.column === i + 1));
253
+ const difference = pairedDifference(rows, column);
254
+ return {
255
+ label: columnLabel(run, i + 1),
256
+ ...(args.decisions?.[i] ? { compare: args.decisions[i] } : {}),
257
+ rates: ratesOf(column),
258
+ ...(difference ? { difference } : {}),
259
+ ...folder,
260
+ params,
261
+ sums: sumsOf(i + 1),
262
+ numbers: Object.fromEntries(
263
+ [...theirs.graders].map(([grader, numbers]) => [
264
+ grader,
265
+ Object.fromEntries(numbers),
266
+ ]),
267
+ ),
268
+ numbersLeftOut: theirs.left,
269
+ cases: column.map((row) => ({
270
+ name: row.name,
271
+ verdict: row.tally.verdict ?? null,
272
+ passed: row.tally.passed,
273
+ trials: row.tally.trials,
274
+ trialIds: idsOf(row.name, i + 1),
275
+ })),
276
+ };
277
+ }),
278
+ }
279
+ : {}),
280
+ ...(args.withTrials ? { trials: trials.map((t) => ({ ...t.record, scores: t.scores })) } : {}),
281
+ ...(args.scored ? { scored: args.scored } : {}),
282
+ };
283
+ const checked = checkSchema(LabReportSchema, report);
284
+ if (!checked.ok) throw new Error(describeProblems("report --json", checked.problems));
285
+ return report;
286
+ }
@@ -0,0 +1,171 @@
1
+ import { basename } from "node:path";
2
+ import { type LabRuns, LabRunsSchema, RUNS_KIND } from "../format/output";
3
+ import type { RunRecord } from "../format/records";
4
+ import { checkSchema, describeProblems } from "../shared/validate";
5
+ import { type Context, loadDataset, workspaceOf } from "./command-context";
6
+ import { graderSpecs } from "./dataset";
7
+ import { bestSoFarOf, loopIdOf, readLoopFolders, readTries } from "./loop";
8
+ import { caseRow } from "./outcome";
9
+ import { barsOf, type CaseBar } from "./runs";
10
+ import { readRunRecord, readTrials, runIds, type StoredTrial, UnreadableRecord } from "./store";
11
+ import { plural } from "./text";
12
+ import type { CaseWorkspace } from "./workspace";
13
+
14
+ type Listed =
15
+ | { at: string; run: LabRuns["runs"][number] }
16
+ | { at: string; loop: LabRuns["loops"][number] }
17
+ | { at: string; unread: LabRuns["unread"][number]; dataset?: string };
18
+
19
+ /** `runs`: the store's runs and loops, newest first, and any run whose records don't read. */
20
+ export function runs(context: Context): number {
21
+ const workspace = workspaceOf(context);
22
+ const only = context.options.dataset;
23
+ const bars = barsBy(context, workspace);
24
+ const listed: Listed[] = [];
25
+ for (const id of runIds(workspace.store)) {
26
+ let run: RunRecord | undefined;
27
+ let trials: StoredTrial[] = [];
28
+ try {
29
+ run = readRunRecord(workspace.store, id);
30
+ if (run) trials = readTrials(workspace.store, id);
31
+ } catch (error) {
32
+ if (!(error instanceof UnreadableRecord)) throw error;
33
+ // "{file} is not valid:" then its problems: the file's name and the first problem do.
34
+ const [head = "", first] = (error as Error).message.split("\n");
35
+ const why = `${basename(head.replace(/ is not valid:$/, ""))}${first ? `: ${first.trim()}` : ""}`;
36
+ if (!run || run.dataset === only || only === undefined) {
37
+ listed.push({ at: id, unread: { id, why }, ...(run ? { dataset: run.dataset } : {}) });
38
+ }
39
+ continue;
40
+ }
41
+ // A loop's runs are its report's.
42
+ if (!run || run.loop !== undefined) continue;
43
+ if (only !== undefined && run.dataset !== only) continue;
44
+ listed.push({ at: id, run: runOf(run, trials, bars(run.dataset)) });
45
+ }
46
+ for (const found of readLoopFolders(workspace.store)) {
47
+ if ("unread" in found) {
48
+ // A loop from before its entry, or broken: listed with why, never in the way.
49
+ if (only === undefined) {
50
+ const id = basename(found.dir);
51
+ listed.push({ at: id.slice(id.indexOf("-") + 1), unread: { id, why: found.unread } });
52
+ }
53
+ continue;
54
+ }
55
+ const { dir, loop } = found;
56
+ if (only !== undefined && loop.dataset !== only) continue;
57
+ const tries = readTries(dir);
58
+ listed.push({
59
+ // A loop sorts among runs by when it started, as a run's id does.
60
+ at: loopIdOf(loop).slice(loop.name.length + 1),
61
+ loop: {
62
+ id: loopIdOf(loop),
63
+ name: loop.name,
64
+ dataset: loop.dataset,
65
+ started: loop.started,
66
+ tries: tries.length,
67
+ kept: bestSoFarOf(tries),
68
+ },
69
+ });
70
+ }
71
+ listed.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
72
+ if (context.options.json) {
73
+ const json: LabRuns = {
74
+ kind: RUNS_KIND,
75
+ runs: listed.flatMap((l) => ("run" in l ? [l.run] : [])),
76
+ loops: listed.flatMap((l) => ("loop" in l ? [l.loop] : [])),
77
+ unread: listed.flatMap((l) => ("unread" in l ? [l.unread] : [])),
78
+ };
79
+ const checked = checkSchema(LabRunsSchema, json);
80
+ if (!checked.ok) throw new Error(describeProblems("runs --json", checked.problems));
81
+ context.stdout(JSON.stringify(json, null, 2));
82
+ return 0;
83
+ }
84
+ const unread = listed.flatMap((l) => ("unread" in l ? [l.unread.id] : []));
85
+ const lines = listed.flatMap((l) => {
86
+ if ("unread" in l) return [];
87
+ if ("loop" in l) {
88
+ const { id, dataset, tries, kept } = l.loop;
89
+ return `${id} ${dataset} loop, ${tries} ${tries === 1 ? "try" : "tries"}, ${kept === 0 ? "keeps the start" : `keeps try ${kept}`}`;
90
+ }
91
+ const { id, dataset, cases, trials, columns, state, stopped, verdicts } = l.run;
92
+ const counted = (["passed", "failed", "flaky", "unclear", "knownFailing", "none"] as const)
93
+ .filter((v) => (verdicts[v] ?? 0) > 0)
94
+ .map(
95
+ (v) =>
96
+ `${v === "none" ? "no verdict" : v === "knownFailing" ? "known failing" : v} ${verdicts[v]}`,
97
+ );
98
+ return [
99
+ `${id} ${dataset} ${plural(cases, "case")}, ${plural(trials, "trial")}${columns > 1 ? ` in ${columns} columns` : ""}`,
100
+ state === "broke" ? "the lab broke" : stopped ? STOPS[stopped] : state,
101
+ ...(counted.length > 0 ? [counted.join(" · ")] : []),
102
+ ].join(" ");
103
+ });
104
+ // Nearly always an older lab's records: the count is enough here, --json names each and why.
105
+ if (unread.length > 0) {
106
+ lines.push(
107
+ `${unread.length === 1 ? "1 run or loop" : `${unread.length} runs or loops`} whose records don't read, left out: older records this lab won't read, in ${workspace.store} (--json names them)`,
108
+ );
109
+ }
110
+ context.stdout(
111
+ lines.length > 0
112
+ ? lines.join("\n")
113
+ : `no runs yet${only ? ` of ${only}` : ""}: awf-lab run makes one`,
114
+ );
115
+ return 0;
116
+ }
117
+
118
+ /** Each dataset's bars as its keys say now, read once; the default bars for one that doesn't read. */
119
+ function barsBy(
120
+ context: Context,
121
+ workspace: CaseWorkspace,
122
+ ): (dataset: string) => ReadonlyMap<string, CaseBar> {
123
+ const read = new Map<string, ReadonlyMap<string, CaseBar>>();
124
+ return (dataset) => {
125
+ let bars = read.get(dataset);
126
+ if (!bars) {
127
+ try {
128
+ const { info, cases } = loadDataset(context, workspace, dataset, "all");
129
+ bars = barsOf(info, cases, graderSpecs(info));
130
+ } catch {
131
+ bars = new Map();
132
+ }
133
+ read.set(dataset, bars);
134
+ }
135
+ return bars;
136
+ };
137
+ }
138
+
139
+ /** How a stopped run is said: as its report says it. */
140
+ const STOPS: Record<NonNullable<RunRecord["stopped"]>, string> = {
141
+ budget: "stopped at --budget",
142
+ compare: "stopped by the comparison",
143
+ precondition: "stopped on preconditions",
144
+ stage: "stopped: a stage never entered",
145
+ };
146
+
147
+ /** A run's line in the list, its verdicts as its report counts them. */
148
+ function runOf(
149
+ run: RunRecord,
150
+ trials: readonly StoredTrial[],
151
+ bars: ReadonlyMap<string, CaseBar>,
152
+ ): LabRuns["runs"][number] {
153
+ const verdicts: LabRuns["runs"][number]["verdicts"] = {};
154
+ for (const { case: name, trials: asked } of run.asked) {
155
+ const bar = bars.get(name) ?? { pass: "all", knownFailing: false, tags: [] };
156
+ const own = trials.filter((t) => t.record.case === name && t.record.column === 0);
157
+ const row = caseRow(name, own, asked, bar.pass, bar.knownFailing, [], bar.deciders);
158
+ const verdict = row.knownFailing ? "knownFailing" : (row.tally.verdict ?? "none");
159
+ verdicts[verdict] = (verdicts[verdict] ?? 0) + 1;
160
+ }
161
+ return {
162
+ id: run.id,
163
+ dataset: run.dataset,
164
+ cases: run.asked.length,
165
+ trials: trials.length,
166
+ columns: run.columns.length,
167
+ state: run.broke ? "broke" : run.finished ? "finished" : "partial",
168
+ ...(run.stopped && !run.broke ? { stopped: run.stopped } : {}),
169
+ verdicts,
170
+ };
171
+ }