@lelouchhe/agent-evals 0.0.0-stage → 0.2.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 (105) hide show
  1. package/.env.example +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +396 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +474 -0
  8. package/dist/checkers/judge/prompt.d.ts +19 -0
  9. package/dist/checkers/judge/prompt.js +55 -0
  10. package/dist/checkers/judge/trace.d.ts +6 -0
  11. package/dist/checkers/judge/trace.js +41 -0
  12. package/dist/checkers/mock/index.d.ts +18 -0
  13. package/dist/checkers/mock/index.js +127 -0
  14. package/dist/checkers/shell/index.d.ts +10 -0
  15. package/dist/checkers/shell/index.js +61 -0
  16. package/dist/checkers/trace/index.d.ts +22 -0
  17. package/dist/checkers/trace/index.js +183 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +453 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +356 -0
  22. package/dist/engine/check-runner.d.ts +1 -0
  23. package/dist/engine/check-runner.js +127 -0
  24. package/dist/engine/check-sandbox.d.ts +18 -0
  25. package/dist/engine/check-sandbox.js +171 -0
  26. package/dist/engine/config.d.ts +171 -0
  27. package/dist/engine/config.js +368 -0
  28. package/dist/engine/env-source.d.ts +10 -0
  29. package/dist/engine/env-source.js +114 -0
  30. package/dist/engine/files.d.ts +84 -0
  31. package/dist/engine/files.js +304 -0
  32. package/dist/engine/forwarder.sh +61 -0
  33. package/dist/engine/ignore.d.ts +29 -0
  34. package/dist/engine/ignore.js +67 -0
  35. package/dist/engine/messages.d.ts +8 -0
  36. package/dist/engine/messages.js +9 -0
  37. package/dist/engine/mock-match.d.ts +44 -0
  38. package/dist/engine/mock-match.js +104 -0
  39. package/dist/engine/mocks.d.ts +35 -0
  40. package/dist/engine/mocks.js +336 -0
  41. package/dist/engine/params.d.ts +18 -0
  42. package/dist/engine/params.js +96 -0
  43. package/dist/engine/placement.d.ts +26 -0
  44. package/dist/engine/placement.js +107 -0
  45. package/dist/engine/regex.d.ts +10 -0
  46. package/dist/engine/regex.js +16 -0
  47. package/dist/engine/registry.d.ts +243 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +420 -0
  51. package/dist/engine/results.d.ts +50 -0
  52. package/dist/engine/results.js +42 -0
  53. package/dist/engine/run.d.ts +50 -0
  54. package/dist/engine/run.js +710 -0
  55. package/dist/engine/runtime-assets.d.ts +6 -0
  56. package/dist/engine/runtime-assets.js +11 -0
  57. package/dist/engine/skills.d.ts +49 -0
  58. package/dist/engine/skills.js +270 -0
  59. package/dist/engine/truncate.d.ts +3 -0
  60. package/dist/engine/truncate.js +7 -0
  61. package/dist/engine/values.d.ts +18 -0
  62. package/dist/engine/values.js +75 -0
  63. package/dist/engine/view.d.ts +10 -0
  64. package/dist/engine/view.js +150 -0
  65. package/dist/engine/workspace.d.ts +63 -0
  66. package/dist/engine/workspace.js +305 -0
  67. package/dist/index.d.ts +16 -0
  68. package/dist/index.js +7 -0
  69. package/dist/platform/macos/launch.d.ts +13 -0
  70. package/dist/platform/macos/launch.js +14 -0
  71. package/dist/platform/macos/policy.d.ts +33 -0
  72. package/dist/platform/macos/policy.js +131 -0
  73. package/dist/platform/macos/supervise.d.ts +26 -0
  74. package/dist/platform/macos/supervise.js +98 -0
  75. package/dist/platform/macos/supervisor.sh +13 -0
  76. package/dist/runners/acp/agent.d.ts +17 -0
  77. package/dist/runners/acp/agent.js +38 -0
  78. package/dist/runners/acp/commands.d.ts +2 -0
  79. package/dist/runners/acp/commands.js +112 -0
  80. package/dist/runners/acp/environment.d.ts +71 -0
  81. package/dist/runners/acp/environment.js +280 -0
  82. package/dist/runners/acp/index.d.ts +21 -0
  83. package/dist/runners/acp/index.js +135 -0
  84. package/dist/runners/acp/session.d.ts +7 -0
  85. package/dist/runners/acp/session.js +48 -0
  86. package/dist/runners/acp/trace.d.ts +23 -0
  87. package/dist/runners/acp/trace.js +44 -0
  88. package/dist/runners/acp/usage.d.ts +12 -0
  89. package/dist/runners/acp/usage.js +56 -0
  90. package/dist/runners/noop/index.d.ts +12 -0
  91. package/dist/runners/noop/index.js +22 -0
  92. package/dist/runners/pi/index.d.ts +21 -0
  93. package/dist/runners/pi/index.js +116 -0
  94. package/dist/runners/pi/params.d.ts +10 -0
  95. package/dist/runners/pi/params.js +3 -0
  96. package/dist/runners/pi/rpc.d.ts +30 -0
  97. package/dist/runners/pi/rpc.js +341 -0
  98. package/dist/runners/pi/safe-process-group.d.ts +7 -0
  99. package/dist/runners/pi/safe-process-group.js +13 -0
  100. package/dist/runners/pi/session.d.ts +56 -0
  101. package/dist/runners/pi/session.js +298 -0
  102. package/dist/runners/pi/shell-wrapper.sh +46 -0
  103. package/dist/runners/pi/supervisor.d.ts +1 -0
  104. package/dist/runners/pi/supervisor.js +101 -0
  105. package/package.json +77 -4
@@ -0,0 +1,420 @@
1
+ import { basename } from "node:path";
2
+ import { ConfigError } from "./config.js";
3
+ import { runOutcome } from "./results.js";
4
+ const INDENT = " ";
5
+ const MAX_REASON = 140;
6
+ const MAX_LABEL = 56;
7
+ /**
8
+ * Render run records the way a test runner reports a session: one line per case with its status,
9
+ * time, tokens and cost, the non-passing assertions indented beneath it, and a totals line. A case
10
+ * is a test and its checks are its assertions, so a passing assertion needs no line of its own.
11
+ *
12
+ * Records are grouped by case document and ordered by completion, which is declaration order for a
13
+ * serial sweep: `startedAt` is stamped when an invocation prepares its runs, so it cannot order them.
14
+ */
15
+ export function formatReport(records) {
16
+ if (records.length === 0) {
17
+ return "no run records found\n";
18
+ }
19
+ const ordered = [...records].sort((left, right) => {
20
+ return left.finishedAt.localeCompare(right.finishedAt) || left.runId.localeCompare(right.runId);
21
+ });
22
+ const documents = grouped(ordered);
23
+ const blocks = [...documents].map(([path, cases]) => document(path, cases));
24
+ if (documents.size > 1) {
25
+ blocks.push(`total ${aggregate(ordered)}`);
26
+ }
27
+ return `${blocks.join("\n\n")}\n`;
28
+ }
29
+ /**
30
+ * Render one markdown table per document: a row per declared check, a column per case, and a cell
31
+ * of `passes/judged` over that case's repetitions. A document qualifies only when every case
32
+ * declares the same checks, because a position must mean the same thing in every column; otherwise
33
+ * the requested comparison does not exist and the command says so.
34
+ */
35
+ export function formatMatrix(records) {
36
+ if (records.length === 0) {
37
+ return "no run records found\n";
38
+ }
39
+ const ordered = [...records].sort((left, right) => {
40
+ return left.finishedAt.localeCompare(right.finishedAt) || left.runId.localeCompare(right.runId);
41
+ });
42
+ const blocks = [...grouped(ordered)].map(([path, cases]) => matrix(path, cases));
43
+ return `${blocks.join("\n\n")}\n`;
44
+ }
45
+ /** Records grouped by document and then by case name, in the order each first finished. */
46
+ function grouped(records) {
47
+ const documents = new Map();
48
+ for (const record of records) {
49
+ const label = record.case.name ?? "(ordinary)";
50
+ let cases = documents.get(record.case.path);
51
+ if (cases === undefined) {
52
+ cases = new Map();
53
+ documents.set(record.case.path, cases);
54
+ }
55
+ const runs = cases.get(label);
56
+ if (runs === undefined)
57
+ cases.set(label, [record]);
58
+ else
59
+ runs.push(record);
60
+ }
61
+ return documents;
62
+ }
63
+ /**
64
+ * A run's results by identity: the declared check and the subject the checker named. A record
65
+ * written before the provenance stamp identifies a result by its position instead, because that is
66
+ * the only identity it has; the two reports never mix the two within one record.
67
+ */
68
+ function observations(run) {
69
+ const grouped = new Map();
70
+ run.checks.forEach((check, position) => {
71
+ const key = check.declaration === undefined
72
+ ? `position:${position}`
73
+ : `declaration:${check.declaration}\u0000${check.subject}`;
74
+ const existing = grouped.get(key);
75
+ if (existing === undefined) {
76
+ grouped.set(key, {
77
+ declaration: check.declaration ?? position,
78
+ subject: check.subject,
79
+ checker: check.checker,
80
+ results: [check],
81
+ });
82
+ }
83
+ else {
84
+ existing.results.push(check);
85
+ }
86
+ });
87
+ return grouped;
88
+ }
89
+ /** Every identity the runs share, ordered by declaration and then by first appearance. */
90
+ function identities(perRun) {
91
+ const firstSeen = new Map();
92
+ let index = 0;
93
+ for (const run of perRun) {
94
+ for (const [key, observation] of run) {
95
+ if (!firstSeen.has(key)) {
96
+ firstSeen.set(key, { declaration: observation.declaration, index: index++ });
97
+ }
98
+ }
99
+ }
100
+ return [...firstSeen.entries()]
101
+ .sort(([, left], [, right]) => left.declaration - right.declaration || left.index - right.index)
102
+ .map(([key]) => key);
103
+ }
104
+ function matrix(path, cases) {
105
+ const labels = [...cases.keys()];
106
+ const declarations = [...cases.values()][0]?.[0]?.resolvedConfig.checks ?? [];
107
+ for (const [label, runs] of cases) {
108
+ for (const run of runs) {
109
+ if (!sameValue(run.resolvedConfig.checks, declarations)) {
110
+ const position = firstDifference(declarations, run.resolvedConfig.checks);
111
+ throw new ConfigError(`--matrix needs one check list across cases: "${label}" declares ${describe(run.resolvedConfig.checks[position])} at check ${position + 1}, not ${describe(declarations[position])}`);
112
+ }
113
+ for (const check of run.checks) {
114
+ if (check.declaration === undefined) {
115
+ throw new ConfigError(`--matrix needs records that name their declared check: "${label}" predates that field; use report instead`);
116
+ }
117
+ }
118
+ }
119
+ }
120
+ const columns = labels.map((label) => {
121
+ const runs = cases.get(label) ?? [];
122
+ const negative = runs.length > 0 && runs.every((run) => run.resolvedConfig.expect === "fail");
123
+ return `${escape(label)}${negative ? " (expect fail)" : ""}`;
124
+ });
125
+ const perCase = labels.map((label) => (cases.get(label) ?? []).map(observations));
126
+ const keys = identities(perCase.flat());
127
+ const rows = keys.map((key, index) => {
128
+ const observation = perCase
129
+ .flat()
130
+ .map((run) => run.get(key))
131
+ .find((entry) => entry !== undefined);
132
+ const subject = `${observation?.checker ?? value(declarations[index]?.["$type"] ?? "check")} ${observation?.subject ?? "check"}`;
133
+ const cells = perCase.map((runs) => cell(runs, key));
134
+ return `| ${index + 1} | ${escape(subject)} | ${cells.join(" | ")} |`;
135
+ });
136
+ const table = [
137
+ `| # | Check | ${columns.join(" | ")} |`,
138
+ `| --- | --- | ${columns.map(() => "---").join(" | ")} |`,
139
+ ...rows,
140
+ ];
141
+ if (rows.length === 0) {
142
+ table.push("", "No check result was recorded for any repetition.");
143
+ }
144
+ return [path, instrument(cases), "", ...table].join("\n");
145
+ }
146
+ /** `passes/judged` for one identity across a case's runs, with errors and absence named. */
147
+ function cell(runs, key) {
148
+ if (runs.length === 0) {
149
+ return "—";
150
+ }
151
+ const observed = runs.flatMap((run) => run.get(key)?.results ?? []);
152
+ const missing = runs.filter((run) => !run.has(key)).length;
153
+ if (observed.length === 0) {
154
+ return `— (${missing} not judged)`;
155
+ }
156
+ const passes = observed.filter((check) => check.status === "pass").length;
157
+ const errors = observed.filter((check) => check.status === "error").length;
158
+ const parts = [`${passes}/${observed.length}`];
159
+ if (errors > 0)
160
+ parts.push(`(${errors} err)`);
161
+ if (missing > 0)
162
+ parts.push(`(${missing} not judged)`);
163
+ return parts.join(" ");
164
+ }
165
+ /** The first declaration position where two lists differ, or the shorter length when nested. */
166
+ function firstDifference(left, right) {
167
+ const length = Math.max(left.length, right.length);
168
+ for (let index = 0; index < length; index += 1) {
169
+ if (!sameValue(left[index], right[index])) {
170
+ return index;
171
+ }
172
+ }
173
+ return Math.min(left.length, right.length);
174
+ }
175
+ /** Arrays are ordered and mappings are not; an authored key order is not a check parameter. */
176
+ function sameValue(left, right) {
177
+ if (Object.is(left, right)) {
178
+ return true;
179
+ }
180
+ if (Array.isArray(left) || Array.isArray(right)) {
181
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
182
+ return false;
183
+ }
184
+ return left.every((value, index) => sameValue(value, right[index]));
185
+ }
186
+ if (typeof left === "object" && left !== null && typeof right === "object" && right !== null) {
187
+ const leftKeys = Object.keys(left);
188
+ const rightKeys = Object.keys(right);
189
+ if (leftKeys.length !== rightKeys.length) {
190
+ return false;
191
+ }
192
+ return leftKeys.every((key) => Object.hasOwn(right, key) &&
193
+ sameValue(left[key], right[key]));
194
+ }
195
+ return false;
196
+ }
197
+ /** A declaration in an error message: one line, bounded, and never the word undefined. */
198
+ function describe(spec) {
199
+ return spec === undefined ? "nothing" : truncate(JSON.stringify(spec), 120);
200
+ }
201
+ /** A table cell is one line: a pipe would open a column and any line ending would end the row. */
202
+ function escape(text) {
203
+ return text.replaceAll("|", "\\|").replaceAll(/\r\n?|\n/g, " ");
204
+ }
205
+ function document(path, cases) {
206
+ const runs = [...cases.values()].flat();
207
+ const lines = [path, instrument(cases), ""];
208
+ const width = Math.min(MAX_LABEL, longest([...cases.keys()]));
209
+ const verdictWidth = Math.max(7, ...[...cases.values()].map((caseRuns) => verdictOf(caseRuns).length));
210
+ for (const [label, caseRuns] of cases) {
211
+ lines.push(caseLine(label, caseRuns, width, verdictWidth));
212
+ for (const detail of details(caseRuns)) {
213
+ lines.push(`${INDENT}${detail}`);
214
+ }
215
+ }
216
+ lines.push("", aggregate(runs));
217
+ return lines.join("\n");
218
+ }
219
+ /** The line under a document heading: which instruments ran it and at what repetition count. */
220
+ function instrument(cases) {
221
+ const runs = [...cases.values()].flat();
222
+ const counts = new Set([...cases.values()].map((entry) => entry.length));
223
+ const judges = judgeInstruments(runs);
224
+ const parts = [
225
+ `runner ${listed(runs.map((run) => value(run.resolvedConfig.runner["$type"])))}`,
226
+ `harness ${listed(runs.map(harness))}`,
227
+ `model ${listed(runs.map(model))}`,
228
+ ...(judges.length === 0 ? [] : [`judge ${listed(judges)}`]),
229
+ counts.size === 1 ? `reps ${[...counts][0]}` : "reps mixed",
230
+ `cases ${cases.size}`,
231
+ ];
232
+ return parts.join(" · ");
233
+ }
234
+ function caseLine(label, runs, width, verdictWidth) {
235
+ const verdict = verdictOf(runs);
236
+ const cells = [
237
+ `${runs.length} run${runs.length === 1 ? "" : "s"}`.padStart(8),
238
+ duration(sum(runs, (run) => run.runner.durationMs)).padStart(8),
239
+ tokens(runs).padStart(11),
240
+ cost(runs).padStart(9),
241
+ ];
242
+ return `${verdict.padEnd(verdictWidth)} ${label.padEnd(width)} ${cells.join(" ")}`.trimEnd();
243
+ }
244
+ /**
245
+ * One line per check that did not pass in every run; the rest are represented by the case verdict.
246
+ * A check is its declared position, not its subject: one case may declare the same subject twice
247
+ * with different parameters, and then two checks share a label. Every run is in the denominator,
248
+ * and a run that recorded no check at all is reported as not judged rather than dropped.
249
+ */
250
+ function details(runs) {
251
+ const perRun = runs.map(observations);
252
+ const lines = [];
253
+ for (const key of identities(perRun)) {
254
+ const observed = perRun.flatMap((run) => run.get(key)?.results ?? []);
255
+ if (observed.length === 0)
256
+ continue;
257
+ const missing = perRun.filter((run) => !run.has(key)).length;
258
+ if (missing === 0 && observed.every((check) => check.status === "pass"))
259
+ continue;
260
+ const subject = perRun.map((run) => run.get(key)).find((entry) => entry !== undefined).subject;
261
+ const counts = new Map();
262
+ for (const check of observed) {
263
+ if (check.status !== "pass")
264
+ counts.set(check.status, (counts.get(check.status) ?? 0) + 1);
265
+ }
266
+ const parts = [...counts.entries()].map(([status, count]) => `${count}/${observed.length} ${status}`);
267
+ if (missing > 0)
268
+ parts.push(`${missing}/${runs.length} not judged`);
269
+ const first = observed.find((check) => check.status !== "pass");
270
+ const reason = truncate(first?.reason ?? "", MAX_REASON);
271
+ lines.push(`✗ ${subject} ${parts.join(", ")}${reason === "" ? "" : ` — ${reason}`}`);
272
+ }
273
+ return lines;
274
+ }
275
+ function verdictOf(runs) {
276
+ const outcomes = runs.map(runOutcome);
277
+ if (outcomes.some((outcome) => outcome === "error" || outcome === "timeout" || outcome === "cancelled")) {
278
+ return "ERROR";
279
+ }
280
+ // A negative case that ever passed is one failure, however many repetitions failed as declared.
281
+ if (outcomes.some((outcome) => outcome === "unexpected-pass"))
282
+ return "UNEXPECTED PASS";
283
+ if (outcomes.every((outcome) => outcome === "pass"))
284
+ return "PASS";
285
+ if (outcomes.every((outcome) => outcome === "fail"))
286
+ return "FAIL";
287
+ if (outcomes.every((outcome) => outcome === "expected-fail"))
288
+ return "EXPECTED FAIL";
289
+ return "FLAKY";
290
+ }
291
+ function aggregate(runs) {
292
+ const outcomes = runs.map(runOutcome);
293
+ const count = (outcome) => outcomes.filter((value) => value === outcome).length;
294
+ const passed = count("pass") + count("unexpected-pass");
295
+ const failed = count("fail") + count("expected-fail");
296
+ const named = [
297
+ ...(passed === 0
298
+ ? []
299
+ : [`${passed} passed${count("unexpected-pass") === 0 ? "" : ` (${count("unexpected-pass")} unexpected)`}`]),
300
+ ...(failed === 0
301
+ ? []
302
+ : [`${failed} fail${count("expected-fail") === 0 ? "" : ` (${count("expected-fail")} expected)`}`]),
303
+ ...["error", "timeout", "cancelled"]
304
+ .filter((status) => count(status) > 0)
305
+ .map((status) => `${count(status)} ${status}`),
306
+ ];
307
+ return [
308
+ `${runs.length} run${runs.length === 1 ? "" : "s"}`,
309
+ ...named,
310
+ duration(sum(runs, (run) => run.runner.durationMs)),
311
+ tokens(runs),
312
+ cost(runs),
313
+ ].join(" · ");
314
+ }
315
+ function tokens(runs) {
316
+ const reported = runs.filter((run) => run.runner.usage?.tokens !== undefined);
317
+ if (reported.length === 0)
318
+ return "—";
319
+ const total = sum(reported, (run) => run.runner.usage?.tokens?.totalTokens ?? 0);
320
+ return `${scaled(total)} tok${coverage(reported.length, runs.length)}`;
321
+ }
322
+ function cost(runs) {
323
+ const reported = runs.filter((run) => run.runner.usage?.cost !== undefined && run.runner.usage.cost !== null);
324
+ if (reported.length === 0)
325
+ return "—";
326
+ const currencies = new Set(reported.map((run) => run.runner.usage?.cost?.currency));
327
+ if (currencies.size !== 1)
328
+ return "—";
329
+ const currency = [...currencies][0] ?? "";
330
+ const total = sum(reported, (run) => run.runner.usage?.cost?.amount ?? 0);
331
+ const text = currency === "USD" ? `$${total.toFixed(4)}` : `${total.toFixed(4)} ${currency}`;
332
+ return `${text}${coverage(reported.length, runs.length)}`;
333
+ }
334
+ /** Say so when only some runs reported a figure, so a subtotal is never read as a total. */
335
+ function coverage(reported, total) {
336
+ return reported === total ? "" : ` (${reported}/${total})`;
337
+ }
338
+ /** Distinct values in first-seen order, so a document that mixes instruments says so. */
339
+ function listed(values) {
340
+ const seen = [];
341
+ for (const item of values) {
342
+ if (!seen.includes(item))
343
+ seen.push(item);
344
+ }
345
+ const shown = seen.slice(0, 3).join(", ");
346
+ return seen.length > 3 ? `${shown}, …` : shown;
347
+ }
348
+ function longest(values) {
349
+ let size = 0;
350
+ for (const item of values) {
351
+ const length = typeof item === "string" ? item.length : item.length;
352
+ if (length > size)
353
+ size = length;
354
+ }
355
+ return size;
356
+ }
357
+ function harness(record) {
358
+ return harnessOf(record.resolvedConfig.runner);
359
+ }
360
+ function model(record) {
361
+ return modelOf(record.resolvedConfig.runner);
362
+ }
363
+ function harnessOf(runner) {
364
+ const agent = runner["agent"];
365
+ if (typeof agent !== "string")
366
+ return value(runner["$type"]);
367
+ const name = basename(agent);
368
+ return value(name.includes(".") ? name.slice(0, name.lastIndexOf(".")) : name);
369
+ }
370
+ function modelOf(runner) {
371
+ const config = runner["config"];
372
+ const configured = typeof config === "object" && config !== null ? config["model"] : undefined;
373
+ return value(configured ?? runner["model"]);
374
+ }
375
+ function judgeInstruments(runs) {
376
+ const result = [];
377
+ for (const run of runs) {
378
+ for (const check of run.resolvedConfig.checks) {
379
+ if (check["$type"] !== "judge")
380
+ continue;
381
+ const declared = check["runner"];
382
+ const runner = typeof declared === "object" && declared !== null && !Array.isArray(declared)
383
+ ? declared
384
+ : run.resolvedConfig.runner;
385
+ const judgeHarness = harnessOf(runner);
386
+ const judgeModel = modelOf(runner);
387
+ result.push(judgeModel === "—" ? judgeHarness : `${judgeHarness}/${judgeModel}`);
388
+ }
389
+ }
390
+ return result;
391
+ }
392
+ function value(input) {
393
+ if (typeof input !== "string")
394
+ return "—";
395
+ const singleLine = input.replace(/\r\n?|[\n\u0085\u2028\u2029]/gu, " ").trim();
396
+ return singleLine === "" ? "—" : singleLine;
397
+ }
398
+ function sum(runs, pick) {
399
+ return runs.reduce((total, run) => total + pick(run), 0);
400
+ }
401
+ function scaled(count) {
402
+ if (count < 1_000)
403
+ return String(count);
404
+ if (count < 1_000_000)
405
+ return `${(count / 1_000).toFixed(1)}k`;
406
+ return `${(count / 1_000_000).toFixed(1)}M`;
407
+ }
408
+ function duration(milliseconds) {
409
+ if (milliseconds < 1_000)
410
+ return `${milliseconds}ms`;
411
+ const seconds = milliseconds / 1_000;
412
+ if (seconds < 60)
413
+ return `${seconds.toFixed(1)}s`;
414
+ const minutes = Math.floor(seconds / 60);
415
+ return `${minutes}m${Math.round(seconds % 60)}s`;
416
+ }
417
+ function truncate(reason, limit) {
418
+ const single = reason.replace(/\s+/gu, " ").trim();
419
+ return single.length > limit ? `${single.slice(0, limit)}…` : single;
420
+ }
@@ -0,0 +1,50 @@
1
+ import type { CaseConfig } from "./config.js";
2
+ import type { MockRecord, RecordedCheckResult, RunnerUsage, TraceEntry } from "./registry.js";
3
+ export type RunStatus = "pass" | "fail" | "error" | "timeout" | "cancelled";
4
+ export type RetainArtifacts = "none" | "on-failure" | "all";
5
+ /** A run read against its case's expectation; the only place `expect` changes a status's meaning. */
6
+ export type RunOutcome = RunStatus | "expected-fail" | "unexpected-pass";
7
+ export declare function classifyOutcome(status: RunStatus, expect: CaseConfig["expect"]): RunOutcome;
8
+ export declare function runOutcome(run: EvaluationRecord): RunOutcome;
9
+ export type RunnerStatus = "completed" | "error" | "timeout" | "cancelled";
10
+ export interface RunnerRecord {
11
+ readonly type: string;
12
+ readonly status: RunnerStatus;
13
+ readonly durationMs: number;
14
+ readonly finalText: string | null;
15
+ /** What the harness reported it consumed; absent when it reports nothing. */
16
+ readonly usage?: RunnerUsage;
17
+ }
18
+ export interface EvaluationRecord {
19
+ readonly schemaVersion: 1;
20
+ readonly runId: string;
21
+ readonly startedAt: string;
22
+ readonly finishedAt: string;
23
+ readonly case: {
24
+ readonly path: string;
25
+ readonly name?: string;
26
+ };
27
+ /** The declared configuration; placeholders remain unsubstituted. */
28
+ readonly resolvedConfig: CaseConfig;
29
+ readonly status: RunStatus;
30
+ readonly runner: RunnerRecord;
31
+ readonly checks: readonly RecordedCheckResult[];
32
+ readonly error?: string;
33
+ readonly diagnostics: readonly string[];
34
+ readonly cleanup: {
35
+ readonly status: "removed" | "failed";
36
+ readonly error?: string;
37
+ };
38
+ readonly artifacts?: {
39
+ readonly status: "retained" | "failed";
40
+ readonly path?: string;
41
+ readonly error?: string;
42
+ };
43
+ }
44
+ export interface ResultPaths {
45
+ readonly directory: string;
46
+ readonly result: string;
47
+ }
48
+ export declare function newRunId(now?: Date): string;
49
+ export declare function createResultDirectory(resultsRoot: string, runId: string): Promise<ResultPaths>;
50
+ export declare function writeResult(paths: ResultPaths, record: EvaluationRecord, trace?: readonly TraceEntry[], mockRecords?: readonly MockRecord[]): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { mkdir, rename, writeFile } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ export function classifyOutcome(status, expect) {
5
+ if (status === "pass") {
6
+ return expect === "fail" ? "unexpected-pass" : "pass";
7
+ }
8
+ if (status === "fail") {
9
+ return expect === "fail" ? "expected-fail" : "fail";
10
+ }
11
+ return status;
12
+ }
13
+ export function runOutcome(run) {
14
+ return classifyOutcome(run.status, run.resolvedConfig.expect);
15
+ }
16
+ export function newRunId(now = new Date()) {
17
+ return `${now.toISOString().replaceAll(":", "-").replaceAll(".", "-")}-${randomUUID().slice(0, 8)}`;
18
+ }
19
+ export async function createResultDirectory(resultsRoot, runId) {
20
+ const directory = resolve(resultsRoot, runId);
21
+ await mkdir(directory, { recursive: true, mode: 0o700 });
22
+ return { directory, result: join(directory, "result.json") };
23
+ }
24
+ export async function writeResult(paths, record, trace, mockRecords) {
25
+ if (trace !== undefined) {
26
+ await writeFile(join(paths.directory, "trace.json"), JSON.stringify(trace, null, 2) + "\n", { mode: 0o600 });
27
+ }
28
+ if (mockRecords !== undefined) {
29
+ await writeFile(join(paths.directory, "mocks.json"), JSON.stringify(mockRecords, null, 2) + "\n", {
30
+ mode: 0o600,
31
+ });
32
+ }
33
+ const temporary = `${paths.result}.tmp`;
34
+ await writeFile(temporary, JSON.stringify(record, null, 2) + "\n", { mode: 0o600 });
35
+ await rename(temporary, paths.result);
36
+ if (record.diagnostics.length > 0) {
37
+ await writeFile(join(paths.directory, "diagnostics.log"), formatDiagnostics(record.diagnostics), { mode: 0o600 });
38
+ }
39
+ }
40
+ function formatDiagnostics(diagnostics) {
41
+ return diagnostics.map((line) => `- ${line.replaceAll("\n", "\n ")}`).join("\n") + "\n";
42
+ }
@@ -0,0 +1,50 @@
1
+ import { type ResolvedCase } from "./config.js";
2
+ import { type Checker, type Registry, type Runner } from "./registry.js";
3
+ import { type EvaluationRecord, type RetainArtifacts } from "./results.js";
4
+ import { type EnvSource } from "./env-source.js";
5
+ export interface RunRequest {
6
+ readonly case: ResolvedCase;
7
+ readonly registry: Registry;
8
+ readonly resultsDir: string;
9
+ readonly retain?: RetainArtifacts;
10
+ readonly signal?: AbortSignal;
11
+ /** Parent directory for the temporary run root. Tests use this to inspect cleanup. */
12
+ readonly tempParent?: string;
13
+ /** Environment-value source override for tests; defaults to `.env` in the invocation cwd. */
14
+ readonly envSource?: EnvSource;
15
+ }
16
+ /** One validated case, bound to run directories that do not exist yet. */
17
+ export interface PreparedEvaluation {
18
+ readonly request: RunRequest;
19
+ readonly runId: string;
20
+ readonly startedAt: string;
21
+ readonly root: string;
22
+ readonly workspaceDir: string;
23
+ readonly homeDir: string;
24
+ readonly tmpDir: string;
25
+ readonly mocksDir: string;
26
+ readonly engineDir: string;
27
+ /** A runner-owned writable directory; only the native Pi runner uses it. */
28
+ readonly configDir: string;
29
+ readonly baselineWorkspaceDir: string;
30
+ readonly baselineHomeDir: string;
31
+ readonly registered: {
32
+ readonly runnerType: string;
33
+ readonly runner: Runner;
34
+ readonly checks: readonly {
35
+ readonly type: string;
36
+ readonly checker: Checker;
37
+ }[];
38
+ /** Shared mutable resource keys across all runners created for this evaluation (case + checkers). */
39
+ readonly concurrencyKeys: readonly string[];
40
+ };
41
+ }
42
+ /**
43
+ * Validate a case and bind it to new run directories without creating them, so a caller can
44
+ * validate every selected case before the first one runs.
45
+ */
46
+ export declare function prepareEvaluation(request: RunRequest): Promise<PreparedEvaluation>;
47
+ /** Validate configuration, execute one runner, run all checks, and clean up. */
48
+ export declare function runEvaluation(request: RunRequest): Promise<EvaluationRecord>;
49
+ /** Execute one prepared case: prepare the run root, drive the runner, check, record and clean up. */
50
+ export declare function executeEvaluation(prepared: PreparedEvaluation): Promise<EvaluationRecord>;