@tobi-or-not/quorum 0.4.0 → 0.6.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 (111) hide show
  1. package/README.md +3 -1
  2. package/dist/bench/fingerprint.d.ts +8 -5
  3. package/dist/bench/fingerprint.js +28 -9
  4. package/dist/bench/records.d.ts +168 -0
  5. package/dist/bench/records.js +106 -1
  6. package/dist/bench/runner.d.ts +18 -0
  7. package/dist/bench/runner.js +30 -4
  8. package/dist/cli/bench.d.ts +11 -4
  9. package/dist/cli/bench.js +34 -17
  10. package/dist/cli/bin.js +2 -2
  11. package/dist/cli/io.d.ts +5 -0
  12. package/dist/cli/main.d.ts +67 -24
  13. package/dist/cli/main.js +288 -59
  14. package/dist/cli/print-config.d.ts +8 -6
  15. package/dist/cli/print-config.js +26 -8
  16. package/dist/cli/render.d.ts +9 -3
  17. package/dist/cli/render.js +43 -2
  18. package/dist/config/claude-code.d.ts +2 -6
  19. package/dist/config/claude-code.js +6 -44
  20. package/dist/config/command.d.ts +10 -0
  21. package/dist/config/command.js +47 -0
  22. package/dist/config/env.d.ts +32 -19
  23. package/dist/config/env.js +95 -32
  24. package/dist/config/from-config.js +21 -3
  25. package/dist/config/resolve.d.ts +13 -1
  26. package/dist/config/resolve.js +27 -1
  27. package/dist/config/schema.d.ts +152 -5
  28. package/dist/config/schema.js +156 -12
  29. package/dist/core/clock.d.ts +17 -0
  30. package/dist/core/clock.js +14 -0
  31. package/dist/core/coverage.d.ts +74 -0
  32. package/dist/core/coverage.js +221 -0
  33. package/dist/core/diff.d.ts +101 -0
  34. package/dist/core/diff.js +178 -35
  35. package/dist/core/errors.d.ts +12 -3
  36. package/dist/core/errors.js +21 -2
  37. package/dist/core/estimate.d.ts +45 -0
  38. package/dist/core/estimate.js +188 -0
  39. package/dist/core/exclude.d.ts +42 -0
  40. package/dist/core/exclude.js +189 -0
  41. package/dist/core/flags.d.ts +14 -1
  42. package/dist/core/flags.js +56 -0
  43. package/dist/core/inputs.d.ts +38 -0
  44. package/dist/core/inputs.js +228 -0
  45. package/dist/core/limits.d.ts +83 -0
  46. package/dist/core/limits.js +169 -0
  47. package/dist/core/output.d.ts +3 -2
  48. package/dist/core/output.js +3 -2
  49. package/dist/core/parts.d.ts +146 -0
  50. package/dist/core/parts.js +388 -0
  51. package/dist/core/ports.d.ts +67 -2
  52. package/dist/core/ports.js +36 -1
  53. package/dist/core/prompts.d.ts +22 -3
  54. package/dist/core/prompts.js +43 -7
  55. package/dist/core/quorum.d.ts +26 -8
  56. package/dist/core/quorum.js +310 -73
  57. package/dist/core/retry.d.ts +36 -0
  58. package/dist/core/retry.js +46 -0
  59. package/dist/core/secrets.d.ts +98 -0
  60. package/dist/core/secrets.js +507 -0
  61. package/dist/core/stages/context.d.ts +131 -23
  62. package/dist/core/stages/context.js +331 -46
  63. package/dist/core/stages/panel.d.ts +13 -6
  64. package/dist/core/stages/panel.js +79 -19
  65. package/dist/core/stages/research.d.ts +110 -25
  66. package/dist/core/stages/research.js +338 -44
  67. package/dist/core/tokens.d.ts +31 -0
  68. package/dist/core/tokens.js +81 -0
  69. package/dist/core/types.d.ts +280 -25
  70. package/dist/core/verify.d.ts +6 -0
  71. package/dist/core/verify.js +6 -3
  72. package/dist/git/run.d.ts +223 -0
  73. package/dist/git/run.js +608 -0
  74. package/dist/git/tree.d.ts +43 -0
  75. package/dist/git/tree.js +171 -0
  76. package/dist/index.d.ts +26 -2
  77. package/dist/index.js +34 -2
  78. package/dist/providers/anthropic.d.ts +3 -1
  79. package/dist/providers/anthropic.js +10 -3
  80. package/dist/providers/claude-code.d.ts +56 -11
  81. package/dist/providers/claude-code.js +70 -25
  82. package/dist/providers/gemini.d.ts +5 -1
  83. package/dist/providers/gemini.js +65 -11
  84. package/dist/providers/http.d.ts +49 -4
  85. package/dist/providers/http.js +155 -14
  86. package/dist/providers/ollama.d.ts +4 -1
  87. package/dist/providers/ollama.js +13 -5
  88. package/dist/providers/openai-compatible.d.ts +4 -1
  89. package/dist/providers/openai-compatible.js +13 -5
  90. package/dist/providers/options.d.ts +12 -3
  91. package/dist/providers/options.js +30 -10
  92. package/dist/providers/size.d.ts +19 -15
  93. package/dist/providers/size.js +33 -73
  94. package/dist/sources/added.d.ts +49 -0
  95. package/dist/sources/added.js +134 -0
  96. package/dist/sources/diff.d.ts +13 -0
  97. package/dist/sources/diff.js +63 -0
  98. package/dist/sources/local.d.ts +41 -0
  99. package/dist/sources/local.js +251 -0
  100. package/dist/sources/paths.d.ts +45 -0
  101. package/dist/sources/paths.js +230 -0
  102. package/dist/sources/range.d.ts +21 -0
  103. package/dist/sources/range.js +75 -0
  104. package/dist/sources/read.d.ts +69 -0
  105. package/dist/sources/read.js +37 -0
  106. package/dist/sources/repository.d.ts +9 -0
  107. package/dist/sources/repository.js +28 -0
  108. package/dist/sources/skips.d.ts +49 -0
  109. package/dist/sources/skips.js +126 -0
  110. package/package.json +1 -1
  111. package/schema/quorum.schema.json +49 -1
@@ -0,0 +1,38 @@
1
+ import type { ConfigIssue } from './errors.ts';
2
+ import type { LeftOutFile, ReviewSource } from './types.ts';
3
+ /** The rules a path review skips a file by: the bench's schema takes the same list. */
4
+ export declare const SKIP_RULES: readonly ["vendored", "lockfile", "minified", "secret", "binary", "submodule", "lfs"];
5
+ /**
6
+ * Every problem with a value given as a review's `source`, so an untyped caller gets issues, never a
7
+ * TypeError: none when it is unset, `source: must be an object`, `source.kind` when the kind is not one
8
+ * of the five, else `source.objectFormat`, and, once the format is known, each id field that is not a full
9
+ * commit id of it (a local or staged source's `head` may be null), a `paths` that is not an array of
10
+ * strings and a `skips` that is not a boolean. A field it does not know is no problem: `sourceOf` leaves it
11
+ * out of the record. No message repeats a value.
12
+ */
13
+ export declare function sourceIssues(value: unknown): ConfigIssue[];
14
+ /**
15
+ * Every problem with a value given as a review's `leftOut`: none when it is unset, `leftOut: must be an
16
+ * array`, else for each entry `leftOut.<index>` when it is no object, its `file` that is not a string, its
17
+ * `reason` that is none of `excluded`, `binary`, `submodule`, `skipped`, `secret` and `deleted-secret`, and
18
+ * its `rule`: one of the seven a skipped file has, one of the nine a held file has (`secret` and
19
+ * `deleted-secret`), which no other reason has. A reason or a rule is a value of this release: a reader of
20
+ * a result takes one it does not know as a file left out, but a caller of `review` names ones it can.
21
+ */
22
+ export declare function leftOutIssues(value: unknown): ConfigIssue[];
23
+ /**
24
+ * Every problem with a value given as a review's `send`: none when it is unset, `send: must be an array`,
25
+ * else `send.<index>: must name a file` for each entry that is not a non-empty string, a hole included. The
26
+ * empty name is the text no header names, which no file of the diff is, so it is no file to send.
27
+ */
28
+ export declare function sendIssues(value: unknown): ConfigIssue[];
29
+ /**
30
+ * A checked source as the review records it: a copy of its known fields, so the caller's later changes to
31
+ * the object, or to its `paths`, never reach the result, and `{ kind: 'diff' }` for an unset source.
32
+ */
33
+ export declare function sourceOf(value: ReviewSource | undefined): ReviewSource;
34
+ /**
35
+ * The files a review leaves out as one list: the source's first, then the diff's, each file, reason and rule
36
+ * once, the first kept. Every entry is a copy of its known fields, `rule` only for a skipped or a held file.
37
+ */
38
+ export declare function mergeLeftOut(source: readonly LeftOutFile[], diff: readonly LeftOutFile[]): LeftOutFile[];
@@ -0,0 +1,228 @@
1
+ import { isRecord } from "./output.js";
2
+ import { SECRET_RULES } from "./secrets.js";
3
+ /** The kinds of source whose ids name a git repository's objects, each with the fields that hold a full commit id. */
4
+ const ID_FIELDS = {
5
+ range: ['base', 'mergeBase', 'head'],
6
+ local: ['head'],
7
+ staged: ['head'],
8
+ paths: ['commit'],
9
+ };
10
+ const OBJECT_FORMATS = ['sha1', 'sha256'];
11
+ /** A full object id of each format: 40 lowercase hexadecimal characters for sha1, 64 for sha256. */
12
+ const OBJECT_IDS = {
13
+ sha1: /^[0-9a-f]{40}$/,
14
+ sha256: /^[0-9a-f]{64}$/,
15
+ };
16
+ const ID_MESSAGE = 'must be a full commit id of its object format: 40 lowercase hexadecimal characters for sha1, 64 for sha256';
17
+ const LEFT_OUT_REASONS = new Set([
18
+ 'excluded',
19
+ 'binary',
20
+ 'submodule',
21
+ 'skipped',
22
+ 'secret',
23
+ 'deleted-secret',
24
+ ]);
25
+ /** The reasons of a file held back as a secret, which carry the rule that held it. */
26
+ const HELD_REASONS = new Set(['secret', 'deleted-secret']);
27
+ const SECRET_RULE_SET = new Set(SECRET_RULES);
28
+ /** The rules a path review skips a file by: the bench's schema takes the same list. */
29
+ export const SKIP_RULES = [
30
+ 'vendored',
31
+ 'lockfile',
32
+ 'minified',
33
+ 'secret',
34
+ 'binary',
35
+ 'submodule',
36
+ 'lfs',
37
+ ];
38
+ const SKIP_RULE_SET = new Set(SKIP_RULES);
39
+ function isGitKind(kind) {
40
+ return typeof kind === 'string' && Object.hasOwn(ID_FIELDS, kind);
41
+ }
42
+ /**
43
+ * Every problem with a value given as a review's `source`, so an untyped caller gets issues, never a
44
+ * TypeError: none when it is unset, `source: must be an object`, `source.kind` when the kind is not one
45
+ * of the five, else `source.objectFormat`, and, once the format is known, each id field that is not a full
46
+ * commit id of it (a local or staged source's `head` may be null), a `paths` that is not an array of
47
+ * strings and a `skips` that is not a boolean. A field it does not know is no problem: `sourceOf` leaves it
48
+ * out of the record. No message repeats a value.
49
+ */
50
+ export function sourceIssues(value) {
51
+ if (value === undefined)
52
+ return [];
53
+ if (!isRecord(value)) {
54
+ return [
55
+ { path: 'source', message: 'must be an object' },
56
+ ];
57
+ }
58
+ const { kind } = value;
59
+ if (kind === 'diff')
60
+ return [];
61
+ if (!isGitKind(kind)) {
62
+ return [
63
+ { path: 'source.kind', message: 'must be diff, range, local, staged or paths' },
64
+ ];
65
+ }
66
+ const issues = [];
67
+ const format = OBJECT_FORMATS.find(candidate => candidate === value.objectFormat);
68
+ if (format === undefined) {
69
+ issues.push({ path: 'source.objectFormat', message: 'must be sha1 or sha256' });
70
+ }
71
+ else {
72
+ const nullable = kind === 'local' || kind === 'staged';
73
+ for (const field of ID_FIELDS[kind]) {
74
+ const id = value[field];
75
+ if (nullable && id === null)
76
+ continue;
77
+ if (typeof id === 'string' && OBJECT_IDS[format].test(id))
78
+ continue;
79
+ issues.push({
80
+ path: `source.${field}`,
81
+ message: nullable
82
+ ? `${ID_MESSAGE}, or null when nothing is committed`
83
+ : ID_MESSAGE,
84
+ });
85
+ }
86
+ }
87
+ if (kind === 'paths') {
88
+ // `Array.from` reads a hole as `undefined`, so a sparse array is no array of strings.
89
+ if (!Array.isArray(value.paths) || !Array.from(value.paths).every(path => typeof path === 'string')) {
90
+ issues.push({ path: 'source.paths', message: 'must be an array of strings' });
91
+ }
92
+ if (typeof value.skips !== 'boolean')
93
+ issues.push({ path: 'source.skips', message: 'must be a boolean' });
94
+ }
95
+ return issues;
96
+ }
97
+ /**
98
+ * Every problem with a value given as a review's `leftOut`: none when it is unset, `leftOut: must be an
99
+ * array`, else for each entry `leftOut.<index>` when it is no object, its `file` that is not a string, its
100
+ * `reason` that is none of `excluded`, `binary`, `submodule`, `skipped`, `secret` and `deleted-secret`, and
101
+ * its `rule`: one of the seven a skipped file has, one of the nine a held file has (`secret` and
102
+ * `deleted-secret`), which no other reason has. A reason or a rule is a value of this release: a reader of
103
+ * a result takes one it does not know as a file left out, but a caller of `review` names ones it can.
104
+ */
105
+ export function leftOutIssues(value) {
106
+ if (value === undefined)
107
+ return [];
108
+ if (!Array.isArray(value)) {
109
+ return [
110
+ { path: 'leftOut', message: 'must be an array' },
111
+ ];
112
+ }
113
+ const issues = [];
114
+ // `Array.from` reads a hole as `undefined`, so it is reported like any other entry that is no object.
115
+ for (const [index, entry] of Array.from(value).entries()) {
116
+ const path = `leftOut.${index}`;
117
+ if (!isRecord(entry)) {
118
+ issues.push({ path, message: 'must be an object with a file and a reason' });
119
+ continue;
120
+ }
121
+ if (typeof entry.file !== 'string')
122
+ issues.push({ path: `${path}.file`, message: 'must be a string' });
123
+ if (!LEFT_OUT_REASONS.has(entry.reason)) {
124
+ issues.push({ path: `${path}.reason`, message: 'must be excluded, binary, submodule, skipped, secret or deleted-secret' });
125
+ }
126
+ else if (entry.reason === 'skipped') {
127
+ if (!SKIP_RULE_SET.has(entry.rule))
128
+ issues.push({ path: `${path}.rule`, message: 'must be vendored, lockfile, minified, secret, binary, submodule or lfs' });
129
+ }
130
+ else if (HELD_REASONS.has(entry.reason)) {
131
+ if (!SECRET_RULE_SET.has(entry.rule))
132
+ issues.push({ path: `${path}.rule`, message: `must be ${SECRET_RULES.slice(0, -1).join(', ')} or ${SECRET_RULES.at(-1)}` });
133
+ }
134
+ else if (entry.rule !== undefined) {
135
+ issues.push({ path: `${path}.rule`, message: 'belongs to a skipped, secret or deleted-secret file only' });
136
+ }
137
+ }
138
+ return issues;
139
+ }
140
+ /**
141
+ * Every problem with a value given as a review's `send`: none when it is unset, `send: must be an array`,
142
+ * else `send.<index>: must name a file` for each entry that is not a non-empty string, a hole included. The
143
+ * empty name is the text no header names, which no file of the diff is, so it is no file to send.
144
+ */
145
+ export function sendIssues(value) {
146
+ if (value === undefined)
147
+ return [];
148
+ if (!Array.isArray(value)) {
149
+ return [
150
+ { path: 'send', message: 'must be an array' },
151
+ ];
152
+ }
153
+ // `Array.from` reads a hole as `undefined`, so it is reported like any other entry that is no name.
154
+ return Array.from(value).flatMap((entry, index) => typeof entry === 'string' && entry !== ''
155
+ ? []
156
+ : [
157
+ { path: `send.${index}`, message: 'must name a file' },
158
+ ]);
159
+ }
160
+ /**
161
+ * A checked source as the review records it: a copy of its known fields, so the caller's later changes to
162
+ * the object, or to its `paths`, never reach the result, and `{ kind: 'diff' }` for an unset source.
163
+ */
164
+ export function sourceOf(value) {
165
+ if (value === undefined)
166
+ return { kind: 'diff' };
167
+ switch (value.kind) {
168
+ case 'diff':
169
+ return { kind: 'diff' };
170
+ case 'range':
171
+ return {
172
+ kind: 'range',
173
+ base: value.base,
174
+ mergeBase: value.mergeBase,
175
+ head: value.head,
176
+ objectFormat: value.objectFormat,
177
+ };
178
+ case 'local':
179
+ case 'staged':
180
+ return { kind: value.kind, head: value.head, objectFormat: value.objectFormat };
181
+ case 'paths':
182
+ return {
183
+ kind: 'paths',
184
+ commit: value.commit,
185
+ paths: [...value.paths],
186
+ skips: value.skips,
187
+ objectFormat: value.objectFormat,
188
+ };
189
+ }
190
+ }
191
+ /** A copy of a file left out with its known fields: `rule` only for a skipped or a held file. */
192
+ function copyOf(entry) {
193
+ switch (entry.reason) {
194
+ case 'skipped':
195
+ return { file: entry.file, reason: entry.reason, rule: entry.rule };
196
+ case 'secret':
197
+ case 'deleted-secret':
198
+ return { file: entry.file, reason: entry.reason, rule: entry.rule };
199
+ default:
200
+ return { file: entry.file, reason: entry.reason };
201
+ }
202
+ }
203
+ /**
204
+ * The files a review leaves out as one list: the source's first, then the diff's, each file, reason and rule
205
+ * once, the first kept. Every entry is a copy of its known fields, `rule` only for a skipped or a held file.
206
+ */
207
+ export function mergeLeftOut(source, diff) {
208
+ const listed = new Set();
209
+ const merged = [];
210
+ for (const entry of [
211
+ ...source,
212
+ ...diff,
213
+ ]) {
214
+ const copy = copyOf(entry);
215
+ const key = JSON.stringify([
216
+ copy.reason,
217
+ copy.file,
218
+ 'rule' in copy
219
+ ? copy.rule
220
+ : null,
221
+ ]);
222
+ if (listed.has(key))
223
+ continue;
224
+ listed.add(key);
225
+ merged.push(copy);
226
+ }
227
+ return merged;
228
+ }
@@ -0,0 +1,83 @@
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` holds the outcome of each of the profile's research parts, in order, a limit's name for a part it
76
+ * stopped, and every vote of `verdicts` whose failure is a limit counts for it. Each detail names the limit with
77
+ * its setting, then what it stopped: `its research` when the research was one part, else `<n> of its <count>
78
+ * research parts`, then `<n> vote(s)`, joined with ` and `.
79
+ */
80
+ export declare function limitGaps(profile: string, research: readonly string[], verdicts: readonly Verdict[], limits: {
81
+ readonly cap: number;
82
+ readonly deadlineMs: number;
83
+ }): IncompleteEntry[];
@@ -0,0 +1,169 @@
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.js";
8
+ /** The most tokens, input and output, one review spends when `maxReviewTokens` is not set. */
9
+ export const DEFAULT_MAX_REVIEW_TOKENS = 2_000_000;
10
+ /** How long one review runs when `reviewTimeoutMs` is not set: 30 minutes. */
11
+ export const DEFAULT_REVIEW_TIMEOUT_MS = 1_800_000;
12
+ /** What `maxReviewTokens` is when it is out of range: a whole number of tokens up to the largest the ledger adds exactly. */
13
+ const CAP_PROBLEM = `must be a whole number of tokens from 1 to ${Number.MAX_SAFE_INTEGER}`;
14
+ /** The problem with a `maxReviewTokens`, in words that say what to write, or undefined for a safe integer of at least 1. */
15
+ export function maxReviewTokensProblem(value) {
16
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1
17
+ ? undefined
18
+ : CAP_PROBLEM;
19
+ }
20
+ /** Every limit, in the order `limitGaps` lists their gaps. */
21
+ const LIMITS = ['token-cap', 'review-deadline'];
22
+ /**
23
+ * What a call ends with when a limit stops it. It is recognised by `instanceof` only, and a provider
24
+ * cannot raise one: an instance from a second copy of quorum is an unknown failure, which fails closed.
25
+ * It has no `kind`, so the retry policy never retries it and it is no provider's failure.
26
+ */
27
+ export class LimitError extends QuorumError {
28
+ limit;
29
+ constructor(limit, message) {
30
+ super(message);
31
+ this.limit = limit;
32
+ }
33
+ }
34
+ /** True for the failure a limit ends a call with. */
35
+ export function isLimit(error) {
36
+ return error instanceof LimitError;
37
+ }
38
+ /**
39
+ * Where an attempt of `tokens` stands: refused when it does not fit beside what was settled, which only grows;
40
+ * waiting when it fits beside that but not beside the attempts in flight, which settle at what they spent or
41
+ * at their whole reservation; else fitting.
42
+ */
43
+ export function fitOf(totals, tokens) {
44
+ if (totals.settled + tokens > totals.cap)
45
+ return 'refused';
46
+ return totals.settled + totals.reserved + tokens > totals.cap
47
+ ? 'waits'
48
+ : 'fits';
49
+ }
50
+ /** True for an integer status of 400 to 499 but 408: a server that refused the request before any work. */
51
+ function refusedBeforeWork(status) {
52
+ return typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 499 && status !== 408;
53
+ }
54
+ /**
55
+ * The tokens an attempt counts once it ends. A valid usage comes first, even above the reservation. Without
56
+ * one, a failure that is a refusal as too large, or an `http` failure of a client status but 408, counts for
57
+ * nothing: no work was done. Anything else counts the whole reservation, so a failure that says nothing
58
+ * never costs less than it may have.
59
+ */
60
+ export function settlementOf(reserved, usage, failure) {
61
+ if (usage !== undefined)
62
+ return usage.inputTokens + usage.outputTokens;
63
+ if (failure !== undefined && (failure.kind === 'too-large' || (failure.kind === 'http' && refusedBeforeWork(failure.status))))
64
+ return 0;
65
+ return reserved;
66
+ }
67
+ /**
68
+ * A ledger for a cap of `cap` tokens. An attempt that waits queues, and each settlement admits the waiters in
69
+ * the order they began to wait, up to the first that still waits; one that can never fit leaves the queue. A
70
+ * newcomer that would fit while an earlier attempt waits waits behind it, so a stream of small votes never holds
71
+ * a large research request back. Nothing deadlocks: every reservation in flight settles, at worst at its
72
+ * attempt's deadline, and with none in flight the head of the queue either fits or is refused.
73
+ */
74
+ export function createLedger(cap) {
75
+ let settled = 0;
76
+ let reserved = 0;
77
+ const waiters = [];
78
+ const refusal = () => new LimitError('token-cap', `the review's token cap of ${cap} tokens leaves no room for this call`);
79
+ function wake() {
80
+ while (waiters.length > 0) {
81
+ const head = waiters[0];
82
+ const fit = fitOf({ cap, settled, reserved }, head.tokens);
83
+ if (fit === 'waits')
84
+ return;
85
+ waiters.shift();
86
+ if (fit === 'fits') {
87
+ reserved += head.tokens;
88
+ head.admit();
89
+ }
90
+ else {
91
+ head.refuse();
92
+ }
93
+ }
94
+ }
95
+ function reserve(tokens, stop) {
96
+ if (stop.aborted)
97
+ return Promise.reject(stop.reason);
98
+ const fit = fitOf({ cap, settled, reserved }, tokens);
99
+ if (fit === 'refused')
100
+ return Promise.reject(refusal());
101
+ if (fit === 'fits' && waiters.length === 0) {
102
+ reserved += tokens;
103
+ return Promise.resolve();
104
+ }
105
+ return new Promise((resolve, reject) => {
106
+ const waiter = {
107
+ tokens,
108
+ admit: () => {
109
+ stop.removeEventListener('abort', onAbort);
110
+ resolve();
111
+ },
112
+ refuse: () => {
113
+ stop.removeEventListener('abort', onAbort);
114
+ reject(refusal());
115
+ },
116
+ };
117
+ function onAbort() {
118
+ const index = waiters.indexOf(waiter);
119
+ if (index !== -1)
120
+ waiters.splice(index, 1);
121
+ reject(stop.reason);
122
+ wake();
123
+ }
124
+ waiters.push(waiter);
125
+ stop.addEventListener('abort', onAbort, { once: true });
126
+ });
127
+ }
128
+ function settle(was, spent) {
129
+ reserved -= was;
130
+ settled += spent;
131
+ wake();
132
+ }
133
+ return { cap, reserve, settle };
134
+ }
135
+ /**
136
+ * The gaps the limits leave in a profile, one entry per limit that stopped work, the token cap's first, or none:
137
+ * `research` holds the outcome of each of the profile's research parts, in order, a limit's name for a part it
138
+ * stopped, and every vote of `verdicts` whose failure is a limit counts for it. Each detail names the limit with
139
+ * its setting, then what it stopped: `its research` when the research was one part, else `<n> of its <count>
140
+ * research parts`, then `<n> vote(s)`, joined with ` and `.
141
+ */
142
+ export function limitGaps(profile, research, verdicts, limits) {
143
+ const failures = verdicts.flatMap(verdict => verdict.votes).map(lensVote => lensVote.failure?.kind);
144
+ const which = {
145
+ 'token-cap': `the review's token cap of ${limits.cap} tokens`,
146
+ 'review-deadline': `the review's deadline of ${limits.deadlineMs} ms`,
147
+ };
148
+ return LIMITS.flatMap((limit) => {
149
+ const votes = failures.filter(kind => kind === limit).length;
150
+ const parts = research.filter(outcome => outcome === limit).length;
151
+ const stopped = [
152
+ ...parts > 0
153
+ ? [
154
+ research.length === 1
155
+ ? 'its research'
156
+ : `${parts} of its ${research.length} research parts`,
157
+ ]
158
+ : [],
159
+ ...votes > 0
160
+ ? [`${votes} vote(s)`]
161
+ : [],
162
+ ];
163
+ return stopped.length === 0
164
+ ? []
165
+ : [
166
+ { profile, reason: limit, detail: `${which[limit]} stopped ${stopped.join(' and ')}` },
167
+ ];
168
+ });
169
+ }
@@ -36,8 +36,9 @@ export interface ResearchReply {
36
36
  }
37
37
  /**
38
38
  * Validate a research reply. The envelope must be exactly `{ findings: [...] }`: a missing or
39
- * non-array `findings` fails the run, because a malformed reply must never read as "no findings",
40
- * and so does any other top-level key, because text planted in an unescaped string could close
39
+ * non-array `findings` is a failed reply, which fails a gating profile's review and is an advisory
40
+ * profile's `research-failed` gap, because a malformed reply must never read as "no findings", and so
41
+ * is any other top-level key, because text planted in an unescaped string could close
41
42
  * the findings array early and move the rest of the reply under a key of its own, where it would
42
43
  * be dropped without a trace. Only the first `limit` listed findings are read, so a flooded reply
43
44
  * costs bounded work; each of those that does not match the schema, or holds a nested object or
@@ -109,8 +109,9 @@ function syntaxAfterAnswer(visible, first, copies) {
109
109
  }
110
110
  /**
111
111
  * Validate a research reply. The envelope must be exactly `{ findings: [...] }`: a missing or
112
- * non-array `findings` fails the run, because a malformed reply must never read as "no findings",
113
- * and so does any other top-level key, because text planted in an unescaped string could close
112
+ * non-array `findings` is a failed reply, which fails a gating profile's review and is an advisory
113
+ * profile's `research-failed` gap, because a malformed reply must never read as "no findings", and so
114
+ * is any other top-level key, because text planted in an unescaped string could close
114
115
  * the findings array early and move the rest of the reply under a key of its own, where it would
115
116
  * be dropped without a trace. Only the first `limit` listed findings are read, so a flooded reply
116
117
  * costs bounded work; each of those that does not match the schema, or holds a nested object or