@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,936 @@
1
+ import type { LabelRecord, RunRecord } from "../format/records";
2
+ import { columnLabel, sharedParams } from "./columns";
3
+ import type { ColumnDecision } from "./compare";
4
+ import { familyOf } from "./families";
5
+ import { type Agreement, JUDGE_CHECK, type PersonAgreement } from "./labels";
6
+ import type { CaseRow, StoredTrialView } from "./outcome";
7
+ import {
8
+ factsOf,
9
+ gradingSpend,
10
+ newestEntries,
11
+ PRECONDITION_STOP,
12
+ preconditionFailure,
13
+ stageFailure,
14
+ trialOutcome,
15
+ votersOf,
16
+ } from "./outcome";
17
+ import { agreements, type Pooled, poolNumbers } from "./pooled";
18
+ import { describeDifference, describeRates, pairedDifference, ratesOf } from "./rates";
19
+ import { describeFolder, median, plural, seconds, usd } from "./text";
20
+ import { type CaseVerdict, EXITS, type ExitCode, exitCodeOf } from "./verdict";
21
+
22
+ const MARK: Record<CaseVerdict, string> = { passed: "✓", failed: "✗", flaky: "~", unclear: "?" };
23
+
24
+ export type RunReport = {
25
+ run: RunRecord;
26
+ rows: CaseRow[];
27
+ trials: StoredTrialView[];
28
+ /** Criteria in the keys, not judged yet. */
29
+ criteria: number;
30
+ /** Grades `score` would make again: a key or grader changed since; or why it couldn't tell. */
31
+ stale?: number | { unread: string };
32
+ /** The rows of each column but the reference, in the run's `columns` order. */
33
+ others?: readonly CaseRow[][];
34
+ /** The person's labels on this run's trials, and how the lab agrees with them. */
35
+ person?: PersonAgreement;
36
+ /** `compare`'s decision on each column but the reference, in `columns` order. */
37
+ decisions?: readonly ColumnDecision[];
38
+ /** Each case's tags, from its key as it is now. */
39
+ tagsOf?: (caseName: string) => readonly string[];
40
+ /** The labeled trials the current judge graded, across the dataset's runs. */
41
+ judgeLabeled?: { labeled: number; needsWork: number };
42
+ /** The `manual` graders `grading.ts` lists. */
43
+ manual?: ReadonlySet<string>;
44
+ /** The `sentences` graders that decide; absent, a grade with an agent is one. */
45
+ judges?: ReadonlySet<string>;
46
+ /** Whose grades decide each case, from the current dataset and keys; all when unread. */
47
+ decidersOf?: (caseName: string) => ReadonlySet<string> | undefined;
48
+ /** Why no grader grades a case, from its key as it is now. */
49
+ ungradedOf?: (caseName: string) => string | undefined;
50
+ /** The run's own plan was printed just before: its header says the run's id alone. */
51
+ followsPlan?: boolean;
52
+ };
53
+
54
+ const percent = (count: number, of: number) =>
55
+ of === 0 ? "" : ` (${Math.round((count / of) * 100)}%)`;
56
+
57
+ function describePooled(pooled: Pooled): string {
58
+ if ("count" in pooled) return `${pooled.count}/${pooled.of}${percent(pooled.count, pooled.of)}`;
59
+ const m = median(pooled.values)!;
60
+ return `median ${Number.isInteger(m) ? m : m.toFixed(2)}`;
61
+ }
62
+
63
+ /**
64
+ * What the deciding `sentences` graders did, your checkout's column: splits, criteria judged from
65
+ * saved files, trials not judged because a grader before them failed them, and the marks on the
66
+ * judge itself.
67
+ */
68
+ function judgeLines(
69
+ trials: readonly StoredTrialView[],
70
+ criteria: number,
71
+ labeled: { labeled: number; needsWork: number } | undefined,
72
+ manual: ReadonlySet<string>,
73
+ judges: ReadonlySet<string> | undefined,
74
+ ): string[] {
75
+ const own = trials.filter((t) => t.record.column === 0);
76
+ // Unlisted, a `sentences` grade is the one that carries the agent it judged with.
77
+ const judged = own.flatMap((t) =>
78
+ newestEntries(t.scores).filter((e) =>
79
+ judges ? judges.has(e.grader) : e.agent && !manual.has(e.grader),
80
+ ),
81
+ );
82
+ if (judged.length === 0) {
83
+ return criteria > 0
84
+ ? [
85
+ `criteria not judged: ${criteria} ${criteria === 1 ? "criterion" : "criteria"} in the keys`,
86
+ ]
87
+ : [];
88
+ }
89
+ const lines: string[] = [];
90
+ const parts = judged.flatMap((e) => (e.skipped || e.errored ? [] : (e.parts ?? [])));
91
+ const split = parts.filter((p) => p.settled === "majority").length;
92
+ const unsettled = parts.filter((p) => p.settled === "unsettled").length;
93
+ const read = parts.filter((p) => (p.data as { readNotRun?: boolean } | undefined)?.readNotRun);
94
+ const skipped = judged.filter((e) => e.skipped).length;
95
+ lines.push(
96
+ [
97
+ `sentences judged ${parts.length}`,
98
+ ...(split > 0 ? [`split 2–1 ${split}`] : []),
99
+ ...(unsettled > 0 ? [`unsettled ${unsettled}`] : []),
100
+ ...(read.length > 0 ? [`read, not run ${read.length}`] : []),
101
+ ...(skipped > 0
102
+ ? [`not judged on ${plural(skipped, "trial")} a grader before it failed`]
103
+ : []),
104
+ ].join(" · "),
105
+ );
106
+ const agent = judged.find((e) => e.agent)?.agent;
107
+ if (agent) {
108
+ // Checked once the person labeled enough trials this judge graded, some of them needing
109
+ // work: a judge that passes everything can't clear it on good ones alone.
110
+ const have = labeled ?? { labeled: 0, needsWork: 0 };
111
+ const checked = have.labeled >= JUDGE_CHECK.labeled && have.needsWork >= JUDGE_CHECK.needsWork;
112
+ const short = checked
113
+ ? ""
114
+ : `, not checked against a person (labeled ${have.labeled} of ${JUDGE_CHECK.labeled}, needs-work ${have.needsWork} of ${JUDGE_CHECK.needsWork}: awf-lab label)`;
115
+ const family = familyOf(agent.model, agent.harness);
116
+ const shared = family
117
+ ? [...new Set(own.flatMap((t) => t.record.models))].filter((m) => familyOf(m) === family)
118
+ : [];
119
+ lines.push(
120
+ [
121
+ `judge: ${agent.harness}/${agent.model} ×${votersOf(agent)}${short}`,
122
+ ...(family === undefined ? ["family unknown"] : []),
123
+ ...(shared.length > 0
124
+ ? [`shares the ${family} family with the workflow's ${shared.join(", ")}`]
125
+ : []),
126
+ ].join(" · "),
127
+ );
128
+ }
129
+ return lines;
130
+ }
131
+
132
+ /**
133
+ * Each `manual` grader of your checkout's column, graded by `score --grader`: on how many trials,
134
+ * at what grading cost, and on how many its verdict differs from the trial's. A manual
135
+ * `sentences` is set against the deciding one's verdict, judge against judge. Which is right is
136
+ * for the person's labels to say.
137
+ */
138
+ function manualLines(
139
+ trials: readonly StoredTrialView[],
140
+ manual: ReadonlySet<string>,
141
+ decidersOf: RunReport["decidersOf"],
142
+ ): string[] {
143
+ const graders = new Map<string, { trials: number; cost: number; differ: number }>();
144
+ for (const t of trials.filter((t) => t.record.column === 0)) {
145
+ const newest = newestEntries(t.scores);
146
+ const deciders = decidersOf?.(t.record.case);
147
+ const judge = newest.find((e) => e.agent && !manual.has(e.grader));
148
+ const { outcome } = trialOutcome(t.record, t.scores, deciders);
149
+ for (const e of newest.filter((e) => manual.has(e.grader) && !e.errored && !e.skipped)) {
150
+ const into = graders.get(e.grader) ?? { trials: 0, cost: 0, differ: 0 };
151
+ graders.set(e.grader, into);
152
+ into.trials++;
153
+ into.cost += e.estimate ?? 0;
154
+ const against = e.agent && judge ? judge.verdict : outcome;
155
+ if (e.verdict && (against === "passed" || against === "failed") && against !== e.verdict) {
156
+ into.differ++;
157
+ }
158
+ }
159
+ }
160
+ return [...graders].map(
161
+ ([name, g]) =>
162
+ `manual: ${name} on ${plural(g.trials, "trial")}${g.cost > 0 ? ` · grading ${usd(g.cost)}` : ""} · differs from the deciding verdict on ${g.differ}`,
163
+ );
164
+ }
165
+
166
+ /** Each stage's median time over these trials, in the order the stages first ran; or none. */
167
+ function stageLine(trials: readonly StoredTrialView[]): string | undefined {
168
+ const order: string[] = [];
169
+ const times = new Map<string, number[]>();
170
+ // A trial that errored, stopped or failed in the workflow's body was cut short: left out.
171
+ for (const t of trials.filter(
172
+ (t) => !t.record.errored && !t.record.workflowError && t.record.stopped === undefined,
173
+ )) {
174
+ for (const [stage, ms] of Object.entries(t.record.stageMs ?? {})) {
175
+ if (!times.has(stage)) {
176
+ order.push(stage);
177
+ times.set(stage, []);
178
+ }
179
+ times.get(stage)!.push(ms);
180
+ }
181
+ }
182
+ if (order.length === 0) return undefined;
183
+ return order.map((stage) => `${stage} ${seconds(median(times.get(stage)!)!)}`).join(" · ");
184
+ }
185
+
186
+ /** Pooled numbers in a line: each grader's, by name. */
187
+ function pooledText(pooled: ReturnType<typeof poolNumbers>): string {
188
+ const each = [...pooled.graders].map(
189
+ ([grader, numbers]) =>
190
+ `${grader} ${[...numbers].map(([name, n]) => `${name} ${describePooled(n)}`).join(", ")}`,
191
+ );
192
+ const left =
193
+ pooled.left > 0 ? `; ${plural(pooled.left, "trial")} the workflow failed left out` : "";
194
+ return `${each.join(" · ")}${left}`;
195
+ }
196
+
197
+ /** Of these trials, how many are another column's, said after a count. */
198
+ function elsewhere(run: RunRecord, trials: readonly StoredTrialView[]): string {
199
+ const counts = new Map<number, number>();
200
+ for (const t of trials) {
201
+ if (t.record.column > 0) counts.set(t.record.column, (counts.get(t.record.column) ?? 0) + 1);
202
+ }
203
+ return [...counts].map(([column, n]) => `, ${n} in ${columnLabel(run, column)}`).join("");
204
+ }
205
+
206
+ const agreed = (a: Agreement) =>
207
+ [
208
+ ...(a.good.labeled > 0 ? [`good ${a.good.labeled}, passed ${a.good.agreed}`] : []),
209
+ ...(a.needsWork.labeled > 0
210
+ ? [`needs-work ${a.needsWork.labeled}, failed ${a.needsWork.agreed}`]
211
+ : []),
212
+ ].join(" · ");
213
+
214
+ /**
215
+ * The person's labels against the lab's verdicts: good and needs-work apart, since a lab that
216
+ * passes everything agrees with a mostly good set; each deciding grader's; each disagreement.
217
+ */
218
+ function personLines(run: RunRecord, person: PersonAgreement): string[] {
219
+ const labeled = person.good.labeled + person.needsWork.labeled + person.notCompared;
220
+ const lines = [
221
+ `labels: ${plural(labeled, "trial")} · ${agreed(person) || "none compared"}${person.notCompared > 0 ? ` · ${person.notCompared} neither passed nor failed` : ""}`,
222
+ ];
223
+ for (const grader of person.graders) {
224
+ const cost = grader.cost > 0 ? ` · grading ${usd(grader.cost)}` : "";
225
+ const manual = grader.deciding ? "" : ", manual";
226
+ lines.push(` ${grader.grader}${manual}: ${agreed(grader)}${cost}`);
227
+ }
228
+ for (const d of person.disagreements) {
229
+ const where = d.column > 0 ? ` (${columnLabel(run, d.column)})` : "";
230
+ lines.push(
231
+ ` disagrees: ${d.case} trial ${d.trial}${where} labeled ${d.mark}${d.note ? `: ${d.note}` : ""}; the lab: ${d.outcome}`,
232
+ );
233
+ }
234
+ return lines;
235
+ }
236
+
237
+ /** Each case's tags, and how each column did on them: passed of cases, and which failed. */
238
+ export function tagRows(
239
+ rows: readonly CaseRow[],
240
+ tagsOf: (name: string) => readonly string[],
241
+ ): { tag: string; cases: number; passed: number; failing: string[] }[] {
242
+ const tags = [...new Set(rows.flatMap((r) => tagsOf(r.name)))].sort();
243
+ return tags.map((tag) => {
244
+ const tagged = rows.filter((r) => tagsOf(r.name).includes(tag) && r.tally.verdict);
245
+ return {
246
+ tag,
247
+ cases: tagged.length,
248
+ passed: tagged.filter((r) => r.tally.verdict === "passed").length,
249
+ failing: tagged.filter((r) => failing(r.tally.verdict)).map((r) => r.name),
250
+ };
251
+ });
252
+ }
253
+
254
+ function tagLines(
255
+ run: RunRecord,
256
+ rows: readonly CaseRow[],
257
+ others: readonly CaseRow[][],
258
+ tagsOf: (name: string) => readonly string[],
259
+ ): string[] {
260
+ const mine = tagRows(rows, tagsOf);
261
+ if (mine.length === 0) return [];
262
+ const theirs = others.map((column) => tagRows(column, tagsOf));
263
+ return [
264
+ "by tag:",
265
+ ...mine.map((t, i) => {
266
+ const elsewhere = theirs.map(
267
+ (column, c) => ` · ${columnLabel(run, c + 1)} ${column[i]!.passed}/${column[i]!.cases}`,
268
+ );
269
+ return ` ${t.tag.padEnd(16)} ${t.passed}/${t.cases} passed${elsewhere.join("")}${t.failing.length > 0 ? ` · failing: ${t.failing.join(", ")}` : ""}`;
270
+ }),
271
+ ];
272
+ }
273
+
274
+ /** The numbers and agreement lines, your checkout's column. */
275
+ function gradersLines(
276
+ trials: readonly StoredTrialView[],
277
+ decidersOf: RunReport["decidersOf"],
278
+ ): string[] {
279
+ const own = trials.filter((t) => t.record.column === 0);
280
+ const lines: string[] = [];
281
+ const pooled = poolNumbers(own);
282
+ if (pooled.graders.size > 0) lines.push(`numbers: ${pooledText(pooled)}`);
283
+ for (const pair of agreements(own, decidersOf)) {
284
+ const said = [
285
+ ...(pair.verdicts.of > 0
286
+ ? [`the same verdict on ${pair.verdicts.alike} of ${plural(pair.verdicts.of, "trial")}`]
287
+ : []),
288
+ ...(pair.parts.of > 0
289
+ ? [`the same label on ${pair.parts.alike} of ${plural(pair.parts.of, "part")}`]
290
+ : []),
291
+ ];
292
+ lines.push(`agreement, ${pair.a} and ${pair.b}: ${said.join("; ")}`);
293
+ }
294
+ return lines;
295
+ }
296
+
297
+ const failing = (v: CaseVerdict | undefined) => v === "failed" || v === "flaky" || v === "unclear";
298
+
299
+ /** Each case of yours beside the same case in another column, and the passes between them. */
300
+ function pairedRows(rows: readonly CaseRow[], column: readonly CaseRow[]) {
301
+ return rows.flatMap((mine) => {
302
+ const theirs = column.find((r) => r.name === mine.name);
303
+ return theirs ? [{ mine, theirs, gap: theirs.tally.passed - mine.tally.passed }] : [];
304
+ });
305
+ }
306
+
307
+ /** A case's passes and verdict, as the columns' differences show it: `1/2 flaky`. */
308
+ const showRow = (row: CaseRow) =>
309
+ `${row.tally.passed}/${row.tally.trials} ${row.tally.verdict ?? row.tally.none ?? ""}`.trim();
310
+
311
+ /** The pairs that came out differently: verdicts differ, or passes by 2 or more; largest first. */
312
+ function cameOutDifferently(pairs: ReturnType<typeof pairedRows>) {
313
+ return pairs
314
+ .filter((p) => p.mine.tally.verdict !== p.theirs.tally.verdict || Math.abs(p.gap) >= 2)
315
+ .sort((a, b) => Math.abs(b.gap) - Math.abs(a.gap));
316
+ }
317
+
318
+ /** The cases that came out differently in another column, as the report lists them. */
319
+ export function differingCases(
320
+ rows: readonly CaseRow[],
321
+ column: readonly CaseRow[],
322
+ ): { case: string; a: string; b: string }[] {
323
+ return cameOutDifferently(pairedRows(rows, column)).map(({ mine, theirs }) => ({
324
+ case: mine.name,
325
+ a: showRow(mine),
326
+ b: showRow(theirs),
327
+ }));
328
+ }
329
+
330
+ /**
331
+ * With more than one column: each column's folder and verdicts, the cases that came out
332
+ * differently (verdicts differ, or passes by 2 or more), largest difference first, and how many
333
+ * cases had more passes on each side. No column is called better: that is `compare`'s.
334
+ */
335
+ function columnLines(
336
+ run: RunRecord,
337
+ rows: readonly CaseRow[],
338
+ others: readonly CaseRow[][],
339
+ trials: readonly StoredTrialView[],
340
+ decisions: readonly ColumnDecision[] | undefined,
341
+ decidersOf: RunReport["decidersOf"],
342
+ ): string[] {
343
+ const reference = columnLabel(run, 0);
344
+ const width = Math.max(14, ...run.columns.map((_, i) => columnLabel(run, i).length + 2));
345
+ const lines = [
346
+ `${"columns".padEnd(width + 2)}passed failed flaky unclear time, median est. cost, median`,
347
+ ];
348
+ const row = (label: string, list: readonly CaseRow[], column: number) => {
349
+ const n = (v: CaseVerdict) => String(list.filter((r) => r.tally.verdict === v).length);
350
+ const sums = trialSums(
351
+ trials.filter((t) => t.record.column === column),
352
+ decidersOf,
353
+ );
354
+ const ms = sums.msMedian;
355
+ const cost = sums.estimateMedian;
356
+ lines.push(
357
+ ` ${label.padEnd(width)}${n("passed").padEnd(8)}${n("failed").padEnd(8)}${n("flaky").padEnd(7)}${n("unclear").padEnd(9)}${(ms !== undefined ? seconds(ms) : "-").padEnd(14)}${cost !== undefined ? usd(cost) : "-"}`,
358
+ );
359
+ };
360
+ row(reference, rows, 0);
361
+ for (const [i, column] of others.entries()) row(columnLabel(run, i + 1), column, i + 1);
362
+ // A budget that stopped the run part way leaves columns short of different cases.
363
+ const notRun = run.columns.map((_, i) => {
364
+ const ran = new Set(trials.filter((t) => t.record.column === i).map((t) => t.record.case));
365
+ return run.asked.map((a) => a.case).filter((name) => !ran.has(name));
366
+ });
367
+ if (notRun.some((names) => names.join() !== notRun[0]!.join())) {
368
+ for (const [i, names] of notRun.entries()) {
369
+ if (names.length > 0) {
370
+ lines.push(
371
+ ` ${columnLabel(run, i)}: ${plural(names.length, "case")} not run (${names.join(", ")})`,
372
+ );
373
+ }
374
+ }
375
+ }
376
+ // A dataset graded by numbers compares by them: each other column's, as yours are below.
377
+ for (const i of others.keys()) {
378
+ const pooled = poolNumbers(trials.filter((t) => t.record.column === i + 1));
379
+ if (pooled.graders.size > 0) {
380
+ lines.push(` numbers, ${columnLabel(run, i + 1)}: ${pooledText(pooled)}`);
381
+ }
382
+ }
383
+ // With no trial passed or failed in any column, as when every case is graded by numbers only,
384
+ // the pass and fail lines would only say that nothing did.
385
+ const decided = new Set(["passed", "failed", "stopped", "undecided"]);
386
+ const passFail = [rows, ...others].some((list) =>
387
+ list.some((r) => r.outcomes.some((o) => decided.has(o))),
388
+ );
389
+ others.forEach((column, i) => {
390
+ const label = columnLabel(run, i + 1);
391
+ const pairs = pairedRows(rows, column);
392
+ const differ = cameOutDifferently(pairs);
393
+ const more = pairs.filter((p) => p.gap > 0).length;
394
+ const fewer = pairs.filter((p) => p.gap < 0).length;
395
+ // With no case apart, the passes and the difference would only say so again.
396
+ if (passFail && differ.length === 0 && more === 0 && fewer === 0) {
397
+ lines.push(`no case came out differently in ${label}`);
398
+ } else if (passFail) {
399
+ if (differ.length > 0) {
400
+ lines.push(`came out differently in ${label}, largest difference first`);
401
+ for (const { mine, theirs } of differ) {
402
+ lines.push(
403
+ ` ${mine.name.padEnd(20)} ${reference} ${showRow(mine)} · ${label} ${showRow(theirs)}`,
404
+ );
405
+ }
406
+ } else lines.push(`no case came out differently in ${label}`);
407
+ lines.push(
408
+ `more passes: ${label} on ${plural(more, "case")}, ${reference} on ${plural(fewer, "case")}`,
409
+ );
410
+ const difference = pairedDifference(rows, column);
411
+ if (difference) lines.push(`difference from ${reference}: ${describeDifference(difference)}`);
412
+ }
413
+ const said = decisions?.[i];
414
+ if (said && "error" in said) lines.push(`compare, ${label}: could not tell: ${said.error}`);
415
+ else if (said) {
416
+ lines.push(
417
+ `compare, ${label}: ${said.decision}${said.stop ? "" : ", more trials may tell"} · ${said.reason}`,
418
+ );
419
+ }
420
+ });
421
+ const once = run.asked.every((a) => a.trials === 1);
422
+ // One trial a case gives examples, which the line below says: rates would claim more.
423
+ if (passFail && !once) {
424
+ lines.push(`rates, ${reference}: ${describeRates(ratesOf(rows))}`);
425
+ for (const [i, column] of others.entries()) {
426
+ lines.push(`rates, ${columnLabel(run, i + 1)}: ${describeRates(ratesOf(column))}`);
427
+ }
428
+ }
429
+ if (once) {
430
+ lines.push("One trial each: these are examples, not rates.");
431
+ } else if (!decisions) {
432
+ lines.push("No compare in grading.ts says which is better. Read the cases.");
433
+ }
434
+ return lines;
435
+ }
436
+
437
+ const cell = (row: CaseRow | undefined) =>
438
+ row
439
+ ? `${row.tally.verdict ?? row.tally.none ?? "-"} ${row.tally.passed}/${row.tally.trials}`
440
+ : "-";
441
+
442
+ /**
443
+ * `report --md`: the run as Markdown to paste into a pull request or an issue: a table of cases
444
+ * by column, each column's rates and its difference and verdict against the reference.
445
+ */
446
+ export function markdownOf(report: RunReport): string {
447
+ const { run, rows, others = [], decisions } = report;
448
+ const { exit } = renderRun(report);
449
+ const labels = run.columns.map((_, i) => columnLabel(run, i));
450
+ const timeOf = (column: number) => {
451
+ const sums = trialSums(
452
+ report.trials.filter((t) => t.record.column === column),
453
+ report.decidersOf,
454
+ );
455
+ if (sums.msMedian === undefined) return "";
456
+ const cost = sums.estimateMedian !== undefined ? `, est. ${usd(sums.estimateMedian)}` : "";
457
+ return `; per trial, median ${seconds(sums.msMedian)}${cost}`;
458
+ };
459
+ const lines = [
460
+ `### ${run.dataset} · run ${run.id}`,
461
+ "",
462
+ `${plural(run.asked.length, "case")} · ${plural(report.trials.length, "trial")}${run.columns.length > 1 ? ` in ${run.columns.length} columns` : ""} · exit ${exit}${exit === 3 ? "" : `: ${EXITS[exit]}`}`,
463
+ "",
464
+ `| case | ${labels.join(" | ")} |`,
465
+ `| --- | ${labels.map(() => "---").join(" | ")} |`,
466
+ ...rows.map(
467
+ (row) =>
468
+ `| ${row.name} | ${[cell(row), ...others.map((o) => cell(o.find((r) => r.name === row.name)))].join(" | ")} |`,
469
+ ),
470
+ "",
471
+ `- **${labels[0]}**: ${describeRates(ratesOf(rows))}${timeOf(0)}`,
472
+ ];
473
+ for (const [i, column] of others.entries()) {
474
+ const difference = pairedDifference(rows, column);
475
+ const said = decisions?.[i];
476
+ lines.push(
477
+ `- **${labels[i + 1]}**: ${describeRates(ratesOf(column))}${difference ? `; ${describeDifference(difference)}` : ""}${said && !("error" in said) ? `; compare: ${said.decision}, ${said.reason}` : ""}${timeOf(i + 1)}`,
478
+ );
479
+ }
480
+ const all = trialSums(report.trials, report.decidersOf);
481
+ if (all.ran && !all.noAgents) {
482
+ lines.push(
483
+ `- **all trials**: est. ${usd(all.estimate - all.grading)}${all.reused > 0 ? `, ${usd(all.reused)} of it reused trials, run before` : ""}${all.unpriced ? ", partly unpriced" : ""}${all.grading > 0 ? `; grading ${usd(all.grading)}` : ""}`,
484
+ );
485
+ }
486
+ return lines.join("\n");
487
+ }
488
+
489
+ /** The trials a run asked for, in every column, that it never ran. */
490
+ export function notRunOf(run: RunRecord, trials: readonly unknown[]): number {
491
+ return Math.max(
492
+ 0,
493
+ run.asked.reduce((n, a) => n + a.trials, 0) * run.columns.length - trials.length,
494
+ );
495
+ }
496
+
497
+ /**
498
+ * Some trials in time and money: the medians of those that ran and didn't error, and the
499
+ * estimates summed, the reused trials' and the grades' included.
500
+ */
501
+ export function trialSums(
502
+ trials: readonly StoredTrialView[],
503
+ decidersOf?: RunReport["decidersOf"],
504
+ ): {
505
+ /** Some trial ran and didn't error, so the medians mean something. */
506
+ ran: boolean;
507
+ msMedian?: number;
508
+ estimateMedian?: number;
509
+ estimate: number;
510
+ reused: number;
511
+ grading: number;
512
+ unpriced: boolean;
513
+ noAgents: boolean;
514
+ } {
515
+ const ran = trials.filter(
516
+ (t) =>
517
+ t.record.trialId &&
518
+ trialOutcome(t.record, t.scores, decidersOf?.(t.record.case)).outcome !== "errored",
519
+ );
520
+ const ms = median(ran.map((t) => t.record.ms));
521
+ const each = median(
522
+ ran.flatMap((t) => (t.record.estimate !== undefined ? [t.record.estimate] : [])),
523
+ );
524
+ const workflow = trials.reduce((sum, t) => sum + (t.record.estimate ?? 0), 0);
525
+ const reused = trials
526
+ .filter((t) => t.record.reused)
527
+ .reduce((sum, t) => sum + (t.record.estimate ?? 0), 0);
528
+ const grading = trials.reduce((sum, t) => sum + gradingSpend(t.scores), 0);
529
+ return {
530
+ ran: ms !== undefined,
531
+ ...(ms !== undefined ? { msMedian: ms } : {}),
532
+ ...(each !== undefined ? { estimateMedian: each } : {}),
533
+ estimate: workflow + grading,
534
+ reused,
535
+ grading,
536
+ // A run with no agents costs nothing to price; one whose agents' count is unknown may.
537
+ unpriced: ran.some(
538
+ (t) =>
539
+ (t.record.estimate === undefined && t.record.agents !== 0) ||
540
+ (t.record.priced ?? 0) < (t.record.agents ?? 0),
541
+ ),
542
+ noAgents: workflow === 0 && ran.every((t) => t.record.agents === 0),
543
+ };
544
+ }
545
+
546
+ /** `run` and `report`'s text, and the exit code from your checkout's column. */
547
+ export function renderRun({
548
+ run,
549
+ rows,
550
+ trials,
551
+ criteria,
552
+ stale,
553
+ decidersOf,
554
+ others = [],
555
+ person,
556
+ judgeLabeled,
557
+ manual = new Set(),
558
+ judges,
559
+ tagsOf = () => [],
560
+ ungradedOf = () => undefined,
561
+ followsPlan = false,
562
+ decisions: compared,
563
+ }: RunReport): {
564
+ text: string;
565
+ exit: ExitCode;
566
+ } {
567
+ const partial = run.finished === undefined || run.broke !== undefined;
568
+ const preconditionStop = run.stopped === "precondition";
569
+ const budgetStop = run.stopped === "budget";
570
+ const exit = exitCodeOf({ cases: rows, partial: partial || budgetStop, preconditionStop });
571
+ const notRun = notRunOf(run, trials);
572
+ const counts = new Set(run.asked.map((a) => a.trials));
573
+ const each =
574
+ counts.size === 1 ? `${plural([...counts][0]!, "trial")} each` : "trials per case as asked";
575
+ // After its plan, which said the dataset, the code and the parameters, a run says what is new.
576
+ const lines = [
577
+ followsPlan
578
+ ? `run ${run.id}${partial ? " (partial)" : ""}`
579
+ : `${run.dataset} · ${plural(run.asked.length, "case")} · ${each} · run ${run.id}${partial ? " (partial)" : ""}`,
580
+ // The plan named each folder and its version.
581
+ ...(followsPlan
582
+ ? []
583
+ : [
584
+ `code: ${describeFolder({ ...run.folders[0]!, path: undefined })} · version ${run.folders[0]!.version}`,
585
+ ...run.folders
586
+ .slice(1)
587
+ .map(
588
+ (folder, i) =>
589
+ `against ${i + 1}: ${describeFolder(folder)} · version ${folder.version}`,
590
+ ),
591
+ ]),
592
+ ...(sharedParams(run).length > 0 && !followsPlan
593
+ ? [`params: ${sharedParams(run).join(" ")}`]
594
+ : []),
595
+ ...(run.stopped
596
+ ? [
597
+ run.stopped === "precondition"
598
+ ? `stopped: ${PRECONDITION_STOP}: ${preconditionFailure(trials) ?? "no trial says which"}; ${plural(notRun, "trial")} not run`
599
+ : run.stopped === "stage"
600
+ ? `stopped: ${stageFailure(trials) ?? "a stage a case named was never entered"}; ${plural(notRun, "trial")} not run`
601
+ : `${run.stopped === "budget" ? "stopped at --budget" : "stopped by the comparison"}: ${plural(notRun, "trial")} not run`,
602
+ ]
603
+ : []),
604
+ ...(run.columns.length > run.folders.length && !followsPlan
605
+ ? [`reference column: ${columnLabel(run, 0)}; the exit code and history are its`]
606
+ : []),
607
+ "",
608
+ ];
609
+ let historyShown = false;
610
+ const line = (row: CaseRow, extra = "") => {
611
+ if (row.history.length > 0) historyShown = true;
612
+ const history =
613
+ row.history.length > 0 ? ` history ${row.history.map((v) => MARK[v]).join("")}` : "";
614
+ const alsoFails = others.flatMap((column, i) => {
615
+ const there = column.find((r) => r.name === row.name)?.tally.verdict;
616
+ return failing(row.tally.verdict) && failing(there)
617
+ ? [`also fails in ${columnLabel(run, i + 1)}`]
618
+ : [];
619
+ });
620
+ const note = row.tally.note;
621
+ const said = [
622
+ ...row.notes,
623
+ ...(row.why ? [row.why] : []),
624
+ ...(note ? [note] : []),
625
+ ...alsoFails,
626
+ ];
627
+ return ` ${row.name.padEnd(20)} ${`${row.tally.passed}/${row.tally.trials}`.padEnd(5)} ${extra}${said.join("; ")}${history}`;
628
+ };
629
+ const section = (title: string, list: CaseRow[], extra?: (row: CaseRow) => string) => {
630
+ if (list.length === 0) return;
631
+ lines.push(title, ...list.map((row) => line(row, extra?.(row))));
632
+ };
633
+ const must = rows.filter((r) => !r.knownFailing);
634
+ const known = rows.filter((r) => r.knownFailing);
635
+ const nowPassing = known.filter((r) => r.tally.verdict === "passed");
636
+ section(
637
+ "failed, must pass",
638
+ must.filter((r) => r.tally.verdict === "failed"),
639
+ );
640
+ section(
641
+ "flaky",
642
+ must.filter((r) => r.tally.verdict === "flaky"),
643
+ );
644
+ section(
645
+ "unclear",
646
+ must.filter((r) => r.tally.verdict === "unclear"),
647
+ );
648
+ section(
649
+ "known failing",
650
+ known.filter((r) => r.tally.verdict !== "passed"),
651
+ );
652
+ section("known failing, now passing", nowPassing, (row) =>
653
+ row.tally.trials >= 3
654
+ ? "remove known-failing from its key? "
655
+ : "confirm with --trials 3 before removing known-failing; ",
656
+ );
657
+ section(
658
+ "passed, with notes",
659
+ must.filter((r) => r.tally.verdict === "passed" && r.notes.length > 0),
660
+ );
661
+ section(
662
+ "no verdict",
663
+ rows.filter((r) => r.tally.none),
664
+ (row) => {
665
+ const why =
666
+ row.tally.none === "not graded" ? (ungradedOf(row.name) ?? "no grader applies") : undefined;
667
+ const head = `${row.tally.none}${why ? `: ${why}` : ""}`;
668
+ const said = row.notes.length > 0 || row.why || row.tally.note;
669
+ return said ? `${head}${why ? "; " : ": "}` : head;
670
+ },
671
+ );
672
+ if (historyShown) {
673
+ lines.push(
674
+ `history: the earlier runs' verdicts, oldest first: ${(Object.entries(MARK) as [CaseVerdict, string][]).map(([v, mark]) => `${mark} ${v}`).join(" · ")}`,
675
+ );
676
+ }
677
+ if (lines.at(-1) !== "") lines.push("");
678
+ if (others.length > 0)
679
+ lines.push(...columnLines(run, rows, others, trials, compared, decidersOf), "");
680
+
681
+ // Each count once, and only when it is some: a zero says nothing.
682
+ const counted = (label: string, n: number, extra = "") =>
683
+ n > 0 ? [`${label} ${n}${extra}`] : [];
684
+ const verdicts = (v: CaseVerdict) => must.filter((r) => r.tally.verdict === v).length;
685
+ const tallies = [
686
+ ...counted("passed", verdicts("passed")),
687
+ ...counted("failed", verdicts("failed")),
688
+ ...counted("flaky", verdicts("flaky")),
689
+ ...counted("unclear", verdicts("unclear")),
690
+ ...counted(
691
+ "known failing",
692
+ known.length,
693
+ nowPassing.length > 0 ? ` (${nowPassing.length} now passing)` : "",
694
+ ),
695
+ ...counted("no verdict", rows.filter((r) => r.tally.none).length),
696
+ ];
697
+ if (tallies.length > 0) lines.push(tallies.join(" · "));
698
+ if (others.length === 0 && ratesOf(rows).cases > 0) {
699
+ lines.push(`rate: ${describeRates(ratesOf(rows))}`);
700
+ }
701
+ const tags = tagLines(run, rows, others, tagsOf);
702
+ if (tags.length > 0) lines.push(...tags);
703
+ const views = trials.map((t) => ({
704
+ ...t,
705
+ view: trialOutcome(t.record, t.scores, decidersOf?.(t.record.case)),
706
+ }));
707
+ const errored = views.filter((t) => t.view.outcome === "errored");
708
+ const by = (who: string) => errored.filter((t) => t.view.errored?.by === who).length;
709
+ const blame = ["dataset", "grading", "harness", "provider", "lab"]
710
+ .filter((who) => by(who) > 0)
711
+ .map((who) => `${by(who)} by ${who}`);
712
+ const reusedCount = trials.filter((t) => t.record.reused).length;
713
+ lines.push(
714
+ [
715
+ `trials ${trials.length}${run.columns.length > 1 ? ` in ${run.columns.length} columns` : ""}`,
716
+ ...counted("reused", reusedCount),
717
+ ...counted(
718
+ "errored",
719
+ errored.length,
720
+ `${blame.length > 0 ? ` (${blame.join(", ")})` : ""}${elsewhere(run, errored)}`,
721
+ ),
722
+ ...counted("undecided", views.filter((t) => t.view.outcome === "undecided").length),
723
+ ...counted("leaked", views.filter((t) => t.view.outcome === "leaked").length),
724
+ ].join(" · "),
725
+ );
726
+ // With more than one column, the table above gave each column's medians: these would mix them.
727
+ const sums = trialSums(trials, decidersOf);
728
+ if (sums.ran) {
729
+ lines.push(
730
+ [
731
+ ...(others.length === 0 && sums.msMedian !== undefined
732
+ ? [`time per trial, median ${seconds(sums.msMedian)}`]
733
+ : []),
734
+ ...(sums.noAgents
735
+ ? ["the workflow ran no agents"]
736
+ : [
737
+ ...(others.length === 0 && sums.estimateMedian !== undefined
738
+ ? [`est. cost per trial, median ${usd(sums.estimateMedian)}`]
739
+ : []),
740
+ `all trials ${usd(sums.estimate - sums.grading)}${sums.reused > 0 ? `, ${usd(sums.reused)} of it reused trials, run before` : ""}${sums.unpriced ? ", partly unpriced" : ""}`,
741
+ ]),
742
+ ...(sums.grading > 0 ? [`grading ${usd(sums.grading)}`] : []),
743
+ ].join(" · "),
744
+ );
745
+ }
746
+ lines.push(...gradersLines(trials, decidersOf));
747
+ // With one trial per case, a stage's time across cases is worth a line; with more, `--case`.
748
+ if (run.asked.every((a) => a.trials === 1)) {
749
+ const stages = stageLine(trials.filter((t) => t.record.column === 0));
750
+ if (stages) lines.push(`time per stage, median across cases: ${stages}`);
751
+ }
752
+ if (typeof stale === "number" && stale > 0) {
753
+ lines.push(
754
+ `${plural(stale, "grade")} out of date, a key or grader changed: awf-lab score ${run.id.slice(-4)}`,
755
+ );
756
+ } else if (typeof stale === "object") {
757
+ lines.push(`grades: couldn't check whether any is out of date: ${stale.unread}`);
758
+ }
759
+ lines.push(...judgeLines(trials, criteria, judgeLabeled, manual, judges));
760
+ lines.push(...manualLines(trials, manual, decidersOf));
761
+ if (person) lines.push(...personLines(run, person));
762
+ lines.push(sandboxLine(run), "");
763
+ const why =
764
+ exit === 3
765
+ ? preconditionStop
766
+ ? `the run stopped: ${PRECONDITION_STOP}`
767
+ : budgetStop
768
+ ? "stopped at --budget; run again to go on"
769
+ : partial
770
+ ? run.broke !== undefined
771
+ ? `the run is partial: the lab broke (${run.broke})`
772
+ : "the run is partial"
773
+ : !rows.some((r) => r.tally.verdict || r.tally.none === "graded by numbers")
774
+ ? "no case was graded"
775
+ : "a case is flaky or unclear"
776
+ : EXITS[exit];
777
+ lines.push(`exit ${exit}: ${why}`);
778
+ // A case unclear only for trials it never ran has nothing to show in detail.
779
+ const first = must.find(
780
+ (r) => failing(r.tally.verdict) && r.outcomes.some((o) => o !== "passed"),
781
+ );
782
+ if (first) lines.push(`detail: awf-lab report ${run.id.slice(-4)} --case ${first.name}`);
783
+ return { text: lines.join("\n"), exit };
784
+ }
785
+
786
+ /** One case in full: each trial's result, facts, refusals and grades, and how to open its logs. */
787
+ export function renderCase({
788
+ run,
789
+ row,
790
+ trials,
791
+ logsCommand,
792
+ deciders,
793
+ others = [],
794
+ labels = new Map(),
795
+ }: {
796
+ run: RunRecord;
797
+ row: CaseRow;
798
+ trials: readonly StoredTrialView[];
799
+ /** How to open a trial's logs: the trial's folder by its id, `shown` in the command. */
800
+ logsCommand: (trialId: string, shown: string) => string;
801
+ deciders?: ReadonlySet<string> | undefined;
802
+ /** This case's row in each other column. */
803
+ others?: readonly (CaseRow | undefined)[];
804
+ /** The person's labels, by trial id. */
805
+ labels?: ReadonlyMap<string, LabelRecord>;
806
+ }): string {
807
+ const tally = (r: CaseRow) =>
808
+ `${r.tally.verdict ?? r.tally.none ?? "no trials"} ${r.tally.passed}/${r.tally.trials}`;
809
+ const lines = [
810
+ `${row.name} · run ${run.id} · ${tally(row)}`,
811
+ ...others.flatMap((other, i) => (other ? [`${columnLabel(run, i + 1)}: ${tally(other)}`] : [])),
812
+ ];
813
+ const stages = stageLine(trials.filter((t) => t.record.column === 0));
814
+ if (stages) lines.push(`time per stage, median: ${stages}`);
815
+ let unlabeled = false;
816
+ for (const trial of trials) {
817
+ const { record } = trial;
818
+ const view = trialOutcome(record, trial.scores, deciders);
819
+ lines.push(
820
+ "",
821
+ `trial ${record.trial}${record.column > 0 ? ` (${columnLabel(run, record.column)})` : ""}: ${view.outcome}${record.trialId ? ` · id ${record.trialId}` : ""} · ${seconds(record.ms)}`,
822
+ );
823
+ const label = record.trialId ? labels.get(record.trialId) : undefined;
824
+ if (label) lines.push(` labeled ${label.mark}${label.note ? `: ${label.note}` : ""}`);
825
+ else if (record.trialId) unlabeled = true;
826
+ if (record.errored) {
827
+ lines.push(
828
+ ` errored by ${record.errored.by} in ${record.errored.phase}${record.errored.code ? ` (${record.errored.code})` : ""}: ${record.errored.reason}`,
829
+ );
830
+ }
831
+ if (record.workflowError) lines.push(` the workflow erred: ${record.workflowError}`);
832
+ if (record.stopped) lines.push(` stopped: ${record.stopped}`);
833
+ if (record.leaked) lines.push(" leaked: the key turned up where the workflow ran");
834
+ for (const refused of record.refused) {
835
+ lines.push(` refused in ${refused.phase}: ${refused.message}`);
836
+ }
837
+ for (const unused of record.unused) lines.push(` ${unused} was faked but never called`);
838
+ if (record.reach && !record.reach.ok) {
839
+ for (const problem of record.reach.problems) lines.push(` reach: ${problem}`);
840
+ }
841
+ const facts = factsOf(trial.scores);
842
+ if (facts) lines.push(` facts: ${JSON.stringify(facts)}`);
843
+ const counted = Object.entries(record.runFacts ?? {}).filter(([, n]) => n !== 0);
844
+ if (counted.length > 0) {
845
+ lines.push(` run facts: ${counted.map(([name, n]) => `${name} ${n}`).join(", ")}`);
846
+ }
847
+ if (record.result !== undefined) lines.push(` result: ${JSON.stringify(record.result)}`);
848
+ // What the workflow's stages answered is where a failure's reason usually is; a stubbed stage
849
+ // is the case's own input.
850
+ if (view.outcome === "failed") {
851
+ for (const [stage, value] of Object.entries(record.stages ?? {})) {
852
+ if (stage in (record.stubbedStages ?? {})) continue;
853
+ lines.push(` stage ${stage}: ${clipped(JSON.stringify(value) ?? "undefined", 300)}`);
854
+ }
855
+ }
856
+ for (const entry of newestEntries(trial.scores)) {
857
+ const verdict = entry.errored
858
+ ? `errored: ${entry.errored.reason}`
859
+ : entry.skipped
860
+ ? "not graded: a grader before it failed the trial"
861
+ : (entry.verdict ??
862
+ (entry.notApplies ? `does not apply: ${entry.notApplies}` : "numbers only"));
863
+ const about = [
864
+ ...(entry.version ? [entry.version] : []),
865
+ ...(deciders && !deciders.has(entry.grader) ? ["not in the verdict"] : []),
866
+ ...(entry.estimate !== undefined ? [`est. ${usd(entry.estimate)}`] : []),
867
+ ...(entry.runId ? [`run ${entry.runId}`] : []),
868
+ ];
869
+ lines.push(
870
+ ` ${entry.grader}: ${verdict}${about.length > 0 ? ` (${about.join(", ")})` : ""}`,
871
+ );
872
+ for (const [name, number] of Object.entries(entry.numbers ?? {})) {
873
+ lines.push(
874
+ ` ${name}: ${"count" in number ? `${number.count}/${number.of}` : number.value}`,
875
+ );
876
+ }
877
+ // A reason a part's own line already says, as its why, is said once.
878
+ const parts = new Set(
879
+ (entry.parts ?? []).filter((p) => p.why && p.why.trim() !== "").map((p) => p.about),
880
+ );
881
+ for (const reason of entry.reasons.filter((r) => !parts.has(r.about))) {
882
+ lines.push(` ${reason.about}: ${reason.text}`);
883
+ }
884
+ for (const part of entry.parts ?? []) {
885
+ const settled = part.settled && part.settled !== "agreed" ? ` [${part.settled}]` : "";
886
+ const read = (part.data as { readNotRun?: boolean } | undefined)?.readNotRun
887
+ ? " (read, not run)"
888
+ : "";
889
+ lines.push(
890
+ ` ${part.about}: ${part.verdict ?? part.label}${settled}${read}${part.why ? ` · ${part.why}` : ""}`,
891
+ );
892
+ // A split is worth reading vote by vote; an agreement is its why.
893
+ if (part.settled && part.settled !== "agreed" && part.settled !== "given") {
894
+ for (const vote of part.votes ?? []) {
895
+ const said = vote.verdict ?? vote.label ?? "no answer";
896
+ lines.push(
897
+ ` ${vote.by}${vote.role ? ` (${vote.role})` : ""}: ${said}${vote.why ? ` · ${vote.why}` : ""}`,
898
+ );
899
+ }
900
+ }
901
+ }
902
+ }
903
+ if (record.files.length > 0) lines.push(` files: ${record.files.join(", ")}`);
904
+ }
905
+ // Each trial's id is above: the commands that take one are said once.
906
+ const withIds = trials.filter((t) => t.record.trialId);
907
+ const logs = [...new Set(withIds.map((t) => logsCommand(t.record.trialId!, TRIAL_ID_SLOT)))];
908
+ if (unlabeled || logs.length > 0) lines.push("");
909
+ if (unlabeled) {
910
+ lines.push(`label a trial: awf-lab label ${TRIAL_ID_SLOT} --good | --needs-work "{note}"`);
911
+ }
912
+ for (const command of logs) lines.push(`a trial's logs: ${command}`);
913
+ return lines.join("\n");
914
+ }
915
+
916
+ const TRIAL_ID_SLOT = "{trial id}";
917
+
918
+ /** A text cut to `most` characters, an ellipsis saying it was. */
919
+ const clipped = (text: string, most: number) =>
920
+ text.length > most ? `${text.slice(0, most - 1)}…` : text;
921
+
922
+ const SANDBOX_TEXT = {
923
+ lab: "the lab's box around each trial, srt, reading no key; the workflow's own set aside",
924
+ workflow: "the workflow's own, its agents' reach checked against sandbox.network",
925
+ } as const;
926
+
927
+ /** Who isolated the trials: one line, naming each column's when their `target.ts`s differ. */
928
+ function sandboxLine(run: RunRecord): string {
929
+ const byColumn = run.columns.map((c) => run.folders[c.folder]?.sandbox.by ?? "lab");
930
+ const kinds = new Set(byColumn);
931
+ if (kinds.size <= 1) return `sandbox: ${SANDBOX_TEXT[byColumn[0] ?? "lab"]}`;
932
+ const each = byColumn.map(
933
+ (by, i) => `${columnLabel(run, i)} ${by === "lab" ? "the lab's box" : "the workflow's own"}`,
934
+ );
935
+ return `sandbox: by column, ${each.join(", ")}`;
936
+ }