@tobi-or-not/quorum 0.2.0 → 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 (49) hide show
  1. package/README.md +3 -1
  2. package/dist/bench/attacks.d.ts +103 -0
  3. package/dist/bench/attacks.js +272 -0
  4. package/dist/bench/fingerprint.d.ts +37 -0
  5. package/dist/bench/fingerprint.js +80 -0
  6. package/dist/bench/independence.d.ts +28 -0
  7. package/dist/bench/independence.js +67 -0
  8. package/dist/bench/records.d.ts +220 -0
  9. package/dist/bench/records.js +184 -0
  10. package/dist/bench/report.d.ts +143 -0
  11. package/dist/bench/report.js +538 -0
  12. package/dist/bench/run-dir.d.ts +127 -0
  13. package/dist/bench/run-dir.js +458 -0
  14. package/dist/bench/runner.d.ts +92 -0
  15. package/dist/bench/runner.js +195 -0
  16. package/dist/bench/score.d.ts +61 -0
  17. package/dist/bench/score.js +85 -0
  18. package/dist/bench/stats.d.ts +105 -0
  19. package/dist/bench/stats.js +158 -0
  20. package/dist/bench/suite.d.ts +132 -0
  21. package/dist/bench/suite.js +454 -0
  22. package/dist/cli/bench.d.ts +43 -0
  23. package/dist/cli/bench.js +537 -0
  24. package/dist/cli/io.d.ts +52 -0
  25. package/dist/cli/io.js +63 -0
  26. package/dist/cli/main.d.ts +7 -37
  27. package/dist/cli/main.js +18 -85
  28. package/dist/cli/render.d.ts +10 -0
  29. package/dist/cli/render.js +20 -11
  30. package/dist/config/load.d.ts +46 -0
  31. package/dist/config/load.js +56 -14
  32. package/dist/core/diff.d.ts +20 -0
  33. package/dist/core/diff.js +102 -0
  34. package/dist/core/errors.d.ts +6 -0
  35. package/dist/core/errors.js +5 -0
  36. package/dist/core/prompts.d.ts +3 -1
  37. package/dist/core/prompts.js +8 -3
  38. package/dist/core/sanitize.d.ts +16 -1
  39. package/dist/core/sanitize.js +28 -4
  40. package/dist/core/stages/context.d.ts +12 -3
  41. package/dist/core/stages/context.js +23 -3
  42. package/dist/providers/anthropic.js +6 -3
  43. package/dist/providers/claude-code.js +11 -10
  44. package/dist/providers/gemini.js +9 -4
  45. package/dist/providers/ollama.js +6 -4
  46. package/dist/providers/openai-compatible.js +6 -4
  47. package/dist/providers/reply.d.ts +6 -2
  48. package/dist/providers/reply.js +13 -3
  49. package/package.json +2 -2
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Every read and write of a bench run directory, which holds `run.json` (written whole when the run begins,
3
+ * and again when a re-score records the suite's new scoring hash), `results.jsonl` (one line per review,
4
+ * appended one at a time), and the reports (`report.md` and `report.json`, rewritten whole). Both data
5
+ * files are read as untrusted, since another run or a person may have written them: strict schemas (see
6
+ * `records.ts`), bounded sizes, and no file that is not a regular file. No write follows a symbolic link:
7
+ * `results.jsonl` is opened with `O_NOFOLLOW`, and every other file is written to a new file that is
8
+ * renamed over the name, which replaces a link there. `run.json` and `results.jsonl` are made readable by
9
+ * their owner only; the reports are made as any new file.
10
+ *
11
+ * Every message is fixed text, the name of a file and, for an I/O failure, the error's code; never the
12
+ * runtime's own message. A directory or a file this run cannot trust as its own is a `ConfigError`; an
13
+ * I/O failure is an `Error`.
14
+ */
15
+ import { randomBytes } from 'node:crypto';
16
+ import { constants } from 'node:fs';
17
+ import { lstat, mkdir, open, opendir, rename, unlink } from 'node:fs/promises';
18
+ import { join, resolve } from 'node:path';
19
+ import { decode, readBounded } from "../config/load.js";
20
+ import { ConfigError } from "../core/errors.js";
21
+ import { inertJson } from "../core/sanitize.js";
22
+ import { MAX_RECORD_BYTES, MAX_RUN_FILE_BYTES, parseRecord, parseRunFile } from "./records.js";
23
+ export const RUN_FILE = 'run.json';
24
+ export const RESULTS_FILE = 'results.jsonl';
25
+ export const REPORT_MARKDOWN = 'report.md';
26
+ export const REPORT_JSON = 'report.json';
27
+ /** How the directory is named in an issue: by the flag that names it. */
28
+ const OUT = '--out';
29
+ /** How `runDifferences` words a configuration that was given no path. */
30
+ const DEFAULT_CONFIGURATION = '(default configuration)';
31
+ /** The bytes read from `results.jsonl` at a time. */
32
+ const CHUNK_BYTES = 64 * 1024;
33
+ /** The byte that ends a line; no multi-byte UTF-8 sequence holds it. */
34
+ const LINE_FEED = 0x0A;
35
+ /** An error code worth printing: `EACCES`, never text. */
36
+ const ERROR_CODE = /^E[A-Z]+$/;
37
+ /** Whether the platform can refuse a symbolic link at the open itself. */
38
+ const HAS_NOFOLLOW = typeof constants.O_NOFOLLOW === 'number';
39
+ const NO_FOLLOW = HAS_NOFOLLOW
40
+ ? constants.O_NOFOLLOW
41
+ : 0;
42
+ /** Without blocking, so a FIFO is refused instead of waited for. */
43
+ const READ_FLAGS = constants.O_RDONLY | constants.O_NONBLOCK | NO_FOLLOW;
44
+ /** Without blocking too, so a FIFO swapped in after the read is refused instead of waited for. */
45
+ const APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_NONBLOCK | NO_FOLLOW;
46
+ const NEW_FILE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL;
47
+ /** The mode `run.json` and `results.jsonl` are made with: read and written by their owner only. */
48
+ const OWNER_ONLY = 0o600;
49
+ /** The name `writeAtomic` gives the temporary file of `run.json`, which a run killed while it wrote can leave. */
50
+ const LEFTOVER_RUN_FILE = /^\.run\.json\.[0-9a-f]{8}\.tmp$/;
51
+ /** What `openRecords` says of a `results.jsonl` whose length is not the one the read found. */
52
+ const CHANGED = 'changed after this run read it, so another run may be using this --out: run one at a time';
53
+ function refusal(path, message) {
54
+ return new ConfigError([
55
+ { path, message },
56
+ ]);
57
+ }
58
+ /** The code of a failed system call, when it is one worth printing. */
59
+ function errorCode(error) {
60
+ const code = error?.code;
61
+ return typeof code === 'string' && ERROR_CODE.test(code)
62
+ ? code
63
+ : undefined;
64
+ }
65
+ /** ` (EACCES)`, or nothing for an error without a code worth printing. */
66
+ function codeSuffix(error) {
67
+ const code = errorCode(error);
68
+ return code === undefined
69
+ ? ''
70
+ : ` (${code})`;
71
+ }
72
+ function ioFailure(file, what, error) {
73
+ return new Error(`${file}: ${what}${codeSuffix(error)}`);
74
+ }
75
+ /**
76
+ * Whether `directory` holds an entry, of any kind, whose name is not that of the temporary `run.json` a
77
+ * killed run leaves: it reads entries until it finds one, and no more.
78
+ */
79
+ async function holdsEntry(directory) {
80
+ try {
81
+ const entries = await opendir(directory);
82
+ try {
83
+ for (let entry = await entries.read(); entry !== null; entry = await entries.read()) {
84
+ if (!LEFTOVER_RUN_FILE.test(entry.name))
85
+ return true;
86
+ }
87
+ return false;
88
+ }
89
+ finally {
90
+ await entries.close().catch(() => undefined);
91
+ }
92
+ }
93
+ catch (error) {
94
+ throw ioFailure(OUT, 'cannot be read', error);
95
+ }
96
+ }
97
+ /** `empty` for a directory with no `run.json` and no entry, the temporary `run.json` of a killed run aside; refused when it holds any other. */
98
+ async function emptyDirectory(directory) {
99
+ if (await holdsEntry(directory))
100
+ throw refusal(OUT, `holds files but no ${RUN_FILE}, so it is not a run directory: name a new directory, or an empty one`);
101
+ return { kind: 'empty' };
102
+ }
103
+ /**
104
+ * What `directory`, the run directory a command was given, holds. A directory that does not exist is
105
+ * `none`, an empty one `empty`, and one holding a `run.json` this quorum can read is that run. Refused,
106
+ * as a `ConfigError`: a symbolic link, anything but a directory, a directory that holds files but no
107
+ * `run.json` (the temporary `run.json` of a killed run aside, which counts as no file and is left where it
108
+ * is), and a `run.json` that is a link, is not a file, is over 1 MiB, or is not a run file of this
109
+ * format. The path is read as written, but for a trailing separator or `.`, which would follow a link;
110
+ * its parents may be links: they are the user's own path.
111
+ *
112
+ * @throws ConfigError as above; Error when the directory or `run.json` cannot be read
113
+ */
114
+ export async function inspectRunDir(directory) {
115
+ // Resolved first: `lstat` follows a link when the path ends in a separator or a `.`.
116
+ const location = resolve(directory);
117
+ let stats;
118
+ try {
119
+ stats = await lstat(location);
120
+ }
121
+ catch (error) {
122
+ if (errorCode(error) === 'ENOENT')
123
+ return { kind: 'none' };
124
+ throw ioFailure(OUT, 'cannot be read', error);
125
+ }
126
+ if (stats.isSymbolicLink())
127
+ throw refusal(OUT, 'is a symbolic link');
128
+ if (!stats.isDirectory())
129
+ throw refusal(OUT, 'is not a directory');
130
+ const bytes = await readBounded(join(location, RUN_FILE), MAX_RUN_FILE_BYTES, '1 MiB', { noFollow: true });
131
+ if ('problem' in bytes) {
132
+ if (bytes.problem === 'does not exist')
133
+ return emptyDirectory(location);
134
+ throw bytes.problem === 'cannot be read'
135
+ ? new Error(`${RUN_FILE}: cannot be read`)
136
+ : refusal(RUN_FILE, bytes.problem);
137
+ }
138
+ const text = decode(bytes.value);
139
+ const run = 'problem' in text
140
+ ? undefined
141
+ : parseRunFile(text.value);
142
+ if (run === undefined)
143
+ throw refusal(RUN_FILE, 'is not a run file this quorum writes');
144
+ return { kind: 'run', run };
145
+ }
146
+ /**
147
+ * What stops a run from resuming `recorded` as the run `current` describes, each an issue to print: the
148
+ * quorum version first of all (a release can change a preset's defaults without changing a fingerprint,
149
+ * which holds the preset by name), then another suite by its name, else a suite whose review hash changed
150
+ * (its case ids, its trials or its patches), then each current configuration the run does not hold, at
151
+ * `--config`, then each recorded one that is not given again. A changed scoring hash alone is no
152
+ * difference: the run's records are scored again under the suite as it is now. A current and a recorded
153
+ * configuration that share a path (`null`, the usual resolution, included) but not a fingerprint are one
154
+ * configuration whose settings changed, and give one issue in place of the two. The same configurations in
155
+ * another order are the same run. A configuration is named by its path as written, or
156
+ * `(default configuration)`: the recorded paths are text from `run.json`, to make inert where they are
157
+ * printed.
158
+ */
159
+ export function runDifferences(recorded, current) {
160
+ const issues = [];
161
+ if (recorded.quorum !== current.quorum) {
162
+ issues.push({ path: RUN_FILE, message: `was written by quorum ${recorded.quorum}, and this is quorum ${current.quorum}: a run belongs to one build, so resume it with the quorum that began it, or name a new ${OUT}` });
163
+ }
164
+ if (recorded.suite.name !== current.suite.name) {
165
+ issues.push({ path: RUN_FILE, message: `is a run of the suite ${recorded.suite.name}, not ${current.suite.name}: name a new ${OUT}` });
166
+ }
167
+ else if (recorded.suite.reviewHash !== current.suite.reviewHash) {
168
+ issues.push({ path: RUN_FILE, message: `the suite's case ids, trials or patches changed since the run began: name a new ${OUT}` });
169
+ }
170
+ const recordedPrints = new Set(recorded.configurations.map(({ fingerprint }) => fingerprint));
171
+ const currentPrints = new Set(current.configurations.map(({ fingerprint }) => fingerprint));
172
+ const changed = new Set();
173
+ for (const { path, fingerprint } of current.configurations) {
174
+ if (recordedPrints.has(fingerprint))
175
+ continue;
176
+ const name = path ?? DEFAULT_CONFIGURATION;
177
+ const before = recorded.configurations.find(entry => entry.path === path && !currentPrints.has(entry.fingerprint) && !changed.has(entry.fingerprint));
178
+ if (before === undefined) {
179
+ issues.push({ path: '--config', message: `${name} is not one of the run's configurations` });
180
+ }
181
+ else {
182
+ changed.add(before.fingerprint);
183
+ issues.push({ path: '--config', message: `the settings of ${name} changed since the run began: name a new ${OUT}` });
184
+ }
185
+ }
186
+ for (const { path, fingerprint } of recorded.configurations) {
187
+ if (!currentPrints.has(fingerprint) && !changed.has(fingerprint))
188
+ issues.push({ path: RUN_FILE, message: `its configuration ${path ?? DEFAULT_CONFIGURATION} is not given` });
189
+ }
190
+ return issues;
191
+ }
192
+ /**
193
+ * Write `run.json` into `directory` whole, through a new file and a rename, which replaces the file that
194
+ * was there. `run.json` is readable by its owner only, so a looser mode its owner gave it is not kept.
195
+ *
196
+ * @throws Error `run.json: cannot be written (<code>)`
197
+ */
198
+ export async function writeRunFile(directory, run) {
199
+ await writeAtomic(directory, RUN_FILE, `${inertJson(run)}\n`, OWNER_ONLY);
200
+ }
201
+ /**
202
+ * Make `directory` and its parents, then write `run.json` into it (see `writeRunFile`).
203
+ *
204
+ * @throws Error `<directory>: cannot be created (<code>)`, or `run.json: cannot be written (<code>)`
205
+ */
206
+ export async function createRun(directory, run) {
207
+ try {
208
+ await mkdir(directory, { recursive: true });
209
+ }
210
+ catch (error) {
211
+ throw ioFailure(directory, 'cannot be created', error);
212
+ }
213
+ await writeRunFile(directory, run);
214
+ }
215
+ /** `results.jsonl` opened to be read, or undefined when there is none; refused when it is a link or not a file. */
216
+ async function openResults(path) {
217
+ let stats;
218
+ try {
219
+ stats = await lstat(path);
220
+ }
221
+ catch (error) {
222
+ if (errorCode(error) === 'ENOENT')
223
+ return undefined;
224
+ throw ioFailure(RESULTS_FILE, 'cannot be read', error);
225
+ }
226
+ if (stats.isSymbolicLink())
227
+ throw refusal(RESULTS_FILE, 'is a symbolic link');
228
+ if (!stats.isFile())
229
+ throw refusal(RESULTS_FILE, 'is not a file');
230
+ try {
231
+ return await open(path, READ_FLAGS);
232
+ }
233
+ catch (error) {
234
+ throw errorCode(error) === 'ELOOP'
235
+ ? refusal(RESULTS_FILE, 'is a symbolic link')
236
+ : ioFailure(RESULTS_FILE, 'cannot be read', error);
237
+ }
238
+ }
239
+ /** The line `bytes` holds, read as a record and handed to `visit`; a line that is none, or that `visit` refuses, is an issue. */
240
+ function visitLine(bytes, line, visit) {
241
+ const text = decode(bytes);
242
+ const record = 'problem' in text
243
+ ? undefined
244
+ : parseRecord(text.value);
245
+ if (record === undefined)
246
+ throw refusal(RESULTS_FILE, `line ${line} is not a record of this run`);
247
+ const problem = visit(record, line);
248
+ if (problem !== undefined)
249
+ throw refusal(RESULTS_FILE, `line ${line} ${problem}`);
250
+ }
251
+ function tooLarge(line) {
252
+ return refusal(RESULTS_FILE, `line ${line} is over 16 MiB`);
253
+ }
254
+ /** Read into `chunk` from `position`; the number of bytes read, 0 at the end of the file. */
255
+ async function readInto(handle, chunk, position) {
256
+ try {
257
+ return (await handle.read(chunk, 0, chunk.length, position)).bytesRead;
258
+ }
259
+ catch (error) {
260
+ throw ioFailure(RESULTS_FILE, 'cannot be read', error);
261
+ }
262
+ }
263
+ /**
264
+ * Read `results.jsonl` line by line and hand each record, with its line number from 1, to `visit`, which
265
+ * returns the problem with a record it refuses, or undefined. A file with no `results.jsonl` holds
266
+ * nothing. Bytes after the last line break are a line a run killed while it appended cut short: it is
267
+ * reported as `torn`, never visited, and the next append must drop it (see `openRecords`). Any other line
268
+ * that is no record, a line over 16 MiB (complete or not), a record `visit` refuses, a link and a file
269
+ * that is none are refused. The file is read in chunks of 64 KiB and split on the line feed byte, and a
270
+ * line over the limit is refused as soon as it is seen to pass it, so no line is read whole before it is
271
+ * known to fit.
272
+ *
273
+ * @throws ConfigError as above; Error `results.jsonl: cannot be read (<code>)` when a read fails
274
+ */
275
+ export async function readRecords(directory, visit) {
276
+ const handle = await openResults(join(directory, RESULTS_FILE));
277
+ if (handle === undefined) {
278
+ return {
279
+ lines: 0,
280
+ validBytes: 0,
281
+ bytes: 0,
282
+ torn: false,
283
+ };
284
+ }
285
+ try {
286
+ const chunk = Buffer.allocUnsafe(CHUNK_BYTES);
287
+ /** The copies of the bytes of the line in progress that earlier chunks held. */
288
+ let pending = [];
289
+ let pendingBytes = 0;
290
+ let lines = 0;
291
+ let validBytes = 0;
292
+ let position = 0;
293
+ for (;;) {
294
+ const bytesRead = await readInto(handle, chunk, position);
295
+ if (bytesRead === 0)
296
+ break;
297
+ const view = chunk.subarray(0, bytesRead);
298
+ let start = 0;
299
+ for (let end = view.indexOf(LINE_FEED); end !== -1; end = view.indexOf(LINE_FEED, start)) {
300
+ lines += 1;
301
+ const piece = view.subarray(start, end);
302
+ const length = pendingBytes + piece.length;
303
+ if (length > MAX_RECORD_BYTES)
304
+ throw tooLarge(lines);
305
+ visitLine(pending.length === 0
306
+ ? piece
307
+ : Buffer.concat([...pending, piece], length), lines, visit);
308
+ pending = [];
309
+ pendingBytes = 0;
310
+ validBytes = position + end + 1;
311
+ start = end + 1;
312
+ }
313
+ pendingBytes += view.length - start;
314
+ if (pendingBytes > MAX_RECORD_BYTES)
315
+ throw tooLarge(lines + 1);
316
+ if (start < view.length)
317
+ pending.push(Buffer.from(view.subarray(start)));
318
+ position += bytesRead;
319
+ }
320
+ return {
321
+ lines,
322
+ validBytes,
323
+ bytes: position,
324
+ torn: pendingBytes > 0,
325
+ };
326
+ }
327
+ finally {
328
+ await handle.close().catch(() => undefined);
329
+ }
330
+ }
331
+ function writeFailure(file, error) {
332
+ return ioFailure(file, 'cannot be written', error);
333
+ }
334
+ /**
335
+ * `results.jsonl` opened to be appended to, never through a symbolic link, never waiting for a FIFO, and
336
+ * cut to `read.validBytes` when it ends in the torn tail the read found. A read that found no bytes opens
337
+ * with `O_CREAT`: a new run's file, or an empty one deleted since, is made. A read that found bytes opens
338
+ * without it, so a file deleted since is refused instead of made again, empty. Refused, with the handle
339
+ * closed: what is not a regular file, a file that is gone or whose length is not `read.bytes`.
340
+ */
341
+ async function openAppend(path, read) {
342
+ if (!HAS_NOFOLLOW && await lstat(path).then(stats => stats.isSymbolicLink(), () => false))
343
+ throw new Error(`${RESULTS_FILE}: cannot be written (ELOOP)`);
344
+ const flags = read.bytes > 0
345
+ ? APPEND_FLAGS
346
+ : APPEND_FLAGS | constants.O_CREAT;
347
+ let handle;
348
+ try {
349
+ handle = await open(path, flags, OWNER_ONLY);
350
+ }
351
+ catch (error) {
352
+ // Under O_NONBLOCK a FIFO with no reader fails with ENXIO and a directory with EISDIR: no regular file.
353
+ // Whatever else opens, a device or a FIFO with a reader, is refused by the stat below; any other
354
+ // failure, such as a socket on macOS, is a write failure. Without O_CREAT, ENOENT is a file that was
355
+ // there when the read found bytes in it, and is not now.
356
+ const code = errorCode(error);
357
+ if (code === 'ENOENT' && read.bytes > 0)
358
+ throw refusal(RESULTS_FILE, CHANGED);
359
+ throw code === 'ENXIO' || code === 'EISDIR'
360
+ ? refusal(RESULTS_FILE, 'is not a file')
361
+ : writeFailure(RESULTS_FILE, error);
362
+ }
363
+ try {
364
+ const stats = await handle.stat();
365
+ if (!stats.isFile())
366
+ throw refusal(RESULTS_FILE, 'is not a file');
367
+ if (stats.size !== read.bytes)
368
+ throw refusal(RESULTS_FILE, CHANGED);
369
+ if (stats.size > read.validBytes)
370
+ await handle.truncate(read.validBytes);
371
+ return handle;
372
+ }
373
+ catch (error) {
374
+ await handle.close().catch(() => undefined);
375
+ throw error instanceof ConfigError
376
+ ? error
377
+ : writeFailure(RESULTS_FILE, error);
378
+ }
379
+ }
380
+ /**
381
+ * Open `results.jsonl` to append to, and cut it to `read.validBytes` (what `readRecords` found valid),
382
+ * which drops a line a killed run left unfinished. `read` is the answer of the `readRecords` this run
383
+ * began with, or `{ validBytes: 0, bytes: 0 }` for a run that is new: the file must still be `read.bytes`
384
+ * long, or another run may have cut it or appended to it since, and cutting it back would drop that run's
385
+ * records. A read that found no bytes makes the file when it is not there, which loses nothing; one that
386
+ * found bytes never makes it, so a file deleted since is refused with nothing written. `O_APPEND` puts
387
+ * each write at the end, `O_NOFOLLOW` refuses a symbolic link, and `O_NONBLOCK` refuses a FIFO instead of
388
+ * waiting for it. A file made here is readable by its owner only, and one that exists keeps its mode.
389
+ * `append` writes one whole line, each call after the one before, so lines never interleave; once a write
390
+ * has failed, none after it is written, so a line is never joined to the fragment of a failed one. `close`
391
+ * waits for the lines asked for and closes.
392
+ *
393
+ * @throws ConfigError `results.jsonl: is not a file`, or `results.jsonl: changed after this run read it,
394
+ * so another run may be using this --out: run one at a time` (a file cut, appended to or deleted since the
395
+ * read); Error `results.jsonl: cannot be written (<code>)` for any other failure to open, cut, write or
396
+ * close
397
+ */
398
+ export async function openRecords(directory, read) {
399
+ const handle = await openAppend(join(directory, RESULTS_FILE), read);
400
+ let failed;
401
+ let tail = Promise.resolve();
402
+ return {
403
+ append: (line) => {
404
+ const written = tail.then(async () => {
405
+ if (failed !== undefined)
406
+ throw failed;
407
+ try {
408
+ await handle.appendFile(line);
409
+ }
410
+ catch (error) {
411
+ failed = writeFailure(RESULTS_FILE, error);
412
+ throw failed;
413
+ }
414
+ });
415
+ tail = written.catch(() => undefined);
416
+ return written;
417
+ },
418
+ close: async () => {
419
+ await tail;
420
+ try {
421
+ await handle.close();
422
+ }
423
+ catch (error) {
424
+ throw writeFailure(RESULTS_FILE, error);
425
+ }
426
+ },
427
+ };
428
+ }
429
+ /**
430
+ * Write `text` as `name` in `directory` whole or not at all: to a new file `.<name>.<8 hex digits>.tmp`
431
+ * made with `O_EXCL` (which never follows a link), written, synced and closed, then renamed over `name`.
432
+ * The rename replaces a symbolic link at `name`, and never writes through it. The temporary file is made
433
+ * with `mode`, which the rename keeps: Node's own default unless a caller asks for another. A failure
434
+ * removes the temporary file it made.
435
+ *
436
+ * @throws Error `<name>: cannot be written (<code>)`
437
+ */
438
+ export async function writeAtomic(directory, name, text, mode = 0o666) {
439
+ const temporary = join(directory, `.${name}.${randomBytes(4).toString('hex')}.tmp`);
440
+ let made = false;
441
+ try {
442
+ const handle = await open(temporary, NEW_FILE_FLAGS, mode);
443
+ made = true;
444
+ try {
445
+ await handle.writeFile(text);
446
+ await handle.sync();
447
+ }
448
+ finally {
449
+ await handle.close();
450
+ }
451
+ await rename(temporary, join(directory, name));
452
+ }
453
+ catch (error) {
454
+ if (made)
455
+ await unlink(temporary).catch(() => undefined);
456
+ throw writeFailure(name, error);
457
+ }
458
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The runner of a bench: it takes the planned reviews and runs each through a quorum of its own, at most
3
+ * `jobs` at once, and hands every review that resolved, or that a model's reply denied, to the caller as a
4
+ * record to write. It knows nothing of the run directory, the report or the terminal: the caller gives it
5
+ * a way to write a line and a callback to report to.
6
+ */
7
+ import type { Env } from '../config/env.ts';
8
+ import type { ResolvedConfig } from '../config/resolve.ts';
9
+ import type { Denial, ReviewRecord } from './records.ts';
10
+ import type { Suite } from './suite.ts';
11
+ /** One planned review: a trial of a case with a configuration. */
12
+ export interface BenchReview {
13
+ readonly trial: number;
14
+ readonly caseId: string;
15
+ /** The configuration's index in `configurations`, from 0. */
16
+ readonly configuration: number;
17
+ }
18
+ /** A configuration to run: the resolved config, and the fingerprint its records are keyed with. */
19
+ export interface RunnerConfiguration {
20
+ readonly config: ResolvedConfig;
21
+ readonly fingerprint: string;
22
+ }
23
+ /** What the runner reports: a review that was recorded, resolved or denied, and written, or one that failed. */
24
+ export type RunnerEvent = {
25
+ readonly type: 'recorded';
26
+ readonly review: BenchReview;
27
+ readonly record: ReviewRecord;
28
+ } | {
29
+ readonly type: 'failed';
30
+ readonly review: BenchReview;
31
+ readonly error: unknown;
32
+ };
33
+ export interface RunReviewsOptions {
34
+ readonly suite: Suite;
35
+ readonly configurations: readonly RunnerConfiguration[];
36
+ readonly reviews: readonly BenchReview[];
37
+ /** At most this many reviews run at once. */
38
+ readonly jobs: number;
39
+ /** What a `claude-code` provider's CLI inherits. */
40
+ readonly env: Env;
41
+ readonly signal?: AbortSignal;
42
+ /** Writes one line of `results.jsonl`; it throws when the write fails. */
43
+ readonly append: (line: string) => Promise<void>;
44
+ readonly events: (event: RunnerEvent) => void;
45
+ /** The most a line may hold, its line break not counted, in bytes; `MAX_RECORD_BYTES` when left out. */
46
+ readonly maxRecordBytes?: number;
47
+ }
48
+ export interface RunReviewsOutcome {
49
+ /** The reviews written to the record. */
50
+ readonly recorded: number;
51
+ /** The reviews that failed, a rejection that is no denial, or whose record was too large to write. */
52
+ readonly failed: number;
53
+ /** Whether the caller's signal was aborted by the time the run ended. */
54
+ readonly interrupted: boolean;
55
+ }
56
+ /** The reviews of a bench in the order they run: by trial from 1, then by case, then by configuration. */
57
+ export declare function planReviews(options: {
58
+ readonly trials: number;
59
+ readonly cases: readonly string[];
60
+ readonly configurations: number;
61
+ }): BenchReview[];
62
+ /**
63
+ * The denial a review's rejection records, or undefined when the review fails and is retried. A review
64
+ * whose research reply could not be used (an `OutputError`), or whose research call the model refused or
65
+ * cut off at its token limit (a `ProviderError` of kind `refusal` or `truncated`), was answered by its
66
+ * model: a retry cannot tell the model's unreliability from an outage, and a poisoned patch provokes such
67
+ * replies on purpose, so the review is recorded as denied, with no result, and counts as incomplete. Any
68
+ * other rejection (an HTTP, network, timeout or process failure, a reply the server shaped wrong) says
69
+ * nothing of the model's answer, so the review fails and runs again. The classes are matched with
70
+ * `instanceof`: an error from a second copy of quorum is no denial, so it fails, which fails closed.
71
+ */
72
+ export declare function denialOf(error: unknown): Denial | undefined;
73
+ /**
74
+ * Run the planned reviews in the order given, at most `jobs` at once, and give the caller each review
75
+ * that resolved, or that a model's reply denied (`denialOf`), as a record: `append` writes its line, then
76
+ * `events` reports it as `recorded`.
77
+ *
78
+ * Each review gets a quorum of its own through `fromConfig`, with an event sink of its own, so its record
79
+ * counts only its own calls. A review that rejects with any other error is reported as `failed` and not
80
+ * recorded, and the others run. One `AbortController` of the runner's, joined to the caller's `signal`,
81
+ * cuts the reviews in flight when the caller is interrupted or a write fails, and a review that has not
82
+ * started when it is aborted does not start. A review that rejects while the run is aborted is neither
83
+ * recorded, a denial included, nor a failure: an interrupt is not a verdict on the review. A review that
84
+ * resolved is recorded, even when the interrupt came while its record was written. A line over
85
+ * `maxRecordBytes` is a failed review and is never written, since the reader of `results.jsonl` refuses
86
+ * a line that long, and with it the whole directory. A write that fails stops the run: it reports
87
+ * nothing for that review, cuts the others, and the run rejects with the error of the write once every
88
+ * review has settled. A callback of `events` that throws does the same.
89
+ *
90
+ * @throws the error of the first `append` (or `events`) that threw
91
+ */
92
+ export declare function runReviews(options: RunReviewsOptions): Promise<RunReviewsOutcome>;