@tobi-or-not/quorum 0.3.0 → 0.5.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 (91) hide show
  1. package/README.md +2 -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 +7 -4
  5. package/dist/bench/fingerprint.js +22 -8
  6. package/dist/bench/independence.d.ts +28 -0
  7. package/dist/bench/independence.js +67 -0
  8. package/dist/bench/records.d.ts +241 -13
  9. package/dist/bench/records.js +64 -11
  10. package/dist/bench/report.d.ts +44 -11
  11. package/dist/bench/report.js +238 -32
  12. package/dist/bench/run-dir.d.ts +52 -26
  13. package/dist/bench/run-dir.js +124 -45
  14. package/dist/bench/runner.d.ts +47 -17
  15. package/dist/bench/runner.js +82 -21
  16. package/dist/bench/score.d.ts +38 -7
  17. package/dist/bench/score.js +64 -17
  18. package/dist/bench/stats.d.ts +61 -7
  19. package/dist/bench/stats.js +82 -7
  20. package/dist/bench/suite.d.ts +54 -9
  21. package/dist/bench/suite.js +264 -96
  22. package/dist/cli/bench.d.ts +27 -9
  23. package/dist/cli/bench.js +174 -83
  24. package/dist/cli/bin.js +2 -2
  25. package/dist/cli/io.d.ts +9 -2
  26. package/dist/cli/io.js +20 -2
  27. package/dist/cli/main.d.ts +34 -14
  28. package/dist/cli/main.js +100 -38
  29. package/dist/cli/print-config.d.ts +8 -6
  30. package/dist/cli/print-config.js +21 -8
  31. package/dist/cli/render.d.ts +2 -2
  32. package/dist/cli/render.js +21 -2
  33. package/dist/config/env.d.ts +32 -19
  34. package/dist/config/env.js +95 -32
  35. package/dist/config/from-config.js +15 -3
  36. package/dist/config/load.d.ts +3 -0
  37. package/dist/config/load.js +17 -8
  38. package/dist/config/resolve.d.ts +9 -1
  39. package/dist/config/resolve.js +17 -1
  40. package/dist/config/schema.d.ts +141 -5
  41. package/dist/config/schema.js +125 -12
  42. package/dist/core/clock.d.ts +17 -0
  43. package/dist/core/clock.js +14 -0
  44. package/dist/core/coverage.d.ts +49 -0
  45. package/dist/core/coverage.js +144 -0
  46. package/dist/core/diff.d.ts +34 -0
  47. package/dist/core/diff.js +140 -18
  48. package/dist/core/errors.d.ts +18 -3
  49. package/dist/core/errors.js +26 -2
  50. package/dist/core/exclude.d.ts +42 -0
  51. package/dist/core/exclude.js +189 -0
  52. package/dist/core/limits.d.ts +82 -0
  53. package/dist/core/limits.js +163 -0
  54. package/dist/core/output.d.ts +3 -2
  55. package/dist/core/output.js +3 -2
  56. package/dist/core/ports.d.ts +57 -2
  57. package/dist/core/ports.js +36 -1
  58. package/dist/core/quorum.d.ts +24 -8
  59. package/dist/core/quorum.js +187 -56
  60. package/dist/core/retry.d.ts +36 -0
  61. package/dist/core/retry.js +46 -0
  62. package/dist/core/stages/context.d.ts +126 -22
  63. package/dist/core/stages/context.js +319 -41
  64. package/dist/core/stages/panel.d.ts +5 -4
  65. package/dist/core/stages/panel.js +30 -11
  66. package/dist/core/stages/research.d.ts +15 -6
  67. package/dist/core/stages/research.js +75 -18
  68. package/dist/core/tokens.d.ts +31 -0
  69. package/dist/core/tokens.js +81 -0
  70. package/dist/core/types.d.ts +77 -10
  71. package/dist/index.d.ts +1 -1
  72. package/dist/providers/anthropic.d.ts +2 -1
  73. package/dist/providers/anthropic.js +14 -6
  74. package/dist/providers/claude-code.d.ts +51 -11
  75. package/dist/providers/claude-code.js +69 -33
  76. package/dist/providers/gemini.d.ts +4 -1
  77. package/dist/providers/gemini.js +72 -15
  78. package/dist/providers/http.d.ts +49 -4
  79. package/dist/providers/http.js +155 -14
  80. package/dist/providers/ollama.d.ts +3 -1
  81. package/dist/providers/ollama.js +17 -9
  82. package/dist/providers/openai-compatible.d.ts +3 -1
  83. package/dist/providers/openai-compatible.js +17 -9
  84. package/dist/providers/options.d.ts +12 -3
  85. package/dist/providers/options.js +30 -10
  86. package/dist/providers/reply.d.ts +6 -2
  87. package/dist/providers/reply.js +13 -3
  88. package/dist/providers/size.d.ts +10 -14
  89. package/dist/providers/size.js +15 -69
  90. package/package.json +1 -1
  91. package/schema/quorum.schema.json +34 -1
package/dist/core/diff.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const GIT_HEADER = 'diff --git ';
2
2
  const QUOTED_NEW_SIDE = ' "b/';
3
3
  const NEW_SIDE_MARKERS = [QUOTED_NEW_SIDE, ' b/'];
4
+ const MOVED_TO_PREFIXES = ['rename to ', 'copy to '];
4
5
  const PATH_PREFIX = /^(?:[ab]\/|\.\/)/;
5
6
  const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
6
7
  /** How many diff lines of a hunk, either side of the cited one, make up a finding's evidence. */
@@ -143,6 +144,61 @@ function headerPath(header) {
143
144
  const names = line.slice(GIT_HEADER.length);
144
145
  return sharedPath(names) || renamedPath(names) || undefined;
145
146
  }
147
+ /**
148
+ * The paths the `rename to ` and `copy to ` lines of a section name, in order, each less a trailing
149
+ * `\r` and decoded when git quoted it. Git does not quote a path that holds a space, so a path with a
150
+ * space before `b/` makes a rename's `diff --git` header read two ways (`a/src/auth.js b/src/x
151
+ * b/dist/auth.js` reads as a rename to `dist/auth.js`), while these lines name the new path whole. A
152
+ * hunk row starts with a space, `+`, `-` or `\`, never with these words, so the section's lines are
153
+ * read with no hunk parsing.
154
+ */
155
+ export function movedTo(text) {
156
+ const paths = [];
157
+ for (const raw of text.split('\n')) {
158
+ const line = raw.endsWith('\r')
159
+ ? raw.slice(0, -1)
160
+ : raw;
161
+ const prefix = MOVED_TO_PREFIXES.find(start => line.startsWith(start));
162
+ if (prefix === undefined)
163
+ continue;
164
+ const name = line.slice(prefix.length);
165
+ paths.push(isQuoted(name)
166
+ ? decodeQuoted(name.slice(1, -1))
167
+ : name);
168
+ }
169
+ return paths;
170
+ }
171
+ /**
172
+ * Every section of a git-style unified diff, in order. Only `diff --git` lines open a section, so the
173
+ * text before the first one is a section of its own, of path '', and a diff without such headers
174
+ * (plain `diff -u` output) is one section of path ''. A header that names no path quorum can read
175
+ * gives a section of path `undefined`, kept here whatever `splitDiff` does with it. A section holds
176
+ * at least one line, so a diff that starts with its header has no section before it, and the texts
177
+ * joined by line feeds are the diff.
178
+ */
179
+ export function diffSections(diff) {
180
+ const sections = [];
181
+ let path = '';
182
+ let lines = [];
183
+ const flush = () => {
184
+ if (lines.length > 0) {
185
+ sections.push({
186
+ path,
187
+ text: lines.join('\n'),
188
+ });
189
+ }
190
+ };
191
+ for (const line of diff.split('\n')) {
192
+ if (line.startsWith(GIT_HEADER)) {
193
+ flush();
194
+ path = headerPath(line);
195
+ lines = [];
196
+ }
197
+ lines.push(line);
198
+ }
199
+ flush();
200
+ return sections;
201
+ }
146
202
  /**
147
203
  * Split a git-style unified diff into sections keyed by file path. Only `diff --git` lines open a
148
204
  * section: inside a hunk every line starts with ' ', '+', '-' or '\', so that text cannot appear
@@ -160,29 +216,18 @@ function headerPath(header) {
160
216
  */
161
217
  export function splitDiff(diff) {
162
218
  const sections = new Map();
163
- let path = '';
164
- let lines = [];
165
- const flush = () => {
166
- if (path === undefined || lines.length === 0)
167
- return;
168
- const text = lines.join('\n');
219
+ const all = diffSections(diff);
220
+ for (const { path, text } of all) {
221
+ if (path === undefined)
222
+ continue;
169
223
  const previous = sections.get(path);
170
224
  sections.set(path, previous === undefined
171
225
  ? text
172
226
  : `${previous}\n${text}`);
173
- };
174
- for (const line of diff.split('\n')) {
175
- if (line.startsWith(GIT_HEADER)) {
176
- flush();
177
- path = headerPath(line);
178
- lines = [];
179
- }
180
- lines.push(line);
181
227
  }
182
- flush();
183
- // `path` is '' only before the first header: when every header was unreadable, the preamble is
184
- // all that is left, and it must not stand for a file.
185
- if (path !== '' && sections.size === 1)
228
+ // A section whose path is not '' means a header was met, an unreadable one included: when every
229
+ // header was unreadable, the preamble is all that is left, and it must not stand for a file.
230
+ if (all.some(({ path }) => path !== '') && sections.size === 1)
186
231
  sections.delete('');
187
232
  return sections;
188
233
  }
@@ -271,6 +316,41 @@ export function locate(sections, file, line) {
271
316
  }
272
317
  return undefined;
273
318
  }
319
+ /**
320
+ * The first line from `start` to `end` that no hunk of `file` holds, or undefined when each sits in
321
+ * one: the answer `locate` gives for each line in turn, found by a binary search over the spans the
322
+ * hunks hold, merged and sorted once per section, so a range costs a search and not a walk over every
323
+ * hunk for each of its lines. The file is resolved as `locate` resolves it, and a file the diff does
324
+ * not hold has no line in a hunk, so the answer is `start`.
325
+ *
326
+ * @throws {RangeError} unless `start` and `end` are safe integers with `start` at most `end`
327
+ */
328
+ export function firstLineOutside(sections, file, start, end) {
329
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end) {
330
+ throw new RangeError('start and end must be safe integers, start at most end');
331
+ }
332
+ const section = sectionFor(sections, file);
333
+ if (!section)
334
+ return start;
335
+ const spans = spansOf(sections, section.path, section.text);
336
+ let before = 0;
337
+ let after = spans.length;
338
+ while (before < after) {
339
+ const middle = (before + after) >>> 1;
340
+ if (spans[middle].start <= start)
341
+ before = middle + 1;
342
+ else
343
+ after = middle;
344
+ }
345
+ const span = before === 0
346
+ ? undefined
347
+ : spans[before - 1];
348
+ if (span === undefined || span.end < start)
349
+ return start;
350
+ return span.end >= end
351
+ ? undefined
352
+ : span.end + 1;
353
+ }
274
354
  /**
275
355
  * The lines the diff adds to `path`, in the order of the diff: the rows of its hunks marked `+`,
276
356
  * read from the hunks `locate` reads, so they are cached with them. `path` is the diff's own path,
@@ -315,6 +395,48 @@ function hunksOf(sections, path, text) {
315
395
  }
316
396
  return hunks;
317
397
  }
398
+ /** The merged spans of each section, built once, in a cache that is dropped with the sections map like `parsedSections`. */
399
+ const coveredSections = new WeakMap();
400
+ /** The new-file lines a hunk holds for `locate`: those it shows from its start, up to its count, or its start alone for a hunk that counts no new line; none for a hunk that shows no row. */
401
+ function heldSpan(hunk) {
402
+ if (hunk.rows.length === 0)
403
+ return undefined;
404
+ const shown = hunk.count === 0
405
+ ? 1
406
+ : Math.min(hunk.count, hunk.rowOfLine.length);
407
+ return shown === 0
408
+ ? undefined
409
+ : { start: hunk.start, end: hunk.start + shown - 1 };
410
+ }
411
+ /** The spans the hunks of a section hold, sorted by start, each merged with the one before it when it starts at most a line after that one's end, so no line between two spans is in either. */
412
+ function spansOf(sections, path, text) {
413
+ let covered = coveredSections.get(sections);
414
+ if (!covered) {
415
+ covered = new Map();
416
+ coveredSections.set(sections, covered);
417
+ }
418
+ let spans = covered.get(path);
419
+ if (!spans) {
420
+ const held = hunksOf(sections, path, text).flatMap(hunk => heldSpan(hunk) ?? []);
421
+ held.sort((first, second) => first.start - second.start);
422
+ const merged = [];
423
+ for (const span of held) {
424
+ const last = merged.at(-1);
425
+ if (last !== undefined && span.start <= last.end + 1) {
426
+ merged[merged.length - 1] = {
427
+ start: last.start,
428
+ end: Math.max(last.end, span.end),
429
+ };
430
+ }
431
+ else {
432
+ merged.push(span);
433
+ }
434
+ }
435
+ spans = merged;
436
+ covered.set(path, spans);
437
+ }
438
+ return spans;
439
+ }
318
440
  /**
319
441
  * Read the hunks of one file section. The header's line counts say where a hunk ends, so file
320
442
  * headers and `` markers are never mistaken for hunk lines, and a line
@@ -1,3 +1,4 @@
1
+ import type { Usage } from './types.ts';
1
2
  /** Base class for every error quorum raises on purpose. */
2
3
  export declare class QuorumError extends Error {
3
4
  constructor(message: string, options?: ErrorOptions);
@@ -26,23 +27,37 @@ export declare class ConfigError extends QuorumError {
26
27
  readonly issues: readonly ConfigIssue[];
27
28
  constructor(issues: readonly ConfigIssue[]);
28
29
  }
29
- /** What went wrong with a provider call. `retryable` is derived from it. */
30
- export type ProviderErrorKind = 'http' | 'network' | 'process' | 'timeout' | 'aborted' | 'refusal' | 'truncated' | 'invalid-response' | 'unsupported' | 'too-large';
30
+ /** Every kind of a provider call's failure: the kinds a `ProviderError` has, and the only ones a gap's detail names. */
31
+ export declare const PROVIDER_ERROR_KINDS: readonly ["http", "network", "process", "timeout", "aborted", "refusal", "truncated", "invalid-response", "unsupported", "too-large"];
32
+ /** What went wrong with a provider call. `retryable` is derived from it, unless the adapter sets it. */
33
+ export type ProviderErrorKind = typeof PROVIDER_ERROR_KINDS[number];
31
34
  /**
32
35
  * A provider call that failed. The message starts with the provider id. Adapters never put request
33
36
  * headers, keys or the runtime's own error text in it; they quote server text through `snippet`.
37
+ * `usage` holds the counts of a reply the provider read and then refused, which the review counts as
38
+ * the failed call's usage.
34
39
  */
35
40
  export declare class ProviderError extends QuorumError {
36
41
  readonly providerId: string;
37
42
  readonly kind: ProviderErrorKind;
38
43
  readonly status: number | undefined;
39
- /** True for network errors, timeouts, 408, 409, 429 and 5xx; a caller may retry the call. */
44
+ /**
45
+ * A caller may retry the call: true for network errors, timeouts, 408, 409, 429 and 5xx, unless
46
+ * the adapter set it. The core retries only `network`, `timeout` and `http` failures, whatever it says.
47
+ */
40
48
  readonly retryable: boolean;
49
+ /** The wait the server asked for at least, in milliseconds, when the adapter read one. */
50
+ readonly retryAfterMs: number | undefined;
51
+ /** What the reply the call failed on reported, when the provider read one: the review counts it as the failed call's usage. */
52
+ readonly usage: Usage | undefined;
41
53
  constructor(details: {
42
54
  providerId: string;
43
55
  kind: ProviderErrorKind;
44
56
  message: string;
45
57
  status?: number;
58
+ retryable?: boolean;
59
+ retryAfterMs?: number;
60
+ usage?: Usage;
46
61
  cause?: unknown;
47
62
  });
48
63
  }
@@ -52,6 +52,19 @@ export class ConfigError extends QuorumError {
52
52
  this.issues = issues;
53
53
  }
54
54
  }
55
+ /** Every kind of a provider call's failure: the kinds a `ProviderError` has, and the only ones a gap's detail names. */
56
+ export const PROVIDER_ERROR_KINDS = [
57
+ 'http',
58
+ 'network',
59
+ 'process',
60
+ 'timeout',
61
+ 'aborted',
62
+ 'refusal',
63
+ 'truncated',
64
+ 'invalid-response',
65
+ 'unsupported',
66
+ 'too-large',
67
+ ];
55
68
  const RETRYABLE_STATUSES = new Set([408, 409, 429]);
56
69
  function isRetryable(kind, status) {
57
70
  if (kind === 'network' || kind === 'timeout')
@@ -61,13 +74,22 @@ function isRetryable(kind, status) {
61
74
  /**
62
75
  * A provider call that failed. The message starts with the provider id. Adapters never put request
63
76
  * headers, keys or the runtime's own error text in it; they quote server text through `snippet`.
77
+ * `usage` holds the counts of a reply the provider read and then refused, which the review counts as
78
+ * the failed call's usage.
64
79
  */
65
80
  export class ProviderError extends QuorumError {
66
81
  providerId;
67
82
  kind;
68
83
  status;
69
- /** True for network errors, timeouts, 408, 409, 429 and 5xx; a caller may retry the call. */
84
+ /**
85
+ * A caller may retry the call: true for network errors, timeouts, 408, 409, 429 and 5xx, unless
86
+ * the adapter set it. The core retries only `network`, `timeout` and `http` failures, whatever it says.
87
+ */
70
88
  retryable;
89
+ /** The wait the server asked for at least, in milliseconds, when the adapter read one. */
90
+ retryAfterMs;
91
+ /** What the reply the call failed on reported, when the provider read one: the review counts it as the failed call's usage. */
92
+ usage;
71
93
  constructor(details) {
72
94
  super(`${details.providerId}: ${details.message}`, details.cause === undefined
73
95
  ? undefined
@@ -75,6 +97,8 @@ export class ProviderError extends QuorumError {
75
97
  this.providerId = details.providerId;
76
98
  this.kind = details.kind;
77
99
  this.status = details.status;
78
- this.retryable = isRetryable(details.kind, details.status);
100
+ this.retryable = details.retryable ?? isRetryable(details.kind, details.status);
101
+ this.retryAfterMs = details.retryAfterMs;
102
+ this.usage = details.usage;
79
103
  }
80
104
  }
@@ -0,0 +1,42 @@
1
+ import type { ConfigIssue } from './errors.ts';
2
+ /** The most patterns `exclude` may hold. */
3
+ export declare const MAX_PATTERNS = 100;
4
+ /** The longest pattern, in characters. */
5
+ export declare const MAX_PATTERN_LENGTH = 256;
6
+ /** What a list of more than `MAX_PATTERNS` patterns is told. */
7
+ export declare const TOO_MANY_PATTERNS = "must hold at most 100 patterns";
8
+ /**
9
+ * The first problem with a pattern, with what to write instead, or undefined when it can be taken.
10
+ * The problems come in this order: empty, too long, a `\`, a `!`, a `{`, a trailing `/`, a `**`
11
+ * inside a name (a segment other than `**` that holds it), and an empty, `.` or `..` name (a segment
12
+ * of the pattern, less one leading `/`, that is one of them: no path in a diff has such a name, so
13
+ * the pattern would match less than its author meant). A pattern that would exclude something other
14
+ * than what its author meant is refused rather than guessed at. No message repeats the pattern.
15
+ */
16
+ export declare function patternProblem(pattern: string): string | undefined;
17
+ /**
18
+ * Every problem with a value given as `exclude`, so an untyped caller gets issues, never a
19
+ * TypeError: none when it is unset, `exclude: must be an array`, `exclude: must hold at most 100
20
+ * patterns` (the entries are then not read), or, for each entry, `exclude.<index>` with `must be a
21
+ * string` or the pattern's own problem.
22
+ */
23
+ export declare function excludeIssues(value: unknown): ConfigIssue[];
24
+ /**
25
+ * Whether `glob`, where `*` stands for any run of characters and `?` for one (a surrogate pair
26
+ * counts once), matches the whole of `name`; every other character is literal and case counts. It
27
+ * is the greedy algorithm: it goes back to the last `*` only, so it takes at most as many steps as
28
+ * the glob has characters times the name has, whatever the two hold. It compares code units, since
29
+ * indexing a string allocates a string per character on Bun.
30
+ */
31
+ export declare function matchName(glob: string, name: string): boolean;
32
+ /**
33
+ * The test of a path against checked patterns, each compiled once into its segments: `*` and `?`
34
+ * inside a name, `**` for whole directories, every other character literal and case-sensitive, and
35
+ * no pattern ever becomes a regular expression. The paths come from the diff, so an attacker
36
+ * controls them, and a matcher that backtracks would hang the review: this one is greedy, going back
37
+ * to the last star only. One pattern and one path cost at most as many steps as the pattern has
38
+ * characters times the path has, so with the caps (100 patterns of 256 characters) a review's
39
+ * matching costs at most 25 600 steps per character of path text, and an ordinary pattern a few.
40
+ * The matcher keeps no reference to the array it was given.
41
+ */
42
+ export declare function excludeMatcher(patterns: readonly string[]): (path: string) => boolean;
@@ -0,0 +1,189 @@
1
+ /** The most patterns `exclude` may hold. */
2
+ export const MAX_PATTERNS = 100;
3
+ /** The longest pattern, in characters. */
4
+ export const MAX_PATTERN_LENGTH = 256;
5
+ /** What a list of more than `MAX_PATTERNS` patterns is told. */
6
+ export const TOO_MANY_PATTERNS = `must hold at most ${MAX_PATTERNS} patterns`;
7
+ const STAR = 0x2A;
8
+ const QUESTION = 0x3F;
9
+ const HIGH_SURROGATES = [0xD800, 0xDBFF];
10
+ const LOW_SURROGATES = [0xDC00, 0xDFFF];
11
+ const WHOLE_DIRECTORIES = '**';
12
+ /** The names a segment of a pattern can hold that no path of a diff has. */
13
+ const NAMES_NO_PATH_HAS = new Set(['', '.', '..']);
14
+ /** How many code units the character at `at` takes: 2 for a surrogate pair, else 1. */
15
+ function width(text, at) {
16
+ const unit = text.charCodeAt(at);
17
+ if (unit < HIGH_SURROGATES[0] || unit > HIGH_SURROGATES[1])
18
+ return 1;
19
+ const next = text.charCodeAt(at + 1);
20
+ return next >= LOW_SURROGATES[0] && next <= LOW_SURROGATES[1]
21
+ ? 2
22
+ : 1;
23
+ }
24
+ /** The segments of a pattern with a `/` in it: those of the pattern less one leading `/`. */
25
+ function anchoredSegments(pattern) {
26
+ return (pattern.startsWith('/')
27
+ ? pattern.slice(1)
28
+ : pattern).split('/');
29
+ }
30
+ /**
31
+ * The first problem with a pattern, with what to write instead, or undefined when it can be taken.
32
+ * The problems come in this order: empty, too long, a `\`, a `!`, a `{`, a trailing `/`, a `**`
33
+ * inside a name (a segment other than `**` that holds it), and an empty, `.` or `..` name (a segment
34
+ * of the pattern, less one leading `/`, that is one of them: no path in a diff has such a name, so
35
+ * the pattern would match less than its author meant). A pattern that would exclude something other
36
+ * than what its author meant is refused rather than guessed at. No message repeats the pattern.
37
+ */
38
+ export function patternProblem(pattern) {
39
+ if (pattern === '')
40
+ return 'must not be empty';
41
+ if (pattern.length > MAX_PATTERN_LENGTH)
42
+ return `must be at most ${MAX_PATTERN_LENGTH} characters long`;
43
+ if (pattern.includes('\\'))
44
+ return 'holds \\, which escapes nothing here: write / between directories, and every other character as it is';
45
+ if (pattern.includes('!'))
46
+ return 'holds !, which negates nothing here: list only the paths to leave out';
47
+ if (pattern.includes('{'))
48
+ return 'holds {, which lists no alternatives here: write one pattern for each';
49
+ if (pattern.endsWith('/'))
50
+ return 'ends with /, so it matches no file: end it with /** to leave out what the directory holds';
51
+ const segments = anchoredSegments(pattern);
52
+ if (segments.some(segment => segment !== WHOLE_DIRECTORIES && segment.includes(WHOLE_DIRECTORIES))) {
53
+ return 'holds ** inside a name: ** stands for whole directories, as in **/*.min.js, and * for any characters of a name';
54
+ }
55
+ if (segments.some(segment => NAMES_NO_PATH_HAS.has(segment))) {
56
+ return 'holds an empty, . or .. name, which no path in a diff has: write the path from the root, as in dist/**';
57
+ }
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Every problem with a value given as `exclude`, so an untyped caller gets issues, never a
62
+ * TypeError: none when it is unset, `exclude: must be an array`, `exclude: must hold at most 100
63
+ * patterns` (the entries are then not read), or, for each entry, `exclude.<index>` with `must be a
64
+ * string` or the pattern's own problem.
65
+ */
66
+ export function excludeIssues(value) {
67
+ if (value === undefined)
68
+ return [];
69
+ if (!Array.isArray(value)) {
70
+ return [
71
+ { path: 'exclude', message: 'must be an array' },
72
+ ];
73
+ }
74
+ if (value.length > MAX_PATTERNS) {
75
+ return [
76
+ { path: 'exclude', message: TOO_MANY_PATTERNS },
77
+ ];
78
+ }
79
+ // `Array.from` reads a hole as `undefined`, so it is reported like any other entry that is not a string.
80
+ return Array.from(value).flatMap((pattern, index) => {
81
+ const problem = typeof pattern === 'string'
82
+ ? patternProblem(pattern)
83
+ : 'must be a string';
84
+ return problem === undefined
85
+ ? []
86
+ : [
87
+ { path: `exclude.${index}`, message: problem },
88
+ ];
89
+ });
90
+ }
91
+ /**
92
+ * Whether `glob`, where `*` stands for any run of characters and `?` for one (a surrogate pair
93
+ * counts once), matches the whole of `name`; every other character is literal and case counts. It
94
+ * is the greedy algorithm: it goes back to the last `*` only, so it takes at most as many steps as
95
+ * the glob has characters times the name has, whatever the two hold. It compares code units, since
96
+ * indexing a string allocates a string per character on Bun.
97
+ */
98
+ export function matchName(glob, name) {
99
+ let g = 0;
100
+ let n = 0;
101
+ let star = -1;
102
+ let mark = 0;
103
+ while (n < name.length) {
104
+ if (g < glob.length && glob.charCodeAt(g) === STAR) {
105
+ star = g++;
106
+ mark = n;
107
+ }
108
+ else if (g < glob.length && glob.charCodeAt(g) === QUESTION) {
109
+ g++;
110
+ n += width(name, n);
111
+ }
112
+ else if (g < glob.length && glob.charCodeAt(g) === name.charCodeAt(n)) {
113
+ g++;
114
+ n++;
115
+ }
116
+ else if (star !== -1) {
117
+ g = star + 1;
118
+ mark += width(name, mark);
119
+ n = mark;
120
+ }
121
+ else {
122
+ return false;
123
+ }
124
+ }
125
+ while (g < glob.length && glob.charCodeAt(g) === STAR)
126
+ g++;
127
+ return g === glob.length;
128
+ }
129
+ /** Whether the segments of a pattern, `**` standing for any number of directories, match all the segments of a path: `matchName`'s loop, over segments. */
130
+ function matchPath(pattern, path) {
131
+ let p = 0;
132
+ let s = 0;
133
+ let star = -1;
134
+ let mark = 0;
135
+ while (s < path.length) {
136
+ if (p < pattern.length && pattern[p] === WHOLE_DIRECTORIES) {
137
+ star = p++;
138
+ mark = s;
139
+ }
140
+ else if (p < pattern.length && matchName(pattern[p], path[s])) {
141
+ p++;
142
+ s++;
143
+ }
144
+ else if (star !== -1) {
145
+ p = star + 1;
146
+ mark++;
147
+ s = mark;
148
+ }
149
+ else {
150
+ return false;
151
+ }
152
+ }
153
+ while (p < pattern.length && pattern[p] === WHOLE_DIRECTORIES)
154
+ p++;
155
+ return p === pattern.length;
156
+ }
157
+ /**
158
+ * The segments a checked pattern matches a path by: no `/` in it reads as `**` then the pattern, so
159
+ * it matches a file's name in any directory; else the pattern less one leading `/`, matched from the
160
+ * root; a last segment `**` gains `*` after it, so `dir/**` holds what is inside `dir` and never a
161
+ * file named `dir`; consecutive `**` collapse into one.
162
+ */
163
+ function segmentsOf(pattern) {
164
+ const segments = pattern.includes('/')
165
+ ? anchoredSegments(pattern)
166
+ : [WHOLE_DIRECTORIES, pattern];
167
+ if (segments.at(-1) === WHOLE_DIRECTORIES)
168
+ segments.push('*');
169
+ return segments.filter((segment, index) => segment !== WHOLE_DIRECTORIES || segments[index - 1] !== WHOLE_DIRECTORIES);
170
+ }
171
+ /**
172
+ * The test of a path against checked patterns, each compiled once into its segments: `*` and `?`
173
+ * inside a name, `**` for whole directories, every other character literal and case-sensitive, and
174
+ * no pattern ever becomes a regular expression. The paths come from the diff, so an attacker
175
+ * controls them, and a matcher that backtracks would hang the review: this one is greedy, going back
176
+ * to the last star only. One pattern and one path cost at most as many steps as the pattern has
177
+ * characters times the path has, so with the caps (100 patterns of 256 characters) a review's
178
+ * matching costs at most 25 600 steps per character of path text, and an ordinary pattern a few.
179
+ * The matcher keeps no reference to the array it was given.
180
+ */
181
+ export function excludeMatcher(patterns) {
182
+ const compiled = patterns.map(segmentsOf);
183
+ if (compiled.length === 0)
184
+ return () => false;
185
+ return (path) => {
186
+ const parts = path.split('/');
187
+ return compiled.some(segments => matchPath(segments, parts));
188
+ };
189
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The limits of a review: the token cap's plain rules and its ledger, the review's deadline, and the failure
3
+ * a limit ends a call with. A limit stops part of a review without failing it: the call path reserves each
4
+ * attempt's worst case here before it sends the attempt, the deadline ends every wait and attempt at once, and
5
+ * the gap a limit leaves is written from the votes and the research it stopped.
6
+ */
7
+ import { QuorumError } from './errors.ts';
8
+ import type { IncompleteEntry, Usage, Verdict } from './types.ts';
9
+ /** The most tokens, input and output, one review spends when `maxReviewTokens` is not set. */
10
+ export declare const DEFAULT_MAX_REVIEW_TOKENS = 2000000;
11
+ /** How long one review runs when `reviewTimeoutMs` is not set: 30 minutes. */
12
+ export declare const DEFAULT_REVIEW_TIMEOUT_MS = 1800000;
13
+ /** The problem with a `maxReviewTokens`, in words that say what to write, or undefined for a safe integer of at least 1. */
14
+ export declare function maxReviewTokensProblem(value: unknown): string | undefined;
15
+ /** The limits a review keeps to, in the order their gaps are listed. */
16
+ export type LimitName = 'token-cap' | 'review-deadline';
17
+ /**
18
+ * What a call ends with when a limit stops it. It is recognised by `instanceof` only, and a provider
19
+ * cannot raise one: an instance from a second copy of quorum is an unknown failure, which fails closed.
20
+ * It has no `kind`, so the retry policy never retries it and it is no provider's failure.
21
+ */
22
+ export declare class LimitError extends QuorumError {
23
+ readonly limit: LimitName;
24
+ constructor(limit: LimitName, message: string);
25
+ }
26
+ /** True for the failure a limit ends a call with. */
27
+ export declare function isLimit(error: unknown): error is LimitError;
28
+ /** What the ledger holds: the cap, the tokens settled so far and the tokens reserved by the attempts in flight. */
29
+ export interface Totals {
30
+ readonly cap: number;
31
+ readonly settled: number;
32
+ readonly reserved: number;
33
+ }
34
+ /** Whether an attempt goes at once, waits for the attempts in flight to settle, or can never fit. */
35
+ export type Fit = 'fits' | 'waits' | 'refused';
36
+ /**
37
+ * Where an attempt of `tokens` stands: refused when it does not fit beside what was settled, which only grows;
38
+ * waiting when it fits beside that but not beside the attempts in flight, which settle at what they spent or
39
+ * at their whole reservation; else fitting.
40
+ */
41
+ export declare function fitOf(totals: Totals, tokens: number): Fit;
42
+ /** What a failed attempt says of itself, as the call path read it: each as found, so either may be anything. */
43
+ export interface SettledFailure {
44
+ readonly kind: unknown;
45
+ readonly status: unknown;
46
+ }
47
+ /**
48
+ * The tokens an attempt counts once it ends. A valid usage comes first, even above the reservation. Without
49
+ * one, a failure that is a refusal as too large, or an `http` failure of a client status but 408, counts for
50
+ * nothing: no work was done. Anything else counts the whole reservation, so a failure that says nothing
51
+ * never costs less than it may have.
52
+ */
53
+ export declare function settlementOf(reserved: number, usage: Usage | undefined, failure?: SettledFailure): number;
54
+ /**
55
+ * One review's token ledger. `reserve` takes an attempt's worst case before it is sent: it resolves once the
56
+ * attempt fits beside what was settled and what the attempts in flight reserved, and rejects with the cap's
57
+ * `LimitError` when it can never fit, or with `stop`'s reason when `stop` aborts first. `settle` returns a
58
+ * reservation and adds what the attempt spent.
59
+ */
60
+ export interface Ledger {
61
+ readonly cap: number;
62
+ readonly reserve: (tokens: number, stop: AbortSignal) => Promise<void>;
63
+ readonly settle: (reserved: number, spent: number) => void;
64
+ }
65
+ /**
66
+ * A ledger for a cap of `cap` tokens. An attempt that waits queues, and each settlement admits the waiters in
67
+ * the order they began to wait, up to the first that still waits; one that can never fit leaves the queue. A
68
+ * newcomer that would fit while an earlier attempt waits waits behind it, so a stream of small votes never holds
69
+ * a large research request back. Nothing deadlocks: every reservation in flight settles, at worst at its
70
+ * attempt's deadline, and with none in flight the head of the queue either fits or is refused.
71
+ */
72
+ export declare function createLedger(cap: number): Ledger;
73
+ /**
74
+ * The gaps the limits leave in a profile, one entry per limit that stopped work, the token cap's first, or none:
75
+ * `research` names the limit that stopped its research request, and every vote of `verdicts` whose failure is a
76
+ * limit counts for it. Each detail names the limit with its setting, then what it stopped: `its research`,
77
+ * `<n> vote(s)`, or `its research and <n> vote(s)`.
78
+ */
79
+ export declare function limitGaps(profile: string, research: LimitName | undefined, verdicts: readonly Verdict[], limits: {
80
+ readonly cap: number;
81
+ readonly deadlineMs: number;
82
+ }): IncompleteEntry[];