diff --git a/AGENTS.md b/AGENTS.md index 09509033..65f06dc7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,10 +21,10 @@ Do not edit `CONTRIBUTING.md`, `assets/CONTEXT.md`, `assets/AGENTS.md`, or shims, or cleanup of what earlier versions wrote. - Starting or spawning quests stops at PR creation. It merges only on a /quest-merge pick: the user's, the one /quest-plan's interview gives its own - PR, or the standing one /quest-run gives a PR with no user-facing behavior - change that adds or expands no quests, or a trivial PR such as a dependency - bump once Pullfrog approves its head; and only after repository checks and - reviews pass. + PR, or the standing one /quest-run gives a low-risk PR in a class + `RISK.md` lists under `## Automatic` that adds or expands no quests, or a + trivial PR such as a dependency bump once Pullfrog approves its head; and + only after repository checks and reviews pass. - A change to the reviewers in `src/cli/models.ts`, the review prompts in `src/cli/review.ts`, or a `REVIEW.md` runs `quest eval run` with the base's build and the head's, and puts both scores and their cost in its PR's diff --git a/README.md b/README.md index 1622fbf8..9fe817f5 100644 --- a/README.md +++ b/README.md @@ -550,6 +550,7 @@ merge-state dirty review-decision - review-record diff-identical 5f1c2e9a8b7d6c5e4f3a2b1c0d9e8f7a6b5c4d3e risk medium diff-identical low It changes when quest gate admits a command. +class - auto-merge - merge-queue - landing-stopped - @@ -569,6 +570,7 @@ comes last, and a missing value prints as `-`: | `mergeable`, `merge-state`, `review-decision` | GitHub's values, lowercased. | | `review-record` | Whether the PR body's [`## Review` record](#review-locally) still covers the head, and the head it names last: `current` when it is the head, `diff-identical` when `git diff ...` prints the same as for it, `stale` otherwise, or `unknown` when GitHub cannot compare them, such as a diff too large; `-` when the record names no full SHA. Whose record counts is the reader's call. | | `risk` | The record's [risk tier](#risk-tiers), `low`, `medium`, or `high`; the same state as `review-record` for the head it names; the tier its classifier set before any reviewer raised it; and the reason. `-` when the record names none. | +| `class` | The `## Automatic` class of the base's `RISK.md` the record's classifier found the change in, or `-`. | | `auto-merge` | Method, who enabled it, when, and the head it was enabled on. | | `merge-queue` | Queue state, position, and when it was enqueued. | | `landing-stopped` | The reason the latest merge-queue entry, auto-merge, or [`quest land`](#the-watchers-own-queue) queue entry ended (such as `merge_conflict`, `failed_checks`, `manual`, `manually_disabled`, or `merged`), who ended it, and when; `-` once the PR has entered the merge queue or auto-merge again since. | @@ -1697,36 +1699,58 @@ own retries, which also counts as the limit there. Each head also gets a risk tier, `low`, `medium`, or `high`: what could break, for whom, and how hard it is to undo, set from the change and never from who -wrote it. Nothing acts on the tier yet; `quest status` and `quest usage` report -it. +wrote it. The tier scales the PR's guardrails: + +| Tier | Local review | CI | Lands on | +|---|---|---|---| +| Low | None; the online reviewer only | The checks its diff reaches | Its own, once its class is in `RISK.md`'s `## Automatic` list; else the maintainer's pick | +| Medium | The size's pick | The checks its diff reaches | The maintainer's pick | +| High | The size's pick and a second reviewer on another model | The full suite [`quest suite`](#run-the-full-suite) names | The maintainer's pick, with the full brief | + +`/quest-run` carries the picks. A change is `high`, with no model, when a changed path on either side of a rename matches a pattern held high: `RISK.md` itself, everything under `.github/workflows/` and `.github/actions/`, and each pattern in the `## High` list of the base's `RISK.md`, at the repository's root: -```markdown +````markdown # Risk Customers run the relay and the player; the CLI is for contributors. +## Automatic + +- `tests` - only tests and their fixtures change + ## High - `src/billing/` - charges customers, and refunds are manual - `**/*.proto` - peers on older releases read the wire format + +## Full suite + +```sh +just gate --all ``` +```` Each item is a backticked path from the root, where `*` and `?` stay within one segment, a whole `**` segment spans any number, and a matched directory covers everything under it, then ` - ` and why changing it is high. The rest of the -file is prose for the classifier, such as what is customer-facing. `quest +file is prose for the classifier, such as what is customer-facing, except +`## Automatic`, whose items are each a backticked class name of lowercase +words joined by hyphens, ` - `, and the rule over the diff a change meets to +fall in it, and `## Full suite`, one fenced block holding the command that +runs the whole test suite. Each section appears at most once. `quest review` reads the file from the base's tip, so a change cannot lower its own tier, and fails on one it cannot read, which the repository's own `quest check` reports first. A base with no `RISK.md` makes every change no path holds high `medium`. Otherwise a classifier reads the diff and the base's `RISK.md` in one read-only -turn and replies with a tier and one sentence on why: Claude Code +turn and replies with a tier, one sentence on why, and the `## Automatic` +class every changed file falls in, or none: Claude Code `claude-haiku-5-5` at low effort, or Codex `gpt-6.1-sol` at low when Claude Code is missing, logged out, has its login rejected, or hit its usage limit. When neither can run, the review fails on the limit that resets first if both @@ -1744,7 +1768,38 @@ the reason of the first to judge it so. The record names it after the base: `Classified:` names `the always-high paths` or `default` when no model set the tier, and a reviewer that raised it adds `- Raised the risk to high: ` -to its block. +to its block. A `- Class:` line follows when the classifier named a class. + +A low head with no finding left to settle runs no local reviewer, unless +`--harness`, `--model`, or `--effort` names one: the record names the head in +full, adds `- Local review: none, since a low-risk head needs only the online +reviewer`, and `next done` says so. A high head also gets a second reviewer: +the first of the size's list on a model other than the pick's that can run, +marked `second`, in a session of its own that reviews every head while the +tier is high and settles its findings after. `--model` and `--effort` change +only the pick, so the second reviewer still runs; the one reviewer `--harness` +names runs alone, with none. A round that raises the tier to +high saves its rounds and runs the second reviewer at once; when that review +fails, as when none can run, it prints those rounds before the error, so their +findings can be answered. When every other model is avoided, as +with no `## Models` record under a harness the list has one model of, the run +fails as a usage error; when they cannot run, as an outage. + +`--override --reason ` records the maintainer's tier for the +branch in place of the reviewed one, as `- Risk: , ` and +`- Overridden: from by the maintainer`. It holds across heads until +the reviewed tier grows riskier than the one overridden, and `quest usage` +counts overrides as a reading of the tier's accuracy. + +### Run the full suite + +`quest suite ` prints the base's `## Full suite` command when the PR's +head needs it: its record names it high, or names no tier that covers the +head. It prints nothing otherwise, so a repository's gate runs the command it +prints beside its scoped checks. The tier is the PR body's, which its author +writes, so a gate runs the full suite itself for an author without write +access. `--base` names the branch whose `RISK.md` it reads, fetched first, +by default origin's default branch. ### Score the reviewer @@ -1867,8 +1922,12 @@ the record names, or its sub-agent, goes to that reviewer. Spend still left fitting several, such as a routed and a shadow reviewer at one effort whose sessions no record names, is split evenly among them and reported as `split`. Each risk tier's PRs, how many merged, -how many a reviewer raised, and how many a later PR's `## Caused by` names -show whether the tiers predict what breaks. Each breakage a merged PR in the +how many a reviewer raised, how many the maintainer overrode, how many a later +PR's `## Caused by` names, and how long they waited on a person show whether +the tiers predict what breaks and what each costs. Each `## Automatic` class +the classifiers named gets the same numbers, and how many of its PRs were low, +to argue for or against merging the class without a pick. A local reviewer +row marked `second` shows what the high tier's second review catches. Each breakage a merged PR in the window names under `## Caused by` follows on its own line, by culprit, even one older than the window, which is read from GitHub: the culprit's tier, size, writers, and local reviewers, who found it and the incident it closes when diff --git a/RISK.md b/RISK.md index a6ffbb70..5fc10d49 100644 --- a/RISK.md +++ b/RISK.md @@ -48,6 +48,21 @@ alone, or a routine dependency or pin bump. Tests, plans under `quest/`, and documentation change nothing others rely on, so they are low. +## Automatic + +A low PR whose author has write access lands without the maintainer's pick +when its whole diff falls in one class below. Only a PR the maintainer +picks changes this list, proposed with `quest usage`'s numbers for the +class: its PRs merged, the culprits among them, and their wait on a person. + +- `tests` - only tests, their fixtures, or benchmarks change +- `internal-docs` - only comments, plans under `quest/`, or documentation + no user, contributor, or other repository reads change +- `refactor` - code changes that keep every behavior and output the same, + such as a rename inside a module or a simplification +- `trivial` - a dependency or pin bump, or another change as small, from + any author, which lands at any tier once Pullfrog approves its head + ## High - `assets/CONTEXT.md` - every agent session in every repository using diff --git a/assets/skills/merge.md b/assets/skills/merge.md index e4e38e08..be236c08 100644 --- a/assets/skills/merge.md +++ b/assets/skills/merge.md @@ -31,6 +31,7 @@ Otherwise, the changes since the reviewed head need no new review only when they The repository's review policy decides whose record counts and may require more, such as a maintainer's review. Where it says nothing, only a record on a PR whose author has write access counts: anyone else writes their own PR body, so their head needs a local review that rewrites the record. On a trivial PR that `/quest-run`'s standing pick covers, Pullfrog's approval of the head stands in for that record unless that policy requires more. +A low head's record counts without a local reviewer; a later head's rise in tier ends the pick: tell the user. Queue the head with `quest merge --land `, adding `--squash` or `--rebase` when the repository's root instructions name that method for the PR's base. Run a `quest` the PR cannot modify, such as an installed release rather than a build from the head's checkout: it refuses a head that leaves its quest inaccurate, a check the head's own code could skip. diff --git a/assets/skills/review.md b/assets/skills/review.md index 68963fde..9d391994 100644 --- a/assets/skills/review.md +++ b/assets/skills/review.md @@ -29,6 +29,9 @@ Pass `--exclude-model` or `--size` only for a PR whose body cannot hold the reco Where the repository's root instructions name other reviewers, pass them with `--harness`, `--model`, and `--effort`, which runs that reviewer alone. Each round rewrites the PR body's `## Review` section, so add context only after it, and write a round's record by hand only when it printed `record skipped`. +`quest review` sets the head's risk tier before any reviewer runs: a low head gets no local reviewer, only a record saying so, and a high one gets a second reviewer on another model, which a round that raises the tier runs at once. +When the user overrides the tier, pass it with `--override --reason `. + Each round ends with a `next` line: follow it until a round of the head reports no finding you have not refuted; never block on the score. Fix in the PR every review finding relevant to it that you do not refute and every gap the change exposes; in other code you read, fix easy findings and suggest the rest as follow-ups. Refute a finding only with evidence the reviewer cannot rebut: a `path:line`, a command's output, or a recorded maintainer decision. diff --git a/assets/skills/run.md b/assets/skills/run.md index cf7e6404..7814e61b 100644 --- a/assets/skills/run.md +++ b/assets/skills/run.md @@ -43,10 +43,10 @@ A PR with open decisions, its `## Waiting` section's or an issue you would solve A PR you would skip or delete rather than fix, such as a superseded one, gets that question instead. Leave a PR whose required checks are still running for a later round; an automated reviewer is not waited on, since the queue waits for an approval the base requires. -A PR whose author has write access and that changes no user-facing behavior carries a standing `/quest-merge` pick, unless the repository's `CONTRIBUTING.md` opts out: run `/quest-merge` on it without asking, and name it as auto-picked in the summary. -That covers only tests, benchmarks, CI, internal docs or comments, and behavior-preserving code. Anything users or other repositories get, such as CLI behavior or output, shipped skills or rules, user-facing docs, dependencies, or release artifacts, needs the user's pick, as does adding or expanding quests. -A trivial PR, such as a dependency bump, carries it too whatever its author, under the same opt-out, but merges only once Pullfrog has approved its head; in a repository without Pullfrog, it needs the user's pick. -Judge the diff, not the title, before every `/quest-merge` run, and ask when unsure: the standing pick ends at the first head that does not qualify, or once a person takes the PR out of the queue. +A PR whose author has write access carries a standing `/quest-merge` pick, unless the repository's `CONTRIBUTING.md` opts out, when `quest status` shows it low for the head, in a class the base `RISK.md` lists under `## Automatic`, adding or expanding no quests: run `/quest-merge` on it without asking, and name it as auto-picked in the summary. +A trivial PR, such as a dependency bump, carries it too whatever its author and tier, under the same opt-out, but merges only once Pullfrog has approved its head; in a repository without Pullfrog, it needs the user's pick. +Judge the diff against the class's rule before every `/quest-merge` run, and ask when unsure: the standing pick ends at the first head that does not qualify, or once a person takes the PR out of the queue. +Ask about a high PR with both reviews and the full suite's result. Ask about every other PR in a question of its own that summarizes it and picks only the action, with `/quest-merge`'s pick options; none covers several PRs. Ask about each of its follow-ups in a question of its own beside it, as the guide's Creation section describes; the answers count only on a `/quest-merge` pick, and go in the brief of the `/quest-iterate` it dispatches. diff --git a/quest/m0/afk-and-waits.md b/quest/m0/afk-and-waits.md index 8956abb5..ec23199b 100644 --- a/quest/m0/afk-and-waits.md +++ b/quest/m0/afk-and-waits.md @@ -4,11 +4,11 @@ Reduce repeated manual prompts during interactive, mobile/travel, and AFK sessions across three coordinated improvements: -1. **`/quest-afk` modes (`assets/skills/afk.md`):** Keep bare `afk` conservative (standing picks only, deferring other merges until [risk-tier guardrails](/quest/m0/benchmark/guardrails.md) earn wider auto-merge), and add two explicit modes: `afk merge` (merge any non-high-risk PR the agent strongly recommends with a clean review and no open decisions, still deferring high-risk or uncertain PRs and quest deletions) and `afk soon` (flush pending decisions in one batch, then automatically enter `afk`). +1. **`/quest-afk` modes (`assets/skills/afk.md`):** Keep bare `afk` conservative (standing picks only, deferring other merges until classes in [`RISK.md`](/RISK.md)'s `## Automatic` list earn wider auto-merge), and add two explicit modes: `afk merge` (merge any non-high-risk PR the agent strongly recommends with a clean review and no open decisions, still deferring high-risk or uncertain PRs and quest deletions) and `afk soon` (flush pending decisions in one batch, then automatically enter `afk`). 2. **PC-local vs tap-anywhere waits (`src/core/waiting.ts`, `quest waiting`, `quest check`, `assets/AGENTS.md`, `assets/skills/run.md`):** Distinguish local/PC maintainer actions (such as password-manager unlocks, hardware checks, or local logins) from decisions answerable from any device, with filtering on `quest waiting` so remote/travel sessions skip PC-local waits and `"at my PC"` sessions batch them. 3. **Pending-CI waiting in `/quest-run` (`assets/skills/run.md`):** When no sub-agent is running and every current question is asked, also block with `quest wait` on open PRs whose required checks are still pending (in addition to queued PRs whose merge unblocks a quest) so those PRs get picked in the same session instead of ending early. -Non-goal: changing risk-tier definitions or automatic low-risk merge classes on bare `afk` (owned by [Scale review, CI, and approval to a PR's risk tier](/quest/m0/benchmark/guardrails.md)). +Non-goal: changing risk-tier definitions or automatic low-risk merge classes on bare `afk` (set by [`RISK.md`](/RISK.md) and the README's Risk tiers section since [moq-dev/quest#802](https://github.com/moq-dev/quest/pull/802)). ## Plan @@ -42,4 +42,4 @@ Agent's choices, for the implementer to revisit: ## Related -- [Scale review, CI, and approval to a PR's risk tier](/quest/m0/benchmark/guardrails.md) - risk tiers define the `high` boundary `afk merge` defers and will widen standing auto-merge separately +- [`RISK.md`](/RISK.md) and the README's Risk tiers section, since [moq-dev/quest#802](https://github.com/moq-dev/quest/pull/802) - risk tiers define the `high` boundary `afk merge` defers and will widen standing auto-merge separately diff --git a/quest/m0/benchmark/README.md b/quest/m0/benchmark/README.md index b738e761..92db762d 100644 --- a/quest/m0/benchmark/README.md +++ b/quest/m0/benchmark/README.md @@ -1,4 +1,4 @@ -# Development as a benchmark +# [M] Development as a benchmark ## Goal @@ -7,7 +7,7 @@ benchmark with several axes. Every change records its risk tier, what it cost (tokens, compute, and time split into working and blocked on CI, GitHub, git, or a person), who wrote and reviewed it, and what it later broke. The tier, set from the change itself, scales its guardrails: review -depth, CI, human approval, and a stated way to undo it. The maintainer +depth, CI, and human approval. The maintainer steers from a report of all of it without reading code, and adds or removes guardrails from that evidence. Every cost is measured so it can be driven toward zero. @@ -67,9 +67,13 @@ maintainer's typed messages since 2026-10-01): Rejected: set at planning and re-judged from the diff; a separate score per axis. - What does the tier scale? - - ✅ Review, approval, and CI, as - [tier guardrails](/quest/m0/benchmark/guardrails.md) lists + - ✅ Review, approval, and CI, as `RISK.md` and the README's Risk tiers + section describe since + [moq-dev/quest#802](https://github.com/moq-dev/quest/pull/802) - Rejected: review and approval only; approval only +- Must a PR state how to undo it? ✅ No (maintainer, 2026-11-22: "I + definitely don't want Undo to be a gate"). Rejected: an `## Undo` + section that `quest merge` requires of every PR not tiered low. - Who moves a class of change into or out of automatic merging? - ✅ The maintainer, both ways: the report flags a class whose breakage rose, and it keeps merging until they act @@ -82,12 +86,11 @@ maintainer's typed messages since 2026-10-01): What the posts add that these quests take: a tier set from the change and not its author, paths that always need a person, evidence and a brief -read in place of the diff, a stated way to undo each change, automatic -merging widened one class at a time on breakage data, and past incidents -kept as a reviewer's test set. Already in place: a different model -reviews each PR, every finding is answered before merge, a design -checkpoint after repeated review rounds, a merge queue, and diff-scoped -gates in moq-dev/moq and moq-dev/moq.pro. +read in place of the diff, automatic merging widened one class at a time +on breakage data, and past incidents kept as a reviewer's test set. +Already in place: a different model reviews each PR, every finding is +answered before merge, a design checkpoint after repeated review rounds, +a merge queue, and diff-scoped gates in moq-dev/moq and moq-dev/moq.pro. No post describes attributing cost, model, and effort to each change, so that part has no precedent to copy. diff --git a/quest/m0/benchmark/guardrails.md b/quest/m0/benchmark/guardrails.md deleted file mode 100644 index d06879d1..00000000 --- a/quest/m0/benchmark/guardrails.md +++ /dev/null @@ -1,111 +0,0 @@ -# [L] Scale review, CI, and approval to a PR's risk tier - -## Goal - -A PR's guardrails follow its risk tier: - -| Tier | Review | CI | Lands on | -|---|---|---|---| -| Low | The online reviewer only | The checks its diff reaches | Its own, once its class of change is on the repository's list; else the maintainer's pick | -| Medium | A local review by a model other than its writer | The checks its diff reaches | The maintainer's pick | -| High | Two independent local reviews, on the strongest reviewers | The repository's full suite | The maintainer's pick, with the full brief | - -A medium or high PR states how to undo it in its body, and `quest merge` -refuses one that does not. The tier replaces `/quest-run`'s standing pick: -the classes that merge on their own are a list in the repository's risk -file, starting with what the standing pick covers today, and only a PR the -maintainer picks changes that list. Automatic merging stays limited to -authors with write access, and to the trivial PRs of any author, such as -dependency bumps, that the standing pick covers once Pullfrog approves -their head. - -Each guardrail's cost and catches reach the PR's records: what each review -found, what the full suite failed that the scoped checks passed, and how -long the PR waited on a person. The report can then show a guardrail that -catches nothing, so the maintainer can remove it. - -## Plan - -Decided 2026-11-13 (user, /quest-plan): - -- What does the tier scale? ✅ Review, approval, and CI (rejected: review - and approval only, keeping CI scoped at every tier; approval only). -- How do low-risk PRs land? ✅ Earned from evidence, starting with the - standing pick's classes (rejected: every low PR from day one; every - merge a tap). -- Who moves a class? ✅ The maintainer, both ways. The report flags a class - whose breakage rose and it keeps merging until they act. Rejected: a - breaker that tightens on its own; automatic both ways. -- Customer-facing changes get "rollbacks and higher quality" (user): the - high tier's stated undo and second review. - -Decided 2026-11-15 (user, /quest-run, moq-dev/quest#738): trivial PRs -merge on their own, so the starting list holds that class too. - -- Which PRs? ✅ Any trivial PR, such as a dependency bump, whatever its - author, judged by its diff (rejected: only Dependabot's and Renovate's - patch or lockfile-only bumps whose every commit is the bot's). -- What review? ✅ Pullfrog's approval of the head, in place of the local - review an author without write access needs (rejected: a local - `quest review`; no review). - -Evidence from the 2026-11-18 [mistake audit](/quest/m0/mistake-audit.md) -run: of 234 merge-pick answers from 2026-11-11 to 11-19, across the -three repositories and the maintainer's hosts, 220 (94%) picked the PR the -agent recommended. Follow-up keep-or-drop answers picked it 79% of the -time, and other questions 73%. That supports widening the list once the -tiers are trusted, not merging every pick on its own. Decided 2026-11-19 -(maintainer, merge pick of -[moq-dev/quest#786](https://github.com/moq-dev/quest/pull/786)): ✅ keep -this evidence here (rejected: drop). - -Decided 2026-11-21 (maintainer, /quest-run): a week of recorded tiers did -not match their sense of risk, since high took 55% of PRs and nearly every -code PR. [moq-dev/quest#794](https://github.com/moq-dev/quest/pull/794) -narrowed high in `RISK.md` to breaking changes to exports, records, or -output, new remote writes, uploads, or spending, merge authority, -credentials, and the held paths. Re-tiered, the week's 56 tiered PRs went -from 32 high to 22, with no low PR moving. - -This quest edits the shipped skills and rules, which the maintainer asked -for by planning it. - -Agent's choices, for the implementer to revisit: - -- `quest` cannot run a repository's CI. Expose the tier to the gate, and - let the risk file name the full-suite command, so moq-dev/moq's - `just gate` and moq-dev/moq.pro's nightly tier run for a high PR and the - scoped checks for the rest. -- Size keeps picking the review effort within a tier. High adds a second - reviewer on a different model from the first; the routing table gains - that column. -- A class is a named rule over the diff in the risk file, such as "only - test files". A PR lands on its own only when it is low and every changed - file falls in a listed class. -- The undo line says which of revert, flag, or redeploy applies and what - it leaves behind, such as a migration. Low PRs are undone by a revert - and need no line. -- A widening is proposed with its class's numbers: PRs merged, culprits - among them, and what a tap cost in waiting time. -- Tell the maintainer when a tier rises on a later head of a PR they - already picked; the pick ends there, as the standing pick's does. A - tier that rises reopens whatever the lower tier skipped. -- The maintainer can override a tier, recorded with its reason, and the - report counts how often they do as a reading of the tier's accuracy. - [#716](https://github.com/moq-dev/quest/pull/716), which set the tier, - left this here, since nothing reads an override until the tier gates - something. - -Open question for the maintainer, asked before the list is written: the -standing pick covers CI changes today, but the post requires a person for -"any CI workflow file", and `quest review` holds workflow files always -high. Recommended: keep them high, which takes CI changes out of -automatic merging. That would also take out a trivial bump of a GitHub -Action, which edits a workflow file: recommended to keep that class -automatic, since the actions are pinned by SHA, Dependabot waits out a -cooldown, and Pullfrog approves the head. - -## Related - -- [Routing evidence](/quest/m0/routing-evidence/README.md) - its shadow - reviewer measures what a deeper review buys diff --git a/quest/m0/routing-evidence/README.md b/quest/m0/routing-evidence/README.md index 1d96bfca..4c66906c 100644 --- a/quest/m0/routing-evidence/README.md +++ b/quest/m0/routing-evidence/README.md @@ -120,7 +120,8 @@ three hosts' saved review rounds: routed pick at S and M, to measure whether raising them pays, and one below at L until L reaches its sample (rejected: unchanged until 12-20, then end it; end it now; a permanent second reviewer at L and - XL, left to [the guardrails](/quest/m0/benchmark/guardrails.md)). XL + XL, left to the risk tiers, whose high tier seats a second reviewer + since [moq-dev/quest#802](https://github.com/moq-dev/quest/pull/802)). XL keeps its step down with L. Compare the step up's pairs as the step down's were, counting only rounds after the retarget merged. - Writer A/B, PRs per arm, first-round findings over the PRs counted in diff --git a/src/cli/main.ts b/src/cli/main.ts index 190e2b5c..ce38c069 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -21,6 +21,8 @@ import { parseRiskFile, questBranch, RISK_FILE, + TIERS, + type Tier, renderBlocker, FINDERS, type Finder, @@ -90,6 +92,7 @@ import { review, nextStep, roundLines, + savedReview, } from "./review"; import { EVAL_FILE, addCase, evalLines, evaluate } from "./review-eval"; import { type Recorded, pullModels, recordRounds } from "./review-record"; @@ -115,6 +118,7 @@ import { KIXEL_QUEST_URL, kixelUrl, tokensPath } from "./tokens"; import { CONTEXT, GUIDE, GUIDE_SECTIONS, SKILLS, guideSections, sectionHeading, skill } from "./skills"; import { type Terminal, Theme } from "./theme"; import { type Snapshot, checkout, collect, load, snapshot, under } from "./tree"; +import { baseRiskFile, suiteFor } from "./suite"; import { pullFileLines, statusLines, viewLines } from "./status"; import { TOKEN_MAX_MISSING, daysBefore, runTokenMax, usage, usageDependencies, usageLines } from "./usage"; import { waitForActivity, WaitTimeout } from "./wait"; @@ -665,12 +669,12 @@ export function main(argv: string[], out: Output): number | Promise { "Print a pull request's head, checks, merge state, reviews, reactions, and unresolved review threads " + "in one call. It reports facts; it does not decide whether the PR is ready or whose review counts.\n\n" + "Plain output prints one record per line, its type first and any free text (a check name or path) last: " + - "url, state, draft, head, mergeable, merge-state, review-decision, review-record, risk, auto-merge, merge-queue, " + + "url, state, draft, head, mergeable, merge-state, review-decision, review-record, risk, class, auto-merge, merge-queue, " + "landing-stopped, and checks, whose state and counts follow the checks that count, pending while an open PR's base requires a check or workflow nothing reports; review-record gives whether the PR body's ## Review record " + "covers the head, as current, diff-identical (git diff ... prints the same as for the head it names), " + "stale, or unknown when GitHub cannot compare them, then the head it names last; risk gives the record's risk " + "tier, the same state for its head, the tier its classifier set before any reviewer raised it, and the " + - "reason last, or - when the record names none; auto-merge gives its method, who enabled it and when, and the head it was " + + "reason last, or - when the record names none; class gives the RISK.md ## Automatic class the record's classifier named, or -; auto-merge gives its method, who enabled it and when, and the head it was " + "enabled on, which differs from head once a push follows, as GitHub keeps auto-merge across a writer's " + "push (- when it cannot be told: a quest land pin names it, and otherwise the head branch's push " + "activity, which GitHub lists up to minutes late); landing-stopped is the latest exit from the merge queue, auto-merge, or " + @@ -713,6 +717,42 @@ export function main(argv: string[], out: Output): number | Promise { ); }); + program + .command("suite") + .summary("Print the full-suite command a PR's risk tier calls for") + .description( + "Print the command in the ## Full suite section of the base's RISK.md when the PR's head needs the " + + "repository's whole test suite beyond the checks its diff reaches: its ## Review record names it high " + + "risk, or names no tier that covers the head, as when it is missing, stale, or cannot be compared. " + + "Prints nothing for a low or medium head, or when RISK.md names no full suite, so a repository's gate " + + "runs `cmd=$(quest suite )` and then the command when one printed. The tier is the PR body's, which " + + "its author writes, so a gate gives a PR from an author without write access the full suite itself. " + + "RISK.md is read from --base, fetched first, by default origin's default branch.\n\n" + + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. " + + FORGE_READS.replace("these reads", "the read") + + "Exits 0 whatever it prints, 2 for invalid arguments, and 1 for other failures, such as a RISK.md it " + + "cannot read.", + ) + .argument("", PR_ARGUMENT) + .option("--base ", "Base branch whose RISK.md to read (default: origin's default branch)") + .action((value: string, options: { base?: string }) => { + const { pull: pr, hosted } = locatePull(value, root(), process.env); + pending = Promise.all([ + forgeFor(pr, forgeDependencies(), Infinity, hosted).then((forge) => forge.status(pr)), + baseRiskFile(root(), options.base), + ]).then( + ([{ value: status }, file]) => { + const command = suiteFor(status.risk, file); + if (command !== null) print(command); + return 0; + }, + (error: unknown) => { + warn(error instanceof Error ? error.message : String(error)); + return 1; + }, + ); + }); + const OWNERSHIP = "Before a session pushes to an existing PR, it takes the PR with iterate, and hands it back with " + "release. A taken PR carries the quest:active label; iterate prints a hold token, the ID of the timeline " + @@ -1426,8 +1466,8 @@ export function main(argv: string[], out: Output): number | Promise { "review thread it opens or a [P] line in its review body, and its first answer's first word takes or " + "declines it. Rollups follow: spend by size, role, harness, model, and " + "effort, accuracy by size and implementer, summing each branch's tallies but the shadow's once, where an Implementer line's own size, as (iterate, XS), wins " + - "over the PR's, with its writing cost over the merged PRs it was found on, the writer A/B by size and arm, counting a sized PR whose every Implementer line names the same arm, as (arm B), under its first line's writer with the spend of every session on it, local reviewers by size, harness, model, effort, and shadow, with their " + - "tallies and reviewing cost per PR, each risk tier's PRs, merged PRs, tiers a reviewer raised, and PRs a later one fixed, each online reviewer's coverage and findings over the merged PRs, and each breakage a merged PR in the window names under ## Caused by: its culprit's tier, size, writers, and local reviewers, read from GitHub when older than the window, who found it and the incident it closes when the line ends with (found by check|reviewer|queue|canary|person|customer; incident ), either part alone allowed, and how long after the culprit merged the fix opened. Without token-max on PATH, it says how to install it and reports the PRs' records alone. " + + "over the PR's, with its writing cost over the merged PRs it was found on, the writer A/B by size and arm, counting a sized PR whose every Implementer line names the same arm, as (arm B), under its first line's writer with the spend of every session on it, local reviewers by size, harness, model, effort, and shadow or second, with their " + + "tallies and reviewing cost per PR, each risk tier's PRs, merged PRs, tiers a reviewer raised, tiers the maintainer overrode, PRs a later one fixed, and time waited on a person, the same for each RISK.md ## Automatic class the classifiers named, with how many were low, each online reviewer's coverage and findings over the merged PRs, and each breakage a merged PR in the window names under ## Caused by: its culprit's tier, size, writers, and local reviewers, read from GitHub when older than the window, who found it and the incident it closes when the line ends with (found by check|reviewer|queue|canary|person|customer; incident ), either part alone allowed, and how long after the culprit merged the fix opened. Without token-max on PATH, it says how to install it and reports the PRs' records alone. " + "--json prints the same report as one object.\n\n" + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. Exits 0 when done, 2 for invalid arguments, and 1 for " + "other failures.", @@ -1614,7 +1654,14 @@ export function main(argv: string[], out: Output): number | Promise { ).join("; "); const classifiers = CLASSIFIERS.map((e) => `${e.harness} ${e.model} ${e.effort}`).join(", then "); /** quest review's exit code for `error`: 2 for a usage error, 3 when no reviewer could run, else 1. */ - const reviewFailure = (error: unknown): number => { + const reviewFailure = (error: unknown, json = false): number => { + // A failure after a raise saved the rounds that ran, so they print for their findings to be answered. + const reviewed = savedReview(error); + if (reviewed !== undefined) { + const { rounds, tallies, risk, skipped } = reviewed; + if (json) print(JSON.stringify({ rounds, tallies, risk, skipped, record: null, next: null })); + else for (const line of roundLines(reviewed)) print(line); + } const outage = error instanceof ReviewerUnavailableError || error instanceof ReviewOutageError; if (error instanceof ReviewInputError || outage) { out.stderr(`error: ${error.message}\n`); @@ -1702,24 +1749,34 @@ export function main(argv: string[], out: Output): number | Promise { "API rejects, or at its usage limit passes the turn to the next; when none is left, the run fails on the " + "limit that resets first if every one hit its own, else as a usage error naming why each failed. A later round on the same head and base " + "RISK.md reuses the tier unless --new. Each reviewer's reply judges the tier too, told the classified one, " + - "and can only raise it: the head's tier is the riskiest, with the reason of the first to judge it so.\n\n" + + "and can only raise it: the head's tier is the riskiest, with the reason of the first to judge it so. " + + "The classifier also names the class of RISK.md's ## Automatic list every changed file falls in, or none. " + + "The tier scales the review: a low head with no finding to settle runs no reviewer unless --harness, " + + "--model, or --effort names one, and a high head also gets a second reviewer: the first of the size's list " + + "on a model other than the pick's that can run, in its own session, which reviews every head while the " + + "tier is high and settles its findings after. --model and --effort change only the pick, so the second " + + "reviewer still runs; the one reviewer --harness names runs alone, with none. A round that raises the tier to high saves its rounds and " + + "runs it at once, printing those rounds before the error when that review fails, as when no second reviewer can run. " + + "--override and --reason record the maintainer's tier for the branch, which holds until the reviewed " + + "tier grows riskier than the one overridden.\n\n" + "Prints the size and where it came from, base, and head, its risk tier and reason, the classifier's tier, " + - "how it was set (model, paths, or default), and reason, and for a model a classifier line (harness, model, " + + "an overridden line with the tier the maintainer overrode, " + + "how it was set (model, paths, or default), and reason, a class line naming the class, and for a model a classifier line (harness, model, " + "effort, session) and its usage line, a skipped line (harness, model, effort, reason) for each reviewer passed over, then for each reviewer its harness, model, and " + - "effort, followed by shadow for the shadow, session, round, an " + + "effort, followed by shadow for the shadow or second for the second reviewer, session, round, an " + "unchanged line for a repeated round, a usage line per turn (input tokens, the " + "part read from the prompt cache, and output), a score from 0 to 10 for how ready the head is to land with " + "its one-sentence rationale, a raised line with the tier and reason when it raised the classifier's, the finding count, each finding by its number, then the last round's findings with " + "their numbers and dispositions; then the `record` line below and a last `next` line naming the author's next step: " + "`next finish` when every finding is low severity, to fix or refute them without another round, " + "`next checkpoint` when a reviewer's every third round reports other findings, to compare the current approach " + - "with the best long-term approach worked out from first principles before fixing them, `next respond` to fix or refute the findings, or `next done`. A reply without a valid score " + + "with the best long-term approach worked out from first principles before fixing them, `next respond` to fix or refute the findings, or `next done`, which for a low head no reviewer ran says so. A reply without a valid score " + "fails as any malformed reply does. --json prints " + "one object: `rounds`, one per reviewer, `tallies`, every reviewer's findings across the branch's rounds, `risk`, the head's tier with its classification, `skipped`, each reviewer passed over with its reason, `record`, and `next`.\n\n" + "After each round, it rewrites the `## Review` section of the branch's open PR into the base, the one from the repository the base's remote pushes to, else the only one from another repository whose pushed head `HEAD` contains, as the " + "user the GitHub token names, keeping the rest of the body, and prints `record `: the reviewed " + "head, named in full only once no reviewer reports a finding, the base, the head's risk tier and reason, " + - "the classifier's tier and who set it, a `- Skipped:` line for each reviewer passed over, and each reviewer, its Reviewer line ending in `, shadow` for the shadow, its " + + "an `- Overridden:` line, the classifier's tier and who set it, a `- Class:` line, a `- Local review: none` line for a low head no reviewer ran on, a `- Skipped:` line for each reviewer passed over, and each reviewer, its Reviewer line ending in `, shadow` for the shadow or `, second` for the second reviewer, its " + "session and round, score, the tier it raised the risk to and why, its tally of findings across the branch's rounds, and each finding with its disposition. With no " + "such PR, several from other repositories that `HEAD` contains, or a remote off GitHub, it prints `record skipped: ` and changes nothing.\n\n" + "Exits 0 once the round finishes, whatever it found, 2 for invalid arguments " + @@ -1762,11 +1819,20 @@ export function main(argv: string[], out: Output): number | Promise { "--branch ", "Branch whose review session to continue, instead of the checked-out one or its upstream", ) + .addOption( + new Option( + "--override ", + "The maintainer's tier for the branch, in place of the reviewed one until its change grows riskier", + ).choices(TIERS), + ) + .option("--reason ", "Why the maintainer overrode the tier, which --override requires") .option("--json", "Print one JSON object") .action( (options: { base?: string; branch?: string; + override?: Tier; + reason?: string; harness?: HarnessName; model?: string; effort?: string; @@ -1780,47 +1846,63 @@ export function main(argv: string[], out: Output): number | Promise { options.responses === undefined ? undefined : readFileSync(options.responses === "-" ? 0 : options.responses, "utf8"); + if ((options.override === undefined) !== (options.reason === undefined)) + throw new UsageError("--override and --reason go together"); + const reason = options.reason?.replace(/\s+/g, " ").trim(); + if (reason === "") throw new UsageError("--reason needs the maintainer's reason"); + const override = + options.override === undefined ? undefined : { tier: options.override, reason: reason! }; const github = claimDependencies(); const run = review( - { ...options, root: root(), exclude: options.excludeModel, responses, fresh: options.new }, + { + ...options, + root: root(), + exclude: options.excludeModel, + responses, + fresh: options.new, + override, + }, { ...reviewDependencies(), models: (dir, base, branch) => pullModels(dir, base, branch, github), }, ); - pending = run.then(async (reviewed) => { - const { rounds, tallies, risk, skipped } = reviewed; - // The rounds are saved in their sessions either way, so their report prints before a failed record. - let record: Recorded | undefined; - let failure: unknown; - try { - record = await recordRounds(root(), reviewed, github); - } catch (error) { - failure = error; - } - if (options.json) - print( - JSON.stringify({ - rounds, - tallies, - risk, - skipped, - record: record ?? null, - next: nextStep(rounds), - }), + pending = run.then( + async (reviewed) => { + const { rounds, tallies, risk, skipped } = reviewed; + // The rounds are saved in their sessions either way, so their report prints before a failed record. + let record: Recorded | undefined; + let failure: unknown; + try { + record = await recordRounds(root(), reviewed, github); + } catch (error) { + failure = error; + } + if (options.json) + print( + JSON.stringify({ + rounds, + tallies, + risk, + skipped, + record: record ?? null, + next: nextStep(rounds), + }), + ); + else { + for (const line of roundLines(reviewed)) print(line); + if (record !== undefined) + print("url" in record ? `record ${record.url}` : `record skipped: ${record.skipped}`); + print(nextStep(rounds)); + } + if (failure === undefined) return 0; + warn( + `the round finished, but recording it in the PR body failed: ${failure instanceof Error ? failure.message : String(failure)}`, ); - else { - for (const line of roundLines(reviewed)) print(line); - if (record !== undefined) - print("url" in record ? `record ${record.url}` : `record skipped: ${record.skipped}`); - print(nextStep(rounds)); - } - if (failure === undefined) return 0; - warn( - `the round finished, but recording it in the PR body failed: ${failure instanceof Error ? failure.message : String(failure)}`, - ); - return 1; - }, reviewFailure); + return 1; + }, + (error) => reviewFailure(error, options.json), + ); }, ); diff --git a/src/cli/review-record.ts b/src/cli/review-record.ts index fa187a7a..844bb312 100644 --- a/src/cli/review-record.ts +++ b/src/cli/review-record.ts @@ -37,9 +37,12 @@ function code(text: string): string { const capitalized = (word: string) => word[0]!.toUpperCase() + word.slice(1); -/** A block's Reviewer line, ending in `, shadow` for the shadow, the size's pick one effort away. */ -const reviewerLine = (seat: Pick) => - `- Reviewer: ${HARNESSES[seat.reviewer]}, ${seat.model}, ${seat.effort} effort${seat.shadow ? ", shadow" : ""}`; +/** + * A block's Reviewer line, ending in `, shadow` for the shadow, the size's pick one effort away, or `, second` for the + * second reviewer a high-risk head gets. + */ +const reviewerLine = (seat: Pick) => + `- Reviewer: ${HARNESSES[seat.reviewer]}, ${seat.model}, ${seat.effort} effort${seat.shadow ? ", shadow" : seat.second ? ", second" : ""}`; /** A tally's counts, as the record's `Rounds:` line and `quest usage` write them. */ export interface Counts { @@ -88,8 +91,7 @@ function classifiedBy({ by }: Risk["classified"]): string { * reviewer the run skipped since it could not run, then every tally on the branch, each round's reviewer's beside its * round, and a reviewer the run left out on its own. */ -export function reviewRecord({ rounds, tallies, risk, skipped }: Reviewed): string { - const [shared] = rounds; +export function reviewRecord({ rounds, tallies, risk, skipped, head, base }: Reviewed): string { // A reviewer the run left out may still hold open findings, which keep the head from passing too. const clean = rounds.every((round) => round.findings.length === 0) && tallies.every((tally) => counted(tally).open === 0); @@ -97,10 +99,13 @@ export function reviewRecord({ rounds, tallies, risk, skipped }: Reviewed): stri MARK, "", // `quest status` counts a full SHA here as a review of that head, which an open finding has not passed. - `- Head: ${clean ? shared!.head : `${shared!.head.slice(0, 12)}, named in full once no reviewer reports a finding`}`, - `- Base: ${shared!.base.ref} at ${shared!.base.sha.slice(0, 12)}`, + `- Head: ${clean ? head : `${head.slice(0, 12)}, named in full once no reviewer reports a finding`}`, + `- Base: ${base.ref} at ${base.sha.slice(0, 12)}`, `- Risk: ${risk.tier}, ${code(risk.reason)}`, + ...(risk.overridden ? [`- Overridden: from ${risk.overridden} by the maintainer`] : []), `- Classified: ${risk.classified.tier} by ${classifiedBy(risk.classified)}`, + ...(risk.classified.class === null ? [] : [`- Class: \`${risk.classified.class}\``]), + ...(rounds.length === 0 ? [`- Local review: none, since a low-risk head needs only the online reviewer`] : []), // Outside the Reviewer blocks, which `parseReview` reads as reviewers that ran. ...skipped.map( (skip) => `- Skipped: ${HARNESSES[skip.harness]}, ${skip.model}, ${skip.effort} effort: ${skip.reason}`, @@ -151,6 +156,8 @@ export interface ReviewSummary { effort: string; /** Whether it is the shadow: the size's pick one effort away, beside it on the same heads. */ shadow: boolean; + /** Whether it is the second reviewer a high-risk head gets, on a model other than the pick's. */ + second: boolean; /** Its latest session, null when the record names none; its round, null when the latest run left it out. */ session: string | null; round: number | null; @@ -209,7 +216,7 @@ export function parseReview(body: string): ReviewSummary[] { if (!found) throw new Error(`the ## Review record has no line matching ${pattern.source}`); return found; }; - const reviewer = match(/^- Reviewer: (.+?), (\S+), (\S+) effort(, shadow)?\r?$/m); + const reviewer = match(/^- Reviewer: (.+?), (\S+), (\S+) effort(?:(, shadow)|(, second))?\r?$/m); const tally = parseCounts(text); // A reviewer the latest run left out has its tally, and its session with no round once tallies name it. const session = @@ -229,6 +236,7 @@ export function parseReview(body: string): ReviewSummary[] { model: reviewer[2]!, effort: reviewer[3]!, shadow: reviewer[4] !== undefined, + second: reviewer[5] !== undefined, session: session && session[2]!, round: session?.[3] === undefined ? null : Number(session[3]), score: score ? Number(score[1]) : null, @@ -352,8 +360,7 @@ export async function pullModels( /** Record a run in the `## Review` section of its branch's open PR. The edit is the token's user's, which `/quest-merge` counts only when that user wrote the PR. */ export async function recordRounds(root: string, reviewed: Reviewed, deps: ClaimDependencies): Promise { - const [shared] = reviewed.rounds; - const pull = await openPull(root, shared!.base.ref, shared!.branch, deps); + const pull = await openPull(root, reviewed.base.ref, reviewed.branch, deps); if ("skipped" in pull) return pull; const next = withReview(pull.body, reviewRecord(reviewed)); if (next !== pull.body) await pull.edit(next); diff --git a/src/cli/review.ts b/src/cli/review.ts index f10136e2..b72b312d 100644 --- a/src/cli/review.ts +++ b/src/cli/review.ts @@ -58,6 +58,9 @@ export class ResponsesError extends ReviewInputError {} * limit. `reason` is the short form the review record names it by. */ export class ReviewerUnavailableError extends Error { + /** Whether the second reviewer, rather than the pick or its shadow, could not run. */ + second = false; + constructor( readonly harness: HarnessName, readonly reason: string, @@ -84,6 +87,14 @@ export interface Skip extends Model { reason: string; } +/** The rounds a run saved before the second review a raise called for failed, by the error that stopped it. */ +const savedBefore = new WeakMap(); + +/** The rounds a failed run saved before it failed, which still need their findings answered, if any. */ +export function savedReview(error: unknown): Reviewed | undefined { + return typeof error === "object" && error !== null ? savedBefore.get(error) : undefined; +} + /** Every eligible reviewer of the size was unavailable, each for the reason `skipped` names. */ export class ReviewOutageError extends Error { constructor( @@ -137,6 +148,8 @@ export interface Round { reviewer: HarnessName; /** The round is the shadow's: the size's pick one effort away, whose findings measure what that step buys. */ shadow?: true; + /** The round is the second reviewer's, on a model other than the pick's, which a high-risk head gets too. */ + second?: true; model: string; effort: string; /** The branch whose session the round continues. */ @@ -186,14 +199,26 @@ export type Classification = /** The head's tier as set before review, and the classifier's turn, empty when no model ran or it was reused. */ export interface Classified extends Assessment { by: Classification; + /** The risk file's `## Automatic` class the classifier found every changed file in, or null for none. */ + class: string | null; usage: Usage[]; } -/** The head's risk after a run: the classifier's tier, raised to the riskiest a reviewer judged it. */ +/** + * The maintainer's tier for a branch, with their reason, in place of the one its reviews settle on while that is no + * riskier than `from`, the tier they overrode; a riskier one ends it, so a change that grows is judged again. + */ +export interface Override extends Assessment { + from: Tier; +} + +/** The head's risk after a run: the classifier's tier, raised to the riskiest a reviewer judged it, or overridden. */ export interface Risk extends Assessment { classified: Classified; /** The seat of the reviewer whose raise set the tier, when one did. */ raisedBy?: SeatId; + /** The tier before the maintainer's override set this one, when one did. */ + overridden?: Tier; } const ASSESSMENT = { @@ -392,6 +417,8 @@ export type ReviewOptions = BaseOptions & { branch?: string; /** Stops the reviewer CLI, failing the round; the session keeps its earlier rounds. */ signal?: AbortSignal; + /** The maintainer's tier for the branch and their reason, which holds until its change grows riskier. */ + override?: Assessment; }; export interface ReviewDependencies { @@ -410,6 +437,8 @@ export interface Tally { reviewer: HarnessName; /** The shadow's tally, kept apart from the size's pick of the same harness. */ shadow?: true; + /** The second reviewer's tally, kept apart from the pick's. */ + second?: true; /** Its latest round's model, effort, and session, which the record names even once a run leaves it out. */ model: string; effort: string; @@ -428,11 +457,17 @@ export interface Tally { /** What a run of `quest review` gives: each reviewer's round, every tally on the branch, the run's first, and the head's risk. */ export interface Reviewed { + /** Each reviewer's round; none when the head's tier is low, which needs no local review. */ rounds: Round[]; tallies: Tally[]; risk: Risk; /** The size's reviewers ranked before the one that ran, which could not run, in the order they were tried. */ skipped: Skip[]; + /** The branch whose session the run continued, and the head, base, and size it reviewed. */ + branch: string; + head: string; + base: Round["base"]; + sized: { size: Size; from: string }; } /** @@ -446,6 +481,8 @@ interface State { tallies: Tally[]; /** The last head's classification, reused while its change and the base's risk file are the same (`key`). */ classified?: { key: string; value: Omit }; + /** The maintainer's override of the branch's tier. */ + override?: Override; } /** One reviewer's session on a branch. */ @@ -453,6 +490,8 @@ interface Session { reviewer: HarnessName; /** The shadow's session; the branch keeps at most one. */ shadow?: true; + /** The second reviewer's session; the branch keeps at most one. */ + second?: true; session: string; /** Each round's head, the merge base its change started from, and its findings. */ rounds: { head: string; mergeBase: string; findings: Finding[] }[]; @@ -1115,6 +1154,24 @@ function replied(reply: { structured?: unknown; text?: string }, what: string): } } +/** The classifier's reply schema: the assessment, and the class the change falls in when the risk file lists any. */ +function classSchema(classes: string[]) { + if (classes.length === 0) return ASSESSMENT; + return { + ...ASSESSMENT, + required: [...ASSESSMENT.required, "class"], + properties: { ...ASSESSMENT.properties, class: { type: ["string", "null"], enum: [...classes, null] } }, + }; +} + +/** The classifier's assessment in `value`, and the class it names, which must be one of `classes`, or null. */ +export function classed(value: unknown, classes: string[], what: string): Assessment & { class: string | null } { + const named = record(value)?.class ?? null; + if (named !== null && !classes.includes(named as string)) + throw new Error(`${what} names ${JSON.stringify(named)}, which is no class the risk file lists`); + return { ...assessment(value, what), class: named as string | null }; +} + /** The tier and reason `value` holds, with its reason on one line, failing as `what` when it holds none. */ export function assessment(value: unknown, what: string): Assessment { const fields = record(value); @@ -1388,6 +1445,7 @@ export function classifyPrompt( file: { sha: string; text: string }, stat: string, patch: string, + classes: string[] = [], ): string { const range = `${change.mergeBase}..${change.head}`; const whole = stat.length + patch.length <= DIFF_BUDGET; @@ -1403,6 +1461,14 @@ export function classifyPrompt( `\n${shown}\n`, "Report the change's tier as JSON matching the response schema, with one sentence on what could break, for " + "whom, and how hard it is to undo.", + ...(classes.length > 0 + ? [ + "Also report as `class` the one class from the risk file's `## Automatic` list whose rule every " + + "changed file meets, judged by what the diff does rather than its title or description, or null " + + "when no single class covers the whole change or you are unsure. A class lets a low change land " + + "without a person, so between a class and null, pick null.", + ] + : []), ].join("\n\n"); } @@ -1484,10 +1550,10 @@ function load(path: string): unknown { } } -/** A reviewer's seat on a branch: its harness, and whether it is the shadow. */ -export type SeatId = { reviewer: HarnessName; shadow?: true }; -const seatKey = (seat: SeatId) => `${seat.reviewer}${seat.shadow ? " shadow" : ""}`; -/** Whether two reviewers hold the same seat: the same harness, both the shadow or neither. */ +/** A reviewer's seat on a branch: its harness, and whether it is the shadow or the second reviewer. */ +export type SeatId = { reviewer: HarnessName; shadow?: true; second?: true }; +const seatKey = (seat: SeatId) => `${seat.reviewer}${seat.shadow ? " shadow" : ""}${seat.second ? " second" : ""}`; +/** Whether two reviewers hold the same seat: the same harness and role. */ export const sameSeat = (a: SeatId, b: SeatId) => seatKey(a) === seatKey(b); /** The efforts a reviewer runs at, from lowest to highest; `quest` never runs `max`. */ @@ -1528,6 +1594,8 @@ export function parseState(value: unknown): State { (tally) => typeof tally?.reviewer === "string" && (tally.shadow === undefined || tally.shadow === true) && + (tally.second === undefined || tally.second === true) && + !(tally.shadow && tally.second) && (tally.session === undefined || typeof tally.session === "string") && typeof tally.rounds === "number" && typeof tally.fixed === "number" && @@ -1540,6 +1608,7 @@ export function parseState(value: unknown): State { (session) => typeof session?.reviewer === "string" && (session.shadow === undefined || session.shadow === true) && + (session.second === undefined || session.second === true) && state.tallies!.some((tally) => sameSeat(tally, session)) && typeof session.session === "string" && Array.isArray(session.rounds) && @@ -1553,11 +1622,17 @@ export function parseState(value: unknown): State { session.given !== null, ) && state.sessions.filter((session) => session.shadow).length <= 1 && + state.sessions.filter((session) => session.second).length <= 1 && (state.classified === undefined || (typeof state.classified?.key === "string" && TIERS.includes(state.classified.value?.tier) && typeof state.classified.value.reason === "string" && - ["model", "paths", "default"].includes(state.classified.value.by?.kind))); + ["model", "paths", "default"].includes(state.classified.value.by?.kind) && + (state.classified.value.class === null || typeof state.classified.value.class === "string"))) && + (state.override === undefined || + (TIERS.includes(state.override?.tier) && + TIERS.includes(state.override.from) && + typeof state.override.reason === "string")); if (!valid) throw new ReviewInputError("the saved review sessions are not ones quest review reads; pass --new"); // A retired reviewer's tally is dropped, so the record never names it. Its session stays only until the run numbers // the last round's findings as that round printed them, so the author's responses keep their numbers. @@ -1694,27 +1769,28 @@ export async function classify(input: Classifying): Promise<{ key: string; value const { path, rule } = hits[0]!; const more = hits.length > 1 ? `, as are ${hits.length - 1} more of its paths` : ""; const reason = `it changes ${path}, which is always high${more}: ${rule.reason}`; - return set({ tier: "high", reason, by: { kind: "paths" } }); + return set({ tier: "high", reason, by: { kind: "paths" }, class: null }); } if (text === null) { const reason = `the base has no ${RISK_FILE} to name what is always high or customer-facing, so every change is medium`; - return set({ tier: "medium", reason, by: { kind: "default" } }); + return set({ tier: "medium", reason, by: { kind: "default" }, class: null }); } + const classes = file!.classes.map((each) => each.name); const diff = (args: string[]) => git(root, ["diff", "--no-ext-diff", "--no-textconv", "--no-color", ...args, range]); - const prompt = classifyPrompt(change, { sha: baseSha, text }, diff(["--stat=160"]), diff(["--patch"])); + const prompt = classifyPrompt(change, { sha: baseSha, text }, diff(["--stat=160"]), diff(["--patch"]), classes); const answer = await ask(CLASSIFIERS, { cwd: root, dir: input.dir, env: input.env, signal: input.signal, instructions: CLASSIFY_INSTRUCTIONS, - schema: ASSESSMENT, + schema: classSchema(classes), prompt, who: "classifier", task: "set the risk tier", - parse: (value) => assessment(value, "the classifier's reply"), + parse: (value) => classed(value, classes, "the classifier's reply"), }); const { tier, reason } = answer.value; return { @@ -1723,6 +1799,7 @@ export async function classify(input: Classifying): Promise<{ key: string; value tier, reason, by: { kind: "model", ...answer.entry, session: answer.session }, + class: answer.value.class, usage: answer.usage ? [{ turn: "classify", ...answer.usage }] : [], }, }; @@ -1836,17 +1913,33 @@ export function settle(classified: Classified, rounds: Round[]): Risk { risk = { ...round.raised, classified, - raisedBy: { reviewer: round.reviewer, ...(round.shadow && { shadow: true }) }, + raisedBy: { + reviewer: round.reviewer, + ...(round.shadow && { shadow: true }), + ...(round.second && { second: true }), + }, }; return risk; } +/** `risk` as the maintainer's `override` sets it, while `risk` is no riskier than the tier they overrode. */ +export function overridden(risk: Risk, override: Override | undefined): Risk { + // An override to the tier the reviews settled on changes nothing, so the record names none. + if (override === undefined || riskier(risk.tier, override.from) || override.tier === risk.tier) return risk; + const { raisedBy: _, ...rest } = risk; + return { ...rest, tier: override.tier, reason: override.reason, overridden: risk.tier }; +} + /** * Review the checkout's committed branch: one round of each reviewer on the same head, the size's pick and its * shadow while it runs, or only `--harness`'s, each resuming its session on the branch unless `fresh`. * Every reviewer runs at once, and the first to fail stops the others and fails the whole, saving no round. A pick * that cannot run, logged out, not installed, or at its usage limit, passes the round to the size's next eligible * reviewer, unless the options name the reviewer; once none is left, the run fails as an outage. + * + * The head's tier scales the review: a low head with nothing left to settle gets no local review, and a high one gets + * a second reviewer on another model, the next of the size's list, which a round that raises the tier to high runs + * at once. */ export async function review(options: ReviewOptions, deps: ReviewDependencies): Promise { // Native Windows installs the reviewer CLIs as batch shims, which `run` cannot start without a shell. @@ -1889,8 +1982,8 @@ export async function review(options: ReviewOptions, deps: ReviewDependencies): next += session.rounds.at(-1)!.findings.length; } const sessions = all.filter(runs); - const plan = (routed: Model) => - seatsFor({ routed, size: sized.size, auto, sessions, firsts, responses: options.responses }); + const plan = (routed: Model, second: Model | null = null) => + seatsFor({ routed, second, size: sized.size, auto, sessions, firsts, responses: options.responses }); // The first candidate's seats are checked before the classifier spends a turn. let at = 0; @@ -1935,50 +2028,167 @@ export async function review(options: ReviewOptions, deps: ReviewDependencies): dir, env: deps.env, }; + // Each reviewer's last round on this head still judges its tier, as does the maintainer's override. + const before = settle( + classified.value, + sessions.map((session) => session.last).filter((round) => round.head === head), + ); + const override = options.override === undefined ? saved?.override : { ...options.override, from: before.tier }; + const base = { ref: baseRef, sha: baseSha }; + const tallies = options.fresh ? dropped(saved) : (saved?.tallies ?? []); + const { usage: _, ...value } = classified.value; + const state = (kept: Session[], tallies: Tally[], risk: Risk): State => ({ + branch, + sessions: kept, + tallies, + classified: { key: classified.key, value }, + // A riskier change than the one the maintainer judged ends their override. + ...(override !== undefined && !riskier(risk.overridden ?? risk.tier, override.from) && { override }), + }); + const named = !auto || options.model !== undefined || options.effort !== undefined; + const settling = + options.responses !== undefined || sessions.some((session) => session.rounds.at(-1)!.findings.length > 0); + const low = overridden(before, override); + if (!named && !settling && low.tier === "low") { + save(statePath, state(sessions, tallies, low)); + return { rounds: [], tallies, risk: low, skipped: [], branch, head, base, sized }; + } + const skipped: Skip[] = []; const messages: string[] = []; // A login or a missing CLI rules out its harness's every model; a usage limit only the model that hit it. const down = new Map(); + // Models passed over this run, which the second reviewer never falls to. + const secondOut = new Set(); + // The second reviewer: the first of the size's list on a model other than the pick's that can run. A list with no + // other model, as when every other one is avoided, cannot review a high head; one whose others cannot run is out. + // It comes from the size's whole list, since --model or --effort narrows only the pick. + const pool = auto ? REVIEWERS[sized.size].filter((each) => !avoided(each)) : candidates; + const secondTo = (routed: Model): Model => { + const others = pool.filter((each) => each.model !== routed.model); + if (others.length === 0) + throw new ReviewInputError( + `a high-risk head needs a second reviewer on a model other than ${routed.model}, and every other model of the size's list is avoided; name the latest writer in the PR's ## Models record or with --exclude-model`, + ); + const next = others.find((each) => !secondOut.has(each.model) && !down.has(each.harness)); + if (next === undefined) throw new ReviewOutageError(sized.size, skipped, messages); + return next; + }; + // --model or --effort changes only the pick, so a high head still gets its second reviewer; --harness's runs alone. + const high = (risk: Risk) => auto && overridden(risk, override).tier === "high"; + // Below high, a second reviewer still settles the findings it left open: its own model while that may review, + // else another, whose new session settles them by number as a replaced pick's does. + const seconded = sessions.find((session) => session.second); + const unsettledSecond = auto && seconded !== undefined && seconded.rounds.at(-1)!.findings.length > 0; + const secondFor = (routed: Model): Model | null => { + if (!high(before) && !unsettledSecond) return null; + if (!high(before)) { + const own = pool.find( + (each) => + each.harness === seconded!.reviewer && + each.model === seconded!.last.model && + each.model !== routed.model && + !secondOut.has(each.model) && + !down.has(each.harness), + ); + if (own !== undefined) return own; + } + return secondTo(routed); + }; + let second = secondFor(candidates[0]!); + planned = plan(candidates[0]!, second); let done: Seated[]; for (;;) { try { done = await runSeats(shared, planned.seats, options.responses, options.signal); break; } catch (error) { - if (!(error instanceof ReviewerUnavailableError) || candidates.length === 1) throw error; + if (!(error instanceof ReviewerUnavailableError)) throw error; if (!(error instanceof ReviewLimitError)) down.set(error.harness, error); + if (error.second && second !== null) { + skipped.push({ ...second, reason: error.reason }); + messages.push(error.message); + secondOut.add(second.model); + second = secondTo(candidates[at]!); + planned = plan(candidates[at]!, second); + continue; + } + if (candidates.length === 1) throw error; let why: ReviewerUnavailableError | undefined = error; while (why !== undefined) { skipped.push({ ...candidates[at]!, reason: why.reason }); messages.push(why.message); + secondOut.add(candidates[at]!.model); at++; why = at < candidates.length ? down.get(candidates[at]!.harness) : undefined; } if (at === candidates.length) throw new ReviewOutageError(sized.size, skipped, messages); - planned = plan(candidates[at]!); + if (second !== null) second = secondFor(candidates[at]!); + planned = plan(candidates[at]!, second); } } - const { seats, kept } = planned; - const tallies = tallied( - options.fresh ? dropped(saved) : (saved?.tallies ?? []), - done.map((each, i) => ({ round: each.round, settles: seats[i]!.session })), - ); - const { usage: _, ...value } = classified.value; - save(statePath, { - branch, - sessions: [...done.map((each) => each.session), ...kept], - tallies, - classified: { key: classified.key, value }, - } satisfies State); - const rounds = done.map((each) => each.round); + let { seats, kept } = planned; // A reviewer this run left out, such as a shadow with nothing to settle, still judged the head its last round reviewed. - const standing = kept.map((session) => session.last).filter((round) => round.head === head); - return { rounds, tallies, risk: settle(classified.value, [...rounds, ...standing]), skipped }; + const standing = () => kept.map((session) => session.last).filter((round) => round.head === head); + const judged = () => settle(classified.value, [...done.map((each) => each.round), ...standing()]); + const persist = () => { + const after = tallied( + tallies, + done.map((each, i) => ({ round: each.round, settles: seats[i]!.session })), + ); + const risk = overridden(judged(), override); + save(statePath, state([...done.map((each) => each.session), ...kept], after, risk)); + return { after, risk }; + }; + let { after, risk } = persist(); + // A round that raised the tier to high gets the second review the lower tier skipped, at once. The rounds already + // run are saved first, so a second reviewer that cannot run costs them nothing; the next run seats it again. + if (!seats.some((seat) => seat.second) && high(judged())) { + const seated = kept.find((session) => session.second); + try { + for (;;) { + const seat: Seat = { reviewer: secondTo(candidates[at]!), second: true, session: seated, first: 1 }; + try { + const [extra] = await runSeats(shared, [seat], undefined, options.signal); + done = [...done, extra!]; + seats = [...seats, seat]; + kept = kept.filter((session) => session !== seated); + break; + } catch (error) { + if (!(error instanceof ReviewerUnavailableError)) throw error; + if (!(error instanceof ReviewLimitError)) down.set(error.harness, error); + skipped.push({ ...seat.reviewer, reason: error.reason }); + messages.push(error.message); + secondOut.add(seat.reviewer.model); + } + } + } catch (error) { + // Whatever stopped the second review, the rounds saved before it still need their findings answered, so + // the failure carries them to the report. + if (typeof error === "object" && error !== null) + savedBefore.set(error, { + rounds: done.map((each) => each.round), + tallies: after, + risk, + skipped, + branch, + head, + base, + sized, + }); + throw error; + } + ({ after, risk } = persist()); + } + const rounds = done.map((each) => each.round); + return { rounds, tallies: after, risk, skipped, branch, head, base, sized }; } -/** What picks a run's seats: the routed reviewer, whether the size picked it, and the branch's sessions. */ +/** What picks a run's seats: the routed reviewer and the second, whether the size picked them, and the branch's sessions. */ interface Seating { routed: Model; + /** The second reviewer a high-risk head gets, or null. */ + second: Model | null; /** The PR's size, which sets the shadow's step. */ size: Size; auto: boolean; @@ -1992,14 +2202,20 @@ interface Seating { * The seats a run of `routed` fills, the saved sessions it keeps without a round, and the refusals that stop it * before any reviewer runs: a session whose findings no seat settles, or responses missing or given for nothing. */ -function seatsFor({ routed, size, auto, sessions, firsts, responses }: Seating): { seats: Seat[]; kept: Session[] } { +function seatsFor({ routed, second, size, auto, sessions, firsts, responses }: Seating): { + seats: Seat[]; + kept: Session[]; +} { const shadow = auto ? shadowOf(size, routed) : null; const seated = (session: Session | undefined) => ({ session, first: session === undefined ? 1 : firsts.get(session)!, }); const seats: Seat[] = [ - { reviewer: routed, ...seated(sessions.find((each) => each.reviewer === routed.harness && !each.shadow)) }, + { + reviewer: routed, + ...seated(sessions.find((each) => each.reviewer === routed.harness && !each.shadow && !each.second)), + }, ]; const unseated = () => sessions.filter((each) => !seats.some((seat) => seat.session === each)); const unsettled = (list: Session[]) => list.filter((each) => each.rounds.at(-1)!.findings.length > 0); @@ -2007,7 +2223,9 @@ function seatsFor({ routed, size, auto, sessions, firsts, responses }: Seating): // session settles the open findings of the reviewer it replaces, by their numbers, so they are never dropped // unanswered. const replaced = - auto && seats[0]!.session === undefined ? unsettled(unseated()).find((each) => !each.shadow) : undefined; + auto && seats[0]!.session === undefined + ? unsettled(unseated()).find((each) => !each.shadow && !each.second) + : undefined; if (replaced !== undefined) seats[0] = { ...seats[0]!, ...seated(replaced) }; // The shadow reviews a branch's first run, then reruns only while it has findings to settle, or once the pick // changed so that the shadow it ran is no longer the size's step from it. Its session carries over to the new @@ -2025,14 +2243,23 @@ function seatsFor({ routed, size, auto, sessions, firsts, responses }: Seating): ); if (auto && (shadowed === undefined ? shadow !== null : open || stale)) seats.push({ reviewer: shadow ?? routed, shadow: true, ...seated(shadowed) }); + // The second reviewer reviews every head while the tier is high, and settles its open findings once it is not. + const seconded = sessions.find((each) => each.second); + if (auto && (second !== null || (seconded !== undefined && unsettled([seconded]).length > 0))) { + const last = seconded?.last; + const reviewer = second ?? { harness: seconded!.reviewer, model: last!.model, effort: last!.effort }; + seats.push({ reviewer, second: true, ...seated(seconded) }); + } // A run of the size's pick drops the other sessions but a shadow's, whose presence keeps it from rerunning. A // run of --harness's reviewer alone keeps them all for the pick's next run. Either refuses to pass a head while // one of them still has findings it cannot settle. const others = unseated(); - const kept = auto ? others.filter((each) => each.shadow) : others; + const kept = auto ? others.filter((each) => each.shadow || each.second) : others; const held = unsettled(others); if (held.length > 0) { - const names = held.map((each) => `${each.reviewer}${each.shadow ? " (shadow)" : ""}`).join(" and "); + const names = held + .map((each) => `${each.reviewer}${each.shadow ? " (shadow)" : each.second ? " (second)" : ""}`) + .join(" and "); // A run of the size's pick seats every shadow with findings, so what it holds is a reviewer only --harness runs. const run = auto ? `${[...new Set(held.map((each) => `--harness ${each.reviewer}`))].join(" or ")}, adding --model or --exclude-model when its size's model is avoided,` @@ -2067,6 +2294,9 @@ async function runSeats( const results = await Promise.allSettled( seats.map((seat) => reviewWith({ ...shared, signal }, seat, responses).catch((error: unknown) => { + // The seats it stops may reject with this same error, which must keep naming the seat that failed. + if (controller.signal.aborted) throw error; + if (error instanceof ReviewerUnavailableError) error.second = seat.second === true; controller.abort(error); throw error; }), @@ -2110,10 +2340,7 @@ function dropped(saved: State | undefined): Tally[] { * and settles the last round's for the reviewer that raised them, `settles`, which is another when the round * replaced it; one it keeps open moves to its own count, since the round reports it again. */ -export function tallied( - tallies: Tally[], - rounds: { round: Round; settles?: { reviewer: HarnessName; shadow?: true } }[], -): Tally[] { +export function tallied(tallies: Tally[], rounds: { round: Round; settles?: SeatId }[]): Tally[] { const by = new Map(tallies.map((tally) => [seatKey(tally), { ...tally, findings: { ...tally.findings } }])); for (const { round, settles } of rounds) { if (round.unchanged) continue; @@ -2130,6 +2357,7 @@ export function tallied( const own = by.get(seatKey(round)) ?? { reviewer: round.reviewer, ...(round.shadow && { shadow: true as const }), + ...(round.second && { second: true as const }), model: round.model, effort: round.effort, rounds: 0, @@ -2180,6 +2408,7 @@ interface Shared { interface Seat { reviewer: Model; shadow?: true; + second?: true; session?: Session; first: number; } @@ -2193,7 +2422,7 @@ interface Seated { /** One reviewer's round, resuming its session when nothing but the head changed. */ async function reviewWith(shared: Shared, seat: Seat, responses: string | undefined): Promise { const { root, change, given, rules } = shared; - const { reviewer: picked, session: stored, first, shadow } = seat; + const { reviewer: picked, session: stored, first, shadow, second } = seat; const harness = picked.harness; const reviewer = CLIS[harness]; const previous = stored?.rounds.at(-1); @@ -2207,7 +2436,7 @@ async function reviewWith(shared: Shared, seat: Seat, responses: string | undefi const resume = previous !== undefined && last !== undefined && - sameSeat(stored!, { reviewer: harness, shadow }) && + sameSeat(stored!, { reviewer: harness, shadow, second }) && stored!.given.instructions === given.instructions && stored!.given.rules === given.rules && last.model === picked.model && @@ -2268,6 +2497,7 @@ async function reviewWith(shared: Shared, seat: Seat, responses: string | undefi const round: Round = { reviewer: harness, ...(shadow && { shadow }), + ...(second && { second }), model: context.model, effort: context.effort, branch: shared.branch, @@ -2300,7 +2530,15 @@ async function reviewWith(shared: Shared, seat: Seat, responses: string | undefi }; return { round, - session: { reviewer: harness, ...(shadow && { shadow }), session, rounds, last: round, given }, + session: { + reviewer: harness, + ...(shadow && { shadow }), + ...(second && { second }), + session, + rounds, + last: round, + given, + }, }; } @@ -2364,6 +2602,7 @@ export async function firstRound( * every third round reports others, else answering them, or nothing left to do. */ export function nextStep(rounds: Round[]): string { + if (rounds.length === 0) return "next done: the head is low risk, so the online reviewer alone reviews it"; const findings = rounds.flatMap((round) => round.findings); if (findings.length === 0) return "next done: no findings remain on this head"; if (findings.every((finding) => finding.severity === "low")) @@ -2382,16 +2621,17 @@ const flat = (text: string) => text.replace(/\s+/g, " ").trim(); * each reviewer's round, one record per line, and its findings, numbered across the reviewers in order, each with its * body indented. */ -export function roundLines({ rounds, risk, skipped }: Pick): string[] { - const [shared] = rounds; +export function roundLines({ rounds, risk, skipped, head, base, sized }: Reviewed): string[] { const { classified } = risk; const by = classified.by; const lines = [ - `size ${shared!.size} ${shared!.sizeFrom}`, - `base ${shared!.base.sha} ${shared!.base.ref}`, - `head ${shared!.head}`, + `size ${sized.size} ${sized.from}`, + `base ${base.sha} ${base.ref}`, + `head ${head}`, `risk ${risk.tier} ${flat(risk.reason)}`, + ...(risk.overridden ? [`overridden ${risk.overridden} by the maintainer`] : []), `classified ${classified.tier} ${by.kind} ${flat(classified.reason)}`, + ...(classified.class === null ? [] : [`class ${classified.class}`]), ...(by.kind === "model" ? [`classifier ${by.harness} ${by.model} ${by.effort} ${by.session}`] : []), ...classified.usage.map((u) => `usage ${u.turn} input ${u.input} cached ${u.cached} output ${u.output}`), ...skipped.map((skip) => `skipped ${skip.harness} ${skip.model} ${skip.effort} ${skip.reason}`), @@ -2400,7 +2640,7 @@ export function roundLines({ rounds, risk, skipped }: Pick { + const ref = await fetchBase(root, base); + const { remote, branch } = parseBase(root, ref); + const tip = `refs/remotes/${remote}/${branch}`; + if (git(root, ["ls-tree", "--name-only", tip, "--", RISK_FILE]) === "") return null; + const file = parseRiskFile(git(root, ["show", `${tip}:${RISK_FILE}`])); + if (file.problems.length > 0) + throw new Error(`the base's ${RISK_FILE} cannot be read: ${file.problems.join("; ")}`); + return file; +} diff --git a/src/cli/usage.ts b/src/cli/usage.ts index 5447bf35..b38e85ed 100644 --- a/src/cli/usage.ts +++ b/src/cli/usage.ts @@ -19,6 +19,7 @@ import { SPLIT_CATEGORIES, type SplitUsage, type Tier, + riskier, TIERS, type TimeSplit, WAIT_KINDS, @@ -179,6 +180,8 @@ export interface ReviewerRow { model: string; effort: string; shadow: boolean; + /** The second reviewer a high-risk head gets, whose findings show what the second review catches. */ + second: boolean; /** PRs whose record tallies this reviewer, each branch counted once, and its findings across every round. */ reviewed: number; tally: Omit; @@ -196,15 +199,37 @@ export interface ArmRow extends Omit { spend: Tokens; } -/** The PRs of one risk tier, or of none (`tier` null): how many merged, how many a reviewer raised, and later fixed. */ +/** + * The PRs of one risk tier, or of none (`tier` null): how many merged, how many a reviewer raised, how many the + * maintainer overrode, how many were later fixed, and how long they waited on a person. + */ export interface TierRow { tier: Tier | null; pulls: number; merged: number; /** PRs a reviewer judged riskier than the classifier did. */ raised: number; + /** PRs whose tier the maintainer overrode, a reading of how often the tier is wrong. */ + overridden: number; /** PRs a later PR names under `## Caused by`. */ culprits: number; + /** Milliseconds their sessions waited on a person's answer, a shared session's in its share. */ + person: number; +} + +/** + * The PRs whose classifier found them in one of the risk file's `## Automatic` classes: how many merged, how many + * were later fixed, and how long they waited on a person, the numbers that argue for or against merging the class + * without a pick. + */ +export interface ClassRow { + class: string; + pulls: number; + /** Those whose tier is low, so the class lands them without a pick. */ + low: number; + merged: number; + culprits: number; + person: number; } /** One online reviewer over the merged PRs reported. */ @@ -249,6 +274,7 @@ export interface Usage { /** The writer A/B's arms, while it runs. */ arms: ArmRow[]; tiers: TierRow[]; + classes: ClassRow[]; online: OnlineRow[]; /** Where each role's time went. */ splits: SplitRow[]; @@ -980,7 +1006,14 @@ function reviewerRows(pulls: PullRow[]): ReviewerRow[] { const rows = new Map(); const latest = tallied(pulls, () => true); const row = (each: PullRow, review: ReviewSummary) => { - const id = JSON.stringify([each.size, review.harness, review.model, review.effort, review.shadow]); + const id = JSON.stringify([ + each.size, + review.harness, + review.model, + review.effort, + review.shadow, + review.second, + ]); let found = rows.get(id); if (!found) { found = { @@ -989,6 +1022,7 @@ function reviewerRows(pulls: PullRow[]): ReviewerRow[] { model: review.model, effort: review.effort, shadow: review.shadow, + second: review.second, reviewed: 0, tally: noCounts(), firstRounds: noFirst(), @@ -1027,8 +1061,8 @@ function reviewerRows(pulls: PullRow[]): ReviewerRow[] { } return [...rows.values()].sort((a, b) => order( - [a.size, a.harness, a.model, a.effort, String(a.shadow)], - [b.size, b.harness, b.model, b.effort, String(b.shadow)], + [a.size, a.harness, a.model, a.effort, String(a.shadow), String(a.second)], + [b.size, b.harness, b.model, b.effort, String(b.shadow), String(b.second)], ), ); } @@ -1078,13 +1112,59 @@ function tierRows(pulls: PullRow[]): TierRow[] { tier, pulls: rows.length, merged: rows.filter((each) => each.state === "merged").length, - raised: rows.filter((each) => each.risk !== null && each.risk.tier !== each.risk.classified).length, + raised: rows.filter( + (each) => + each.risk !== null && riskier(each.risk.overridden ?? each.risk.tier, each.risk.classified), + ).length, + overridden: rows.filter((each) => each.risk?.overridden != null).length, culprits: rows.filter((each) => each.fixedBy.length > 0).length, + person: rows.reduce((sum, each) => sum + personWait(each.sessions), 0), }, ]; }); } +/** One row per `## Automatic` class the PRs' classifiers named, by name. */ +function classRows(pulls: PullRow[]): ClassRow[] { + const names = [...new Set(pulls.flatMap((each) => each.risk?.class ?? []))].sort(); + return names.map((name) => { + const rows = pulls.filter((each) => each.risk?.class === name); + return { + class: name, + pulls: rows.length, + low: rows.filter((each) => each.risk!.tier === "low").length, + merged: rows.filter((each) => each.state === "merged").length, + culprits: rows.filter((each) => each.fixedBy.length > 0).length, + person: rows.reduce((sum, each) => sum + personWait(each.sessions), 0), + }; + }); +} + +/** How a record's tier came to differ from its classifier's: a reviewer's raise, the maintainer's override, or both. */ +function riskNote(risk: RecordedRisk): string { + const reviewed = risk.overridden ?? risk.tier; + return [ + ...(reviewed === risk.classified ? [] : [`raised from ${risk.classified} by a reviewer`]), + ...(risk.overridden === null ? [] : [`overridden from ${risk.overridden} by the maintainer`]), + ] + .map((note) => `; ${note}`) + .join(""); +} + +/** How long `sessions` waited on a person's answer, in milliseconds, a shared session's in its share. */ +function personWait(sessions: SessionRow[]): number { + return waitsByKind(sessions).get("person") ?? 0; +} + +/** How long `sessions` waited, in milliseconds by kind, a shared session's waits counted in its share. */ +function waitsByKind(sessions: SessionRow[]): Map { + const totals = new Map(); + for (const s of sessions) + for (const w of s.waits ?? []) + totals.set(w.kind, (totals.get(w.kind) ?? 0) + (Date.parse(w.end) - Date.parse(w.start)) / s.pulls.length); + return totals; +} + function onlineRows(pulls: PullRow[]): OnlineRow[] { const merged = pulls.filter((each) => each.state === "merged"); const rows = new Map(); @@ -1217,6 +1297,7 @@ export async function usage(root: string, options: UsageOptions, deps: UsageDepe reviewers: reviewerRows(rows), arms: armRows(rows), tiers: tierRows(rows), + classes: classRows(rows), online: onlineRows(rows), splits: splitRows(rows), breakages, @@ -1367,13 +1448,8 @@ function splitTotals(sessions: SessionRow[]): string { * waits are unknown, as for those read on another host; empty when there is nothing to say. */ function waitTotals(sessions: SessionRow[]): string { - const totals = new Map(); - let unknown = 0; - for (const s of sessions) { - if (s.waits === null) unknown++; - for (const w of s.waits ?? []) - totals.set(w.kind, (totals.get(w.kind) ?? 0) + (Date.parse(w.end) - Date.parse(w.start)) / s.pulls.length); - } + const totals = waitsByKind(sessions); + const unknown = sessions.filter((s) => s.waits === null).length; const parts = WAIT_KINDS.filter((kind) => totals.has(kind)).map((kind) => `${kind} ${duration(totals.get(kind)!)}`); if (unknown) parts.push(`unknown for ${unknown} session${unknown === 1 ? "" : "s"} on other hosts`); return parts.join(", "); @@ -1403,7 +1479,7 @@ export function usageLines(report: Usage): string[] { ); if (row.risk) lines.push( - ` risk: ${row.risk.tier}, ${row.risk.reason}${row.risk.tier === row.risk.classified ? "" : `; raised from ${row.risk.classified} by a reviewer`}`, + ` risk: ${row.risk.tier}, ${row.risk.reason}${riskNote(row.risk)}${row.risk.class === null ? "" : `; class ${row.risk.class}`}`, ); for (const i of row.implementers) { const notes = [i.size, i.arm && `arm ${i.arm}`].filter(Boolean).join(", "); @@ -1413,7 +1489,7 @@ export function usageLines(report: Usage): string[] { if (row.unreadReview) lines.push(` unread review: ${row.unreadReview}`); for (const r of row.review) lines.push( - ` review: ${r.harness}, ${r.model}, ${r.effort} effort${r.shadow ? ", shadow" : ""}; ${r.round === null ? "not in the latest run" : `round ${r.round}, score ${r.score ?? "-"}/10`}; ${r.tally === null ? "no tally" : `rounds ${r.tally.rounds}, ${findingsText(r.tally)}`}`, + ` review: ${r.harness}, ${r.model}, ${r.effort} effort${r.shadow ? ", shadow" : r.second ? ", second" : ""}; ${r.round === null ? "not in the latest run" : `round ${r.round}, score ${r.score ?? "-"}/10`}; ${r.tally === null ? "no tally" : `rounds ${r.tally.rounds}, ${findingsText(r.tally)}`}`, ); for (const o of row.online) lines.push(` online review: ${o.reviewer}, ${o.finalHead ? "" : "not "}at the final head; ${answers(o)}`); @@ -1480,7 +1556,7 @@ export function usageLines(report: Usage): string[] { r.size ?? "-", r.harness, r.model, - `${r.effort}${r.shadow ? ", shadow" : ""}`, + `${r.effort}${r.shadow ? ", shadow" : r.second ? ", second" : ""}`, `${r.reviewed} reviewed: rounds ${mean(r.tally.rounds, r.reviewed)}, ${findingsText({ ...r.tally, first: null })}, ${firsts(r.firstRounds)}; ${per(r.spent, "PR reviewed")}`, ]), ), @@ -1509,7 +1585,19 @@ export function usageLines(report: Usage): string[] { report.tiers.map((t) => [ " ", t.tier ?? "-", - `${t.pulls} PRs, ${t.merged} merged, ${t.raised} raised by a reviewer, ${t.culprits} later fixed`, + `${t.pulls} PRs, ${t.merged} merged, ${t.raised} raised by a reviewer, ${t.overridden} overridden, ${t.culprits} later fixed; waited on a person ${duration(t.person)}`, + ]), + ), + ); + if (report.classes.length) + lines.push( + "", + "By automatic class:", + ...table( + report.classes.map((c) => [ + " ", + c.class, + `${c.pulls} PRs, ${c.low} low, ${c.merged} merged, ${c.culprits} later fixed; waited on a person ${duration(c.person)}`, ]), ), ); diff --git a/src/core/forge.ts b/src/core/forge.ts index 228f7ab6..455a4f86 100644 --- a/src/core/forge.ts +++ b/src/core/forge.ts @@ -140,9 +140,10 @@ export interface Status { /** * The head's risk tier as the `## Review` record names it, and the classifier's own tier, lower when a reviewer * raised it; null when the record names none. `state` is the review record's, which a line after it carries to a - * later head, else `current` when the record names the head and `stale` when not. + * later head, else `current` when the record names the head and `stale` when not. `class` is the risk file's + * `## Automatic` class the classifier found the change in, or null. */ - risk: { tier: Tier; reason: string; classified: Tier; state: ReviewRecord["state"] } | null; + risk: { tier: Tier; reason: string; classified: Tier; class: string | null; state: ReviewRecord["state"] } | null; reactions: Reaction[]; /** Unresolved review threads, oldest first. */ threads: Thread[]; @@ -573,7 +574,13 @@ const status = shape({ checkpoints: list(shape({ reviewer: string, round: count, url: string })), reviewRecord: nullable(shape({ state: oneOf(reviewStates), head: string })), risk: nullable( - shape>({ tier, reason: string, classified: tier, state: oneOf(reviewStates) }), + shape>({ + tier, + reason: string, + classified: tier, + class: nullable(string), + state: oneOf(reviewStates), + }), ), reactions: list(shape({ content: string, actor: string, createdAt: time, url: string })), threads: list( diff --git a/src/core/index.ts b/src/core/index.ts index ed315b8a..31ffcff4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -38,6 +38,7 @@ export { type ClosedPull, handBackWaits, handedBack, landed, withoutHandBack } f export { reviewSection } from "./review"; export { ALWAYS_HIGH, + type Class, DEFAULT, type HighPath, PATHS, diff --git a/src/core/risk.ts b/src/core/risk.ts index bc6b00d9..6b13f32b 100644 --- a/src/core/risk.ts +++ b/src/core/risk.ts @@ -1,7 +1,7 @@ // A pull request's risk tier: what could break, for whom, and how hard it is to undo, set from its diff and never // from who wrote it. The repository's RISK.md lists the paths whose change is always high and says what else is // customer-facing there; `quest review` sets the tier and records it in the PR body's `## Review` section. -import type { List, ListItem, Paragraph, RootContent } from "mdast"; +import type { Code, List, ListItem, Paragraph, RootContent } from "mdast"; import { markdown } from "./doc"; import { reviewSection } from "./review"; @@ -66,37 +66,69 @@ export function matches(pattern: string, path: string): boolean { return new RegExp(`^${source}(?:/.*)?$`).test(path); } -/** What a risk file holds: its always-high paths, and each mistake that keeps it from being read. */ +/** A class of change that may land without the maintainer's pick, and the rule over the diff that defines it. */ +export interface Class { + name: string; + rule: string; +} + +/** What a risk file holds: its always-high paths, automatic classes, and full suite, and what keeps it from being read. */ export interface RiskFile { high: HighPath[]; + classes: Class[]; + /** The command that runs the repository's whole test suite, which a high change gets beyond its scoped checks. */ + suite: string | null; problems: string[]; } /** - * The risk file `text`: each item of its `## High` list is a backticked {@link patternError} pattern, ` - `, and why - * changing what it matches is always high. The rest of the file is prose the classifier reads, such as what is - * customer-facing. A file without the section lists no paths. + * The risk file `text`, whose sections are each optional and appear at most once: + * + * - `## High`: each item a backticked {@link patternError} pattern, ` - `, and why changing what it matches is always + * high. + * - `## Automatic`: each item a backticked class name, ` - `, and the rule over the diff a change meets to fall in it. + * - `## Full suite`: one fenced code block holding the command that runs the whole test suite. + * + * The rest of the file is prose the classifier reads, such as what is customer-facing. */ export function parseRiskFile(text: string): RiskFile { - const high: HighPath[] = []; const problems: string[] = []; const nodes = markdown(text).children; - const headings = nodes.filter( - (node) => node.type === "heading" && node.depth === 2 && headingText(text, node) === "High", - ); - if (headings.length > 1) problems.push(`${RISK_FILE} has ${headings.length} ## High sections; merge them into one`); - const at = headings.length > 0 ? nodes.indexOf(headings[0]!) : -1; - if (at < 0) return { high, problems }; - for (const node of nodes.slice(at + 1)) { - if (node.type === "heading" && node.depth <= 2) break; - if (node.type !== "list") continue; - for (const item of (node as List).children) { - const entry = highPath(text, item); - if (typeof entry === "string") problems.push(`${RISK_FILE}:${item.position!.start.line}: ${entry}`); - else high.push(entry); - } + const section = (title: string): RootContent[] | null => { + const headings = nodes.filter( + (node) => node.type === "heading" && node.depth === 2 && headingText(text, node) === title, + ); + if (headings.length > 1) + problems.push(`${RISK_FILE} has ${headings.length} ## ${title} sections; merge them into one`); + if (headings.length === 0) return null; + const at = nodes.indexOf(headings[0]!); + const end = nodes.findIndex((node, index) => index > at && node.type === "heading" && node.depth <= 2); + return nodes.slice(at + 1, end < 0 ? undefined : end); + }; + const items = (title: string, parse: (item: ListItem) => T | string): T[] => + (section(title) ?? []).flatMap((node) => { + if (node.type !== "list") return []; + return (node as List).children.flatMap((item) => { + const entry = parse(item); + if (typeof entry !== "string") return [entry]; + problems.push(`${RISK_FILE}:${item.position!.start.line}: ${entry}`); + return []; + }); + }); + const high = items("High", (item) => highPath(text, item)); + const classes = items("Automatic", (item) => automaticClass(text, item)); + for (const [index, each] of classes.entries()) + if (classes.findIndex((other) => other.name === each.name) < index) + problems.push(`${RISK_FILE} lists the class \`${each.name}\` twice`); + const suiteSection = section("Full suite"); + let suite: string | null = null; + if (suiteSection !== null) { + const blocks = suiteSection.filter((node): node is Code => node.type === "code"); + if (blocks.length !== 1 || blocks[0]!.value.trim() === "") + problems.push(`${RISK_FILE}'s ## Full suite must hold one fenced code block with the command`); + else suite = blocks[0]!.value.trim(); } - return { high, problems }; + return { high, classes, suite, problems }; } function headingText(text: string, node: RootContent): string { @@ -106,19 +138,36 @@ function headingText(text: string, node: RootContent): string { .trim(); } -/** One `## High` item, or why it is not one. */ -function highPath(text: string, item: ListItem): HighPath | string { +/** A list item's backticked code and the text after its ` - `, or null when it has not that shape. */ +function codeItem(text: string, item: ListItem): { code: string; rest: string } | null { const [first, ...rest] = item.children; - const shape = "a `## High` item is a backticked pattern, ` - `, and why its change is high"; - if (first?.type !== "paragraph" || rest.length > 0) return shape; + if (first?.type !== "paragraph" || rest.length > 0) return null; const [code] = (first as Paragraph).children; - if (code?.type !== "inlineCode") return shape; + if (code?.type !== "inlineCode") return null; const after = text.slice(code.position!.end.offset!, first.position!.end.offset!); - const reason = /^[ \t]+-[ \t]+(\S[\s\S]*)$/.exec(after)?.[1]?.replace(/\s+/g, " ").trim(); - if (reason === undefined) return shape; - const problem = patternError(code.value); - if (problem !== null) return `\`${code.value}\` is no pattern: ${problem}`; - return { pattern: code.value, reason }; + const tail = /^[ \t]+-[ \t]+(\S[\s\S]*)$/.exec(after)?.[1]?.replace(/\s+/g, " ").trim(); + return tail === undefined ? null : { code: code.value, rest: tail }; +} + +/** One `## High` item, or why it is not one. */ +function highPath(text: string, item: ListItem): HighPath | string { + const parsed = codeItem(text, item); + if (parsed === null) return "a `## High` item is a backticked pattern, ` - `, and why its change is high"; + const problem = patternError(parsed.code); + if (problem !== null) return `\`${parsed.code}\` is no pattern: ${problem}`; + return { pattern: parsed.code, reason: parsed.rest }; +} + +/** A class name: lowercase words joined by hyphens, so a record names it as one token. */ +const CLASS_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +/** One `## Automatic` item, or why it is not one. */ +function automaticClass(text: string, item: ListItem): Class | string { + const parsed = codeItem(text, item); + if (parsed === null) return "an `## Automatic` item is a backticked class name, ` - `, and the rule over the diff"; + if (!CLASS_NAME.test(parsed.code)) + return `\`${parsed.code}\` is no class name: use lowercase words joined by hyphens`; + return { name: parsed.code, rule: parsed.rest }; } /** The risk the PR body's `## Review` record names for its head. */ @@ -133,6 +182,10 @@ export interface RecordedRisk { session: string | null; /** The head the record names: in full, or its first 12 characters while a finding is open. */ head: string; + /** The `## Automatic` class the classifier found the change in, or null for none. */ + class: string | null; + /** The tier before the maintainer overrode it to `tier`, or null when they did not. */ + overridden: Tier | null; } /** @@ -153,6 +206,10 @@ export function recordedRisk(body: string): RecordedRisk | null { throw new Error(`the ## Review record's risk is malformed: ${line[1]}`); const by = classified[2]!; const session = /, session (`+) ?(.*?) ?\1$/.exec(by); + const named = /^- Class: `([a-z0-9-]+)`\r?$/m.exec(text); + const overridden = /^- Overridden: from (low|medium|high) by the maintainer\r?$/m.exec(text); + if (/^- Class:/m.test(text) !== (named !== null) || /^- Overridden:/m.test(text) !== (overridden !== null)) + throw new Error("the ## Review record's class or override is malformed"); return { tier: risk[1] as Tier, reason: risk[3]!, @@ -160,6 +217,8 @@ export function recordedRisk(body: string): RecordedRisk | null { by: by === PATHS ? "paths" : by === DEFAULT ? "default" : "model", session: session ? session[2]! : null, head: head[1]!, + class: named ? named[1]! : null, + overridden: overridden ? (overridden[1] as Tier) : null, }; } diff --git a/src/github/status.ts b/src/github/status.ts index 87790ce6..1c5bd3e0 100644 --- a/src/github/status.ts +++ b/src/github/status.ts @@ -182,7 +182,13 @@ function risk(body: string, head: string, record: ReviewRecord | null): Status[" const recorded = recordedRisk(body); if (recorded === null) return null; const state = record?.state ?? (head.startsWith(recorded.head) ? "current" : "stale"); - return { tier: recorded.tier, reason: recorded.reason, classified: recorded.classified, state }; + return { + tier: recorded.tier, + reason: recorded.reason, + classified: recorded.classified, + class: recorded.class, + state, + }; } async function reviewRecord( diff --git a/test/review.test.ts b/test/review.test.ts index b50825d3..b59315f8 100644 --- a/test/review.test.ts +++ b/test/review.test.ts @@ -1271,7 +1271,8 @@ fakes( async () => { const s = setup(); moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile(["- `src/` - customers' averages run on it"]))); - const listed = await quest("--root", s.repo, "review"); + // A high head gets a second reviewer on a model other than the pick's and the writer's. + const listed = await quest("--root", s.repo, "review", "--exclude-model", "claude-opus-5-5"); expect(listed.code, listed.stderr).toBe(0); const reason = "it changes src/lib.ts, which is always high: customers' averages run on it"; expect(listed.stdout).toContain(`\nrisk high ${reason}\nclassified high paths ${reason}\n\nreviewer codex`); @@ -1287,7 +1288,7 @@ fakes( git(t.repo, "merge", "-q", "--no-edit", "origin/main"); git(t.repo, "mv", ".github/workflows/ci.yml", "ci.yml"); git(t.repo, "commit", "-qm", "retire the workflow"); - const moved = await quest("--root", t.repo, "review"); + const moved = await quest("--root", t.repo, "review", "--exclude-model", "claude-opus-5-5"); expect(moved.code, moved.stderr).toBe(0); expect(moved.stdout).toContain(`base ${base} origin/main\n`); expect(moved.stdout).toContain( @@ -1302,7 +1303,7 @@ fakes( async () => { const s = setup(); moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile(["- `billing/**/*.ts` - charges customers"]))); - vi.stubEnv("FAKE_RISK", JSON.stringify({ tier: "low", reason: "Only a constant\nchanges." })); + vi.stubEnv("FAKE_RISK", JSON.stringify({ tier: "medium", reason: "Only a constant\nchanges." })); vi.stubEnv("FAKE_REPLY", JSON.stringify({ score: 10, rationale: "Lands as is.", findings: [] })); const first = await quest("--root", s.repo, "review"); expect(first.code, first.stderr).toBe(0); @@ -1311,8 +1312,8 @@ fakes( const session = call!.argv[call!.argv.indexOf("--session-id") + 1]; expect(first.stdout).toContain( [ - "risk low Only a constant changes.", - "classified low model Only a constant changes.", + "risk medium Only a constant changes.", + "classified medium model Only a constant changes.", `classifier claude claude-haiku-5-5 low ${session}`, "usage classify input 40 cached 0 output 3", "", @@ -1449,7 +1450,10 @@ fakes("a question no model answers usably throws with what each reply took", asy fakes("a reviewer raises the tier, and the record keeps the classifier's beside it", async () => { const s = setup(); moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile([]))); - const pull = { number: 7, body: "Fixes averaging.\n\n## Models\n\n- Size: S\n" }; + const pull = { + number: 7, + body: "Fixes averaging.\n\n## Models\n\n- Size: S\n- Implementer: Claude Code, claude-opus-5-5, high effort\n", + }; onGitHub(s.repo, [pull]); vi.stubEnv("FAKE_RAISE", "high"); try { @@ -1470,6 +1474,9 @@ fakes("a reviewer raises the tier, and the record keeps the classifier's beside "- Raised the risk to high: `It rewrites the wire format peers read.`", ].join("\n"), ); + // The raise to high gets the second review the medium tier skipped, in the same run. + expect(result.stdout).toContain("\nreviewer claude claude-sonnet-5-5 medium second\n"); + expect(pull.body).toContain("- Reviewer: Claude Code, claude-sonnet-5-5, medium effort, second\n"); expect(recordedRisk(pull.body)).toEqual({ tier: "high", reason: "It rewrites the wire format peers read.", @@ -1477,6 +1484,8 @@ fakes("a reviewer raises the tier, and the record keeps the classifier's beside by: "model", session, head: git(s.repo, "rev-parse", "HEAD").slice(0, 12), + class: null, + overridden: null, }); // A reviewer never lowers it. @@ -1491,9 +1500,97 @@ fakes("a reviewer raises the tier, and the record keeps the classifier's beside } }); +fakes( + "a raise to high saves its rounds before the second review, which falls back, and seats one second reviewer", + async () => { + const s = setup(); + moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile([]))); + const pull = { + number: 7, + body: "Fixes averaging.\n\n## Models\n\n- Size: S\n- Implementer: Claude Code, claude-opus-5-5, high effort\n", + }; + onGitHub(s.repo, [pull]); + vi.stubEnv("FAKE_RAISE", "high"); + const responses = join(s.repo, ".tmp", "responses.md"); + write(s.repo, ".tmp/responses.md", "1. Fixed.\n2. Fixed.\n3. Fixed.\n"); + const seconds = (out: string) => out.split("\n").filter((line) => /^reviewer .* second$/.test(line)); + try { + // The second reviewer the raise calls for cannot run, and no other model is left: an outage naming it. + vi.stubEnv("FAKE_LIMITED", "reset"); + vi.stubEnv("FAKE_FAILS", "claude-sonnet-5-5"); + const out = await quest("--root", s.repo, "review"); + expect(out.code).toBe(3); + expect(out.stderr).toContain("no eligible S reviewer could run: claude-sonnet-5-5 medium ("); + expect(out.stderr).not.toContain("gpt-6.1-sol"); + // The rounds that ran are saved and printed, so their findings can be answered. + expect(out.stdout).toContain("\nreviewer codex gpt-6.1-sol medium\n"); + expect(out.stdout).toContain("\nrisk high It rewrites the wire format peers read.\n"); + expect(out.stdout).toContain("\nfindings 1\n"); + + // The pick's raising round was saved, so the next run resumes it and seats the second reviewer at once. + vi.stubEnv("FAKE_LIMITED", undefined); + vi.stubEnv("FAKE_FAILS", undefined); + const resumed = await quest("--root", s.repo, "review", "--responses", responses); + expect(resumed.code, resumed.stderr).toBe(0); + expect(seconds(resumed.stdout)).toEqual(["reviewer claude claude-sonnet-5-5 medium second"]); + expect(pull.body).toContain( + "- Reviewer: Codex, gpt-6.1-sol, medium effort\n- Session: `thread-1`, round 2", + ); + + // On a new head the tier starts at medium, and the second reviewer settles its findings; when the + // round raises the tier again, that same seat is its second review, not another. + write(s.repo, "src/lib.ts", "export const x = 3;\n"); + git(s.repo, "commit", "-qam", "another constant"); + const again = await quest("--root", s.repo, "review", "--responses", responses); + expect(again.code, again.stderr).toBe(0); + expect(again.stdout).toContain("\nrisk high It rewrites the wire format peers read.\n"); + expect(seconds(again.stdout)).toEqual(["reviewer claude claude-sonnet-5-5 medium second"]); + + // A run naming the pick's effort still seats the second reviewer to settle its findings, from the + // size's whole list rather than the one reviewer --effort narrows the pick to. + write(s.repo, "src/lib.ts", "export const x = 4;\n"); + git(s.repo, "commit", "-qam", "a third constant"); + const named = await quest("--root", s.repo, "review", "--effort", "high", "--responses", responses); + expect(named.code, named.stderr).toBe(0); + expect(seconds(named.stdout)).toEqual(["reviewer claude claude-sonnet-5-5 medium second"]); + } finally { + vi.unstubAllGlobals(); + } + }, +); + +fakes("a raise to high with no other model left prints its saved rounds before the usage error", async () => { + const s = setup(); + moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile([]))); + vi.stubEnv("FAKE_RAISE", "high"); + try { + const out = await quest( + "--root", + s.repo, + "review", + "--size", + "S", + "--exclude-model", + "claude-opus-5-5", + "--exclude-model", + "claude-sonnet-5-5", + ); + expect(out.code).toBe(2); + expect(out.stderr).toContain("every other model of the size's list is avoided"); + expect(out.stdout).toContain("\nrisk high It rewrites the wire format peers read.\n"); + expect(out.stdout).toContain("\nreviewer codex gpt-6.1-sol medium\n"); + expect(out.stdout).toContain("\nfindings 1\n"); + } finally { + vi.unstubAllGlobals(); + } +}); + fakes("a raise from a reviewer the run leaves out holds while its last round reviewed the head", async () => { const s = setup(); - const pull = { number: 7, body: "Fixes averaging.\n\n## Models\n\n- Size: S\n" }; + const pull = { + number: 7, + body: "Fixes averaging.\n\n## Models\n\n- Size: S\n- Implementer: Claude Code, claude-opus-5-5, high effort\n", + }; onGitHub(s.repo, [pull]); vi.stubEnv("FAKE_REPLY", JSON.stringify({ score: 10, rationale: "Lands as is.", findings: [] })); // Only the shadow, Sol at high effort for an S PR, raises the tier. @@ -1532,6 +1629,108 @@ fakes("a raise from a reviewer the run leaves out holds while its last round rev } }); +fakes( + "a low head gets no local review, and the maintainer's override sets the tier until the change grows", + async () => { + const s = setup(); + moveBase(s.repo, (dir) => + write(dir, "RISK.md", `${riskFile([])}\n## Automatic\n\n- \`constants\` - only constants change\n`), + ); + const pull = { + number: 7, + body: "Fixes averaging.\n\n## Models\n\n- Size: S\n- Implementer: Claude Code, claude-opus-5-5, high effort\n", + }; + onGitHub(s.repo, [pull]); + vi.stubEnv( + "FAKE_RISK", + JSON.stringify({ tier: "low", reason: "Only a constant changes.", class: "constants" }), + ); + vi.stubEnv("FAKE_REPLY", JSON.stringify({ score: 10, rationale: "Lands as is.", findings: [] })); + try { + const low = await quest("--root", s.repo, "review"); + expect(low.code, low.stderr).toBe(0); + expect(low.stdout).toContain("\nrisk low Only a constant changes.\n"); + expect(low.stdout).toContain("\nclass constants\n"); + expect(low.stdout).not.toContain("\nreviewer "); + expect(low.stdout).toContain( + "\nnext done: the head is low risk, so the online reviewer alone reviews it\n", + ); + // Only the classifier ran, told the classes it may name. + const reviewers = ["gpt-6.1-sol", "claude-opus-5-5", "claude-sonnet-5-5"]; + expect(s.calls().filter((call) => reviewers.some((model) => call.argv.join(" ").includes(model)))).toEqual( + [], + ); + const [call] = classifying(s.calls()); + const schema = JSON.parse(call!.argv[call!.argv.indexOf("--json-schema") + 1]!); + expect(schema.properties.class.enum).toEqual(["constants", null]); + const head = git(s.repo, "rev-parse", "HEAD"); + // The head is named in full, so the record counts as its review. + expect(pull.body).toContain(`- Head: ${head}\n`); + expect(pull.body).toContain( + "- Class: `constants`\n- Local review: none, since a low-risk head needs only the online reviewer", + ); + expect(recordedRisk(pull.body)).toMatchObject({ tier: "low", class: "constants", overridden: null }); + + // The maintainer holds it high: the pick and a second reviewer on another model review it. + const held = await quest("--root", s.repo, "review", "--override", "high", "--reason", "It ships tonight."); + expect(held.code, held.stderr).toBe(0); + expect(held.stdout).toContain("\nrisk high It ships tonight.\noverridden low by the maintainer\n"); + expect(held.stdout).toContain("\nreviewer codex gpt-6.1-sol medium\n"); + expect(held.stdout).toContain("\nreviewer claude claude-sonnet-5-5 medium second\n"); + expect(recordedRisk(pull.body)).toMatchObject({ + tier: "high", + overridden: "low", + reason: "It ships tonight.", + }); + // The override outlasts a new head whose change is no riskier. + write(s.repo, "src/lib.ts", "export const x = 3;\n"); + git(s.repo, "commit", "-qam", "another constant"); + const kept = await quest("--root", s.repo, "review"); + expect(kept.stdout).toContain("\nrisk high It ships tonight.\n"); + // --effort changes only the pick, so a high head still gets its second reviewer. + write(s.repo, "src/lib.ts", "export const x = 7;\n"); + git(s.repo, "commit", "-qam", "a constant at a named effort"); + const effort = await quest("--root", s.repo, "review", "--effort", "high"); + expect(effort.code, effort.stderr).toBe(0); + expect(effort.stdout).toContain("\nreviewer codex gpt-6.1-sol high\n"); + expect(effort.stdout).toContain("\nreviewer claude claude-sonnet-5-5 medium second\n"); + // A riskier change than the one overridden ends it. + vi.stubEnv("FAKE_RISK", JSON.stringify({ tier: "medium", reason: "It changes the output.", class: null })); + write(s.repo, "src/lib.ts", "export const x = 4;\n"); + git(s.repo, "commit", "-qam", "a riskier constant"); + const grown = await quest("--root", s.repo, "review"); + expect(grown.code, grown.stderr).toBe(0); + expect(grown.stdout).toContain("\nrisk medium It changes the output.\n"); + expect(grown.stdout).not.toContain("\noverridden "); + + // An override to the tier the reviews settled on changes nothing, so nothing records one. + const same = await quest("--root", s.repo, "review", "--override", "medium", "--reason", "As it is."); + expect(same.code, same.stderr).toBe(0); + expect(same.stdout).toContain("\nrisk medium It changes the output.\n"); + expect(same.stdout).not.toContain("\noverridden "); + expect(recordedRisk(pull.body)).toMatchObject({ tier: "medium", overridden: null }); + + expect((await quest("--root", s.repo, "review", "--override", "low")).stderr).toContain( + "--override and --reason go together", + ); + + // A second reviewer that cannot run is the one the outage names, never the pick it ran beside. + // On a new head Codex runs until the failure stops it, so its seats fail with that same error. + write(s.repo, "src/lib.ts", "export const x = 5;\n"); + git(s.repo, "commit", "-qam", "a constant for the outage"); + vi.stubEnv("FAKE_HANG", join(s.bin, "..", "codex.pid")); + vi.stubEnv("FAKE_LIMITED", "reset"); + vi.stubEnv("FAKE_FAILS", "claude-sonnet-5-5"); + const out = await quest("--root", s.repo, "review", "--override", "high", "--reason", "It ships tonight."); + expect(out.code).toBe(3); + expect(out.stderr).toContain("no eligible S reviewer could run: claude-sonnet-5-5 medium ("); + expect(out.stderr).not.toContain("gpt-6.1-sol"); + } finally { + vi.unstubAllGlobals(); + } + }, +); + fakes("a malformed risk file on the base fails before any model runs", async () => { const s = setup(); moveBase(s.repo, (dir) => write(dir, "RISK.md", riskFile(["- `/etc/` - absolute", "- src/ without a reason"]))); diff --git a/test/risk.test.ts b/test/risk.test.ts index 17ce7cbd..cacd3de6 100644 --- a/test/risk.test.ts +++ b/test/risk.test.ts @@ -85,9 +85,16 @@ test("a risk file's ## High list is each backticked pattern and its reason; the { pattern: "src/billing/", reason: "charges customers, and refunds are manual" }, { pattern: "**/*.proto", reason: "peers on older releases read the wire format" }, ], + classes: [], + suite: null, + problems: [], + }); + expect(parseRiskFile("# Risk\n\nNothing is always high here.\n")).toEqual({ + high: [], + classes: [], + suite: null, problems: [], }); - expect(parseRiskFile("# Risk\n\nNothing is always high here.\n")).toEqual({ high: [], problems: [] }); const broken = parseRiskFile( [ @@ -132,6 +139,8 @@ test("the review record's risk reads back, and a record without one names none", by: "model", session: "thread-9", head, + class: null, + overridden: null, }); expect( recordedRisk( @@ -154,6 +163,82 @@ test("the review record's risk reads back, and a record without one names none", expect(() => recordedRisk(record([`- Head: ${head}`, "- Risk: low, `x`"]))).toThrow("risk is malformed"); }); +test("a risk file's ## Automatic list names each class and its rule, and ## Full suite one command", () => { + const text = [ + "# Risk", + "", + "## Automatic", + "", + "Each class below lands without a pick once low.", + "", + "- `tests` - only tests and their fixtures", + "- `internal-docs` - documentation no user reads,", + " such as plans", + "", + "## Full suite", + "", + "Run it for a high change.", + "", + "```sh", + "just gate --all", + "```", + ].join("\n"); + expect(parseRiskFile(text)).toEqual({ + high: [], + classes: [ + { name: "tests", rule: "only tests and their fixtures" }, + { name: "internal-docs", rule: "documentation no user reads, such as plans" }, + ], + suite: "just gate --all", + problems: [], + }); + + const broken = parseRiskFile( + [ + "## Automatic", + "", + "- `Tests` - capitalized", + "- tests - not backticked", + "- `docs` - one", + "- `docs` - twice", + "", + "## Full suite", + "", + "just gate", + ].join("\n"), + ); + expect(broken.classes).toEqual([ + { name: "docs", rule: "one" }, + { name: "docs", rule: "twice" }, + ]); + expect(broken.suite).toBeNull(); + expect(broken.problems).toEqual([ + "RISK.md:3: `Tests` is no class name: use lowercase words joined by hyphens", + "RISK.md:4: an `## Automatic` item is a backticked class name, ` - `, and the rule over the diff", + "RISK.md lists the class `docs` twice", + "RISK.md's ## Full suite must hold one fenced code block with the command", + ]); + expect(parseRiskFile("## Full suite\n\n```\na\n```\n\n```\nb\n```\n").problems).toEqual([ + "RISK.md's ## Full suite must hold one fenced code block with the command", + ]); +}); + +test("the review record's class and override read back", () => { + const record = (lines: string[]) => + ["## Review", "", `- Head: ${"a".repeat(40)}`, "- Risk: low, `the maintainer says so`", ...lines].join("\n"); + expect( + recordedRisk( + record(["- Overridden: from medium by the maintainer", "- Classified: low by default", "- Class: `tests`"]), + ), + ).toMatchObject({ tier: "low", class: "tests", overridden: "medium" }); + expect(() => recordedRisk(record(["- Classified: low by default", "- Class: tests"]))).toThrow( + "class or override is malformed", + ); + expect(() => recordedRisk(record(["- Classified: low by default", "- Overridden: by someone"]))).toThrow( + "class or override is malformed", + ); +}); + test("tiers order from low to high", () => { expect(riskier("high", "medium")).toBe(true); expect(riskier("medium", "medium")).toBe(false); diff --git a/test/status.test.ts b/test/status.test.ts index dbb394cc..7d640bf5 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -60,6 +60,7 @@ test("reports checks by requiredness, each reviewer's latest review against the "review-decision review_required", "review-record -", "risk -", + "class -", "auto-merge -", "merge-queue -", "landing-stopped -", @@ -120,7 +121,7 @@ test("a queued PR with auto-merge and no checks reports both, and JSON is determ threads: page([]), }); const status = await pullRequestStatus(pr, setup([body]).deps); - expect(statusLines(status).slice(2, 13)).toEqual([ + expect(statusLines(status).slice(2, 14)).toEqual([ "draft true", `head ${A}`, "mergeable mergeable", @@ -128,6 +129,7 @@ test("a queued PR with auto-merge and no checks reports both, and JSON is determ "review-decision -", "review-record -", "risk -", + "class -", "auto-merge squash kixelated 2026-10-07T12:00:00Z -", "merge-queue awaiting_checks 2 2026-10-07T12:01:00Z", "landing-stopped -", @@ -846,7 +848,13 @@ describe("the risk tier", () => { test("names the record's tier, the classifier's, and whether it covers the head", async () => { expect(await risk(record(A))).toEqual({ line: "risk high current medium it rewrites the wire format", - risk: { tier: "high", reason: "it rewrites the wire format", classified: "medium", state: "current" }, + risk: { + tier: "high", + reason: "it rewrites the wire format", + classified: "medium", + class: null, + state: "current", + }, }); // A record with an open finding names its head by 12 characters, and no full SHA. expect((await risk(record(A.slice(0, 12)))).line).toBe("risk high current medium it rewrites the wire format"); diff --git a/test/suite.test.ts b/test/suite.test.ts new file mode 100644 index 00000000..c24feddc --- /dev/null +++ b/test/suite.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from "vitest"; + +import { parseRiskFile } from "../src/core"; +import { suiteFor } from "../src/cli/suite"; + +test("the full suite runs for a high head, or one no tier covers, and only where the risk file names it", () => { + const file = parseRiskFile("## Full suite\n\n```sh\njust gate --all\n```\n"); + const risk = (tier: "low" | "medium" | "high", state: "current" | "diff-identical" | "stale" | "unknown") => ({ + tier, + reason: "why", + classified: tier, + class: null, + state, + }); + expect(suiteFor(risk("high", "current"), file)).toBe("just gate --all"); + expect(suiteFor(risk("medium", "current"), file)).toBeNull(); + expect(suiteFor(risk("low", "diff-identical"), file)).toBeNull(); + // A record that does not cover the head says nothing about it, so the gate runs everything. + expect(suiteFor(risk("low", "stale"), file)).toBe("just gate --all"); + expect(suiteFor(risk("low", "unknown"), file)).toBe("just gate --all"); + expect(suiteFor(null, file)).toBe("just gate --all"); + // Without a full suite there is nothing beyond the scoped checks to add. + expect(suiteFor(risk("high", "current"), parseRiskFile("# Risk\n"))).toBeNull(); + expect(suiteFor(null, null)).toBeNull(); +}); diff --git a/test/usage.test.ts b/test/usage.test.ts index f9060ca1..9da54ad0 100644 --- a/test/usage.test.ts +++ b/test/usage.test.ts @@ -279,7 +279,13 @@ describe("PR records", () => { const risk: Risk = { tier: "medium", reason, - classified: { tier: "medium", reason, by: { kind: "paths" }, usage: [] }, + classified: { tier: "medium", reason, by: { kind: "paths" }, class: null, usage: [] }, + }; + const at = { + branch: round.branch, + head: round.head, + base: round.base, + sized: { size: round.size, from: round.sizeFrom }, }; const tallies = [ { ...tally("codex", 3, { high: 1, medium: 1, low: 2 }, 2, 1), first: { high: 1, medium: 0, low: 1 } }, @@ -296,7 +302,7 @@ describe("PR records", () => { }; test("reads back each reviewer's round and tally quest review records, after the land fixer's lines", () => { - const body = `Summary.\n\n## Review\n\nmechanical fix by codex, gpt-6.1-sol, medium effort: \`merged\` (head ${"d".repeat(40)})\n\n${reviewRecord({ rounds: [round, second], tallies, risk, skipped: [SKIP] })}\n\n## Models\n\n- Size: L\n`; + const body = `Summary.\n\n## Review\n\nmechanical fix by codex, gpt-6.1-sol, medium effort: \`merged\` (head ${"d".repeat(40)})\n\n${reviewRecord({ ...at, rounds: [round, second], tallies, risk, skipped: [SKIP] })}\n\n## Models\n\n- Size: L\n`; expect(body).toContain( "\n- Rounds: 3; first round 2 (high 1, low 1); findings 4 (high 1, medium 1, low 2): fixed 2, refuted 1, open 1\n", ); @@ -310,6 +316,7 @@ describe("PR records", () => { model: "gpt-6.1-sol", effort: "high", shadow: false, + second: false, session: THREAD, round: 3, score: 7, @@ -329,6 +336,7 @@ describe("PR records", () => { model: "gpt-6.1-sol", effort: "medium", shadow: true, + second: false, session: "thread-2", round: 1, score: 10, @@ -349,6 +357,7 @@ describe("PR records", () => { model: "m", effort: "high", shadow: false, + second: false, session: CLAUDE, round: null, score: null, @@ -368,9 +377,9 @@ describe("PR records", () => { expect(body).not.toContain("b".repeat(40)); // Claude's left-out tally still holds an open finding, which keeps it short too. const clean = [{ ...round, findings: [] }, second]; - expect(reviewRecord({ rounds: clean, tallies, risk, skipped: [] })).not.toContain("b".repeat(40)); + expect(reviewRecord({ ...at, rounds: clean, tallies, risk, skipped: [] })).not.toContain("b".repeat(40)); const settledAll = [tally("codex", 3, { high: 1, medium: 1, low: 2 }, 3, 1), tallies[1]!]; - expect(reviewRecord({ rounds: clean, tallies: settledAll, risk, skipped: [] })).toContain( + expect(reviewRecord({ ...at, rounds: clean, tallies: settledAll, risk, skipped: [] })).toContain( `- Head: ${"b".repeat(40)}\n`, ); expect(fixes(body)).toEqual(["codex, gpt-6.1-sol, medium effort"]); @@ -380,6 +389,7 @@ describe("PR records", () => { expect(reviewSessions(newer)).toEqual([THREAD, "thread-2", CLAUDE]); expect(classifierSessions(body)).toEqual([]); const classified = reviewRecord({ + ...at, rounds: [round], tallies, skipped: [], @@ -395,7 +405,7 @@ describe("PR records", () => { }); test("a record written before tallies has none, and a Rounds line that does not add up fails", () => { - const record = reviewRecord({ rounds: [second], tallies: [tallies[1]!], risk, skipped: [] }); + const record = reviewRecord({ ...at, rounds: [second], tallies: [tallies[1]!], risk, skipped: [] }); const older = `## Review\n\n${record.replace(/^- Rounds: .*\n/m, "")}\n`; expect(parseReview(older)[0]!.tally).toBeNull(); // The settled count `quest usage` prints reads back. @@ -518,6 +528,7 @@ describe("usage", () => { const RISK = [ "- Risk: high, `It rewrites the wire format.`", `- Classified: medium by Claude Code, claude-haiku-5-5, low effort, session \`${OWNED}\``, + "- Class: `tests`", ].join("\n"); const json = (value: unknown) => new Response(JSON.stringify(value), { status: 200 }); const pr = (number: number, branch: string, body: string, created: string, extra: object = {}) => ({ @@ -1032,7 +1043,7 @@ describe("usage", () => { " review: Codex, gpt-6.1-sol, medium effort, shadow; not in the latest run; rounds 1, findings 3 (high 3): fixed 2, refuted 1, open 0\n", ); expect(text).toContain( - "#10 L high merged: PR 10 (quest/m0/a)\n risk: high, It rewrites the wire format.; raised from medium by a reviewer\n", + "#10 L high merged: PR 10 (quest/m0/a)\n risk: high, It rewrites the wire format.; raised from medium by a reviewer; class tests\n", ); expect(text).toContain("#11 - - merged: PR 11 (fix/a)\n"); // #11 breaks down by culprit, #2 read from GitHub; #12 never merged, and #99 is no PR. @@ -1057,11 +1068,16 @@ describe("usage", () => { ); // #10 is the one PR with a tier, and a later PR fixed it; #11, #5, and #6 of the rest merged. expect(report.tiers).toEqual([ - { tier: "high", pulls: 1, merged: 1, raised: 1, culprits: 1 }, - { tier: null, pulls: 9, merged: 3, raised: 0, culprits: 0 }, + { tier: "high", pulls: 1, merged: 1, raised: 1, overridden: 0, culprits: 1, person: 0 }, + { tier: null, pulls: 9, merged: 3, raised: 0, overridden: 0, culprits: 0, person: 0 }, ]); expect(text).toContain( - "By risk tier:\n high 1 PRs, 1 merged, 1 raised by a reviewer, 1 later fixed\n - 9 PRs, 3 merged, 0 raised by a reviewer, 0 later fixed", + "By risk tier:\n high 1 PRs, 1 merged, 1 raised by a reviewer, 0 overridden, 1 later fixed; waited on a person 0s\n - 9 PRs, 3 merged, 0 raised by a reviewer, 0 overridden, 0 later fixed; waited on a person 0s", + ); + // A class the classifier named, though the high tier keeps it from landing without a pick. + expect(report.classes).toEqual([{ class: "tests", pulls: 1, low: 0, merged: 1, culprits: 1, person: 0 }]); + expect(text).toContain( + "By automatic class:\n tests 1 PRs, 0 low, 1 merged, 1 later fixed; waited on a person 0s", ); expect(text).toContain("findings 2 (high 1, low 1): fixed 1, refuted 0, settled 1, open 0\n"); expect(text).toContain(