Library API
The TypeScript API that @tobi-or-not/quorum exports, from src/index.ts: createQuorum and its ports, a review and its events, a judgment of findings a program gives, an estimate of what a review or a judgment may cost, reading a source, what a review comes to, abort, the errors, the config types, and every export. Install the package with npm install @tobi-or-not/quorum and import from it: the examples on this page do, from a file of a project that has it installed. The package is ES modules with declarations, which a TypeScript project resolves with moduleResolution set to node16, nodenext or bundler; the older node10 ignores exports and finds no types. Node 22.18 or later on the 22 line, or 23.6 or later, runs a .mts file of these examples as it is, since the code is erasable TypeScript only, and so does Bun. A clone's src/index.ts exports the same API.
createQuorum
declare function createQuorum(options: QuorumOptions, ports: QuorumPorts): Quorum
interface QuorumOptions {
readonly profiles: readonly Profile[]
readonly concurrency?: number
readonly maxFindings?: number
readonly findingsCap?: number
readonly maxScannerIssues?: number
readonly exclude?: readonly string[]
readonly maxReviewTokens?: number
readonly reviewTimeoutMs?: number
readonly partTokens?: number
readonly relatedCode?: boolean
}
interface QuorumPorts {
readonly profiles: Readonly<Record<string, ProfilePorts>>
readonly events?: EventSink
}
interface ProfilePorts {
readonly research: Provider
readonly voters: Readonly<Record<string, Provider>>
}
interface Quorum {
readonly review: (input: ReviewInput, options?: ReviewOptions) => Promise<QuorumResult>
readonly judge: (input: JudgeInput, options?: ReviewOptions) => Promise<QuorumResult>
readonly estimate: (input: { readonly diff: string, readonly send?: readonly string[], readonly context?: ReviewContext, readonly findings?: readonly GivenFinding[], readonly relatedCode?: boolean }, limits?: { readonly maxReviewTokens?: number, readonly reviewTimeoutMs?: number, readonly findingsCap?: number }) => Estimate
readonly warnings: readonly string[]
readonly budgets: Readonly<Record<string, ProfileBudgets>>
}
interface ReviewInput {
readonly diff: string
readonly source?: ReviewSource
readonly leftOut?: readonly LeftOutFile[]
readonly send?: readonly string[]
readonly context?: ReviewContext
}
interface ReviewOptions {
readonly signal?: AbortSignal
readonly interrupt?: AbortSignal
readonly store?: ReplyStore
readonly maxReviewTokens?: number
readonly reviewTimeoutMs?: number
readonly findingsCap?: number
readonly relatedCode?: RelatedCodeReader
}JudgeInput, GivenFinding and the other types of judge are exported with these.
Options and ports
| Field | Holds | Default |
|---|---|---|
profiles | The profiles to run: at least one, ids unique | Required |
concurrency | The most provider calls in flight at once in one review, shared by every profile, with no lane and no adaptation; a positive integer. Unset, each provider has a lane of its own that follows its rate-limit headers, from LANE_START (4) calls at once, up to REVIEW_CEILING (16) calls in all: Lanes | Lanes |
maxFindings | The findings every research request of a profile that sets none of its own is sized by (Reply budgets), and the most findings of the research each profile reads, the only ones that can reach its panel, unless findingsCap says another; a positive integer | 50 |
findingsCap | The most findings of the research each profile sends to its panel in one review; a positive integer. It sizes no request, so a findingsCap above maxFindings changes no request, splits no reply and moves no store key, and a capped review's findings-capped gap names it as its lever. A review's own findingsCap option takes its place for that review | maxFindings |
maxScannerIssues | The most scanner issues each profile's panel judges in one review, as candidates; a positive integer. A cap of its own beside findingsCap, neither counted in the other, so a profile's panel judges at most their sum: a flood of issues never pushes a finder's finding out, nor the reverse, and each has its own gap (issues-capped, findings-capped) and its own lever. The least severe candidates are the ones left out: Scanner reports | 50 |
exclude | Path patterns of the files left out of every request (Excludes). Each file excluded reaches no model and is listed in meta.leftOut as excluded, never as a gap. At most 100 patterns, each at most 256 characters | None |
maxReviewTokens | The most tokens, input and output, one review may spend: The token cap. A whole number from 1 to 9007199254740991 | 2000000 |
reviewTimeoutMs | The deadline of one review, in milliseconds, from 1000 to 86400000: The review's deadline | 1800000 |
partTokens | The most tokens of diff text one research part holds: Research in parts. A whole number from 1024 to 9007199254740991 | 32768 |
relatedCode | Whether the quorum's reviews read related code, the definitions and callers of the names on a finding's cited row, from the repository outside the diff, for the votes of the lenses that ask for it (Lens.relatedCode). A review given a reader (ReviewOptions.relatedCode) reads it whatever this says; with it true, a review of a source that names a commit to read at must be given one, and is refused before any call when it is not: review. A quorum with it true and no lens that asks warns: warnings | false |
ports.profiles | One entry per profile, keyed by profile id: research, its research provider, and voters, one provider per lens keyed by lens id. A provider may state its timeoutMs, its stallTimeoutMs, its retries, its worstCase, its room, its window, its maxTokens, its thinking, its adapts, what quorum may change by itself in a review, its streams, true when it streams its replies, and its slots, how many calls its server serves at once, a whole number of at least 1, which its lane starts and stays at (the lesser of it and 16): What a provider states. A request carries thinking (low or off), structuredOutput (prompt) and stream (false, whole replies, or 'bare', a stream with no stream options) when quorum made that change, which an adapter honours only when it states the matching adapts, and onProgress, which hears each sign of life of a streamed reply as a StreamSignal: { kind: 'headers' }, sent for a reply whose media type is the stream's alone, never for a whole reply, { kind: 'data', outputTokens, answer, reasoning } or { kind: 'keep-alive' }. A response carries whole: true when the server answered a streamed request whole: Streaming. The changes: What quorum adapts by itself. A shipped adapter takes the option thinking, 'low' or 'off', sent as its protocol's own control and stated as its level: Thinking | Required |
ports.events | The event sink: a function that receives every event of every review | None |
One provider object may fill several ports: the research provider of a profile can also be every one of its voters.
Input checks
createQuorum checks its options and ports before anything else, and throws one ConfigError that lists every issue, one path: message line each, never a TypeError, so a program without types gets the same report:
| Path | Message |
|---|---|
options, ports | must be an object |
profiles | must be an array of profiles, or must hold at least one profile |
profiles.<index>, <id> and below | The profile's own issues: The checks |
profiles.<index>.id | repeats the profile id "security" |
<id>.maxFindings | A profile's own maxFindings: must be a positive integer, got 0, the value quoted when it is a number, else must be a positive integer |
<id>.changedLinesOnly | A profile's own changedLinesOnly: must be true or false |
<id>.lenses.<n>.relatedCode | A lens's own relatedCode: must be true or false |
concurrency, maxFindings, findingsCap, maxScannerIssues | must be a positive integer, got 0, the value quoted when it is a number |
maxReviewTokens | must be a whole number of tokens from 1 to 9007199254740991 |
reviewTimeoutMs | must be a whole number of milliseconds from 1000 to 86400000 |
partTokens | must be a whole number of tokens from 1024 to 9007199254740991 |
relatedCode | must be true or false |
exclude | must be an array, or must hold at most 100 patterns |
exclude.<index> | must be a string, or what to write instead: must not be empty, must be at most 256 characters long, ends with /, so it matches no file: end it with /** to leave out what the directory holds, holds ** inside a name: …, holds an empty, . or .. name, which no path in a diff has: …, holds \, which escapes nothing here: …, holds !, which negates nothing here: … or holds {, which lists no alternatives here: … |
ports.profiles | must be an object keyed by profile id |
ports.profiles.<id> | is missing, must be an object with a research provider and voters, or names no profile of the run |
ports.profiles.<id>.research | is missing, or must be a provider: an object with a string id, a string model and a complete function |
ports.profiles.<id>.voters | is missing, or must be an object keyed by lens id |
ports.profiles.<id>.voters.<lens> | is missing, the provider message above, or names no lens of the profile |
ports.profiles.<id>.research.timeoutMs, ports.profiles.<id>.voters.<lens>.timeoutMs | must be a whole number of milliseconds from 1000 to 518400000 |
ports.profiles.<id>.research.stallTimeoutMs, ports.profiles.<id>.voters.<lens>.stallTimeoutMs | must be a whole number of milliseconds from 1000 to 86400000 |
ports.profiles.<id>.research.retries, ports.profiles.<id>.voters.<lens>.retries | must be a whole number from 0 to 5 |
ports.profiles.<id>.research.window, ports.profiles.<id>.research.maxTokens and the same under voters.<lens> | must be a whole number of tokens of at least 1 |
ports.profiles.<id>.research.thinking, ports.profiles.<id>.voters.<lens>.thinking | must be default, low or off |
ports.profiles.<id>.research.adapts, ports.profiles.<id>.voters.<lens>.adapts | must be an object whose thinking is low or off and whose prompt and stream are true, each optional |
ports.profiles.<id>.research.worstCase, ports.profiles.<id>.voters.<lens>.worstCase | must be a function |
ports.profiles.<id>.research.room, ports.profiles.<id>.voters.<lens>.room | must be a function |
ports.events | must be a function |
profiles.<id> | the research request on <provider> leaves <room> tokens for the diff, less than the 1024 a hunk may need: contextTokens <window> counts <fixed> for <parts>, <template> for the chat template and <reply> for the reply: <fix> (for a room below 0, leaves no tokens for the diff, its other tokens <n> over the window, where a hunk may need 1024, <n> being the room's absolute value), and the same for the vote request on <provider> for the longest finding: a profile whose fixed text leaves a provider that states its room and its window no room for a diff, checked once the ports pass. <parts> is the instructions alone for a profile with no document, else the instructions and each document the request carries with its tokens (the instructions (1685), the guidelines (16308), the do-not-report text (5259) and the rules (3140), the rules being the whole block of every rule the profile lists, whatever files a change holds); a vote's is the instructions and the finding, then the guidelines (<g>) and the rule it cites, at the largest (<u>), the vote of a finding that cites a rule carrying that one rule, counted at the largest rule the profile lists. <fix> names those documents, the largest first, a vote's rule as the rules (shorten the rules or the guidelines), before lower maxTokens, or state a larger window (Room accounting) |
A port for a profile or a lens the review does not have is refused, as a likely typo. A profile's ports are checked only when the profile itself has no issue, and no port is checked when profiles is not an array. Every record keyed by an id is read through its own properties, so constructor is as valid an id as any other. For the security profile with concurrency: 0, maxFindings: 2.5, a research port that is not a provider, its defenses voter missing and one named typo instead, a port for a profile named other, and a sink that is a string, the message reads:
concurrency: must be a positive integer, got 0
maxFindings: must be a positive integer, got 2.5
ports.profiles.security.research: must be a provider: an object with a string id, a string model and a complete function
ports.profiles.security.voters.defenses: is missing
ports.profiles.security.voters.typo: names no lens of the profile
ports.profiles.other: names no profile of the run
ports.events: must be a functionThe snapshot
Each profile is compiled once, when the quorum is created: its vote template rendered for each lens, its thresholds resolved, and its providers captured beside the { id, model } each had then, which is what events and meta report, with the window, maxTokens and thinking each stated, from which the profile's reply budgets are computed once (Reply budgets). A later change to a profile, to exclude, or to which provider a port names, is never seen by a review of that quorum. The provider objects themselves are called as they are.
budgets
Quorum.budgets holds each profile's ProfileBudgets by profile id, frozen, at its providers' stated windows: the reply budget of its research and of each lens's vote (replyTokens), the N its research asks for (findings, and findingsWithoutThinking) and the ceiling of that ask (maxFindings, the profile's own, else the quorum's), the tokens of diff its research provider's stated room leaves a one-request research and a part (rooms.one and rooms.part), the room each voter leaves the vote of the longest finding (room), and worstPart, the tokens the review's token cap reserves for a part that holds as much diff as its room and partTokens allow, with how many of them maxReviewTokens holds: the worst case of a part that lists no file, so where partTokens bounds the diff the figure runs low and holds high, by the size of the file list a real part carries, and where the room bounds it both are exact. A provider that states no room has no rooms, worstPart or room. --print-config prints them. A profile whose rooms fall below 1,024 tokens never gets this far: createQuorum throws it (Room accounting). fromConfig keeps the field.
warnings
The settings of the profiles that cannot take full effect, each starting at its profile id, such as a policy level that is never reached, the deprecated gating, or a failOn of low while the policy's low is off: Warnings. A quorum with warnings still runs. One warning is the quorum's and starts at relatedCode: relatedCode: is on, and no lens of the quorum's profiles asks for related code: set relatedCode on a lens, given once when the switch is true and no lens of any profile has relatedCode set. A lens that asks while the switch is off is no warning.
review
const result = await quorum.review({ diff, source, leftOut }, {
signal: AbortSignal.timeout(10 * 60_000),
store: await fileStore('/home/me/.quorum-state', { providers: config.providers })
})diffis the unified diff, as a string. A blank one runs no stage, calls no model and resolves with empty lists, the review still sendingrun:startandrun:end. One whose every fileexcludeleaves out does the same, except that itsmeta.leftOutlists the files, aleft-outevent is sent, and the text before the first header, a mail's message say, is still researched.source, optional, is where the diff came from: it is checked and recorded inmeta.sourceas given, with its known fields only, and{ kind: 'diff' }when it is unset. The source lists its five kinds.settings, optional, is what the review runs under, which the core cannot know, since it holds provider objects and not the config's presets, auth styles orextraBody: the caller builds it (the CLI does, withreviewSettings). The review checks it against the schema of a result,settingsSchema, refuses one that does not match before any event, and records a copy of it, made before the review's firstawait, inmeta.settings, which isnullwhen none is given: The settings. The record holds no base URL and no key by its schema, so a program that builds one cannot put one in.leftOut, optional, lists the files a source left out before it made the diff. They come first inmeta.leftOutand in theleft-outevent, before the diff's own, each file, reason and rule once, and abinary,submoduleorsecretone is a gap of every profile, as the diff's are. Askippedone, with itsrule, and adeleted-secretone are no gap, and one of the rulesecret, or of the reasonsecretordeleted-secret, raises asecret-fileflag ahead of the diff's flags: A file left out.send, optional, names the files to send the models though they are held back as secrets: each is the path as the diff writes it, the onemeta.leftOutlists, matched exactly, so./.envnames no file.env. A file named here is not held, so it is neither listed nor flagged as a secret, and anexcludepattern still leaves it out first. The text no header names, which has the empty name, can never be named, and neither can a file by a changed spelling: such a file stays held, with its path inmeta.leftOutto write. The array is copied before the review's firstawait. A program that reads a config'ssendpasses it here itself, as it passesexcludetoreadSource, and as the CLI does with the config'ssendand--sendmerged.context, optional, is the review's repository documents, as the CLI's reader of the repository hands them over: each is sent with the profile it names, after that profile's own text and documents, cleaned and capped as every document is, and recorded inmeta.context: Documents. Each names the commit its text was read at, which the core checks againstsource: a range's base, a path review's commit, a local source's head. Adiffsource, and a local source before a first commit, names none and takes no document. Itsreportsare scanner reports, which the core places against the change and judges as candidates: Scanner reports. ItstestCoverageare coverage reports, which a profile that reads test coverage is sent the changed lines' state of: Test coverage.- A file held back as a secret is no part of any request: a file whose name is a secret's, or that holds a credential quorum recognizes, leaves the diff whole, is listed in
meta.leftOutassecretwith itsrule, raises asecret-fileflag and is asecretgap of every profile, which no flag lifts for a gating profile (--fail-on nonemakes a profile advisory, and its gaps then change no code). A change that deletes a file named as a secret whole lists it asdeleted-secret, with its flag and no gap; a deletion of a file held for a credential in it, whose removed code would go unread, is asecretgap. A diff whose every file is held runs no stage and still records the gaps: Files held back as secrets. signal, optional, stops the review: Abort. Its meaning is unchanged.interrupt, optional, stops the review gently, and the review resolves with what it read: Interrupt.INTERRUPT_GRACE_MS, exported, is the 5000 ms it gives the calls in flight.store, optional, is aReplyStore: where the review keeps the calls it paid for and finds them again on a rerun, which reuses every call the store holds for a request sent as it was, and still pays the calls that failed, about the calls in flight more (concurrency, or up to 16 with lanes), and every call of a provider whose settings changed. Each research call whose reply passed its envelope check and each vote that parsed is put as it completes, and a research reply that was cut off or listed as many findings as it was asked for at most is put as a marker that sends its part straight to recovery; a failed call is never put. Each send is looked up under a key of the request as it is sent, never of its bytes, so a changed diff, prompt, budget, thinking level or mode is a miss. A stored reply is checked as a fresh one and reused only if it passes, and spends nothing: no reservation, no usage, acallevent that saysreused, and the count inmeta.reused. Agetor aputthat throws, rejects or never settles in a review that is stopped is a miss or a write that did not happen, and a stored call that is noStoredCallis a miss: the review is as if it had no store.fileStoreis the CLI's own: Saved state.findingsCap, optional, is the most findings of the research each profile sends to its panel in this review alone, in place of the quorum'sfindingsCap, else itsmaxFindings: a positive integer, else aConfigErrorbefore any event (findingsCap: must be a positive integer). Every research request is still sized bymaxFindings, its reply budget and the findings it asks for, so afindingsCapabove it changes no request, splits no reply and moves no store key; the findings past it are thefindings-cappedgap. The CLI gives a--pathreview whose config sets neitherfindingsCapnormaxFindingsfour findings per research part, at least 50: The bounds of a path review.maxReviewTokensandreviewTimeoutMs, optional, are the token cap and the deadline of this review alone, in place of the quorum's, and each is checked as the quorum's is: a whole number of tokens from 1 to 9007199254740991, and of milliseconds from 1000 to 86400000, else aConfigErrorbefore any event. A caller that knows how large its input is gives its review the bounds that fit it, and the reviews that give none keep the quorum's. The CLI gives a--pathreview its estimate's worst case, never below 2000000, and 24 hours when the config sets none: The bounds of a path review. The gaps read the limits the review kept to, and so dorun:stoppingand the summary's bounds.relatedCode, optional, is the reader of the repository's code, asopenRelatedCodeopens one, which makes the review carry related code: each finding of a profile with a lens that asks (Lens.relatedCode,falsewhen unset) has the related code of its cited row worked out before its votes, one finding at a time for each profile, and a lens that asks is sent the first excerpts that fit in a block of its own, first in its vote, fenced as code and never in a system message; every other lens's vote, and every vote of a review with none, is the one it would be with related code off, digest for digest. The excerpts are the definitions of the names on the cited row and the callers of the function around it, read at the commit the source names, from files the change does not touch, comment lines left out; a vote carries as many of the first as fit the least of 8 KiB, a quarter of its voter's stated room (the room of its request with an empty diff block) and the room the request as it is sent leaves, its diff block chosen as it is with no related code, and 8 KiB when its voter states no room. A row is looked up once, whatever the findings and profiles that cite it, and a file is read once, within 32 MiB of files in all: a finding whose unread files pass what is left of them has none (review-cap), and a later finding whose files fit is read. The result holds a verdict'srelatedCode, each vote'srelatedCodeandquotesRelatedCode, andmeta.relatedCode, and the sink hearsrun:start'srelatedCodeand arelated-codeevent for each finding: Related code, Events. A lookup or a read that git fails is counted for the finding (unreadable) and the review goes on; the review's deadline or interrupt ends one asstopped, and its abort rejects the review with the reason. The core opens no repository and fetches nothing.- A quorum reviews any number of diffs, one per call. Each review has its own concurrency limit and its own signal, and several may run at once.
It resolves with the result, or rejects:
| With | When |
|---|---|
A ConfigError | The input is malformed, before any event: input: must be an object holding the diff string when the input is not an object, such as the diff text passed on its own; diff: must be a string; source: must be an object, source.kind: must be diff, range, local, staged or paths, source.objectFormat: must be sha1 or sha256, source.<field>: must be a full commit id of its object format: 40 lowercase hexadecimal characters for sha1, 64 for sha256 (and, for the head of a local or staged source, , or null when nothing is committed), source.paths: must be an array of strings or source.skips: must be a boolean; settings: must be a review's settings record, as reviewSettings builds it: <path> does not match, with the path of the first field that does not match, such as settings.partTokens.origin, and no value; leftOut: must be an array, leftOut.<index>: must be an object with a file and a reason, leftOut.<index>.file: must be a string, leftOut.<index>.reason: must be excluded, binary, submodule, skipped, secret or deleted-secret, leftOut.<index>.rule: must be vendored, lockfile, minified, test, secret, binary, submodule or lfs (for a skipped file, which has one), leftOut.<index>.rule: must be name, private-key, aws-key, github-token, slack-token, google-key, stripe-key, anthropic-key or openai-key (for a secret or deleted-secret file, which has one) or leftOut.<index>.rule: belongs to a skipped, secret or deleted-secret file only; send: must be an array or send.<index>: must name a file (an entry that is not a non-empty string, a hole included); context: must be an object holding documents, and the messages of a context's documents, which Documents lists, of its reports, which Scanner reports lists, and of its coverage reports, which Test coverage lists; options: must be an object; signal: must be an AbortSignal, interrupt: must be an AbortSignal, or store: must be a reply store: an object with get and put functions; and, once the source passed its checks, the checks of relatedCode, in this order of case: relatedCode: is on, and this review was given no reader: pass the one openRelatedCode opens, or turn it off (the quorum's switch is on, the source names a commit to read at and no reader is given), relatedCode: must be a reader of related code, as openRelatedCode opens one (an object whose commit is a full commit id and whose lookup and read are functions), relatedCode: is given for a source that names no commit to read related code at: give none (a diff source, or local changes before a first commit) or relatedCode: reads at <short>, and this review's source reads related code at <short>: open the reader on the review's source, each <short> the first 7 characters of a commit id |
| The signal's reason | The signal aborted, before the review or while it ran |
| The sink's error | The event sink threw |
A ProviderDownError | No research call of any profile answered, and a research provider was found down, or each of whose calls failed for a reason of its own, though fewer than three did: ProviderDownError. It is the only error a model's failure rejects a review with |
A failed research part, its call or its reply, never rejects a review: it is its profile's research-failed gap, a gating profile's too. A failed vote never rejects a review either: it is recorded in its verdict. A provider that is down is called no more, and the research parts and votes it was never sent are provider-down gaps: the review rejects only when no part of any profile was read.
A finding's line is the line its finder cited, unless the harness moved the finding to the nearest occurrence of its quote in the cited file's section before the panel voted: Finding.citedLine then holds the cited line, and the key is absent, never undefined, for a finding that stayed where it was cited. quoteMatched is of the final line. Finding.foundBy, of the type FoundBy, says what proposed a finding: { kind: 'model' } for one the model's finder reported, set by code where research reads its replies, and { kind: 'scanner', report, scanner, ruleId, level }, with fileLevel and suppressed when they hold, for a candidate a scanner's report gave (Scanner reports). The voters of a candidate read its scanner, its rule and its claim, and a model finding's foundBy reaches no request. A verdict lists the fields, and the quote check says when a finding moves.
judge
interface JudgeInput extends Omit<ReviewInput, 'context'> {
readonly context?: Omit<ReviewContext, 'reports'>
readonly findings: readonly GivenFinding[]
}
interface GivenFinding {
readonly profile: string
readonly file: string
readonly line: number
readonly category: string
readonly summary: string
readonly rule?: string
}// A change to https://github.com/example/project that builds a query from a request's id, and the finding a person gives the panel to judge.
const result = await quorum.judge({
diff,
findings: [
{
profile: 'security',
file: 'src/users.js',
line: 12,
category: 'CWE-89',
summary: 'the id of the request reaches the query unescaped'
},
],
}, { store })
console.log(result.meta.judged) // { findings: 1 }
console.log(result.kept.map(verdict => [verdict.file, verdict.line, verdict.confidence]))judge runs the panel of each finding's profile alone, on the findings it is given, and runs no research: no research request is built and none is sent. Each finding goes to every lens of its profile, each vote asked of the lens's own provider as a review would ask it of the same finding, digest for digest, and each verdict is computed in code from the votes by the profile's thresholds. The finding is what a finder's reply states, less its quote, and everything of it the voters read is the diff's: its evidence is the diff's lines around the cited line, as a review's is.
diff,source,settings,leftOutandsendare a review's, checked and recorded asreviewdoes.settingsis recorded inmeta.settingsand isnullwhen none is given.context, optional, is a review's less itsreports: the repository documents of Documents and the coverage reports of Test coverage, since every vote of a profile carries its guidelines, the vote of a finding that cites a rule carries that rule as the review sent it, and a lens that asks for test coverage carries its line. Acontextthat holdsreportsis refused: a scanner's report adds candidates, andjudgejudges the findings it is given.findingsare one or moreGivenFindings, each aprofileof the quorum, afileand alineof the diff, acategory, asummary, and arulewhen the profile lists rules (the id of a rule the review sends for the file). Itscategoryandsummaryare cleaned and capped as a finder's are, at 80 and 500 characters, and the finding is named by itsidand itsfingerprintas a finder's is, found by the model (foundByis{ kind: 'model' }). It has no quote, so no check moves it:quoteMatchedisfalseandcitedLineis absent.optionsare a review's,ReviewOptions, and mean whatreviewsays:signal,interrupt,store,maxReviewTokens,reviewTimeoutMs,findingsCapandrelatedCode, whose reader a given finding's cited row is read through as a review's finding's is, and whose checks a judgment keeps. The cap and the deadline are a review's, so a vote they stop is a failed vote of kindtoken-cap,review-deadlineorinterrupted, with its gap.findingsCapis the most given findings of each profile, the quorum's unless set. The quorum's own event sink hears the judgment's events, a review's less the research stage: no event says "judge", andmeta.judgedis the field that does. Astorekeeps a vote under the key a review keeps it under, so a judgment reuses the votes a review stored for the same finding, and a review the votes a judgment stored.
The checks a given finding passes
The input is refused, as one ConfigError, before any event and before any call, at the paths below. The checks run in stages, and the error lists every issue of the first stage that fails, in this order: (1) the input and the options, checked as review checks them, their relatedCode among them, listed with the findings' fields and the refusal of context.reports; (2) the profiles with the repository documents of context, which review checks too; (3) the findings' fields and the refusal of context.reports again, against the profiles as the review sends them, whose rules a repository document may add; (4) the cap; (5) the code checks of each finding:
| Path | Message |
|---|---|
findings | must be an array of the findings to judge, or must hold at least one finding |
findings.<n> | must be a finding to judge: an object with profile, file, line, category and summary |
findings.<n>.<key> | is not a known field, for a key other than profile, file, line, category, summary and rule; a key that is no safe name is printed as * |
findings.<n>.profile | must be a string, or names no profile of the quorum |
findings.<n>.file | must be a non-empty string |
findings.<n>.line | must be a whole number of at least 1 |
findings.<n>.category | must be a string |
findings.<n>.summary | must be a string that holds the claim: a string with nothing left once cleaned as a finder's is |
findings.<n>.rule | must be a string, or names a rule, and <profile> lists none: a profile lists a rule when it or a repository document of context gives it one |
context.reports | Quorum.judge judges the findings it is given, and reads no scanner report |
findings | holds <k> findings of <profile>, past the findings cap of <c>, one for each profile given more than the cap |
findings.<n> | The reason research writes when it drops a finding, for the finding a check would drop or change: <file>:<line> is not in the diff (outside the diff the review reads, which is the diff less the excluded and the held files, at a line no hunk shows), "<file>":<line> is more than two lines from a line the change adds or removes (a profile that reviews changed lines only), "<file>":<line> cites no rule this review sent (a rule the review does not send for the file), "<file>":<line> cites no rule, which the profile requires |
findings.<n> | repeats findings.<m>: the same profile, file, line and category, for a finding the dedup stage would drop |
The code checks are research's own (checkFindings), run on each given finding alone, with no anchor. A finder's finding a check drops is dropped and counted in invalidFindings; a given finding is the caller's input, which a library refuses before it spends anything, as it refuses a malformed diff, so judge judges every finding it is given, meta.judged.findings is the number of verdicts in the result, and a finding a check would change, a rule the review does not send that research would strip, is refused too, never judged as another finding. A caller that cannot know the diff the review reads gets the answer from estimate, which makes no call.
What a judgment holds
The result is a review's, from the same schema, with these differences:
- No research. Each profile's
researchis{ parts: 0, listed: 0, panel: <its given findings>, capped: 0, saturated: 0 }, and itsstagesholddedupandpanel.meta.callscounts the votes alone. meta.judged,{ findings: <given> }, afterconcurrency, in the result and in the public view: meta.- Coverage. The same for every profile: a file
excludekeeps out of every request isexcluded, a file left out as binary, a submodule or a secret isunreviewedwith that reason, and every other file isunreviewedwith the reasonnot-researched, since no research read the change and so no file reads as reviewed: Coverage. - The gaps are the panel's and the limits':
vote-failed,request-too-large,token-cap,review-deadline,interruptedandprovider-down, and a coverage report's for a profile that reads test coverage. A file left out and a hunk too large for research are no gap of a judgment, since a gap says research could not read them and the coverage says no research read anything. - The rest is a review's:
meta.source,leftOut,flags,context,adaptations,reusedandconcurrency.
It rejects as review does, with the signal's reason or a sink's error, and with a ProviderDownError only when no vote was cast: the error of the first voter's provider, in profile and lens order, that was found down, else of the first whose every call failed for a reason of its own, though fewer than three did. A judgment whose votes all failed for any other reason resolves, with its verdicts unreviewed. A quorum from fromConfig refuses a context that lacks a repository document its config lists, as for review and estimate.
Documents
A profile reads policy as documents: text a person wrote, which a model reads as the criteria to judge by (guidelines), as what the finder is told not to report (do-not-report), or as review rules a finding may cite (rules). The core cleans, caps, joins, sends and records them, and reads no file: a program, or the CLI's readers, hand it the text.
interface Profile {
guidelines?: string
doNotReport?: string
rules?: readonly ReviewRule[]
requireRule?: boolean
documents?: readonly ReviewDocument[]
// ...
}
interface ReviewRule {
readonly id: string
readonly text: string
readonly paths?: readonly string[]
}
interface ReviewDocument {
readonly profile: string
readonly kind: 'guidelines' | 'do-not-report' | 'rules'
readonly origin: DocumentOrigin
readonly text?: string
readonly rules?: readonly ReviewRule[]
readonly removed?: Removed
}
type DocumentOrigin
= | { readonly kind: 'config', readonly sha256?: string }
| { readonly kind: 'repository', readonly path: string, readonly commit: string, readonly sha256?: string }
interface ReviewContext {
readonly documents?: readonly ReviewDocument[]
readonly reports?: readonly ScannerReport[]
readonly testCoverage?: readonly CoverageReport[]
}- Where a profile's documents come from.
Profile.guidelinesandProfile.doNotReportare its own text.Profile.documentsholds documents of originconfig, each naming the profile that holds it.ReviewInput.context.documentsholds documents of originrepository, each naming a profile of the quorum and the commit its text was read at, andQuorum.estimatetakes the samecontext. The texts of a kind are joined by a blank line in that order: the profile's own, its documents, then the review's. A blank one is recorded and sent as nothing, and a repository document with notextis an optional one that was not found; a config document with none is refused (.text: must be a string: a config document is never missing). - What the core does to each text, whoever read it: it cleans it with
cleanProse, adds what its pass removed to theremovedits reader gave, and refuses it over its cap once cleaned. A profile's ownguidelines, which 0.12.0 sent as given, are cleaned and capped too. - Where each kind goes. The guidelines are a block of every request of the profile, the research call and every vote. The do-not-report text is a paragraph of the research system message, right after the instructions, and no vote carries it. The rules are a block of every research request, after the diff: The layout of a request.
- Review rules. A
ReviewRuleis anidthat matches^[a-z][a-z0-9._-]{0,63}$, atextof 1 to 1,024 code points once cleaned, andpaths, when set, 1 to 20 patterns ofexclude's syntax. A profile's rules areProfile.rules, then the rules of itsdocumentsof kindrules(each such document holdsrulesin place oftext), then those of the review's repository documents of that kind, all ids unique, at most 100 rules in all. A research request carries the rules whosepathsmatch a file of the filtered diff, and every rule with nopaths, the same block in every part of a change researched in parts; a profile that lists a rule asks each finding for a sixth field,rule, the id of the rule it breaks or an empty string, and a profile that lists none sends the requests it always did. A reply whoseruleis absent ornullreads as citing none, and one whoseruleis no string leaves its finding unreadable. A rules document's record holds its count ofrulesand thebytesof its entries as the block sends them. - The rule citation. Once
verifyFindingshas anchored a finding, so on the line of its quote when the harness moved it,checkCitationsreads theruleits finder cited, trimmed: it holds when it names a rule of the ones the review sent whosepathsmatch the finding's file (a rule with none matches every file), and the finding then carriesFinding.rule, the rule's own id as the configuration states it and never the finder's text, and each of its votes carries that rule's block. Any other citation fails with the reason"<file>":<line> cites no rule this review sent, the file JSON-quoted and cut at 80 characters, and a finding that cites none fails with"<file>":<line> cites no rule, which the profile requireswhenProfile.requireRuleistrue. A failed citation drops its finding whenrequireRuleistrue; otherwise the finding goes on with norule, and one that cites none is kept as it is. Each failure is afinding:invalidevent of causeruleand counts inmeta.profiles.<id>.invalidRules, apart frominvalidFindings; no reason holds what the finder cited. A reply whose finding cites a wrong rule was read, so no reply is sent once more for it and no gap is recorded: a failed citation is one finding's, never its reply's. A profile withrequireRulethat sends no rule for a change asks its research nothing: it makes no call, every part readsreviewed, itsstage:startforresearchsaysparts: 0, and its estimate is that of a profile that makes no call.requireRulemust betrueorfalse, and it isfalsewhen unset. - The caps, in UTF-8 bytes of the cleaned text:
| What | Cap |
|---|---|
| A guidelines document, and a profile's guidelines in all | 16 KiB (16,384 bytes) |
| A do-not-report document, and a profile's do-not-report text in all | 8 KiB (8,192 bytes) |
| A rule's text, in code points once cleaned | 1,024 |
| The cleaned texts of a profile's rules in all | 32 KiB (32,768 bytes) |
| The rules of a profile, and the patterns of one rule | 100, and 20 |
| A document's text before it is cleaned, as a reader decodes it | 64 KiB (65,536 bytes) |
| The documents of one kind a profile holds, a rule written in a config (a rules document of one rule and no hash) not counted | 16 |
| The documents of a review's context | 256 |
- Nothing is cut. A document over a cap, one the cleaner still changes after 16 passes, a review whose repository documents leave a research provider less than 1,024 tokens of diff (Room accounting), and an input that is no context are refused as a
ConfigErrorbefore any call, and no message holds a text, only counts and a path. The room check runs again on the run a review builds for a profile its context names a document of, since a repository document only adds to the profile's fixed text; a profile the context names none of keeps the run it was created with. - Every document is in the request's key. The guidelines and the rules are blocks of the request and the do-not-report text is in its instructions, and the sixth field is in its reply schema, so a rerun with a store after a document changed reuses no stored reply of a request that carries it.
What createQuorum and review refuse of documents, each message at its path:
| Path | Message |
|---|---|
<id>.guidelines, <id>.doNotReport | must be a string, holds <n> bytes once cleaned, over the 16 KiB a guidelines document may hold (8 KiB a do-not-report document), or nests HTML comments or character references too deep to clean in 16 passes: remove them |
<id>.rules | must be an array of rules, or must hold at most 100 rules |
<id>.rules.<index> | must be an object with an id and a text |
<id>.rules.<index>.id | must match ^[a-z][a-z0-9._-]{0,63}$, or repeats the rule id "no-any" |
<id>.rules.<index>.text | must be a string, must hold 1 to 1024 characters once cleaned, or nests HTML comments or character references too deep to clean in 16 passes: remove them |
<id>.rules.<index>.paths, <id>.rules.<index>.paths.<n> | must be an array of patterns, must hold 1 to 20 patterns, must be a string, or what exclude.<index> is told to write instead |
<id>.rules.<index> | takes the profile's rules to <n> bytes once cleaned, over the 32 KiB they may hold in all, at the first rule that takes the cleaned texts over the cap |
<id>.documents | must be an array of documents, or must hold at most 16 documents of one kind |
<id>.documents.<index> | must be an object; the cap and unsettled messages above; or takes the profile's guidelines to <n> bytes once cleaned, over the 16 KiB they may hold in all (do-not-report text, 8 KiB it may hold in all), at the first document that takes the profile's texts of its kind over the cap, its own text counted first |
<id>.documents.<index> of kind rules | must hold at most 100 rules, or takes the profile's rules to <n> bytes once cleaned, over the 32 KiB they may hold in all, at the first rules document that takes the profile's rules over either cap, counting its own rules and the rules documents before it; a document over a cap by itself is told at its own .rules or the rule that takes it over, and never twice. The <n> of the bytes message is always the profile's total at the rule that takes it over: its own rules, the rules documents before it, then the document's rules up to that rule |
<id>.documents.<index>.profile, .kind, .origin, .origin.sha256, .text, .rules, .removed | must name the profile that holds it; must be guidelines, do-not-report or rules; must be a config document: a { repository } document comes from the review's context; must be 64 lowercase hexadecimal digits; must be a string, or holds <n> bytes, over the 64 KiB quorum reads of a document, or, for a rules document, must be absent: a rules document holds rules; must be an array of rules: a config document is never missing, or, for another kind, must be absent: only a rules document holds rules; must hold counts of characters, comments and entities |
<id>.documents.<index>.rules.<n> | The rule messages above at the rule's own field, and repeats the rule id "no-any" at the rule's id when an earlier rule of the profile, its own or a document's, has that id |
context | must be an object holding documents |
context.documents | must be an array of at most 256 documents |
context.documents.<index>.profile | names no profile of the quorum |
context.documents.<index>.origin | must be a repository document: a { file } document belongs in the profile's documents |
context.documents.<index>.origin.commit | must be the commit the review's source reads documents from, or, for an estimate, which names no source, must be a full commit id: 40 or 64 lowercase hexadecimal digits |
context.documents.<index>.origin.path | must be a path of at most 4096 characters |
context.documents.<index> | needs a commit to read it from, which the review's source does not name (a diff source, or local changes before a first commit); "REVIEW.md" at 1f3a9c2 holds 17020 bytes once cleaned, over the 16 KiB a guidelines document may hold, the path JSON-quoted and cut at 100 characters and the first 7 characters of the commit before the cap, unsettled and in-all messages above; or the shape messages of .profile to .removed above |
context.documents.<index> of kind rules | must hold at most 100 rules or takes the profile's rules to <n> bytes once cleaned, over the 32 KiB they may hold in all, at the first rules document that takes the profile's rules, its own and its config documents' counted first, over either cap |
context.documents.<index>.rules.<n> | The rule messages above, and repeats the rule id "no-any" at a rule whose id the profile's rules or an earlier document's already hold, each after the document's path and commit as above |
profiles.<id> | The room message of Input checks, for a review whose repository documents leave a provider no room |
A review records every document in meta.context and sends one context event; neither holds a text. The types ReviewRule, ReviewDocument, ReviewContext, DocumentKind, DocumentOrigin, ContextDocument and ContextRecord are exported.
Scanner reports
A review can judge the issues a scanner already found. The core reads no file and never runs a scanner: a program hands it reports, as a reader of a SARIF log or of a saved SonarQube response hands them over, in ReviewInput.context.reports (and Quorum.estimate's input takes the same), each for one profile. The core places every issue against the change, and an issue on the change becomes a candidate: a finding a scanner proposed, which the profile's own panel judges as it judges the finder's, by every lens, with the scanner's claim and the text of its rule as fenced data. A scanner never decides a verdict, and a report only adds candidates, never removes a finding.
interface ScannerReport {
readonly format: 'sarif' | 'sonarqube'
readonly profile: string
readonly sha256?: string
readonly scanner?: string
readonly commits?: readonly string[]
readonly problems: readonly ReaderProblem[]
readonly total?: number
readonly skipped: number
readonly unreadable: number
readonly notRead?: number
readonly runs?: number
readonly issues: readonly ScannerIssue[]
}
interface ScannerIssue {
readonly path?: string
readonly unmapped?: true
readonly line?: number
readonly scanner: string
readonly ruleId: string
readonly ruleText?: string
readonly message: string
readonly level: 'error' | 'warning' | 'note' | 'none' | 'unknown'
readonly suppressed?: true
readonly snippet?: string
}- What a program hands over.
profileis the id of a profile of the quorum, whose panel judges the report's candidates, so a report for a profile the quorum does not run is refused.pathis the repository path after the path rules, absent for an issue that sits on no file, andunmappedistruefor an issue whose path the reader could not place.lineis a safe integer of at least 0, absent when the issue gives none.problemsis what is wrong with the file as a whole (missing,cannot-read,not-a-file,too-large,not-the-format,no-results,truncated,too-many,scanner-failed),commitseach revision a run states,skippedthe entries that are no open issue andunreadablethe ones the reader could not read.notReadis the entries the file held past the reader's caps and the reader did not read, 0 when absent: the results (the issues, for a SonarQube response) a run holds past its 25,000, and every result of each run past a log's 20th, counted from the length of its result list, andrunsis a log's runs when it holds more than 20. The core addsnotReadto what the report lists, and says it in the gap as<r> of its <t> results were not read; a report with anotReadabove 0 is read in part withtoo-many, whether or not itsproblemssay it. The core cleans and caps every text a report holds, so no field needs to be cleaned first. - What the core checks of a report. The reports are an array of at most 16, and each is an object of exactly these fields, every text within the bound its reader cuts it to, in UTF-16 units: a
messageof 2,000, aruleTextof 8,192, aruleIdof 1,024, ascannerof 256, asnippetof 2,000 and a revision of 64, at most 500,000 issues in a report (20 runs of 25,000 results). A message names the path of the first field that does not match and never a value. - Where each issue ends. Under exactly one outcome, counted in the report's record in
meta.context.reports:held(its text holds what reads as a credential, or a text the cleaner cannot settle, so no model was sent it),unmapped,leftOut(its file is one the review left out),notInChange(its path names no file of the diff, exactly),used(a candidate: its line is near a line the change adds or removes, or, for an issue with no usable line (none, 0, or a Trivy result's line 1), the file's first changed line,foundBy.fileLevel),unchanged(any other line of a file of the change),capped(a candidate pastmaxScannerIssues), and the reader'sskippedandunreadable; what the reader did not read is countednotRead, beside them. A report that states another commit than the review's, or a revision that is no commit id, is refused whole and places no issue; a review that names no commit (adiffsource, an estimate) checks none. - Where a candidate goes. A profile's candidates join its findings, the finder's first, before dedup, at most
maxScannerIssuesof them, the most severe first (error,warning,note,none,unknown, then the order of the reports). Dedup's key is unchanged, so a candidate on the file, line and category of a finder's finding is left out for it, and a scanner's issue and a finder's finding on one line are two verdicts when their categories differ. The candidate'scategoryis its rule id, itssummarythe scanner's message, and itsfoundBysays what found it.requireRuleandchangedLinesOnlybind the finder alone, so a profile whose research asks nothing, failed or was refused still judges its candidates.meta.profiles.<id>.research.panelcounts the finder's findings alone. - What a voter sees, and who. The voters of a candidate read, in place of the finder's claim,
Finding: <file>:<line> [<rule id>],Reported by: <scanner>, rule <rule id>andClaim by the scanner (unverified): <message>, and the text of the rule, cleaned and capped at 2,048 characters, in a block of its own after the diff, each as fenced data the data notice names as a scanner's, unverified and possibly planted. Its level, its place in the list and its suppression are sent to no one. No report text reaches the finder, a system message or the votes of another finding, and a model's finding's votes are as they were. - Gaps. A report no issue of which was used is a
report-unreadablegap, one read in part areport-partialgap, each once for the report and the profile it feeds, and a profile's capped candidates are oneissues-cappedgap: Incomplete reasons. A gating profile's gap exits4, and--allow-incompletelifts none.
What createQuorum, review and estimate refuse of reports, each message at its path:
| Path | Message |
|---|---|
context.reports | must be an array of at most 16 scanner reports |
context.reports.<index> | must be a scanner report as readContext reads it: <path> does not match, the path of the first field of the report that does not match, such as issues.0.message, and never a value |
context.reports.<index>.profile | names no profile of the quorum |
maxScannerIssues | must be a positive integer, got 0, the value quoted when it is a number |
A review records every report in meta.context.reports and sends it in the context event, never with a path or a text. The types ScannerReport, ScannerIssue, ReaderProblem, ReportProblem, IssueLevel, IssueOutcome, ContextReport, FoundBy, ModelFound and ScannerFound are exported.
Test coverage
A review can tell its profiles which changed lines the project's tests ran. The core reads no file and never runs a test: a program hands it coverage reports, as a reader of an lcov tracefile hands them over, in ReviewInput.context.testCoverage (and Quorum.estimate's input takes the same). A report is no scanner's: it adds no candidate, drops no finding and has no profile of its own. It is read by each profile that sets Profile.testCoverage, and a review that hands over a coverage report while no profile of the quorum reads test coverage is refused.
interface CoverageReport {
readonly sha256?: string
readonly problems: readonly ReaderProblem[]
readonly unreadable: number
readonly unmapped: number
readonly files: readonly CoverageFile[]
}
interface CoverageFile {
readonly path: string
readonly lines: readonly CoverageLine[]
}
interface CoverageLine {
readonly line: number
readonly hits: number
readonly missedBranch?: true
}- What a program hands over.
filesare the file records the reader read, each with its repository path after the path rules, compared with the diff's paths exactly and never opened, and the lines it lists:linein the new file andhits, safe integers of at least 0, andmissedBranch: truewhen a branch on the line was taken 0 times or never evaluated.unreadablecounts the file records the reader could not read andunmappedthose whose path it could not place in the repository;problemsis what is wrong with the file as a whole, as for a scanner report (missing,cannot-read,not-a-file,too-largeandnot-the-formatleave nothing of the report used). - The states. A changed line is a line the filtered diff adds, in the new file; a file with no added row is in no block and no count. Each is
covered(hits above 0 and no missed branch),partial(hits above 0 and a missed branch),zero(listed with no hit) ornot-measured(no hit listed for it, or no record of its file). The records merge line by line, within a report and across reports, each line taking the strongest state any record gives it:covered, thenpartial, thenzero.coveredmeans a test ran the line, not that a test checks it, andnot-measuredis no proof that no test runs it. - What a profile that reads it is sent. When at least one report could be used, each research request of the profile carries a block of its own files' changed lines, one line for each file of the request's own diff that has one, in the diff's order:
src/a.js: zero hits 12-15, 20; missed branch 16; not measured 22-24; covered 10-11(a state with no line left out), orsrc/b.js: not in the coverage report, thenand <n> more fileswhen the block's budget ends first. The block is thetestsblock, after the rules and before the guidelines, and its budget is a quarter of the lesser ofpartTokensand the room a request with no block leaves (a quarter ofpartTokensfor a provider that states no room), which the planner asks of every room, so no part outgrows its window. A lens that setsLens.testCoverageis sent, in its vote, the cited file's line of that block, at most 1,024 bytes, its ranges and then, and <n> more range(s): Test coverage in a lens. Each finding of the profile carriestestCoverage, the state of its final line, any row: A verdict. - What reaches a model. Code's words and the diff's own file names, and no word of a report: not its test name, not a path it lists that the diff does not name, not a line of the file. A report can say which changed lines a test ran, and nothing else.
- Nothing is dropped. The panel judges each finding as it always did, and no finding is dropped on a report's word. A profile that reads none sends and records what it always did, and a review that read no report sends every profile the requests it always sent, with the same store keys: no block and no line. The one difference in its result is that a profile that reads test coverage records
testCoveragenoneinmeta.profiles, andtestCoverage: truein its settings record, in every review. - Gaps. A report nothing of which was used is a
report-unreadablegap and one read in part areport-partialgap, each once for the report and each profile that reads test coverage, with the report's place amongmeta.context.reports(the scanner reports first) and no profile in its words: A coverage report's record. A gating profile's gap exits4, and--allow-incompletelifts none.meta.profiles.<id>.testCoveragesaysread, ornonewhen no report could be used.
What createQuorum, review and estimate refuse of coverage reports, each message at its path:
| Path | Message |
|---|---|
context.testCoverage | must be an array of at most 16 coverage reports, or no profile of the quorum reads test coverage |
context.testCoverage.<index> | must be a coverage report as readContext reads it: <path> does not match, the path of the first field of the report that does not match, such as files.0.lines.0.hits, and never a value; a key a reader does not write is must be a coverage report as readContext reads it |
context | holds <n> reports in all, past the 16 a review reads: the scanner reports and the coverage reports count together, so 10 of one and 7 of the other are refused |
<id>.testCoverage, <id>.lenses.<index>.testCoverage | must be true or false |
A lens that sets testCoverage in a profile that does not is a warning, <id>.lenses.<index>.testCoverage: has no effect while the profile reads no test coverage, listed in warnings. A review records every coverage report in meta.context.reports, after the scanner reports', and sends it in the context event, never with a path or a text. The types CoverageReport, CoverageFile, CoverageLine and LineTestCoverage are exported.
readContext
declare function readContext(config: ResolvedConfig, options: {
readonly source: ReviewSource
readonly cwd: string
readonly env: Env
readonly signal?: AbortSignal
readonly reports?: readonly ReportRequest[]
readonly scanRoot?: string
}): Promise<ReviewContext>
type ReportRequest
= | { readonly format: 'sarif' | 'sonarqube', readonly path: string, readonly profile?: string }
| { readonly format: 'lcov', readonly path: string, readonly profile?: undefined }readContext reads the files a review takes besides its diff, as the CLI does: the documents of the repository, the scanner reports and the lcov coverage reports. The documents are the { repository } entries of the profiles of a ResolvedConfig, which a profile holds as ResolvedProfile.repository, each read from the commit options.source names, never from the working tree or the change. options.source is the source of readSource's answer. It gives the context of review and estimate, which fromConfig refuses an input without, as below.
import { fromConfig, loadConfig, readContext, readSource } from '@tobi-or-not/quorum'
const { config } = await loadConfig({ configPath: 'quorum.yaml' })
const quorum = await fromConfig(config)
const env = process.env
const input = await readSource({ kind: 'range', range: 'main...feature' }, {
cwd: process.cwd(),
env
})
const context = await readContext(config, {
source: input.source,
cwd: process.cwd(),
env
})
const result = await quorum.review({ ...input, context })- The commit is
documentCommit(source): a range'sbase, a path review'scommit, theheadof a local or staged source. Adiffsource names none and a local source before a first commit has none, so each entry is refused at itsrepositorypath, before any git runs:"REVIEW.md" needs a commit to read it from, which a diff file or standard input does not name: review with --range, --local, --staged or --path, or name the file with { file }, or..., and the repository has none yet: make a first commit, or name the file with { file }. - One listing and one read. The profiles' entries are listed in one
git ls-treeof that commit and their files read in onegit cat-file --batch, every problem reported at once as oneConfigErrorwith an issue for each refused entry: a path the commit lacks (unlessoptional), a link, a submodule, a file over 64 KiB, a text that is no UTF-8 or holds a NUL among its first 8000 bytes, one the cleaner cannot settle and one over a cap: Rules and guidelines has each message. A git command that fails is aGitError. - A config with no entry and no report gives
{}and runs no git. Otherwise each document is aReviewDocumentof originrepository, in the order of the entries, with the SHA-256 of its text as read and what the cleaner removed; an optional file the commit lacks is a document with notext. The package fills in the platform and takes no other git than the system's, asreadSourcedoes. - The completeness check. A quorum
fromConfigbuilds refuses areview, ajudgeor anestimatewhosecontextholds no document for a{ repository }entry of its config, or holds one with notextfor an entry that is notoptional(only an optional entry may be missing), with its profile, kind and path, as aConfigErrorbefore any call, one issue at each entry'srepositorypath:"REVIEW.md" was not read for this review: pass the context readContext reads to the estimate and the review. So a program that forgetsreadContextnever runs a profile without its policy. A quorum fromcreateQuorumhas no entries to check: its profiles hold no repository entry, since a{ repository }entry lives beside aProfileinResolvedProfile.repository, so a profile a program handscreateQuorumreads no repository document. Build such a quorum withfromConfig, or passreadContext's documents in the review's context; its input is checked as Documents says. - The reports.
options.reportsnames the reports to read, at most 16 in all, each aReportRequest: itsformat(sariffor a SARIF 2.1.0 log,sonarqubefor a savedapi/issues/searchresponse,lcovfor an lcov tracefile), its file'spath, relative tooptions.cwdunless absolute, and, for a scanner report, theprofileit feeds, which may be left out while one profile runs; an lcov request names none. The result'sreports, oneScannerReportfor each scanner request in the order given, is thecontext.reportsofreviewandestimate: Scanner reports; itstestCoverage, oneCoverageReportfor each lcov request in the order given, is theircontext.testCoverage: Test coverage. Each key is left out when no request of its kind is named, so a call that names none gets neither. Each file is read through the bounded reader, as a regular file, never through a link, at most 16 MiB, one at a time, and its bytes are hashed (sha256). A file that is missing, a link, no regular file, over 16 MiB, no UTF-8 text or in no known format is no error: it is a report with itsproblemsand no issue, which the review turns into areport-unreadablegap of its profile (of each profile that reads test coverage, for a tracefile). A report for a profile that does not run, or for none while several run, an lcov report while no profile of the config reads test coverage (Profile.testCoverage:--lcov: no profile that runs reads test coverage, as best-practices does, at--lcov), more than 16 reports, a list of requests that is no array (must be a list of reports, atreports), a request of the wrong shape (aformatthat is none ofsarif,sonarqubeandlcov, apaththat is no string, an lcov request that names a profile, or no object at all, which a program that does not type its call can write:report <n> must name a format, sarif, sonarqube or lcov, and a path that is a string, and an lcov report names no profile, at its place from 1, never its value) and ascanRootthat is no absolute directory (with no empty,.or..segment) are aConfigErrorat--sarif,--sonarqube,--lcov,reportsandscanRoot, before any git or any read. - The scan root and the repository.
options.scanRootis the absolute directory the scanners ran in, stripped from the absolute paths their reports name; the repository's top level when unset, and none for adiffsource, whose reports place an absolute path only under ascanRoot: The paths. The repository is opened once, as the source's flag opens it, when a document is read or a report is named under a git source, since a report needs the top level, and a config with no entry and no report gives{}and runs no git. ResolvedProfile.repositorylists a profile's entries,guidelines,doNotReportthenrules, each as aRepositoryEntry: itskind(guidelines,do-not-reportorrules),path,optional,at, the config path of itsrepositoryfield, andindex, its place among its field's entries. The typeRepositoryEntryis exported.ResolvedProfile.builtInRulesisfalsewhen the entry dropped the built-in profile's rules, and absent otherwise.ResolvedProfile.baseis the built-in profile a resolved profile starts from: itsextends, else its own id when that is a built-in profile's, and absent for a profile of its own.
openRelatedCode
declare function openRelatedCode(options: {
readonly source: ReviewSource
readonly cwd: string
readonly env: Env
readonly signal?: AbortSignal
readonly flag?: string
}): Promise<RelatedCodeReader | undefined>
interface RelatedCodeReader {
readonly commit: string
readonly lookup: (names: readonly string[], signal?: AbortSignal) => Promise<ReadonlyMap<string, readonly RelatedHit[] | 'over'>>
readonly read: (paths: readonly string[], maxBytes: number, signal?: AbortSignal) => Promise<ReadonlyMap<string, Uint8Array> | undefined>
}
interface RelatedHit {
readonly path: string
readonly line: number
readonly text: string
}openRelatedCode opens the reader of the repository's code beside a review's diff: the commit it reads at, a lookup of names in the files it lists and a read of those files' bytes. It is the one place that reads a repository for related code, and it reads through the same git runner as readSource: never the working tree, no revision as typed and nothing fetched. options.source is the source of readSource's answer. The package fills in the platform of the process and takes no other git than the system's, which needs git 2.41 or later, on Linux or macOS. A review reads it when it is given as review's relatedCode, and checks before any call that it reads at the commit the review's source names. The types RelatedCodeOptions, RelatedCodeReader and RelatedHit are exported, with the types of what a result and an event record of it, RelatedCode, RelatedCodeMeta, RelatedDropped, RelatedExcerpt, RelatedNone, RelatedStart and RelatedTotals; RelatedCodeOptions also holds the platform and the git the package fills in.
import { openRelatedCode, readSource } from '@tobi-or-not/quorum'
const input = await readSource({ kind: 'range', range: 'main...feature' }, {
cwd: process.cwd(),
env: process.env
})
const reader = await openRelatedCode({
source: input.source,
cwd: process.cwd(),
env: process.env
})
const hits = await reader?.lookup(['safeJoin'])- The commit is
reader.commit, a full id: a range's merge base, theheadof a local or staged source and a path review'scommit. Adiffsource names none and a local source before a first commit has none, so the reader isundefinedand no git runs. - One listing. The commit is listed once, and only the files related code may read are kept: regular files (never a link or a submodule's commit) of at most 1 MiB, with a path that is UTF-8, an extension of the nine languages quorum reads, and no default skip (vendored, lockfile, minified or test file), no secret's name and no name like a file of instructions for an agent (
AGENTS.md,CLAUDE.md,.cursorrules,.github/copilot-instructions.mdand the like). A file the listing does not keep is never looked up or read. lookupruns onegit grepof the commit fornames, which are 1 to 16 distinct identifiers of 3 to 64 characters (else aRangeErrorbefore any git runs), as fixed strings and whole words, with the commit's own attributes and not the working tree's. Each name gets its hits on the listed files, in git's order, path then line, each with its row's text (a CRLF file's keeps its carriage return); a row over 1000 bytes and a row that is no UTF-8 are no hit. A name whose hits pass 256 KiB is'over'and holds none. A failure of git rejects with aGitError, aQuorumError: a review counts a rejection with anyQuorumErrorfor the finding it was asked for (unreadable), which then goes without related code, and a rejection that is noQuorumErrorfails the whole review.readanswers with the bytes of each path, read by id in onegit cat-file --batch, or withundefined, before any read, when the listed sizes of the paths together passmaxBytes. A path the listing does not hold, a link or a file over 1 MiB among them, is aRangeErrorbefore any read:a path to read must be a file the listing holds. A review reads a rejection ofreadas it readslookup's: anyQuorumError, aGitErroramong them, costs the finding its excerpts (unreadable), and a rejection that is noQuorumError, thatRangeErroramong them, fails the whole review.- The refusals are a
ConfigErrorat the source's flag, or atoptions.flagwhen it is given, before any call. A commit the repository does not hold or that git cannot list, a partial clone's missing blob among them (nothing is fetched for it), isrelated code cannot read the commit <short> it is read at (<message>): review with --no-related-code, and a listing of more than 16 MiB of file names isrelated code would list more than 16 MiB of file names at <short>, more than quorum reads: review with --no-related-code. At--clones, which reads panel cases from a local clone, the fix of the first readsfetch the commit's objects wholeinstead, and the fix of the second, which no fetch cures, readsleave the case out with --case. A git that is missing or older than 2.41, and a working directory in no repository, are theConfigErrorof the source's opening, asreadSourcewords them. signalstops a lookup or a read with the signal's reason, asoptions.signalstops every call of the reader.
reviewSettings
declare function reviewSettings(config: ResolvedConfig, facts: SettingsFacts): ReviewSettings
interface SettingsFacts {
readonly budgets: Readonly<Record<string, ProfileBudgets>> // Quorum.budgets
readonly runtime: RuntimeRecord // { name, version, platform, arch }
readonly bounds?: {
readonly maxReviewTokens: SettingValue
readonly reviewTimeoutMs: SettingValue
readonly findingsCap: SettingValue
}
}reviewSettings builds the record a review is given as ReviewInput.settings, which the result keeps in meta.settings: the runtime, the config's strict, relatedCode and each lens that asks for it while related code is on, concurrency and exclude, the review's bounds, each provider of the config and each profile that runs, with the budgets of Quorum.budgets. Each provider is the view --print-config prints, less its origin, command, args and apiKey, so the record holds no base URL and no key; its headers and query keep their names and write no value, and its extraBody writes a value only where a rule that fails closed finds it safe: What a result records of a provider. A prompt and a lens question are their hashes. The settings lists every field.
- The bounds are the config's (
origin: 'config') or the defaults ('default'),findingsCapbeing the config'sfindingsCap, else itsmaxFindings, else 50, andmaxScannerIssuesthe config's, else 50, never derived. The record'smaxScannerIssuesis required, so a settings record a program builds by hand without it is refused byreview. A caller that works a bound out from its input gives it infacts.bounds, each with its origin ('derived'for a bound it worked out), and they win over the config's: the CLI does for a--pathreview. - The record passes
settingsSchemaand shares no object with the config, so a copy of it is safe to keep. A program that reviews with provider objects builds its own, or passes none and recordsnull.
import { fromConfig, loadConfig, reviewSettings } from '@tobi-or-not/quorum'
const { config } = await loadConfig({ configPath: 'quorum.yaml' })
const quorum = await fromConfig(config)
const settings = reviewSettings(config, {
budgets: quorum.budgets,
runtime: {
name: 'node',
version: process.versions.node,
platform: process.platform,
arch: process.arch
}
})
const result = await quorum.review({ diff, settings })The types ReviewSettings, ProfileSettings, ProviderSettings, RuntimeRecord, SettingValue, SettingOrigin and SettingsFacts are exported. A SettingValue is { value, origin }, a SettingOrigin is 'config' (the config or the variable that sets it did), 'default' or 'derived', and a ProviderSettings is the record of one provider as the result writes it.
Events
The sink receives every event of a review, synchronously and in order, as each thing happens:
| Event | Fields | Sent |
|---|---|---|
run:start | profiles, the ids in order; providers, who reviews for each profile: research and lenses, each a { id, model }; relatedCode, only when the review was given a reader of related code, { status: 'on', commit, basis, lenses }, the full id of the commit it reads at, how the source names it (merge-base for a range, head for local and staged changes, commit for a path review) and, by profile id, the lenses that ask, in the profile's order, for each profile that has one, and, when the quorum's relatedCode is on and the source names no commit to read at, { status: 'off', reason }, diff or no-commit-yet | First, when the review starts |
left-out | files, as meta.leftOut holds them, the input's own first: A file left out | Once, right after run:start, when the review leaves a file out |
context | context, as meta.context holds it: documents, one record for each document the review sends as policy, by hash, path, commit and counts, never text, and reports, one record for each scanner report the review reads, with the outcome of each of its issues, never a path or text: The context; rules, present when a profile lists a review rule or requires one (requireRule), how many rules each such profile lists and sent, { listed, sent } by profile id, as meta.profiles.<id>.rules records them ({ listed: 0, sent: 0 } for a profile that requires a rule and lists none), with asksNothing: true for a profile whose research asks nothing, one that requires a rule and sends none, which its stage:start says too with parts: 0 and meta.profiles.<id>.asksNothing records for every report | Once, right after run:start and the left-out event and before the gaps, when a profile has a document, lists a review rule or requires one, or the review reads a scanner report; none otherwise |
flag | flag, as meta.flags holds it, the secret-file flags of the files left out first and the scanner-config-edited flags last: A flag | Once per flag, after run:start, the left-out and context events and the gaps, before any stage |
stage:start | profile; stage: research, dedup or panel; parts, for research, the plan's count of research parts, 1 for a change in one request, 0 for a profile that requires a rule and sends none, which asks its research nothing; votes, for panel, the votes it will cast, its findings, the scanner's candidates among them, times the profile's lenses | When a stage of a profile starts |
stage:end | profile, stage; durationMs, the stage's wall-clock time, waits for a concurrency slot included; count, the findings it produced, or the verdicts for panel | When that stage ends |
call | call, the call's number, the one its call:start carried, absent for a call that sent none (one the store answered); profile; role: research or vote; lens, for a vote; part, for a research call, its position as call:start gives it; finding, for a vote, the finding's id; listed, for a research reply its check read, the findings it listed; reasoning, true or false when the provider could tell whether the reply showed reasoning; firstTokenMs and longestSilenceMs, on a call that answered after a streamed attempt that showed a data event: the time from that attempt's send to its first data event, the headers excluded, and its longest silence, the time between two signs of progress, its send and its end included, the headers one of them, in whole milliseconds on the review's clock; ceilingMs, on such a call whose answered attempt had its deadline grow while it streamed: the ceiling it reached, in milliseconds (The deadline of an attempt); provider, its { id, model }; durationMs, from the call's first attempt to its end, inside its slot, the waits between attempts included; ok; attempts, the number of attempts, an adaptation's re-send counted as one of the call's, only when the call made more than one; usage, summed over its attempts, when the counts they reported are valid: a call that succeeded, or one that failed on a reply its provider read and refused, whose error carries them in an own usage property (ProviderError); spent, the tokens the review's cap counted for the call: each attempt's reported usage, nothing for one the server refused before any work, else its reservation (The token cap); reused, true only for a call the review's store answered with no attempt made, which holds no usage and no attempts, has a spent of 0 and reserved nothing; model, on a call that was answered, the model its reply named (CompletionResponse.model, which an adapter whose server names none fills with the configured model), cleaned as a finding's category is, its hidden characters removed and its white space collapsed, and cut at 100 characters with …, absent when nothing is left of it, when a provider object's reply names none, and on a call that failed or that the store answered, which no provider answered in this review; a call whose reply the stage could not read carries it; failure, on a call that failed (ok is false), what its last failure said of itself, as call:retry's does, a CallFailure: kind, status for an http failure, exhausted, and stalledMs and ceilingMs for a timeout, absent when no failure of the provider ended the call (the token cap, the review's deadline or its interrupt did, or the provider was found down since the call's last send), and, on an answered call (ok is true, with no listed) whose reply the stage could not read, an UnusableReply, { kind: 'unusable-reply' }: facts only, never a word a server or a reply held | Once per provider call, failed ones included, sent after the check of its reply, which is why it holds listed; a research in parts makes one call per part, in order, and up to 15 for a part that recovery splits; none for a call that the cap, the deadline or the review's abort stopped before its first attempt |
call:start | call, the call's number in the review, from 1, in the order calls start; profile; role; lens, for a vote; provider, its { id, model }; part, for a research call, its position { index, count } of its research parts, with piece { index, count } when recovery split the part; finding, for a vote, the finding's id; reserved, the tokens its first attempt reserved in the review's ledger; timeoutMs, the ceiling of its first request's attempts: the provider's timeoutMs, else the one its reply budget sizes (The deadline of an attempt); stream, true when its first attempt is streamed, so it is watched for progress | Once per call, inside its slot, when its first attempt's token reservation is granted and before the attempt is sent. A call the store answered, the down rule refused or the token cap or the deadline stopped before its first attempt sends none. A call its provider's size guard refuses as too large sends one, the guard refusing inside the attempt. Every field is a number, an id or a code word |
call:retry | call, the call's number; attempt, the number of the attempt that failed, from 1, within the send that was retried; retries, the retries the provider states; failure, what the failure said of itself, a CallFailure: kind, status for an http failure, exhausted, and stalledMs for a timeout that was a stream with no progress, the window it stalled at, and ceilingMs for a timeout at a ceiling that grew while its stream progressed, the ceiling it reached; or an UnusableReply, { kind: 'unusable-reply' }, for a reply that came back and the stage could not read. A kind of no-answer (a reply of only reasoning), a vote's truncated and an unusable-reply are the call's one more send of a bad reply, as it is, once the adaptations had their try, within the provider's retries: no other retry has them; attemptMs, how long the failed attempt ran, from the moment its request was handed to the provider to its failure, on the review's clock, in whole milliseconds; waitMs, the wait before the next attempt, in milliseconds | Once before each wait between two attempts of a call, once the wait is known and the review's stop has not fired. A failure the stop ends instead of a retry sends none. Every field is a number or a code word |
call:progress | call, the call's number; outputTokens, the output its streamed attempt has shown, the larger of the server's own count and a quarter of the characters streamed; signal: tokens when the output grew since the call's last call:progress, keep-alive when only keep-alives came | At most once a second per call, on the review's clock, from the signs of life of a streamed attempt: never for its headers alone, and never for a call that is not streamed. Every field is a number or a code word |
adapted | adaptation, as meta.adaptations holds it: provider, setting, from, to and cause, a provider's id and code words: The adaptations | Once per provider and setting in a review, when a probe settles on a move: thinking lowered, a lowering the server refused (lowering-refused), the structured output moved to prompt, or the stream moved to bare, a stream with no stream options, or to whole, whole replies (stream-refused), and, with no probe, when a streamed call was answered whole (stream-answered-whole), or a derived reply budget was held to what a learned cut lets through (replyTokens, cut-on-the-way, sent after the cut event). Sent before the call event of the call that was the probe, and a probe that moved nothing sends none |
cut | provider, the provider's id; afterMs, the length of its cut in milliseconds; holds, the tokens a reply may hold at the lowest rate the attempts cut at that length streamed, four fifths of what the cut lets through and at least 1024, absent when no rate was measured; lowered, whether a derived reply budget the provider serves was held to holds (never with maxTokens set, where holds is the value to lower it to); fits, true when maxTokens is unset and every derived budget it serves was already at or under holds, so nothing was lowered and there is no advice | Once per provider in a review, when two of its cut attempts ended at about the same length (the larger of 5 percent of the shorter and 5000 ms apart at most): each later call cut there is read as a reply cut off at its limit. A lowered cut is followed by an adapted event of replyTokens. An exhaustive switch over the event types needs this case: A gateway that cuts long calls |
concurrency | provider, its { id, model }; limit, its lane's limit once the change is made; cause: grown (one more call, the headers holding it), regrown (back toward its start after a cut, with no header), cut (halved by a throttle signal, with from, the limit before it, and failure, the throttle as call:retry words it), paused (new calls held for a Retry-After, with waitMs, at most 60000, and failure), paced (a call waits waitMs, at most 60000, for the headers' reset) or slots (the lane holds the slots the provider states, limit the lesser of them and 16); waitMs and failure where the cause says | Once per change of a lane's limit, pause and pacing wait of a review with concurrency unset, and once per provider that states slots, when its lane begins: Lanes. A pause and a pacing wait are sent once each time one is set or lengthened, not once per call that waits. With concurrency set none is sent |
stored-refused | provider, the provider's id; role: research or vote | Once per provider and role in a review given a store, when a reply the store held failed the check a fresh reply passes, so it was not used and the call was made: whoever wrote the store wrote it. It holds no text, key or path: Saved state |
finding:invalid | profile; reason, such as src/auth.js:3 is not in the diff; cause, rule for a rule citation that failed its check, away for a finding a profile that reviews changed lines only dropped for standing away from the change, absent for a finding outside the diff: the reason is then "src/auth.js":3 cites no rule this review sent or "src/auth.js":3 cites no rule, which the profile requires for the cause rule, and "src/auth.js":3 is more than two lines from a line the change adds or removes for the cause away, which name the finding's file and line and never the rule the finder cited | Once per finding dropped for citing code outside the diff, once per finding dropped for standing away from the change, and once per rule citation that failed its check, in that order for one research: the findings outside the diff, those away from the change, then the citations |
provider-down | provider, the id of the provider found down; kind, what its calls failed with, and for an http failure status; calls, how many failed in a row, 3, or 1 with exhausted; noAnswer, for a no-answer kind, what the last reply lacked, thinking or empty; exhausted, true only when the failure said the account's credit, quota or spend limit is used up; cutAfterMs, present only when every call of the streak was cut on the way (a network failure, or an HTTP 502, 504 or 524, whose last attempt ran at least 60 000 ms), the shortest of their attempts' lengths; stalledMs, present only when every call of the streak stalled, the shortest of their windows, which fixes with raise stallTimeoutMs, or timeoutMs; refused, stream only when the last failure was an HTTP 400 or 422 that named the stream or its options, which fixes with stream: false | Once per provider, when the third of its calls in a row ends with a failure of its own (network, http, timeout, process, unsupported, invalid-response or no-answer), or at its first call that failed with a used-up quota (exhausted, an http failure alone, never retried), whatever profile or role asked it: no call goes to it for the rest of the review, and the calls in flight run to their end. A reply that came back resets the count |
reply-lacked | provider, the provider's id; kind: truncated or no-answer; noAnswer: reply, thinking, window or empty; limit, the reply limit the request was sent with, outputTokens, inputTokens and window, each when known | Once per provider and line in a review, the first time a call's final failure is a reply that lacked its answer in a way that needs a setting changed: a server that caps replies below limit (truncated, with outputTokens below limit), a window that ended a reply (window), a reply with only reasoning (no-answer, thinking), or with nothing (no-answer, empty). A cut-off at its limit sends none. Every field is a count or a code word the code read, never a word the error's message or the reply held: What a reply lacked |
recovered | profile; part and parts, the part's position, from 1, and 1 and 1 for a research of one request; noAnswer, what the first reply that was split lacked: reply, thinking, window or saturated; limit, the reply limit it was cut at, when the request carried one, cutAfterMs, in place of limit, the length in milliseconds a reply was cut on the way at, for a part split for a learned cut, and findings, the findings a saturated reply was asked for at most; thinkingLowered, whether the provider's thinking had been lowered when recovery began; pieces, how many final pieces the part ended with, each read or left at the floor, not every piece asked on the way, read, how many were read, and unreadHunks and unreadFiles, what the floor left unread, cut off even alone | Once per research part that recovery split, once its pieces have answered, and no event for a part that was cut off at the floor at once: Recovering a cut-off part. Every field is a count or a code word |
part | profile; part, { index, count }, the part's position among its profile's research parts, 1 and 1 for a research of one request; outcome, what became of it: reviewed when every piece was read, else the first unread piece's in the diff's order (request-too-large, token-cap, review-deadline, research-failed, provider-down or reply-cut-off); durationMs, from the start of its first call to its end, 0 when it made none; spent, the tokens its calls counted; reused, true only for a part that made at least one call and whose every call the review's store answered, which spent 0 tokens (the CLI words it reused from the saved state in place of answered in); listed, the findings its read replies listed, absent when none was read; failure, for a failed part, what the first call that failed said of itself, as call:retry gives it, with cutAfterMs when its last attempt was cut on the way, the attempt's length in milliseconds, stalledMs when it was a stalled stream, the window in milliseconds, ceilingMs when it was a timeout at a grown ceiling, the ceiling in milliseconds, and refused, stream, when an HTTP 400 or 422 named the stream or its options; pieces, for a part recovery split, { count, read, unread }, unread counting the unread pieces by outcome | Once per research part, as it ends, in the order parts end, after its recovered event when it has one, whatever became of it: a part a limit or the down rule settled with no call sends one with a durationMs of 0. A research that is one request, a blank part of a packing of one included, is part 1 of 1. Every field is a count, a duration or a code word |
incomplete | entry, as meta.incomplete will hold it | Once per gap, as it is recorded: the gaps of the binary, submodule and held files left out first, in that order, then the profile's too-large gap, then the report-unreadable and report-partial gaps of its scanner reports and its issues-capped gap, right after run:start, the left-out and context events and before any call; the gaps of a research in parts once every part has answered, after the finding:invalid events; a limit's gap last for its profile, after the stage:end of its panel |
related-code | profile, findingId, file and line, the finding's; excerpts, how many it was given, and their bytes and commentLines; held, the excerpts held back whole, { credential, hidden, addressed }; none, why the rules read nothing for it, as Related code says, when they read nothing; failed, true when git failed its lookup or its read; durationMs, the time its related code took, a finding that waits for a row another finding is looking up included | Once per finding of a profile with a lens that asks, in a review given a reader, when its related code is worked out and before its votes: two findings on one cited row share the lookup and each have an event. Every field is a count, a number, a code word and the finding's own file and id |
vote | profile, findingId, lens; keep: true, false, or null when the vote failed; error, then failure, for a failed vote: its kind, for an http failure its status, and for a truncated or no-answer failure its noAnswer when it said what the reply lacked, as the result's vote holds them (VoteFailure, A vote) | Once per vote |
verdict | profile, findingId, keptVotes, totalVotes; confidence, when it reached one; status: kept, discarded or unreviewed | Once per finding, when all its votes are in |
run:stopping | cause: review-deadline or interrupt; inFlight, the attempts sent and not settled; graceMs, for the interrupt, the time they have to end | Once, when the review's deadline falls or its interrupt aborts while its stages run, before the calls it stops end. At the deadline no call in flight is waited for and no new call starts, and what is left undone is a review-deadline gap. At the interrupt no new call starts and every wait ends, the calls in flight have graceMs (INTERRUPT_GRACE_MS, 5000) to end, and what is left undone is an interrupted gap. None for a review that ends before either |
run:end | kept, discarded, unreviewed and incomplete, the counts; durationMs | Last, when the review ends |
The first events of the review on The JSON result, as the sink received them:
{"type":"run:start","profiles":["security"],"providers":{"security":{"research":{"id":"default","model":"qwen3.6:27b"},"lenses":{"reachability":{"id":"default","model":"qwen3.6:27b"},"impact":{"id":"default","model":"qwen3.6:27b"},"defenses":{"id":"default","model":"qwen3.6:27b"}}}}}
{"type":"stage:start","profile":"security","stage":"research","parts":1}
{"type":"call:start","call":1,"profile":"security","role":"research","provider":{"id":"default","model":"qwen3.6:27b"},"part":{"index":1,"count":1},"reserved":12000,"timeoutMs":600000,"stream":true}
{"type":"call","call":1,"profile":"security","role":"research","provider":{"id":"default","model":"qwen3.6:27b"},"part":{"index":1,"count":1},"durationMs":0,"ok":true,"usage":{"inputTokens":1840,"outputTokens":412},"spent":2252,"model":"qwen3.6:27b","listed":5,"firstTokenMs":0,"longestSilenceMs":0}
{"type":"part","profile":"security","part":{"index":1,"count":1},"outcome":"reviewed","durationMs":0,"spent":2252,"listed":5}
{"type":"finding:invalid","profile":"security","reason":"src/auth.js:3 is not in the diff"}
{"type":"incomplete","entry":{"profile":"security","reason":"finding-unreadable","detail":"findings[4]: quote: Invalid input: expected string, received undefined"}}
{"type":"stage:end","profile":"security","stage":"research","durationMs":8,"count":3}- A sink ignores an event type it does not know. The events grow: a release adds an event type, as one added
concurrency, and a sink that switches overtypeends on adefaultthat does nothing. Aswitchthat must name every type no longer compiles when a release adds one, which is why a type added is a breaking change while quorum is v0. - The sink runs inside the review. Each event is delivered before the review goes on, so a slow sink slows the review.
eventSchemais internal, and its JSON Schema is the contract. Every event is typed in zod, insrc/core/event-schema.ts, which the package does not export: a type test holds it equal toQuorumEvent, so the schema and the type cannot differ. A program that reads events in another language, or reads--progress jsonfor a tool, checks each line againstschema/progress.schema.jsonof the release that wrote it: The contract files.- Events carry no model text beyond
errorstrings and the served model, themodelof an answeredcallevent, which the server wrote and quorum cleans and cuts at 100 characters, the file name afinding:invalidreason quotes, which is the finder's, cleaned and capped at 80 characters (a rule citation's reason quotes the file as JSON, cut at 80 characters, and never what the finder cited), and, for a diff without per-file headers, thefileanddetailof avote-failedentry or of a vote'srequest-too-largeentry, which hold the finder's name for the file, cleaned and capped at 260. Thefileof aflagevent is the diff's own path, and absent for a diff without per-file headers. Thefileof aleft-outevent's files is the diff's own path, or"", and for a file the input'sleftOutlists, the name the caller gave. - The sink gets a copy of each event. Changing one changes neither the review nor its result.
meta.settingsis the input's. It is thesettingsthe review was given, copied, andnullwhen it was given none: no event holds it.metaagrees with the events.meta.usage,meta.calls(ProviderCallsfor each provider id: thecallevents'models, counted by provider,ServedModelentries first seen first, at most 8, and the calls of the rest inservedOthers, thenresearchandvote, each aRoleCalls: the role'scallevents counted, the failed ones by thekindof theirfailure, the stopped ones (failed with none), the sends beyond each call's first, the reused ones, the usage and the time, the sum of theirdurationMsand the longest: The calls),meta.profiles.<id>.stages(ProfileMeta.stages, aPartial<Record<StageName, number>>: thedurationMsof each of the profile'sstage:endevents, keyed by stage) and eachinvalidFindings,invalidRulesandawayFromChangeare counted from them, the first from thefinding:invalidevents with no cause, the second from those of causeruleand the third from those of causeaway,meta.contextis the record thecontextevent holds,meta.reusedcounts thecallevents that sayreusedby role, andmeta.adaptationsholds theadaptationof eachadaptedevent, in order,meta.profiles.<id>.recoverycounts therecoveredevents of the profile,meta.profiles.<id>.research(ProfileMeta.research), aResearchRecordof five counts (Per profile), has aspartsthepartsof the profile's researchstage:startand aslistedthe sum of itspartevents'listed, andmeta.concurrencyrecords, per provider, the range of the limits theconcurrencyevents gave its lane and how many were cuts.- A sink that throws aborts the review with its error, so the bug surfaces instead of being swallowed: no profile starts another call, no further event is delivered, and the review rejects with that error, even when it threw on
run:end.
ReplyStore
type StoredCall
= | { readonly reply: { readonly text: string, readonly model: string, readonly usage?: Usage } }
| { readonly lacked: { readonly noAnswer: 'reply' | 'thinking' | 'window' | 'saturated', readonly usage?: Usage } }
interface ReplyStore {
readonly get: (entry: { readonly key: string, readonly provider: string }) => Promise<StoredCall | undefined>
readonly put: (entry: { readonly key: string, readonly provider: string }, call: StoredCall) => Promise<void>
}The port a review keeps its paid calls through. key is the core's, a SHA-256 of the call's role, the request's content, its reply budget and the thinking level and mode it is sent with, and provider is the id of the provider it went to: a store that serves several providers or versions adds what tells them apart to its own key, as fileStore does. A reply is one call that passed its check, and a lacked marker is a research reply that was cut off (reply, thinking or window) or saturated, with its usage and never any text: it can only send a part to recovery. Whatever a store gives back is as untrusted as a reply: the review reads it as own data, checks a reply as a fresh one, and takes a get or a put that throws or rejects, or a call that is no StoredCall, for a miss or a write that did not happen.
fileStore
declare function fileStore(directory: string, options: { readonly providers: ResolvedConfig['providers'] }): Promise<ReplyStore>The store the CLI's --state <dir> opens, one file per call in directory. providers are the config's: the settings of each, every field but its key, timeoutMs, stallTimeoutMs, retries, stream, streams and slots, are part of an entry's key, so a changed provider is a miss (a raised deadline, a stall window, a retry count, a stream setting or a lane's slots is not: each decides whether a reply arrives, never what it says), and a provider the config does not name keeps nothing. The platform, the user that owns the process, quorum's version and the process's standard error, where each warning is one inert line, are filled in from process. It makes the directory with mode 0700 when it is missing, and rejects with a ConfigError at --state, naming the flag and never the path, for a directory that is a symbolic link or no directory, that another user owns or that its group or others may write, that lies inside a git work tree, or that holds files but no marker quorum wrote. Whoever can write the directory can write a part's review, so keep it where only you can, never restore it from a cache another job can write, and remove it once the review it serves is done: Saved state.
Abort
const controller = new AbortController()
const pending = quorum.review({ diff }, { signal: controller.signal })
controller.abort()
await pending // rejects with controller.signal.reasonAn aborted review never resolves, and never fails open:
- It rejects with the signal's reason, whatever error a call it cut raised. A signal already aborted rejects at once, before any event or call.
- The signal is checked before every stage, and inside every call's concurrency slot before the provider is called, so a call still queued when the review is aborted never starts. Every request carries its attempt's signal, so a provider can stop a call in flight. It is checked once more after the profiles have run, a blank diff included, so an abort that lands when no stage is left to check still rejects.
- A vote cut by the abort is never a failed vote. It rethrows the abort's reason, so an aborted review never resolves with a finding the abort left unreviewed, and the review rejects at once, without waiting for the votes still in flight.
- No event is delivered once the review is aborted.
- A failed research part stops no profile. It is its profile's
research-failedgap, a gating profile's too, and the other parts and profiles go on. A review that rejects with aProviderDownErrordoes so once every profile's research has ended, so no event arrives after the rejection, and no call is in flight. - An abort after
run:endhas no effect: the review is over, and resolves with its result. - The review's deadline is no abort: at
reviewTimeoutMsthe review resolves, its calls and waits stopped and recorded asreview-deadlinegaps, while an abort rejects. An abort that comes after the deadline still rejects, with its own reason: The review's deadline. - The review never waits for a call it stopped. Each attempt has a signal of its own, aborted with the review's or at its deadline, and the review settles the attempt at once; the shipped adapters stop their request or process on it, and a provider that ignores it works on, outside the review.
Interrupt
const controller = new AbortController()
process.once('SIGINT', () => controller.abort())
const result = await quorum.review({ diff }, { interrupt: controller.signal })
// result.meta.incomplete holds the interrupted gaps; outcome(result) is { status: 'interrupted', exitCode: 130, lifted: false }interrupt is what the CLI's first Ctrl-C or SIGTERM is. An abort rejects at once. An interrupt rejects as any review does, on an abort, on a sink's error, or with ProviderDownError when nothing was read and a provider was found down, and otherwise resolves, and never fails open:
- No new call starts and every wait ends at once, when it aborts or at once when it was aborted already: a call queued behind a call in flight, waiting for room under the token cap or backing off after a failure ends where it is, sending nothing. One
run:stoppingevent, withcauseinterrupt, says how many calls are in flight and the grace. - The calls in flight have
INTERRUPT_GRACE_MS, 5000 ms on the review's clock, to end. A reply that comes within it is read, checked and put in thestoreas in any review, and the review asks no vote on what it reads. A call still in flight at the end is cancelled, its attempt's signal aborted. - It resolves with what it read. What it stopped, the research parts not read and the votes not asked, is an
interruptedgap of each profile,interruptedin the files' coverage, and a failed vote of kindinterruptedon each finding leftunreviewed. No option lifts it. - An abort still rejects.
signalaborting during the grace, or before the interrupt, rejects with its reason; so does an interrupt that is not anAbortSignal, with aConfigError(interrupt: must be an AbortSignal). - The timer and the listener go however the review ends. None is left armed when it resolves or rejects.
estimate
const estimate = quorum.estimate({ diff, send })
if (!estimate.fits) console.error('this review may not finish under its token cap')interface Estimate {
profiles: Record<string, ProfileEstimate>
expected: number
worst: number
inFlight: number
maxFindings: number
findingsCap: number
maxReviewTokens: number
reviewTimeoutMs: number
fits: boolean
held: number
}
interface ProfileEstimate {
parts: number[]
votes: number
candidates: number
vote: Record<string, number>
expected: number
worst: number
findings: number
maxFindings: number
provider: string
documents: { research: number, vote: number }
relatedCode?: Record<string, number>
}estimate says what a review of the diff may cost, in tokens, before any call. Its input takes the review's context too, the repository documents of Documents: each is counted in the reservation of every part and the bound of every vote of the profile it names, as review sends it, and refused as review refuses it, a document that leaves a provider no room included, but its commit is not checked, since an estimate names no source. Its scanner reports (Scanner reports) are placed against the change as review places them, with no commit to check, and the candidates a profile's panel would judge, at most the quorum's maxScannerIssues, are counted in its votes, worst and inFlight. Those figures are a ceiling and never an exact count: the estimate counts a candidate the review would drop for a finder's finding on the same file, line and category, and one a report that states another commit would have lost, since it names no source and checks no commit. Its second argument, limits, is the cap, the deadline and the findings cap the estimate is made under, in place of the quorum's, as review's maxReviewTokens, reviewTimeoutMs and findingsCap are, and checked the same way: the estimate's maxReviewTokens, reviewTimeoutMs, fits and held read the first two, and findingsCap counts each lens's votes, so it moves findingsCap, each profile's votes and worst, inFlight and what fits and held read of it, and no part, request or expected figure, as maxFindings sizes them. The worst case is the same whatever the token cap, which is why a caller may make one estimate for its worst case and another under the cap it derives from it. It sends nothing and reads no file: it filters the diff and plans each profile's research as review does, then asks each provider for the worstCase and the room it states, on the requests the review would build. Every figure is what the review's token ledger reserves for a call, not what the call spends. With findings, the same given findings judge takes, it is the estimate of that judgment: it refuses what judge refuses, a finding a code check would drop or change, one past the cap and a context.reports included, with the same ConfigError, and every profile is estimated as one whose research makes no call, with parts: [], expected 0 and no candidate, its votes the given findings of the profile times its lenses, each lens's at the bound a finder's finding has, citing the largest section of the diff, and worst and inFlight from those votes. limits.findingsCap bounds the findings of each profile. The input is { diff, send, context, findings, relatedCode }, send and context optional as review's are, and findings, which a review takes none of, optional too: given, it makes the estimate that of a judgment, as above. relatedCode, a boolean, makes the estimate count related code: with it true, or unset and the quorum's switch true (Options and ports), each vote of a lens that asks for it (Lens.relatedCode) is bounded with a block of the most its room holds, at the request of the vote's bound (the largest section, the longest finding or candidate), and false counts none, whatever the switch. The estimate is given no reader and reads no file, so it counts the worst case, a block the review's reader may fill and never overfill, and the block is in vote, worst and inFlight and in the calls an adaptation and a bad reply send once more, as every vote is; the research is sent none, and every estimate with it unset and the switch off is the one it was. A relatedCode that is no boolean is refused, relatedCode: must be true or false. The estimate reads the diff less its held files, so a file held back as a secret costs nothing and one send names is counted, and it counts the repository documents of context, with no commit to check them against. It throws a ConfigError for an input review would refuse, such as a diff that is not a string.
| Field | Holds |
|---|---|
profiles | One entry per profile, keyed by its id, in the run's order |
profiles.<id>.parts | What the ledger reserves for each research request of the profile, in order: one for a diff researched whole, else one per part that holds more than white space, as Research in parts packs them. Empty when research makes no call |
profiles.<id>.votes | The most votes the panel casts: findingsCap and candidates, times the profile's lenses, so a ceiling. 0 when research makes no call and no scanner issue falls on the change. In the estimate of a judgment (findings given), the profile's given findings times its lenses |
profiles.<id>.candidates | The scanner issues the profile's panel would judge: those of the review's reports that fall on the change, at most maxScannerIssues. 0 when the estimate names no report. A profile whose research makes no call, one that requires a rule and sends none, still judges them, so it has votes. An upper bound: it counts a candidate the review drops for a finder's finding on the same file, line and category, and one a report that states another commit would have lost, since an estimate checks no commit |
profiles.<id>.vote | What the ledger reserves at most for one vote of each lens, keyed by lens id: the request for a finding at the longest the harness lets one be, citing the largest section of the diff. For a lens whose voter states a room that section exceeds, it is the partial request, filled to that room. For a profile that judges candidates, the larger of that and a candidate's: the longest one, with a scanner's name, a rule id and a rule text at their caps. Empty when research makes no call and the profile judges no candidate |
profiles.<id>.expected | The research parts alone, each counted at a third of its input, rounded up (the bound is one token per byte, and code takes about one per three), and its reply at the lesser of its budget and 4096 tokens, its usual size, so a large maxTokens is headroom and no expectation. No recovery and no vote is in it, since how many findings research reports is not known before it runs |
profiles.<id>.worst | An upper bound: the parts in full, each with what recovery may add to it (3d + 14h + 14 (r - d + e) for a part of d diff tokens, reservation r, largest file header h and e the tokens a piece's request holds beyond its part's: Recovering a cut-off part), findingsCap votes of every lens at its bound, and a vote of every lens for each candidate at a candidate's bound, so a ceiling for the candidates as candidates is |
profiles.<id>.findings | The findings its research requests ask for at most, N: maxFindings, or fewer when the research provider's reply budget holds fewer (Reply budgets). Below maxFindings, a part whose reply lists that many is split, which expected counts no call for |
profiles.<id>.maxFindings | The findings its research requests ask for at most before the reply budget narrows them: the profile's own maxFindings, else the quorum's. findings is compared with it, and the CLI's line for a provider whose reply holds fewer names it |
profiles.<id>.provider | The id of the profile's research provider |
profiles.<id>.documents | What the profile's documents add to what the ledger reserves for one research request (research: its guidelines and its do-not-report text) and for one vote (vote: its guidelines, at the lens that adds most), each the difference of the request built over no diff with them and without them, a review's repository documents included. 0 and 0 for a profile with none, and for one whose research makes no call, but for a judgment's given findings, whose votes carry the documents: vote is then the profile's, research 0. It is not in expected, worst or inFlight, which already count the documents in each request: it says what share of each request they are |
profiles.<id>.relatedCode | When the estimate counts related code and the profile has a lens that asks for it, the budget B of the block of each such lens, keyed by lens id, in tokens of the size guard's bound, which are never fewer than a text's UTF-8 bytes, so a block within B is within 8192 bytes: the least of 8192, a quarter of the room its voter states for the request with no diff and no related block, and the room that request leaves as the review sends it, its diff block chosen, with an empty related block, never below 0; a voter that states no room takes 8192. A vote of the lens is bounded with a block of B tokens in vote, so a B of 0 adds none, and a lens with two budgets, a finder's finding's and a candidate's, states the larger. The review fits the excerpts it reads in the same B. Absent when the estimate counts no related code, and for a profile with no lens that asks; {} for a profile that asks when none of its votes is bounded, as for a blank diff, which makes no research call and holds no candidate |
expected | The sum over the profiles |
worst | The sum over the profiles, each call once more of a provider that states a retry, whatever its thinking (its research parts, each with recovery's bound, findingsCap votes of each of its lenses at their bound and a vote of each for every candidate: a bad reply is sent once more, What is retried), and the calls an adaptation sends once more: for each provider and each setting its adapts states, a stream counting as two, one per step, per setting at most concurrency calls (16 with lanes), counted as the concurrency (else 16) largest reservations of its calls, a research part's with what a piece's position adds. A provider that states no adapts adds none (What quorum adapts by itself) |
inFlight | What the calls that run at once reserve: the sum of the concurrency largest bounds among every research part and every vote of every profile, a lens's bound counted findingsCap times, and a candidate's bound counted once for each candidate, each of those a ceiling as candidates is. With concurrency unset, each provider counts the largest bounds among its own calls, as many as its lane starts with (4, or its slots), and the 16 largest of those count in all |
maxFindings, findingsCap, maxReviewTokens, reviewTimeoutMs | The limits the estimate was made under: limits' when given, else the quorum's, as createQuorum took them: findingsCap is limits' when it gives one, else the quorum's findingsCap, else maxFindings |
fits | expected + inFlight <= maxReviewTokens: whether the research may finish under the cap. It leaves recovery and the adaptations out, which only a failing or an adversarial review reaches and which would refuse every large path review: worst counts them |
held | How many research parts the cap holds: the parts of every profile, in profile order and then in the order they are sent, counted while their expected spends and inFlight stay within maxReviewTokens. 0 for a cap below inFlight, every part when fits. The CLI's warning for a cap the config sets below the estimate names it |
A blank diff, and one whose every file exclude leaves out or is held back as a secret, make no call: every token figure is 0, parts and vote are empty and fits is true, with findings, maxFindings and provider as the profile's research provider states them. The CLI prints the estimate of a path review, derives the review's token cap and deadline from it and never refuses one for its size: The bounds of a path review. A blank diff has held 0. It is an estimate, not a limit: each call of a review still reserves its worst case against maxReviewTokens, whatever fits says, so a review that does not fit stops at the cap with a token-cap gap, and one that fits may stop there too, since the votes are in worst alone.
readSource
declare function readSource(spec: SourceSpec, context: {
readonly cwd: string
readonly env: Env
readonly signal?: AbortSignal
readonly exclude?: readonly string[]
readonly send?: readonly string[]
}): Promise<SourceRead>
type SourceSpec
= | { readonly kind: 'diff', readonly text: string }
| { readonly kind: 'range', readonly range: string }
| { readonly kind: 'local' | 'staged', readonly trustRepoConfig?: boolean }
| { readonly kind: 'paths', readonly paths: readonly string[], readonly at?: string, readonly skips?: boolean }
interface SourceRead {
readonly diff: string
readonly source: ReviewSource
readonly leftOut: LeftOutFile[]
}readSource makes the diff a review reads, as the CLI does, and answers with what review takes as its input: the diff, where it came from (source, which review records in meta.source) and the files the source left out before it made the diff (leftOut). It is the one entry to every source of Sources, whose pages say what each does:
kind | Reads | Its fields |
|---|---|---|
diff | The text it holds, as it is | text: a diff over 16 MiB of UTF-8 is refused |
range | The commits <base>...<head>: the merge base diffed with the head | range, written <base>...<head>, as --range takes it |
local | What git add -A would commit: the staged, the unstaged and the untracked changes | trustRepoConfig: true when the repository is yours, so a filter its own config names may run: Trust |
staged | What the next commit holds | trustRepoConfig, as local |
paths | The files under each path at a commit, each written as a new file | paths, relative to cwd as --path is; at, the commit, HEAD when unset; skips, whether the default skips (vendored, lockfile, minified, binary and test files) apply, true when unset: a secret is skipped whatever it says |
- The context is where it reads.
cwdis the directory a git source opens as its repository, and a path ofpathsis relative to;envis the environment, whosePATHgit is looked up in (its absolute entries only) and from which the git child gets an allowlist and nothing else;signalstops a git command in flight;excludeholds the patterns of Excludes, which a source that reads files applies before it reads them: the untracked files oflocal, and each file ofpaths; andsendholds the filespathsreads though it skips a secret otherwise, by its name or by a credential in its text, each the path as the diff writes it andmeta.leftOutlists it, an exact string. The same list goes toreview'ssend, since the review holds back what it is sent all the same. The package fills in the platform, and takes no other git than the system's: a git source runs Linux and macOS, and needs git 2.41 or later. - It refuses with a
ConfigError, each issue naming the flag the CLI names for it as its path:--range,--local,--stagedor--path, and--atfor a commit that names nothing. A diff's issues have an empty path, andkindis the path of an unknown kind (must be diff, range, local, staged or paths), so a spec built without types never getsundefined. A git command that fails is aGitErrorinstead: Git errors. - Nothing is cut or dropped in silence. A source that cannot read all of what it was asked to refuses, or lists what it left out in
leftOut: a skipped file with its rule, an excluded one, a binary file or a submodule. A reader that meets akind, areasonor aruleit does not know takes it as a source it cannot describe, or a file left out, never as an error.
import { readSource } from '@tobi-or-not/quorum'
// `quorum` comes from `createQuorum`, as in the complete example below.
const spec = {
kind: 'paths',
paths: ['src']
} as const
const input = await readSource(spec, {
cwd: process.cwd(),
env: process.env,
exclude: ['**/*.spec.ts']
})
// The cap follows the estimate's worst case, never below the default, as the CLI's does for a path review.
const { worst } = quorum.estimate(input)
const limits = {
maxReviewTokens: Math.max(worst, 2_000_000),
reviewTimeoutMs: 86_400_000
}
const result = await quorum.review(input, limits)outcome
declare function outcome(result: QuorumResult | PublicView, options?: { readonly allowIncomplete?: boolean }): Outcome
type OutcomeStatus = 'pass' | 'findings' | 'incomplete' | 'interrupted'
interface Outcome {
readonly status: OutcomeStatus
readonly exitCode: 0 | 1 | 4 | 130
readonly lifted: boolean
}outcome says what a review comes to: the rule that decides the CLI's exit code, for a program that reads a result. status is pass, findings, incomplete or interrupted, exitCode is the code that says it, and lifted is true when allowIncomplete turned an incomplete review into a pass, so a report never calls that run complete. It reads the result, or its public view, as the result it came from, and calls nothing. What decides each, in this order:
130,interrupted. An entry ofmeta.incompleteis aninterruptedgap, of any profile, an advisory one's included. It wins over everything else, andallowIncompletenever lifts it.1,findings. A kept finding is at or above the level of its profile,meta.profiles.<id>.failOn:highfails ahighfinding,mediumahighormediumone,lowany, andnonenone (Gating). It wins over4, whatever else is missing.4,incomplete. An unreviewed finding, or an entry ofmeta.incomplete, belongs to a gating profile: one whose level is notnone. The gaps and findings of a profile atnonechange nothing.0,pass. Neither of the two.
A result of an earlier release has no failOn, and outcome reads its gating: false is none, anything else high, and a failOn that is a level wins. A failOn that is no level, or that the entry only inherits, is unreadable, so outcome reads the gating beside it the same way: gating: false gives none. A profile with no readable field at all, one missing from meta.profiles or an entry that is null, gates at high, so a gap in a result never hides a finding.
allowIncomplete lifts what the CLI's --allow-incomplete lifts, and nothing else: the 4 becomes 0, lifted is true, only when every gap of a gating profile is a vote-failed one and every failed vote behind the gaps failed in passing, never when a 1 is due: Exit codes. A secret gap, a too-large gap and every other reason stay 4, since a pull request can cause them. A public view has no vote's vote, so outcome reads a vote of a view by its keep: cast when it is a boolean and the vote's failure is null or absent, failed otherwise. A job that holds only the view, such as the post job of a review run with --view public, concludes what the review job's --allow-incomplete did.
import { outcome } from '@tobi-or-not/quorum'
// `result` comes from `quorum.review`, as in the complete example below.
const { status, exitCode, lifted } = outcome(result, { allowIncomplete: true })renderReport
declare function renderReport(input: ReportInput, options: ReportOptions): string
type ReportInput = QuorumResult | PublicView
type ReportFormat = 'text' | 'json' | 'brief' | 'markdown' | 'payload' | 'sarif'
interface ReportOptions {
readonly format: ReportFormat
readonly color?: boolean
readonly outcome?: Outcome
}renderReport writes a review's result, or its public view, as the report the CLI writes on stdout, a text that ends in a line feed: The report. It reads the input, as review returns it, and the options, and nothing else: no terminal, no environment, no file. It hands the input to the format as it is, so json of a view is the view, and text and brief of a view are the report of the result it came from, but for the two lines of text that the view has no detail or usage for: a gap is written in the fixed words of its reason, and the time has no token count.
formatistext, the report for a person,json, the result asinertJsonwrites it,brief, one line of counts and code words that holds no file name and no model text, ormarkdown, the summary a pull request or a job summary shows, orpayload, the documentquorum-actionposts, asinertJsonwrites it: a JSON object withversion,head,conclusion,summary,commentsandunplaced, typedActionPayload, whose comments areActionComments: The Action's payload, orsarif, SARIF 2.1.0 for GitHub's code scanning asinertJsonwrites it: one run, a result for each kept or unreviewed finding on a file of the diff and a notification for each gap, whose levels agree with the exit code.markdown,payloadandsarifrender the public view of what they are given, so they hold no reasoning, no discarded finding, no model and no usage whatever the input is: Reports for GitHub. Any other value throws aConfigErroratformat:format: must be text, json, brief, markdown, payload or sarif.texthas the findings with their evidence, each profile's counts and coverage, what was left out, the gaps, the flags, the time and the tokens, and last the verdict, as The text report shows: every line isinertLineof its text, 80 columns wide but for a path, a category or a row of code.colorisfalseunless it istrue.textis the one format that colors: withtrueit wraps the level, the location, the cited row's marker, a row's+or-and the verdict's status word in SGR sequences, never a word a model or the diff wrote, and a line whose textinertLinechanges beyond its hidden characters is written uncolored.json,brief,markdown,payloadandsarifnever color. The CLI colors on a terminal unlessNO_COLORis set, whichrenderReportdoes not read: it reads no environment, so the choice is yours.outcomeis what the report says the review came to, whichtextstates as its last line,briefas its status and its exit code,markdownas its verdict andpayloadas itsconclusion;sarifstates no outcome, since its levels and itsexecutionSuccessfulcome from the result, by the rules the exit code is made of. Pass the one your program exits with: when it is absent,renderReportcomputesoutcome(result), which lifts nothing. A program that callsoutcome(result, { allowIncomplete: true })for its exit code passes that, so the report and the code say the same.
import { outcome, renderReport } from '@tobi-or-not/quorum'
// `result` comes from `quorum.review`, as in the complete example below.
const done = outcome(result, { allowIncomplete: true })
process.stdout.write(renderReport(result, { format: 'brief', outcome: done }))
process.exitCode = done.exitCodeEvery part of the report that holds text from a model or from the diff passes inertLine or inertJson, so a program can print it as it is: Printing a review yourself.
publicView
declare function publicView(input: QuorumResult | PublicView): PublicViewpublicView makes the result less what helps an attacker, for a sink a stranger can read: a pull request comment, the job summary, an artifact, a CI log. It withholds each vote's reasoning and error, the discarded findings the finder reported, which it counts in meta.profiles.<id>.discarded, and lists those a scanner found, the providers and models, meta.usage, meta.calls, meta.settings, each profile's meta.profiles.<id>.research counts and each gap's detail, and keeps every other field, a held file's name, reason and rule and the flags with their details included. meta.view is "public". Each field and why it goes: The public view; the shape: The JSON result.
- The types are
PublicView,PublicVerdict,PublicVote,PublicMeta,PublicProfileMetaandPublicGap. APublicVerdictis aVerdictwhosevotesarePublicVotes,{ angle, keep, failure }, andPublicView['discarded']holds the discarded verdicts a scanner found,[]for a review that read no report. - It is pure and idempotent. The view holds new arrays and objects and never a part of the result, the result is never changed, and
publicView(view)isview. - It checks every view it returns, the one it makes and the one it is given, against the strict schema
readResultreads a public view by. A view that fails it throws aTypeError:the public view is not one quorum writes, at <path>, the path of the first issue written asreadResult's is, and never a value. So a forgedmeta.viewthat keeps a vote'sreasoning, a profile id or a fingerprint that holds Markdown, and a reason, a rule or a flag's code outside its closed list, are refused before a reporter writes them bare. A file is refused earlier, byreadResult. renderReportandoutcometake either, the result or its view, and the exit code and the conclusion are the same for both.
import { outcome, publicView, renderReport } from '@tobi-or-not/quorum'
// `result` comes from `quorum.review`, as in the complete example below.
const view = publicView(result)
const done = outcome(view, { allowIncomplete: true })
process.stdout.write(renderReport(view, { format: 'json', outcome: done }))readResult
declare function readResult(text: string): QuorumResult | PublicViewreadResult reads a result a review saved, or its public view, back from its JSON text. It is the reader behind quorum report and takes text, since only the program reads a file: quorum report. The text is untrusted, so it is checked in this order, and the first check that fails throws a ConfigError with one issue at the empty path, a message of quorum's own words that holds no value and no part of the text, and no key but a code word:
| Check | Message |
|---|---|
| The size, in bytes of UTF-8, at most 256 MiB | the result is over 256 MiB, the most quorum reads |
JSON.parse | the result is not JSON |
meta.version, as own data, equals the version of this release | the result was written by another release of quorum: render it with the release that wrote it |
The strict schema: the public view's when meta.view is public, the result's otherwise | the result is not one quorum writes, at <path>, or without the path when the first issue has none |
- The cap holds every result a review of the largest diff quorum reads can write, and stays under the longest string the engine makes.
- The same release only. A result of another release is refused before its shape is read, since a release mismatch is the likeliest mistake of two jobs, and the schema is the release's own: render a result with the release that wrote it.
- The schema is strict at every level. An unknown key anywhere is refused, and so is a value outside a closed list, a profile id that matches no
^[a-z][a-z0-9_-]*$, a verdict or a gap of a profile the result does not hold, a fingerprint or a finding id of the wrong form, a text over its cap, a kept finding with no confidence and a discarded or an unreviewed one with one. A public view is refused when it still holds a vote'sreasoningorerror, ausage, a profile'sproviders, a gap'sdetail, or a discarded finding the finder reported, and a verdict a scanner found is refused when itsfoundBy.reportnames no record of its own profile inmeta.context.reports. The path of an issue names a key that is no code word as*, as a config error does. - It runs nothing and reads nothing but its text. What it returns is data a reporter may render:
renderReportandoutcometake it as they take a review's result.
import { readFile } from 'node:fs/promises'
import { readResult, renderReport } from '@tobi-or-not/quorum'
const result = readResult(await readFile('result.json', 'utf8'))
process.stdout.write(renderReport(result, { format: 'markdown' }))cleanProse
declare function cleanProse(text: string): CleanedProse
interface CleanedProse {
readonly text: string
readonly removed: Removed
readonly settled: boolean
}
interface Removed {
readonly characters: number
readonly comments: number
readonly entities: number
}cleanProse removes from prose a model reads as policy, a guideline or a rules file, three kinds of text a renderer does not show: the HTML comments, the numeric character references and the hidden characters but the line feed and the tab, in passes until one removes nothing, at most 16. Other Markdown a renderer hides, a link reference definition such as [//]: # (...), passes untouched, and the hidden characters include joiners and variation selectors a reader sees (ZWJ, ZWNJ, U+FE0F). It makes the text well formed and every line end a line feed first. What it removes, in what order and why one pass is not enough: Prose a review reads as policy.
textis the cleaned text, andremovedcounts the hidden characters (by code point), the comments and the references removed. A line end it rewrites and a lone surrogate it replaces count nothing.settledisfalsewhen the text was still changing in the 16th pass, which nesting deeper than 15 levels causes. Refuse such a text, and never send it:textis what the passes left of it.- It is pure. It reads no profile, file or setting, and it cleans prose, never code: the diff and the evidence do not pass through it.
import { readFile } from 'node:fs/promises'
import { cleanProse } from '@tobi-or-not/quorum'
const { text, removed, settled } = cleanProse(await readFile('guidelines.md', 'utf8'))
if (!settled) throw new Error('guidelines.md nests comments or references too deep to clean: remove them')
console.error(`removed ${removed.characters} hidden characters, ${removed.comments} comments and ${removed.entities} references`)
// `text` is what a model may read as policy.Errors
| Class | Extends | Fields | Thrown for |
|---|---|---|---|
QuorumError | Error | name, the class's own name | The base of every error quorum raises on purpose |
ConfigError | QuorumError | issues, each a { path, message }, every one; the message holds one path: message line per issue for the first 50, then and <n> more issues | Invalid configuration or input, every issue at once. The CLI exits 2 on it |
ProviderError | QuorumError | providerId, kind, status, retryable, exhausted, retryAfterMs, usage, noAnswer, refused (structuredOutput, streamOptions or stream: the field an HTTP 400 or 422 named as a whole word), stalledMs (set by the core alone, on a timeout that is a stalled stream: the window it showed no progress for), ceilingMs (set by the core alone, on a timeout at a ceiling that grew while its stream progressed: the ceiling it reached), cutAfterMs (set by the core alone, on the truncated failure it reads a learned cut as), rateLimit (a RateLimit: what the failed reply's rate-limit headers stated) | A provider call that failed: ProviderError |
OutputError | QuorumError | stage, reason; snippet, the first 200 characters of the reply | A model reply that could not be read: <stage> reply unusable: <reason> (reply starts: "<snippet>") |
ProviderDownError | QuorumError | providerId, kind, status, count, streak, exhausted, cutAfterMs, the shortest attempt in milliseconds when every call it counts was cut on the way, noAnswer, for a no-answer kind, refused, stream when the last failure was a refused stream, stalledMs, the shortest window in milliseconds when every call it counts stalled; cause, the last failure | A provider whose calls stopped: <id>: 3 calls in a row failed (<kind>): no more calls go to it in this review: <fix> when three of its calls in a row failed for a reason of its own, else <id>: its one call failed (<kind>): <fix> or its <n> calls failed, for a provider every call of which failed though fewer than three did. <fix> is a phrase naming what to check, as the CLI's progress line words it; for a provider whose quota is used up (exhausted) the message is <id>: the account's credit, quota or spend limit is used up (<kind> <status>): no more calls go to it in this review: add credit or raise the limit at the provider, or wait until it resets, whatever the count; for a provider down by replies with no answer the message says what they lacked instead: <id>: 3 calls in a row had no answer, only reasoning: ..., or had no answer and no reasoning: .... It rejects a review only when no research call of any profile answered, and it is recognised by instanceof alone, as a limit's error is, so a provider cannot raise one. It is no ProviderError. The CLI exits 3 on it, and writes its message, then the cause's |
GitError | QuorumError | operation, the git subcommand (diff, rev-parse, ls-tree, and version for --version); exitCode, git's, or null when it did not start or did not finish | A git command a source ran that failed: below. The CLI exits 3 on it |
A failed research call or an unusable research reply, a gating profile's included, is its profile's research-failed gap, in words the code writes: the research call failed (http 503) after 3 attempts, or the research reply could not be read: <reason>, which quote nothing a server or a model wrote, and a provider found down leaves provider-down gaps. A research call's ProviderError or OutputError never rejects the review itself. The same errors from a vote are recorded in the vote's error and failure instead, a vote its provider was never sent with the failure provider-down. A ProviderError of kind too-large, from research or from a vote, is a request-too-large gap instead: the review does not reject, and a provider of your own raises it to have its own refusal of an oversized request recorded so. Any object with an own kind property of 'too-large' counts, whatever its class, so a refusal from a second copy of quorum is a gap too.
RateLimit
What a reply's rate-limit headers stated, as numbers, on a CompletionResponse, on the headers StreamSignal of a stream and on a ProviderError, a whole reply's failure included, each field there only when the reply sent it well formed:
interface RateLimit {
readonly requests?: number
readonly tokens?: number
readonly tokensLimit?: number
readonly requestsResetMs?: number
readonly tokensResetMs?: number
}requests and tokens are what is left of the window, tokensLimit is the window's tokens, and the resets are milliseconds until each count resets. A provider object of your own may state it on its responses and errors. The names the shipped adapters read, and what they ignore: The rate-limit headers.
Git errors
A GitError comes from readSource, never from review. Its message says the git subcommand and what happened, and holds git's stderr only cut to 500 characters and written as a JSON string, so a line of it is inert: git diff failed (exit 128): "fatal: bad object". The others are git could not start (ENOENT), git diff did not finish within 120000 ms, git diff was stopped by SIGKILL, git rev-parse printed an object format quorum does not read, git ls-tree printed an entry quorum cannot read, git ls-tree could not size an object the commit names: the repository lacks it, as a partial clone does, git cat-file did not return each listed blob at its listed size, git <subcommand> printed more than quorum reads, when a call prints over the cap it is held to, and git <subcommand> printed something quorum cannot read, when a call exits cleanly and prints what is no full id or list of filter keys. A revision as typed and a path are never in it: How quorum runs git. A source that refuses what it was given, git missing or older than 2.41 included, is a ConfigError instead.
Config types
declare function defineConfig(config: QuorumConfig): QuorumConfigloadConfig reads a named config file and fromConfig builds a quorum from a config: loadConfig and fromConfig. The CLI and runQuorum read their settings through these two functions: Configuration. These exports write and type-check a config:
QuorumConfigtypes what a TS or JS config exports as its default:$schema, for an editor,version,providers,roles,concurrency,maxFindings,findingsCap,partTokens,maxReviewTokens,reviewTimeoutMs,strict,relatedCode,exclude,sendandprofiles, every one optional.relatedCodeturns related code on, and a lens of a profile sets its own: Related code in a lens.sendis a list of non-empty file paths, the files to send the models though they are held back as secrets: Sending a held file. A provider is an object implementingProvider, or its settings, every one optional too:preset,protocol,baseUrl,model,contextTokens,apiKeyEnvandapiKey, thenauth,headers,query,extraBody,structuredOutput,temperature,maxTokens,maxTokensField,systemPrompt,stream,timeoutMs,stallTimeoutMsandretries, as Providers and Deadlines and retries describe them, and the fields of aclaude-codeprovider,argsand, in a code config only,command: Claude Code options.QuorumConfigFiletypes what a YAML or JSON config holds: the same settings, as data only, so a provider is always its settings, and names the environment variable that holds its key inapiKeyEnv, never holding one.ConfigInputtypes whatfromConfigtakes: the settings ofQuorumConfig, with every prompt a string and every document a{ text }or a{ repository, optional }, since a program's config reads no file and so holds no{ file }: the config loader puts the text of a file in the same place. An entry ofrulesis a rule (id,textand optionallypaths), a{ text, format }(yamlorjson) for a rules file the program loaded itself, or a{ repository, optional }. A{ repository }entry, of any field, is read byreadContext, not byfromConfig, which refuses a review whose context holds no document for it, a rules file's document holdingruleswhere another holds a text.defineConfigreturns the config it is given, as it is. Wrapping a default export in it has the editor check every field.
A config that imports nothing from quorum when it runs types its object with import type and satisfies instead, since import type is erased:
// quorum.config.mts
import type { QuorumConfig } from '@tobi-or-not/quorum'
export default {
providers: {
local: { preset: 'ollama', model: 'qwen3.6:27b', contextTokens: 131072 },
hosted: {
preset: 'openai',
model: 'gpt-5',
contextTokens: 400000,
apiKey: process.env.OPENAI_API_KEY
},
},
roles: { research: 'local', voter: 'hosted' },
} satisfies QuorumConfigThe import is erased when the file loads, so it matters to the editor alone: it resolves the types when the package is installed in the project that holds the config, for example as a dev dependency. The .mts extension makes the file an ES module whatever the nearest package.json says: Node refuses export in a .ts or .js file of a package whose package.json says "type": "commonjs". Node also strips erasable TypeScript only, so a config holds no enum, namespace or parameter property. An editor checks a YAML or JSON config against the JSON Schema committed as schema/quorum.schema.json, which the package ships as node_modules/@tobi-or-not/quorum/schema/quorum.schema.json: a YAML file names it in a comment, # yaml-language-server: $schema=<path or URL of the schema>, and a JSON file in its "$schema" field.
loadConfig and fromConfig
declare function loadConfig(options?: {
readonly cwd?: string
readonly env?: Env
readonly configPath?: string
readonly selection?: ProfileSelection
readonly failOn?: FailOnOverride
}): Promise<{ readonly config: ResolvedConfig, readonly source: string | undefined, readonly warnings: readonly string[] }>
declare function fromConfig(
config: ConfigInput | ResolvedConfig,
options?: { readonly env?: Env, readonly events?: EventSink },
): Promise<Quorum>
type Env = Readonly<Record<string, string | undefined>>
interface ProfileSelection {
readonly ids: readonly string[]
readonly path: string
}
interface FailOnOverride {
readonly all?: FailOn
readonly profiles: ReadonlyMap<string, FailOn>
readonly path: string
}loadConfig reads the config file it is named, if any, lays the environment over it and resolves the result into a ResolvedConfig: every layer merged, every reference bound, every key read. fromConfig builds a quorum from a config: a ConfigInput, which it checks and resolves, or a ResolvedConfig, which it uses as it is. Both read process.env when no env is given, and both throw a ConfigError before anything is sent, with every issue of the step that failed: loadConfig, those of the file, or else those of the resolution; fromConfig, those of the config's check, or else those of the resolution and the providers.
import { fromConfig, inertLine, loadConfig } from '@tobi-or-not/quorum'
const { config } = await loadConfig({ configPath: 'quorum.yaml' })
const quorum = await fromConfig(config)
for (const warning of quorum.warnings) console.error(inertLine(`warning: ${warning}`))
const result = await quorum.review({ diff })fromConfig({}, { env: process.env }) needs no file: the environment alone names a provider, a model and the model's context size, with QUORUM_RESEARCH_MODEL and QUORUM_RESEARCH_CONTEXT_TOKENS. The CLI and runQuorum read the QUORUM_* variables, with the deprecated RESEARCH_* and VOTER_* aliases, and the file QUORUM_CONFIG names through these two functions.
options.cwdis the directory a relativeconfigPathresolves against, the working directory by default.sourceis the absolute path of the file read, andundefinedwhen none was.QUORUM_CONFIGmust be an absolute path. A relative one is refused with aConfigErrorholding the issueQUORUM_CONFIG: must be an absolute path, whether or notconfigPathis given: a variable set once would resolve inside whatever directory the process runs in, and in CI that is a pull request's checkout, which could plant the file. AconfigPathis named per call, so it may be relative.options.selectionnames the profiles that run, overQUORUM_PROFILES, which is still read and checked: a malformed variable is refused even when a selection is given.pathis what the selection's issues name, and the CLI passes--profile. Each id must match^[a-z][a-z0-9_-]*$, and none may repeat.options.failOnsets the fail-on level of the profiles that run, over the config's. It is aFailOnOverride:allis the level of every profile that runs,profilesthe level of each profile it names, which wins overall, andpathwhat its issues name; the CLI passes--fail-on. Each profile that runs is then a new frozenResolvedProfilewith that level as itsfailOn, someta.profilesrecords it. A name inprofilesthat is not among the profiles that run is refused with aConfigErroratpath,names the profile "<id>", which does not run, ornames a profile that does not runfor an id that is not a safe name: a typo must not leave a gate weaker or missing. A level that is none of the four is refused whenfromConfigbuilds the quorum:<id>.failOn: must be one of high, medium, low or none.- The CLI reads each
--fail-onvalue withparseFailOn, which the package does not export, as<level>or<profile>=<level>: the level ishigh,medium,lowornone, the profile matches^[a-z][a-z0-9_-]*$, and the value is split at its first=. It is checked before any config is read, and refused at--fail-on, each issue once and none repeating a value:must be a level, high, medium, low or none, or <profile>=<level>for a value that is neither form,takes one level for every profilefor a second level for every profile, equal or not, andnames a profile more than once. options.eventsis the event sink of the quorum, ascreateQuorumtakes it.options.envis also the environment aclaude-codeprovider's child starts from, less what the provider's auth mode removes: The auth modes. Without anenv,fromConfighandsprocess.envto theclaudechild, the whole of it, for aResolvedConfigtoo. A program that holds secretsclaudedoes not need passes anenvof its own, withPATHand whatclaudeauthenticates with.- A process imports a TS or JS config once. A second
loadConfigof the same file gets the module the first import cached, since Node and Bun cache a module by its URL. - A program passes its config's
senditself.fromConfigbuilds a quorum, andsendbelongs to one review's input, so a program that readsconfig.sendof aResolvedConfiggives it toreadSource's context and toreview(andestimate) itself, as the CLI does, with whatever it adds of its own:const send = [...config.send ?? [], ...mine]. A review that is not given it holds the file back. - A named config is trusted input. It chooses where each key goes, and a TS or JS one runs code: in CI it must come from the base branch or from outside the pull request's checkout, never from the pull request under review, and its prompt files with it (Layering).
- A
ResolvedConfigholdsproviders, the ones a profile that runs uses, by name: a spec with its key read intoapiKey, or the snapshot of an object implementingProvider;profiles, each aResolvedProfile: itsprofile,research, the name of its research provider,voters, the name of each lens's provider, by lens id,repository, its{ repository }entries, whichreadContextreads, andbase, the built-in profile it starts from (itsextends, else its own id when that is a built-in profile's), absent for a profile of its own;concurrency,maxFindings,maxReviewTokensandreviewTimeoutMswhen the variables or the config set them,strict,true, when the config'sstrictorQUORUM_STRICTistrue,relatedCode,true, when the config'srelatedCodeis (resolveConfigandloadConfigtake it as an option, over the config's),partTokenswhen the config sets it,excludewhen the config lists a pattern,sendwhen it lists a file, andwarnings. It is a copy, frozen all the way down: a provider object is a frozen snapshot of the program's, with no prototype, named by its config key as itsid, and holding thetimeoutMs,retries,window,maxTokens,thinking,worstCaseandroomit states. - A
ResolvedConfigholds the keys it read, as a code config does: never print or log one. The CLI's--print-configredacts them. fromConfigof aResolvedConfigreads no environment: whatloadConfigresolved is what runs, whateveroptions.envholds, except that aclaude-codeprovider's child still starts fromoptions.env, elseprocess.env.- A config is read as its own fields, with one limit. A field planted on
Object.prototypeis a prototype pollution bug in the same process. An enumerable one is a field of every object, so it is refused asis not a known fieldwherever the schema does not know it: a plantedbaseUrlis refused at the top level, while a plantedconcurrency,maxFindings,findingsCap,partTokens,maxReviewTokens,reviewTimeoutMs,strict,exclude,sendorversionpasses when the config holds no object that refuses it, and a plantedexcludeis the one that widens what passes unread, and a plantedsendwhat a provider is sent. One planted withObject.definePropertyis not enumerable, and the schema reads each field it knows through the prototype, so it becomes a field of the config, or of every provider that leaves it unset. Code that can plant either can read the keys directly: quorum does not defend against it.
Layering
Each layer sits over the one before it: the built-in defaults, then the file configPath names (else the one QUORUM_CONFIG names), then the environment.
- The built-in defaults. A config that defines no provider gets one named
default, with no model and no context size, soQUORUM_RESEARCH_MODELandQUORUM_RESEARCH_CONTEXT_TOKENS, or a file, must set them. The rule: with no provider configured and no base URL, preset or protocol variable for a role, that role talks to the Ollama on this machine through its native API,http://localhost:11434, where Ollama listens, on127.0.0.1, by default; a role whose variables set a base URL without a preset or a protocol speaksopenai-compatibleto that URL, as before. A voter with no variables of its own shares the research provider: The voter's fallback. The native API tells Ollama the context size and makes it refuse an overflow (Ollama 0.12.6 or later; an older server ignorestruncateandshift), where its OpenAI-compatible/v1cuts an oversized prompt in silence. A config with noprofilesfield runs thesecurityprofile. - A profile over its base. A profile named after a built-in profile, or with
extends, starts from it: its prompts and its policy levels replace the base's one field at a time, and its lenses replace the base's lenses as a whole. undefinedis unset,nullis set. In a program's config or a code config, a field set toundefinedleaves the layer below's value in place, as if it were not written;nullis a value, such astemperature: null, which leaves the field out of the request.- No file is searched for. A file loads only when it is named, by
configPathfirst, thenQUORUM_CONFIG: aquorum.config.yamlin the working directory is never read, since in CI that directory is a pull request's checkout, and a pull request could plant one. - A named config is trusted like code. It chooses where each key goes: a
baseUrlof its own beside anapiKeyEnvsends the key that variable holds to that host. A TS or JS config also runs, with the job's environment. So in CI a named config must come from the base branch or from a path outside the pull request's checkout, never from the pull request under review, and its prompt files, which resolve against its directory, must come from the same place.
The environment variables
| Variable | Sets |
|---|---|
QUORUM_CONFIG | loadConfig only: the config file to read, when configPath is not given. It must be an absolute path |
QUORUM_PROFILES | The profiles that run: ids separated by commas, each a profile the config defines or a built-in one, none twice |
QUORUM_RESEARCH_PRESET, QUORUM_VOTER_PRESET | A role's provider, built from a preset |
QUORUM_RESEARCH_PROTOCOL, QUORUM_VOTER_PROTOCOL | A role's provider, built from a wire protocol: openai-compatible, anthropic, gemini or ollama, or claude-code for your installed Claude Code CLI |
QUORUM_RESEARCH_BASE_URL, QUORUM_VOTER_BASE_URL | The base URL of a role's provider. Set on its own, with no provider in a config and no preset or protocol variable for the role, it names an openai-compatible server, except for a voter derived from a research provider whose variables name a preset or a protocol, which keeps that protocol: The role variables |
QUORUM_RESEARCH_MODEL, QUORUM_VOTER_MODEL | The model of a role's provider |
QUORUM_RESEARCH_CONTEXT_TOKENS, QUORUM_VOTER_CONTEXT_TOKENS | The context window of a role's provider's model, in tokens: a whole number from 1 to 999999999. It has no deprecated alias |
QUORUM_RESEARCH_TIMEOUT_MS, QUORUM_VOTER_TIMEOUT_MS | The deadline of one attempt of a role's provider, in milliseconds: a whole number from 1000 to 86400000; unset, it grows with the attempt's reply budget. On a claude-code provider it is Claude Code's wait for each attempt's response headers, and the whole run's deadline is that times the retries plus one: Stopping, nesting and the version. It has no deprecated alias |
QUORUM_RESEARCH_STALL_TIMEOUT_MS, QUORUM_VOTER_STALL_TIMEOUT_MS | How long a streamed attempt of a role's provider may show no progress before it fails as a timeout, in milliseconds: a whole number from 1000 to 86400000. Unset, the window is learned: The stall window. It has no deprecated alias |
QUORUM_RESEARCH_RETRIES, QUORUM_VOTER_RETRIES | How many times a call of a role's provider that failed in passing is tried again: a whole number from 0 to 5. It has no deprecated alias |
QUORUM_RESEARCH_STREAM, QUORUM_VOTER_STREAM | Whether a role's provider streams its replies: true or false, written exactly. true pins the stream and false asks for whole replies, as the stream field does; unset, the provider streams and steps down by itself when a server refuses: Streaming. It has no deprecated alias |
QUORUM_RESEARCH_THINKING, QUORUM_VOTER_THINKING | The thinking of a role's provider: off or low, sent as its protocol's own control: Thinking. It has no deprecated alias |
QUORUM_RESEARCH_API_KEY, QUORUM_VOTER_API_KEY | The key of a role's provider, as a literal apiKey |
QUORUM_CLAUDE_CODE_COMMAND | The claude executable of every claude-code provider a profile uses: an absolute path, or a name found in the absolute entries of PATH; a relative path and a .cmd or .bat file are refused. It wins over a code config's command: Where the command comes from |
QUORUM_MAX_REVIEW_TOKENS | The review's token cap: a whole number of tokens from 1 to 9007199254740991, over the config's maxReviewTokens |
QUORUM_REVIEW_TIMEOUT_MS | The review's deadline, in milliseconds: a whole number from 1000 to 86400000, over the config's reviewTimeoutMs |
QUORUM_FINDINGS_CAP | The most findings of the research each profile sends to its panel in a review: a whole number from 1 to 999999999, over the config's findingsCap |
QUORUM_STRICT | true or false, written exactly: true turns the config's strict on, false sets nothing and never turns it off. Under strict, a key sent over plain http to a host other than this machine is refused before any call, not warned of: Keys |
RESEARCH_BASE_URL, RESEARCH_API_KEY, RESEARCH_MODEL, VOTER_BASE_URL, VOTER_API_KEY, VOTER_MODEL | Deprecated aliases: each is read as the QUORUM_ variable of the same name |
- The
QUORUM_form wins over its alias when both are set, and one warning names every alias that is set, whichever form won:RESEARCH_MODEL is deprecated: set QUORUM_RESEARCH_MODEL instead. A preset, a protocol, a context size, a thinking, a deadline and a retry count have no alias. - Every value is trimmed, and a blank one is unset. Only the variables the environment holds itself are read, never one an object it inherits from holds.
QUORUM_PROFILESrefuses what would review nothing or the wrong thing: an empty id, an id that is not lower-case letters, digits,_and-after a letter, or an id named twice.QUORUM_MAX_REVIEW_TOKENS,QUORUM_REVIEW_TIMEOUT_MSandQUORUM_FINDINGS_CAPbelong to no role. Each is read as strictly as a role's numbers, and a value that is read wins over the config's field;fromConfighands all three tocreateQuorum: The limits of a review.
The role variables
- The research variables set the provider
roles.researchnames, which a voter or a lens that shares it inherits. - The voter variables set the provider
roles.voternames when that is another provider than research's. When the voter shares the research provider, they derive a provider namedvoterfrom it, and bind the voter role to it. A config that already has a provider namedvotercannot be derived over: rename it. - A derived voter keeps what is safe on its endpoint, as the voter's fallback of Configuration does, and a key, header, query parameter, body field or model never reaches another origin:
QUORUM_VOTER_BASE_URL | The voter's base URL | Its key | Its model | Its context size | The rest of the research provider's settings |
|---|---|---|---|---|---|
| Unset | The research provider's | QUORUM_VOTER_API_KEY, else the research provider's key | QUORUM_VOTER_MODEL, else the research provider's | QUORUM_VOTER_CONTEXT_TOKENS, else the research provider's while the voter variables name no preset, protocol, base URL or model | All kept |
| The same origin as the research provider's | QUORUM_VOTER_BASE_URL | QUORUM_VOTER_API_KEY, else the research provider's key | QUORUM_VOTER_MODEL, else the research provider's | QUORUM_VOTER_CONTEXT_TOKENS only | All kept |
Another origin, or no http(s) origin | QUORUM_VOTER_BASE_URL | QUORUM_VOTER_API_KEY, else none: a preset's own variable is not read | QUORUM_VOTER_MODEL, which is then required | QUORUM_VOTER_CONTEXT_TOKENS only | apiKeyEnv, headers, query, extraBody and model dropped; the preset, protocol, auth, structuredOutput, thinking, temperature, maxTokens, maxTokensField, systemPrompt, stream, timeoutMs, stallTimeoutMs and retries kept |
A QUORUM_VOTER_PRESET or QUORUM_VOTER_PROTOCOL is set | Its own, or the preset's | QUORUM_VOTER_API_KEY, else the preset's own variable at the preset's origin | QUORUM_VOTER_MODEL, which is then required | QUORUM_VOTER_CONTEXT_TOKENS only | None: the provider is built from the voter variables alone |
The origin is compared as the voter's fallback compares it: the scheme, the host in lower case with no trailing dot, and a port that is not the default.
- On the built-in
defaultprovider, a voter base URL on its own isopenai-compatible. A derived voter whose variables set a base URL with no preset or protocol speaksopenai-compatible, on another origin than research's and on the same one too (QUORUM_VOTER_BASE_URL=http://localhost:11434/v1), and does not inherit the default's native protocol. One that sets only a model, a context size or a key keeps research's endpoint and protocol. A voter derived from a provider a config defines, or from a research provider whose variables name a preset or a protocol, inherits that provider's protocol, as before. - A
PRESETorPROTOCOLvariable builds the role's provider afresh.QUORUM_RESEARCH_PRESET=anthropicis not merged into thedefaultprovider, whose protocol it would contradict: the research provider is a provider of that preset, from the role's variables alone.BASE_URL,MODEL,CONTEXT_TOKENS,TIMEOUT_MS,RETRIESandAPI_KEYalone override fields of the provider they reach. - A context size belongs to one model on one endpoint. A role's preset, protocol, base URL or model variable drops the context size of the provider it sets, unless
QUORUM_<ROLE>_CONTEXT_TOKENSsets one; a variable that sets only a key, a deadline or a retry count keeps it. A derived voter never inherits the research provider's context size for another model or another endpoint. - No variable changes a provider object. A role bound to an object that implements
Providerwith a variable set for it is an issue at the variable, never an ignored one.
Roles and profiles
- The role defaults. One provider binds both roles. Several need
roles.research, or the config is refused;roles.voterisroles.researchwhen unset. A profile's ownrolesoverride the top-level ones, and a lens'sprovideroverrides both. - Which profiles run. The ones
selectionnames, else the onesQUORUM_PROFILESnames, else the onesprofilesdefines, elsesecurity.profiles: {}with no selection is refused: a run that reviews nothing never passes. - A profile's base. A profile named after a built-in profile starts from it, so
profiles: { security: { failOn: 'none' } }is the security profile without gating; so does one withextends. A profile of its own needs both prompts and its lenses. ItsfailOnis the entry's own, else what its deprecatedgatingsays (trueishigh,falseisnone), else the base's, elsehigh; a profile never keeps agating, and an entry that sets both is refused. - Every defined profile and provider is checked, whether or not a run selects or uses it, so a broken definition fails every run, as an unknown field does.
Keys
A provider's key is the first of:
- A literal
apiKey: a program's or a code config's, orQUORUM_<ROLE>_API_KEY, which wins over a variable a file names withapiKeyEnv. An empty one is unset, as a blank variable is, so the next source applies. - The variable
apiKeyEnvnames. A variable that is not set is an issue, never a silent run without a key. - The preset's own variable (
OPENAI_API_KEYforopenai), only while the base URL keeps the preset's origin. At another origin it is not read, and a warning says so. - For
azure-openai, whose preset has no base URL,AZURE_OPENAI_API_KEY, only on anhttpshost underopenai.azure.com.
- A
claude-codeprovider reads a key inapi-keymode only:apiKey, then the variableapiKeyEnvnames, elseANTHROPIC_API_KEY. It has no preset, and a key in another mode is refused. AZURE_OPENAI_API_KEYis one variable for every Azure resource. It is read for any host underopenai.azure.com, so a voter whose own variables name theazure-openaipreset on another Azure host sends that key there.- A
QUORUM_<ROLE>_BASE_URLset on a provider with an explicitapiKeyEnvkeeps that key at the new URL. It overrides the provider itself, not a fallback, so a literalapiKey,headers,query,extraBodyandmodelalso stay with the provider at the new URL. A preset's own variable is withheld off its origin, with a warning. - A voter derived onto another origin gets no key of the research provider, whichever way it was set:
apiKey,apiKeyEnv, a preset's variable or aQUORUM_RESEARCH_API_KEY. - Keys are read only for the providers a profile that runs uses, so a CI job that runs one profile needs that profile's keys alone. Every provider is still checked, without its key.
- A key sent over plain
httpto a host other than this machine (localhost,*.localhost,127.0.0.0/8and[::1]are this machine) is warned about. - A resolved config holds its keys, so never print or log one. No message or warning repeats a key, a URL, a header value or a variable's value, and a variable's name is printed only when it is an upper-case name.
Warnings and errors
loadConfig returns the config's warnings: the deprecation line, the line naming the QUORUM_ variables that nothing reads, a preset's key that is not sent, a key sent over plain http, a key that Claude Code would bill, and a profile entry's deprecated gating. The warnings of the quorum fromConfig returns hold those first, then the core's: a profile setting that cannot take full effect, Warnings. A provider object is read only while its config is checked, inside the guard that keeps what it throws to the error's name: its model once and its complete twice (the check of plain data, then the snapshot), into a frozen snapshot with no prototype that calls the object as it is, and that snapshot is named by its config key in events and in meta, whatever id the object holds. Its timeoutMs and retries are read there too, as own data and never through a getter, into the snapshot, which keeps each that is in range; one out of range is refused at providers.<name>.timeoutMs or providers.<name>.retries, and a getter or an inherited property states nothing. So is its worstCase: read as own data into a function of the snapshot that calls it on the object, so the review's token cap reserves what the object says one call may cost, and refused at providers.<name>.worstCase when it is no function; the fingerprint and --print-config never see it, as they never see its complete. So is its room, read into a function of the snapshot that calls it on the object and refused at providers.<name>.room when it is no function; the fingerprint and --print-config never see it either.
| Path | Message | Cause |
|---|---|---|
| The path as given | The file's own problem, such as does not exist, is not valid YAML at line 2, column 1 (DUPLICATE_KEY), has a syntax error or failed to load (Error) | loadConfig could not read the file, or it is not valid |
QUORUM_CONFIG | must be an absolute path | loadConfig read a relative QUORUM_CONFIG; configPath may be relative to cwd |
config | must be an object | A ConfigInput that is not a plain object |
config | could not be read (Error) | A getter or a proxy of the config threw, one of a provider object's included: each provider object is read only here, and only the error's name is kept, an error when that is not a plain class name |
config | holds more than 10000 values | A ConfigInput too large to walk |
<path> | is not allowed as a key: it can replace the prototype of an object, must be plain data: an object, an array, a string, a finite number, true, false or null, must be a finite number, or is nested more than 64 keys deep | A ConfigInput that holds data a config may not |
<path> | The schema's: is not a known field, is required, must be a string, must be at least 1, and the like | A field of the wrong shape, at its path |
QUORUM_PROFILES | must list profile ids separated by commas, each matching ^[a-z][a-z0-9_-]*$ | An empty id, or an id of another form |
QUORUM_PROFILES | names a profile more than once | security,security |
QUORUM_PROFILES, or the selection's path (--profile) | unknown profile "tema" (did you mean "team"?), or unknown profile "style": the profiles are team, security, code-review, best-practices and performance | An id that is neither defined nor built in |
The selection's path | must be a profile id matching ^[a-z][a-z0-9_-]*$ | An empty id, or an id of another form, in selection.ids |
The selection's path | names a profile more than once | selection.ids names an id twice |
The selection's path | must name at least one profile | selection.ids is empty |
QUORUM_RESEARCH_CONTEXT_TOKENS, QUORUM_VOTER_CONTEXT_TOKENS | must be a whole number of tokens, from 1 to 999999999 | A context size variable that is not a whole number written in decimal digits in that range: 32k, 1e5, 0x10, 1.5 and 0 are refused, and the message never repeats the value |
QUORUM_RESEARCH_TIMEOUT_MS, QUORUM_VOTER_TIMEOUT_MS | must be a whole number of milliseconds, from 1000 to 86400000 | A deadline variable that is not a whole number written in decimal digits in that range: 999, 120s, 1e5, 0x3e8 and 0120000 are refused, and the message never repeats the value |
QUORUM_RESEARCH_STALL_TIMEOUT_MS, QUORUM_VOTER_STALL_TIMEOUT_MS | must be a whole number of milliseconds, from 1000 to 86400000 | A stall window variable that is not a whole number written in decimal digits in that range, as a deadline variable is: the message never repeats the value |
QUORUM_RESEARCH_RETRIES, QUORUM_VOTER_RETRIES | must be a whole number, from 0 to 5 | A retries variable that is not a whole number written in decimal digits in that range: 6, -1, 1.5 and 02 are refused, and the message never repeats the value |
QUORUM_RESEARCH_STREAM, QUORUM_VOTER_STREAM | must be true or false | A stream variable that is neither true nor false, written exactly, and the message never repeats the value |
QUORUM_RESEARCH_THINKING, QUORUM_VOTER_THINKING | must be low or off | A thinking variable that is neither low nor off, and the message never repeats the value. A thinking the provider's protocol cannot honour, or that sits beside the same control in extraBody, is refused at the variable too, with the builder's words: Thinking |
QUORUM_MAX_REVIEW_TOKENS | must be a whole number of tokens, from 1 to 9007199254740991 | The review's token cap variable is not a whole number written in decimal digits in that range: 0, 1e6, +5, 02000000 and 9007199254740992 are refused, and the message never repeats the value |
QUORUM_REVIEW_TIMEOUT_MS | must be a whole number of milliseconds, from 1000 to 86400000 | The review's deadline variable is not a whole number written in decimal digits in that range: 999, 86400001 and 30m are refused, and the message never repeats the value |
QUORUM_FINDINGS_CAP | must be a whole number of findings, from 1 to 999999999 | The finding cap variable is not a whole number written in decimal digits in that range: 0, 1.5, abc, 01 and 1000000000 are refused, and the message never repeats the value |
QUORUM_VOTER_MODEL | must be set when the voter variables name another endpoint than the research provider's | The voter variables name another origin, a preset or a protocol, and no model |
QUORUM_RESEARCH_MODEL, and the other variables of a role | cannot change providers.mine, an object implementing Provider | A variable set for a role bound to a provider object |
providers.voter | is the name the voter variables give the provider they derive: rename this provider | The voter variables derive a provider, and one is already named voter |
profiles | must hold at least one profile, or be left out | profiles: {} with no QUORUM_PROFILES |
profiles.<id>.prompts.research, profiles.<id>.prompts.vote, profiles.<id>.lenses | is required: the profile extends no built-in profile | A profile of its own without prompts or lenses |
profiles.<id> | is named after the built-in <id> profile and brings its own research template and lenses: set extends: <id> to start from the built-in, or rename the profile to keep it your own | An entry with no extends, named code-review, best-practices or performance, that sets both its own prompts.research and its own lenses: Changing one |
roles.research, roles.voter, profiles.<id>.roles.research, profiles.<id>.roles.voter, profiles.<id>.lenses.<index>.provider | unknown provider "claud" (did you mean "claude"?), or unknown provider "x": the providers are a and b | A reference to a provider that is not defined: the defined name one or two edits away, else the names. A name that is not a safe name is not repeated: names an unknown provider |
roles.research | is required when several providers are defined | Several providers, and no research role |
profiles.<id>.failOn | must be one of high, medium, low or none | A failOn that is none of the four levels |
profiles.<id>.gating | is deprecated and cannot be set with failOn: remove it | An entry that sets both failOn and the deprecated gating |
profiles.<id> and below | The profile's own issues: The checks | A profile that fails a check |
| No path | no model configured: set QUORUM_RESEARCH_MODEL, or name a config file that sets one | The built-in provider has no model |
| No path | no context size configured: set QUORUM_RESEARCH_CONTEXT_TOKENS, or name a config file that sets contextTokens | The built-in provider has no context size. A missing model is reported first, and alone |
providers.<name>.contextTokens | is required: the model's context window in tokens, which quorum checks every request against | A provider of the config with no contextTokens, used by a profile or not. A derived voter that shares the research provider, context size included, is not reported twice: the research provider's issue stands for it |
QUORUM_RESEARCH_CONTEXT_TOKENS | must be set when the research variables name a model or an endpoint: a context size belongs to one model on one endpoint | The research variables name a preset, a protocol, a base URL or a model, which drops the context size of the provider they set |
QUORUM_VOTER_CONTEXT_TOKENS | must be set when the voter variables name a model or an endpoint: a context size belongs to one model on one endpoint | The same for the voter variables, on the derived voter or on the voter's own provider |
providers.<name> | CORP_KEY is not set | The variable apiKeyEnv names, or the preset's own, is not set; ANTHROPIC_API_KEY for a claude-code provider in api-key mode |
providers.<name> | claude CLI not found; install Claude Code or set QUORUM_CLAUDE_CODE_COMMAND | A claude-code provider a profile uses, and no command and no claude in an absolute entry of PATH |
QUORUM_CLAUDE_CODE_COMMAND | must be an absolute path, or a name to find on PATH, is a Windows script, which runs only through a shell: name claude.exe instead, or names no executable file | A relative path, a .cmd or .bat file, or a command that is no executable file. A code config's command has the last at providers.<name>.command |
providers.<name>.apiKeyEnv | names a variable that is not set | The same, for a name that is not an upper-case variable name: a key pasted there is never printed |
providers.<name>.<field> | The builder's: Presets as data and Configuration errors | A provider that the builder refuses, defined or derived |
QUORUM_RESEARCH_PRESET and the other variables of a role: the preset, the protocol, the base URL, the model, the context size, the deadline, the stall window, the retries and the key | The builder's, such as must be one of ollama, ollama-cloud, ... | A provider that the builder refuses on a field a variable set: the issue names the variable, never the provider the variables built |
providers.<name>.model | must be a string | A provider object whose model is not a string |
providers.<name>.timeoutMs, providers.<name>.stallTimeoutMs, providers.<name>.retries | must be a whole number of milliseconds from 1000 to 518400000, must be a whole number of milliseconds from 1000 to 86400000 (stallTimeoutMs), or must be a whole number from 0 to 5 | A provider object that states one out of range, as an own data property |
providers.<name>.streams | must be true | A provider object that states a streams that is not true, as an own data property |
providers.<name>.window, providers.<name>.maxTokens | must be a whole number of tokens of at least 1 | A provider object that states one that is not, as an own data property |
providers.<name>.thinking | must be default, low or off | A provider object that states another value, as an own data property |
providers.<name>.worstCase | must be a function | A provider object that states a worstCase, as an own data property, that is no function |
providers.<name>.room | must be a function | A provider object that states a room, as an own data property, that is no function |
providers.gpu.baseUrl | sends the key over plain http to a host other than this machine, and strict refuses it: use an https URL | strict is on, in the config or in QUORUM_STRICT, and a key would travel in cleartext: the refusal of the warning below. When a QUORUM_* variable set the base URL, the path is that variable's, QUORUM_RESEARCH_BASE_URL or, for a derived voter, QUORUM_VOTER_BASE_URL |
QUORUM_STRICT | must be true or false | The variable is neither, written exactly |
The warnings, each but the first two starting at the path it is about:
| Warning | Cause |
|---|---|
RESEARCH_MODEL is deprecated: set QUORUM_RESEARCH_MODEL instead | A deprecated alias is set; one line names every alias, and every QUORUM_ variable to set instead |
QUORUM_PROFILE is not a variable quorum reads | A QUORUM_ variable that is set and that quorum does not read: one line names every such variable, sorted, and prints a name that is not an upper-case variable name as * |
providers.gpt.baseUrl: is not the endpoint of the openai preset, so OPENAI_API_KEY is not sent: set apiKeyEnv to send a key | A provider of a preset whose base URL is not the preset's origin |
providers.voter.baseUrl: is not the endpoint of the research provider, so OPENAI_API_KEY is not sent: set QUORUM_VOTER_API_KEY to send a key | A derived voter on another origin than research's, whose provider keeps a preset that has a key variable |
providers.gpu.baseUrl: sends the key over plain http to a host other than this machine | A key that would travel in cleartext, without strict |
providers.default: ANTHROPIC_API_KEY is set, so Claude Code bills that key rather than its login: unset it, or set auth to login or api-key | A claude-code provider a profile uses, under inherit or with no auth, while ANTHROPIC_API_KEY is set |
profiles.team.gating is deprecated: set failOn instead, high for true and none for false | A profile entry that sets gating, which still reads: true as high, false as none |
Exports
| Values | |
|---|---|
createQuorum | Build a quorum |
defineConfig | Type a TS config: Config types |
INTERRUPT_GRACE_MS | How long the calls in flight have to end once a review's interrupt aborts, 5000 ms: Interrupt |
LANE_START, REVIEW_CEILING | Where a provider's lane starts, 4 calls at once, and the most calls in flight over every lane, 16: Lanes |
fileStore | The CLI's --state store, as a ReplyStore for review's store: fileStore |
fromConfig | Build a quorum from a config: loadConfig and fromConfig |
loadConfig | Read a named config file and resolve it with the environment: loadConfig and fromConfig |
securityProfile | The default profile, frozen: Profiles |
codeReviewProfile | The advisory profile for functional defects, frozen and unmeasured: Profiles |
bestPracticesProfile | The advisory profile bound to four review rules, frozen and unmeasured: Profiles |
performanceProfile | The advisory profile bound to six cost-pattern rules, frozen and unmeasured: Profiles |
defaultPolicy | { high: 'unanimous', medium: 'majority', low: 'off' }, frozen |
anthropic | The Anthropic Messages adapter: Providers |
claudeCode | The adapter that runs your installed Claude Code CLI: Providers |
gemini | The Gemini generateContent adapter: Providers |
ollama | The Ollama native chat adapter: Providers |
openaiCompatible | The OpenAI-compatible adapter: Providers |
presets | The presets, frozen: Presets |
readSource | Read the diff, its source and the files it left out, from a diff, a range, the local changes or the files at a commit: readSource |
openRelatedCode | Open the reader of the code beside a diff, at the commit its source reads: a lookup of names and a read of the files it lists, nothing fetched: openRelatedCode |
outcome | What a review comes to, its status and the exit code that says it: outcome |
renderReport | Write a result, or its public view, as the report the CLI writes, in the format text, json, brief, markdown, payload or sarif: renderReport |
publicView | The result less each vote's reasoning and error, the discarded findings the finder reported, the providers, the usage and each gap's detail, for a sink a stranger can read: publicView |
readResult | Read a saved result or public view back from its JSON text, of this release only, through a strict schema and a cap: readResult |
QuorumError, ConfigError, ProviderError, ProviderDownError, OutputError, GitError | The error classes |
inertLine, inertJson, codeSpan, fencedBlock, inertPlain | Render a line for a terminal or a log, a value as JSON, text in Markdown and plain text a viewer may link, inert: Output handling |
cleanProse | Remove the HTML comments, numeric character references and hidden characters from prose a model reads as policy, to a fixpoint of at most 16 passes: cleanProse |
runQuorum | Deprecated: below |
The types: ActionComment, ActionPayload, Adaptation, CleanedProse, ConcurrencyRecord, Confidence, CoverageEntry, CoverageReason, CoverageStatus, CredentialKind, Estimate, FailOn, Finding, Flag, FlagCode, FoundBy, IncompleteEntry, IncompleteReason, LeftOutFile, LeftOutReason, LeftRange, Lens, LensVote, ObjectFormat, Outcome, OutcomeStatus, Profile, ProfileEstimate, ProfileMeta, ProfileProviders, Prompts, ProviderCalls, ProviderRef, PublicGap, PublicMeta, PublicProfileMeta, PublicVerdict, PublicView, PublicVote, Quorum, QuorumEvent, QuorumMeta, QuorumOptions, QuorumResult, RelatedCode, RelatedCodeMeta, RelatedCodeOptions, RelatedCodeReader, RelatedDropped, RelatedExcerpt, RelatedHit, RelatedNone, RelatedStart, RelatedTotals, Removed, ReportFormat, ReportInput, ReportOptions, ReportView, ResearchRecord, ReviewInput, ReviewSource, RoleCalls, SecretRule, ServedModel, SkipRule, SourceRead, SourceSpec, StageName, Thresholds, Usage, Verdict, VerdictStatus, Vote, VoteFailure and VoteFailureKind; Adapts, ChatMessage, CompletionRequest, CompletionResponse, EventSink, JsonSchema, ProfilePorts, Provider, QuorumPorts, ReplyStore, StoredCall and StreamSignal; ConfigIssue, NoAnswer, ProviderErrorKind and ReplyLack; ProfileBudgets, ReplyFacts and ThinkingLevel; PolicyRules and Rule; AnthropicOptions, Auth, ClaudeCodeAuth, ClaudeCodeOptions, GeminiOptions, HttpProviderOptions, OllamaOptions, OpenAICompatibleOptions, StructuredOutput and SystemPrompt; Preset, PresetName and Protocol; ConfigInput, QuorumConfig and QuorumConfigFile; Env, FailOnOverride, ProfileSelection, ResolvedConfig, ResolvedProfile and ResolvedProvider. HttpProviderOptions holds the options an HTTP provider takes, OpenAICompatibleOptions adds maxTokensField, and AnthropicOptions, GeminiOptions and OllamaOptions are HttpProviderOptions as it is: Providers. ClaudeCodeOptions holds the options of claudeCode and ClaudeCodeAuth its three auth modes. Preset types a row of presets, PresetName names one, and Protocol names the four wire protocols.
The stages and the profile checks are not exported: a program reaches the stages through createQuorum. The exit-code rule is outcome.
runQuorum
declare function runQuorum(diff: string, onProgress?: (message: string) => void): Promise<QuorumResult>Deprecated: use loadConfig and fromConfig. runQuorum reviews diff as the CLI does with no flag: it calls loadConfig() and fromConfig on the result, so it reads the file QUORUM_CONFIG names, if any, which must be an absolute path, and the QUORUM_* variables of process.env with their RESEARCH_* and VOTER_* aliases, and it runs the profiles they select, the security profile alone by default: Configuration. It gives the review the config's send, so a file that list names is sent though held as a secret, and it takes no send of its own. onProgress receives the CLI's progress lines, the left out: and flag: lines included, each one inert and each profile's line starting with [<id>] when several run, but neither the banner, nor a warning, nor empty diff: nothing to review, which the CLI writes itself. A configuration error, a missing model included, rejects with a ConfigError, for an empty diff too. It passes no context, so a config that lists a { repository } entry is refused before any call, at the entry, with reads a document of the repository, which runQuorum cannot read: build the quorum with fromConfig and pass readContext's context to review. A diff names no commit to read related code at, so a config that turns relatedCode on is reviewed without it: the result records meta.relatedCode as off, and onProgress receives the warning that says so. To review a source that names one, build the quorum with fromConfig, open the reader with openRelatedCode and pass it to review.
A complete example
review.mts, in a project that has the package installed: the finder on a local model, the panel on a hosted one, a line on stderr per verdict and per gap and the result on stdout, both inert, a ten-minute limit, and the CLI's exit codes.
import { readFile } from 'node:fs/promises'
import { ConfigError, createQuorum, inertJson, inertLine, ollama, openaiCompatible, outcome, securityProfile } from '@tobi-or-not/quorum'
import type { QuorumEvent } from '@tobi-or-not/quorum'
const USAGE = 'Usage: node ./review.mts <diff-file>'
function progress(event: QuorumEvent): void {
if (event.type === 'verdict') console.error(inertLine(`${event.findingId}: ${event.keptVotes}/${event.totalVotes} ${event.status}`))
if (event.type === 'incomplete') console.error(inertLine(`incomplete: ${event.entry.reason} (${event.entry.detail})`))
}
/** The `Error:` line of a failure, inert: its message can hold text a server sent, and a value with no text form gets a fixed one. */
function errorLine(error: unknown): string {
let message: string
try {
message = error instanceof Error
? error.message
: String(error)
} catch {
message = 'an error with no text form'
}
return inertLine(`Error: ${message}`)
}
/** Review the diff file at `path`, with the CLI's exit codes: 2 for usage or configuration, 3 for a review that failed. */
async function main(path: string | undefined): Promise<number> {
let diff: string
try {
if (path === undefined) throw new Error('no diff file given')
diff = await readFile(path, 'utf8')
} catch (error) {
console.error(errorLine(error))
console.error(USAGE)
return 2
}
try {
const finder = ollama({
id: 'local',
baseUrl: 'http://localhost:11434',
model: 'qwen3.6:27b',
contextTokens: 131072
})
const panel = openaiCompatible({
id: 'hosted',
baseUrl: 'https://api.openai.com/v1',
model: 'gpt-6-astra',
contextTokens: 400000,
apiKey: process.env.OPENAI_API_KEY?.trim() || undefined,
temperature: null,
maxTokensField: 'max_completion_tokens'
})
const voters = Object.fromEntries(securityProfile.lenses.map(lens => [lens.id, panel]))
const quorum = createQuorum({
profiles: [securityProfile]
}, {
profiles: {
security: { research: finder, voters }
},
events: progress
})
const result = await quorum.review({ diff }, {
signal: AbortSignal.timeout(10 * 60_000)
})
console.log(inertJson(result))
return outcome(result).exitCode
} catch (error) {
console.error(errorLine(error))
return error instanceof ConfigError
? 2
: 3
}
}
process.exitCode = await main(process.argv[2])OPENAI_API_KEY=sk-... node ./review.mts ./my.diff > result.jsonIt exits as the CLI does: 0, 1 or 4 by outcome of the result; 2 when no file is given, the file cannot be read, or a setting is invalid, such as a key with a space inside it once trimmed; and 3 when the review fails, its ten-minute limit included.
Related
- Providers — the provider port, the shipped adapters and writing a provider.
- Profiles — writing a profile, and running several in one review.
- The JSON result — every field
reviewresolves with. - Architecture — the modules behind this API, and the stages of a review.
