Repository navigation
feat(review): give every line of a large diff an accountable reviewer - #6612
Conversation
Review agents were handed the diff *command* and left to run it themselves. Shell tool output is capped at 30 000 characters and split head-1/5 / tail-4/5, so on a large changeset every agent received a few hundred lines off the top of the first file, the tail of the last file, and a truncation marker in place of everything between. Measured on a 211 000-character diff: 14.4% of the changeset, the same 14.4% for all ten agents. Nineteen of the twenty defects maintainers eventually confirmed on that PR lay in the hidden 85.6%. The ten-way dimension fan-out multiplied redundant reads of the visible sliver rather than adding coverage, and each review round sampled a different subset of the bugs depending on which files an agent happened to open on its own. The diff is now captured to a file and partitioned. `read_file` still caps a single read at ~25 000 characters, so writing the diff out is necessary but not sufficient — a whole-file read of that diff returns its first 611 lines. Chunks are therefore bounded by both a line budget (attention) and a character budget (what one un-truncated read returns), split on hunk boundaries, and never through the middle of a function. They tile the diff exactly, which is what makes the new coverage receipts checkable: past 500 diff lines each chunk gets one agent that owns it and must account for it, and a chunk with no receipt is re-reviewed before the run proceeds. "No blockers" can no longer be reported over code nobody read. Coverage alone did not close the gap. Chunk agents held every state-machine defect in that PR inside their assigned territory and reported none of them: the bugs were not inside any hunk but between new lines sitting two thousand lines apart, and what the agents lacked was not the lines but the question. A heavily rewritten file now also gets three whole-file agents that walk a fixed invariant checklist — mutable fields cleared on every exit path, timers cancelled on every close without discarding captured data, map inserts matched by deletes, retry counters incremented at every entry, status returns actually checked, error codes classified permanent versus transient, config honoured on every path, early returns that skip a required side effect. The checklist is split three ways deliberately: one agent asked to run all eight checks over a 2 400-line file runs one of them properly. Verification is sharded at eight findings per agent, because one verifier re-reading code for sixty findings degrades on the tail of its list. A verifier may now downgrade a Critical but never delete one — a rejected Critical is invisible to every later stage, a downgraded one still reaches a human. The reverse audit fans out per chunk instead of asking a single context-starved agent to re-read the whole diff, no longer skips verification, and stops after two consecutive dry rounds rather than one: on the PR that motivated this, the review reported "no blockers" twice and the next round surfaced five Criticals, three of them in code present since the first commit.
Step 3A told every agent to read the whole diff in one call. `read_file` truncates a single call at ~25 000 characters, so a 500-line diff of long lines would come back short — the same blind spot the chunk plan removes, reintroduced at a smaller scale. Across the last 39 merged PRs that take the Step 3A path the largest diff is 23 570 characters, so this never fired in practice, but the margin is six percent. Step 3A now walks the chunk ranges, which are sized to fit one un-truncated read: one or two calls at this size. Derive a file's pre-change line count from the diff instead of measuring it with a second `git show` per file. `git show <base>:<newpath>` returns nothing for a renamed file, reporting zero pre-change lines and classifying a wholesale rewrite as light. The identity holds exactly for creations, deletions, renames and ordinary edits, and halves the process spawns.
There was a problem hiding this comment.
Pull request overview
This PR updates the /review workflow to avoid truncated diffs on large PRs by capturing the diff to disk, partitioning it into bounded chunks that tile the entire diff, and assigning each chunk to exactly one agent with an explicit coverage receipt. It also adds additional whole-file invariant review for heavily rewritten files, shards verification work, and improves reverse-audit behavior on large diffs.
Changes:
- Capture PR diffs as raw bytes to a temp file, build a diff “chunk plan” bounded by both line and character budgets, and emit chunk/file rewrite metrics in
fetch-pr’s report. - Add diff-plan parsing + chunking implementation with unit tests to guarantee exact tiling and safe split behavior for oversized hunks.
- Update the bundled review skill + user docs to describe the new large-diff topology (chunk agents, invariant agents, sharded verification, per-chunk reverse audit).
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/core/src/skills/bundled/review/SKILL.md | Documents the new diff-file + chunk-based review topology and coverage receipts. |
| packages/core/src/skills/bundled/review/DESIGN.md | Explains design rationale for sharded verification, per-chunk reverse audit, and invariant-agent checklist splitting. |
| packages/cli/src/commands/review/lib/git.ts | Adds gitRaw() to capture diffs as raw bytes (no CRLF normalization, no trim, larger buffer). |
| packages/cli/src/commands/review/lib/diff-plan.ts | New unified-diff parser + chunk planner enforcing line/char budgets and exact diff tiling. |
| packages/cli/src/commands/review/lib/diff-plan.test.ts | Tests chunk tiling, reconstruction, safe split points, char budget binding, and edge cases. |
| packages/cli/src/commands/review/fetch-pr.ts | Captures diff to .qwen/tmp, builds chunk plan, computes per-file rewrite/heavy metrics, and emits them in the report. |
| packages/cli/src/commands/review/fetch-pr.test.ts | Unit tests for the heaviness classification rule (including rounding vs exact ratio). |
| docs/users/features/code-review.md | Updates user-facing docs for Step 3A/3B and the new chunk/invariant/sharded verification/reverse-audit pipeline. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Diff size is a bad proxy for review risk because test code dominates it. Across this repo's last 40 merged PRs the median diff is 41% test code and 14 of the 40 are more than half tests; PR QwenLM#6457, which motivated the territory fan-out, is itself 58% tests. Gating on raw diff lines therefore carved small production changes into territories: a change of 173 source lines shipping 489 lines of new tests went to the chunked topology, where its production code ended up owned by a single agent, when the dimension fan-out would have read it through eight lenses. Territory fan-out is worth it when there is a lot of risky code to divide, not a lot of lines. The gate is now `srcDiffLines > 500`, with `diffLines > 2400` as a second clause — a delivery bound rather than a risk one, since past that point chunking uses fewer agents than the ten-lens topology anyway and reading a diff that large dilutes all ten. On the 40-PR sample six PRs move back to the dimension fan-out, for about 5% more agents in total across the sample. Paths are classified as source, test, or generated, and the per-kind line counts ship in the fetch report. Chunking is unchanged: the plan still tiles every line, tests and generated files included. What the gate decides is how many reviewers there are and what each is asked to do. Heaviness is likewise restricted to source files — the invariant checklist asks about fields, timers, collections, and error taxonomies, and a rewritten test file has none of those.
`git diff` C-quotes any path with a control character or a non-ASCII byte, so a file named `sub/中文文件.ts` arrives as `"b/sub/\344\270\255..."`. The chunk planner stripped the backslashes, turning it into `sub/344270255...ts` — a name that exists nowhere. Every downstream use of the path then failed silently: the line count came back zero, the file could never be classified as heavy, and the chunk agent was told it was reviewing a file that does not exist. Reuse core's `unquoteCStylePath`, which reassembles the octal escapes as UTF-8 bytes, rather than keeping a second, wrong decoder here. Coverage was never affected — line ranges stayed correct — but this repo has non-ASCII paths, so the mislabelling was reachable. Also correct two places that claimed hunks are never split. They are: a hunk larger than the chunk target is split at a top-level declaration, because a brand-new file arrives as one enormous hunk and treating it as atomic would hand a single agent a 50 000-character territory.
Four defects, all found in review of this branch. Diff capture obeyed whatever the user's git config said. With `color.diff=always` every `diff --git` line arrives wrapped in ANSI escapes, the parser recognises none of them, and the plan comes back with zero files and zero chunks — the coverage guarantee silently evaluates to nothing. `diff.mnemonicPrefix` renames the `a/`/`b/` prefixes to `i/`/`w/` and every path is then wrong; `diff.external` and textconv filters emit output that is not a unified diff at all. Capture now pins `--no-ext-diff --no-textconv --no-color --unified=3` and the two prefixes. The `diff --git` header was split with a greedy regex. Git separates the two paths with a space and does not quote a path merely for containing one, so `a/img with space.png b/img with space.png` split into `space.png`. Usually the `---`/`+++` headers disambiguate, but a binary or mode-only section has neither. For a non-rename both paths are the same string, so the split point is arithmetic; a rename states its new path outright in `rename to`. A chunk boundary could land on a `-` line. Those exist only on the old side, so the "starts at a top-level declaration" guarantee did not hold for the post-change file an invariant agent later reads. Split points are now restricted to lines present on the new side. An `oversized` chunk — one hunk with no safe interior boundary — can exceed what a single `read_file` returns. Chunks now carry their character count, and a chunk agent is told to page when a read reports truncation. A `Covered:` receipt for a range the agent only half read is worse than no receipt at all.
…or anchors Both defects surfaced running the new review against PR QwenLM#6591. A 1431-line React component was emitted as a single 45 675-character chunk — nearly twice what one `read_file` returns — because the splitter looked for a safe boundary only inside the 400-line budget window, found none, and gave up on the entire remainder. Twenty-seven boundaries existed further along; the first sat 460 lines in. It now reaches past the window for the next one, so a single distant boundary can no longer collapse a whole file into one chunk. That PR goes from 15 chunks with one over the read cap to 18 with none. Step 7 validated comment anchors by trial. GitHub rejects an entire review with a 422 if any comment's line falls outside every hunk of its file, and the skill offered no cheap way to check, so a run against a real PR submitted five throwaway reviews carrying the bodies `Test`, `Test`, `t`, `t`, `t` to discover which anchors would stick. Those are permanent, public reviews on someone else's pull request. The fetch report now carries each file's hunks as new-side line ranges, which turns the check into a lookup, and the skill states plainly that a review is never submitted to test an anchor.
wenshao
left a comment
There was a problem hiding this comment.
— qwen3.7-max via Qwen Code /review
Suggestions — commit
|
| File | Issue | Suggested fix |
|---|---|---|
diff-plan.ts:465 |
|| vs ?? on numeric newStart — 0 is valid for +0,0 deletion hunks |
Replace || with ?? |
fetch-pr.ts:166-172 |
fileLineCount spawns N sequential git show processes (100+ files = seconds of overhead) |
Batch with git ls-tree -l or git diff --numstat |
diff-plan.ts:485 |
diffText split into lines array twice (parseDiff + buildDiffPlan) |
Have parseDiff return the lines array |
git.ts:55-58 |
No --no-ext-diff passed — external diff tools could be invoked on PR content |
Add --no-ext-diff to gitRaw('diff', ...) |
diff-plan.ts:119 |
MAX_CHUNK_CHARS coupling to read_file threshold is comment-only |
Import actual threshold or add runtime assertion |
fetch-pr.ts:143-148 |
Deleted files flagged as heavy when changedLines >= 800 |
Exclude deleted files from heavy, or add deleted flag |
fetch-pr.ts:335 |
No -M for explicit rename detection — relies on user git config |
Pass -M to gitRaw('diff', ...) |
fetch-pr.ts:226 |
resolveMergeBase discards fetch return value — failure is not logged |
Log when fetch returns null |
diff-plan.ts:216-226 |
parseDiff doesn't guard ---/+++ checks against open hunk — a removed line starting with -- matches --- |
Add !curHunk guard to header checks |
diff-plan.ts:47-48 |
GENERATED_RE misses generated/ dirs and *.generated.* files |
Add `(^ |
git.ts:57-61 |
No --no-color — color.ui=always injects ANSI escapes into captured diff |
Add --no-color to gitRaw |
diff-plan.ts:177 |
diff --git regex greedy on paths with spaces (mode-only/binary sections) |
Document limitation or use --name-status -z |
diff-plan.ts:44 |
TEST_RE misses Cypress (*.cy.ts), *.e2e.ts, cypress/ dir |
Add Cypress/e2e patterns |
— qwen3.7-max via Qwen Code /review
wenshao
left a comment
There was a problem hiding this comment.
Downgraded from Request changes to Comment: self-PR. Critical findings are inline.
Eleven defects from review of this branch. The worst two were silent. A unified diff emits a removed line whose content starts with `-- ` as `--- ...`, and an added line whose content starts with `++ ` as `+++ ...`. SQL, Lua and Haskell comments start with `-- `. The parser read those payload lines as file headers: the path was overwritten by the line's text, and the line vanished from the add/remove counts. A two-file diff — one SQL file losing a comment, one text file gaining a `++ ` line — came back with the second file named `plus line`. Metadata is now only recognised before a file's first hunk. The tiling invariant — every diff line belongs to exactly one chunk, which is what makes a missing coverage receipt mean something — was asserted only in tests. `buildDiffPlan` now checks it and refuses to return a plan with a hole. The rest: a split point could take a *deleted* blank line as evidence of the blank line before a declaration, though that blank exists only in the old file; whole-file invariant agents were pointed at `chunks[].files[]`, which merges hunks at lines 10 and 900 into one `10-902` span and would have had them report pre-existing defects as new; pure-deletion hunks were exported as the inclusive range `[N, N]`, so a right-side comment could be anchored where GitHub has no line and the 422 would sink the whole review; a deleted file could be marked heavy and send three agents to read a post-image that does not exist; a chunk holding a single line longer than one `read_file` can never be fully read by paging, and must now report itself uncoverable rather than receipt a lie; capture did not pin rename detection or `--no-relative`; `gitRaw` had no timeout, so a credential prompt on headless CI would hang forever; a failed base fetch was swallowed, leaving a stale merge-base and a structurally complete report describing the wrong diff; and local reviews still captured with a bare `git diff`, which `color.diff=always` alone renders unparseable. Adds an integration test that drives the real capture against a real repository under hostile git config, covering the paths synthetic fixtures cannot: renames and binaries and mode-only changes with spaces in their names, C-quoted non-ASCII names, and payload lines that impersonate headers.
wenshao
left a comment
There was a problem hiding this comment.
Downgraded from Request changes to Comment: self-PR; CI still running. Critical findings are inline.
— GPT-5 via Qwen Code /review
…nk spans Four defects from review of this branch. Diff capture left submodules to user config. `diff.ignoreSubmodules=all` hides a changed gitlink completely — a silent coverage hole in the file that is now the review's source of truth — and `diff.submodule=log` replaces the whole `diff --git` section with prose no parser can read. Both are pinned now, and the integration test asserts a bumped gitlink survives them. Whole-file invariant agents were handed `files[].hunks[]` as "the changed lines". A hunk spans the three context lines git prints either side of every change: on PR QwenLM#6457's `QQChannel.ts` those spans cover 1 962 new-side lines of which only 1 403 were written. The agent would have reported defects in 559 lines that predate the PR. The report now also carries `addedRanges[]` — the exact lines the change wrote — and the skill gates invariant agents on those, keeping `hunks[]` for the one thing it is right for, GitHub anchor validation. `Uncoverable:` was introduced as a chunk agent's answer for a chunk holding a line longer than one read, but the receipt accounting still demanded a `Covered:` line from every chunk and relaunched any chunk lacking one — so an uncoverable chunk would have been retried forever. It is now a first-class terminal status: accepted by the accounting, carried into Step 6 under "Not reviewed", and it blocks an Approve verdict. Step 3A, which also walks the chunk plan, is covered by the same rule. The integration test built its fixture repository inside the developer's git environment, so a global `core.hooksPath` or `commit.gpgsign` ran during the test and `~/.gitconfig` decided what the "clean" baseline was. It now disables system and global config, hooks and signing, and sets the executable bit through the index rather than shelling out to `chmod`, which does nothing on Windows.
The report tells an agent how to page everything else, so it has to be readable in one `read_file` — about 25 000 characters. Running the real `fetch-pr` against PR QwenLM#6457 produced 25 070. Two constraints pull against each other. Compact JSON is a single enormous line, and `read_file` pages at line boundaries, so a report too big for one call could never be read at all. Indented JSON pages fine but spends four lines on `{ "start": 812, "end": 815 }`, and a heavily rewritten file contributes hundreds of them: `QQChannel.ts` alone carries 140 added ranges and 49 hunks. So indent the structure and inline the leaves. Same JSON, same keys, one range per line, still pageable — and 28% smaller. The QwenLM#6457 report goes from 25 070 bytes to 18 042, and the "page it" warning that used to fire on a seven-file PR now stays quiet. The earlier attempt at this trimmed `addedRanges` to heavy files only and landed at 24 992 bytes on the same PR. Eight bytes of headroom was not a fix. Tests pin the three properties that matter: the collapsed text parses back to an identical object, no range spans two lines, and a path that literally spells a range is not mistaken for one — JSON escapes the quotes inside a string value, and the collapse patterns require unescaped ones.
…es behind
`cleanStale` and `cleanup` both guarded `git worktree remove` behind
`existsSync(path)`, and neither ever pruned. Delete the directory by hand — which
is exactly what reclaiming disk with `rm -rf .qwen/tmp` does — and git keeps the
worktree registered but missing. From then on `/review` on that PR cannot run:
$ git worktree add .qwen/tmp/review-pr-6457 qwen-review/pr-6457
fatal: '...' is a missing but already registered worktree;
use 'add -f' to override, or 'prune' or 'remove' to clear
and the branch delete that `cleanStale` does next fails too, because the phantom
worktree still has that branch checked out. Nothing in the review command surface
ran `git worktree prune`, so nothing ever cleared it.
This surfaced running the real skill: the orchestrator's first `fetch-pr` failed,
it fell back to `qwen review cleanup`, and retried. The leak is not rare — three
abandoned worktrees from May and June were still registered in this checkout,
one per review that died before Step 9.
`releaseWorktree` now does both halves in the order they depend on: remove the
directory if it is there, prune the registration unconditionally (a no-op when
nothing is stale), and only then let the caller delete the branch. Both callers
share it.
The tests drive real git. Deleting a worktree directory by hand and re-adding it
throws "missing but already registered" without the prune, and `branch -D` throws
"used by worktree" — both assertions fail if the prune is removed, which is the
point of writing them.
`read_file` returns the first `truncateToolOutputThreshold` characters — 25 000 by default — sets `isTruncated`, and pages by line. `pr-context` wrote "## Open inline comments (no replies yet — may still need attention)" last, so on a PR with a long history it was the first thing lost, and nothing read the flag that said so. On PR QwenLM#5738 that section began at character 27 125 of a 31 220-character file. The review submitted "Reviewed — no blockers." Five Critical threads were unresolved; four had in fact been addressed, but the fifth — `clearCiEnv()` clearing only `CI*` while `writeTerminalTitle` branches on `TMUX`/`STY`/ `ZELLIJ`/`DVTM` — was live, in the diff, and never seen. Regenerating the context for ten PRs: four lost part or all of the section, and all four were the PRs with the most review rounds. Small PRs never trip it. - Emit the open threads before the already-discussed ones. The findings a round must answer outrank the ones already settled. - `pr-context` warns when the file exceeds the threshold, naming any headings past the cut, and says so plainly when the loss is inside the last section's body instead. - Step 2 of SKILL.md now tells the agent to read `isTruncated` and page the remainder before Step 3. Reordering buys headroom; it does not create it. A 40 000-character context still loses its tail, which is what the warning is for.
|
@qwen-code /triage |
…ls before approving Two gaps the dogfood on live PRs surfaced, both invisible from reading the skill. `load-rules` looks for a `## Code Review` heading in AGENTS.md and QWEN.md. Neither had one, so it wrote an empty file on every run: every `/review` in this repo reviewed with zero project rules. Add the section, distilled from the conventions already scattered through AGENTS.md (ESM, no cross-package relative imports, kebab-case/PascalCase naming, collocated tests, comments-only-when-why), plus the two hard lessons below. The section loads from the base branch by design — a PR cannot inject its own review rules — so it takes effect once merged. The skill treated a zero-Critical outcome as a fallback rather than a claim. On one PR it published two Criticals citing code not present at the reviewed commit (a fabricated blocker on an already-approved PR); on another it submitted C=0 while a live, twice-filed Critical still stood (a dropped blocker). Add a step before the verdict: for each unresolved Critical on the PR, read the code at the reviewed commit and record still-stands / fixed-by-this-diff / cannot-tell. The event follows from the code, not from the finding count or the thread flags — `isResolved`/`isOutdated` track the anchored line, not whether the bug was fixed. - AGENTS.md: new `## Code Review` section. - load-rules.ts: export `extractCodeReviewSection`; load-rules.test.ts covers the boundary scan and asserts AGENTS.md's own section extracts non-empty, so deleting the heading fails the build. - SKILL.md: re-verification step ahead of the Verdict.
What this PR does
/reviewused to hand each review agent the diff command and let the agent run it. Shell tool output is capped at 30 000 characters and split one-fifth head, four-fifths tail, so on a large changeset every agent received a few hundred lines off the top of the first file, the tail of the last file, and a truncation marker in place of everything between. This PR captures the diff to a file, partitions it into chunks that each fit inside one un-truncated read, and makes every chunk the responsibility of exactly one agent who must return a coverage receipt for it. A chunk with no receipt is re-reviewed before the run proceeds, so a review can no longer report "no blockers" over code that nobody read.The topology is chosen from the diff's source lines, not its raw size. Test code dominates diff size — across this repo's last 40 merged PRs the median diff is 41% tests, and the PR that motivated this work is itself 58% tests — so a gate on raw size would carve a 173-line production change into territories merely because it shipped 489 lines of new tests, leaving that production code with one reviewer instead of eight lenses. Chunking still covers every line either way; the gate decides only how many reviewers there are and what each is asked to do.
Coverage alone turned out not to be enough. A source file that has been largely rewritten now also gets three agents that read it whole and walk a fixed invariant checklist: mutable fields cleared on every exit path, timers cancelled on every close without discarding data the callback already captured, map inserts matched by deletes, retry counters incremented at every entry point, status return values actually checked, error codes classified permanent versus transient, config options honoured on every path that should honour them, and early returns that skip a side effect a later path depends on. The checklist is split three ways on purpose — one agent asked to run all eight checks over a 2 400-line file runs one of them properly.
Three smaller changes follow from the same evidence. Verification is sharded at eight findings per agent, since a single verifier re-reading code for sixty findings degrades badly on the tail of its list. A verifier may now downgrade a Critical but never delete one, because a rejected Critical is invisible to every later stage while a downgraded one still reaches a human. And the reverse audit fans out per chunk rather than asking one context-starved agent to re-read the whole diff, no longer skips verification, and stops after two consecutive dry rounds instead of one.
Why it's needed
Large PRs were taking a dozen review rounds and still surfacing blocking defects. The cause was measurable rather than a matter of prompt quality. On a real 211 000-character changeset, the truncation left each agent seeing 14.4% of the diff — and the same 14.4% for all ten of them, so the ten-way fan-out along review dimensions multiplied redundant reads of one visible sliver instead of adding coverage. Nineteen of the twenty defects maintainers eventually confirmed on that PR lay in the hidden 85.6%. Whatever those reviews did find, they found by opening source files on their own initiative, which is why each round returned a different, apparently random subset of the bugs and why the process never converged.
Writing the diff to a file is necessary but not sufficient: a single whole-file read of that same diff returns only its first 611 lines. That is why chunks are bounded by both a line budget, for attention, and a character budget, for what one read actually returns, and why the chunks are required to tile the diff exactly. Exact tiling is what turns "did anyone look at this hunk?" from an unanswerable question into an assertion the orchestrator can check.
The invariant agents exist because visibility is necessary and not sufficient. On the same PR, chunk agents held every state-machine defect inside their assigned territory and reported none of them. Those bugs were not inside any single hunk; they were between new lines sitting two thousand lines apart — a timer armed near the top of a file and a teardown path near the bottom. What the agents lacked was not the lines but the question. "Review this diff for bugs" and "list every retry counter, then check the increment at each of its call sites" are not the same instruction, and only the second one finds a ceiling that can never be reached.
Reviewer Test Plan
How to verify
Run
qwen review fetch-pragainst any large PR and inspect the report it writes. It should now containdiffPath,diffPathAbsolute,diffLines, achunksarray, and a per-filefilesarray carrying rewrite metrics. Confirm the captured diff is byte-identical togit diff <mergeBaseSha>..<fetchedSha>, that the chunk ranges reconstruct it verbatim with no gap or overlap, and that no chunk exceeds the character budget. Reading a chunk withread_file(file_path=diffPathAbsolute, offset=startLine-1, limit=lines)should return the full range with nothing elided; reading the same diff in one call should not.On a PR carrying more than 500 lines of source change (or more than 2 400 diff lines in total), a review should now launch one agent per chunk rather than ten agents over the whole diff, each agent should end its response with a
Covered:receipt, and the receipts should account for every chunk id exactly once. On a PR that heavily rewrites an existing file, three additional whole-file agents should run against that file, and the fetch report'sfilesarray should mark itheavy. A brand-new file should not be marked heavy, even though its rewrite ratio is 1.0 by definition.Unit coverage:
npx vitest run src/commands/reviewfrompackages/cli(70 tests, including 7 that drive a real git repository under hostile config). The diff-plan tests assert exact tiling, verbatim reconstruction, that a chunk boundary never falls inside a function, and that both the line and character budgets bind. The fetch-pr tests pin the heaviness rule, including the two cases that were wrong in an earlier draft — a new file must not count as a rewrite, and the ratio threshold must be compared against the exact ratio rather than the rounded one, or 399 changed lines in a 1 000-line file would clear a 0.40 threshold it does not meet.Behavioural evidence, measured on the first commit of an existing PR against the nine defects maintainers later confirmed in that commit: the review as it stands today found two of nine in one pass and needed eight rounds over two days to reach all nine. The chunked topology found two of nine. The invariant agents found three to five of nine on their own, and every one of them was in the class the checklist targets — none in the test-coverage or sanitization classes it does not target, which was predicted before the run. Together the two changes found five to seven of nine in a single pass. The range reflects two scoring rules for three agents that produced two answers apiece; the lower bound takes each agent's final answer and the upper bound takes the union.
Evidence (Before & After)
N/A — no user-visible or TUI surface.
Tested on
Environment (optional)
Unit tests plus a live
qwen review fetch-pragainst a real PR, and the productiontruncateAndSaveToFile/processSingleFileContentfunctions driven directly over that PR's real 211 000-character diff to measure what each topology actually delivers to an agent.Risk & Scope
ceil(N/8)verifiers and per-chunk reverse-audit rounds. Each agent's context is much smaller, and the comparison is not 26 calls against 14 — the PR that motivated this took eight rounds at 12 to 14 calls each and had not converged. PRs with a small source change keep the existing ten-agent topology; across the last 40 merged PRs the re-gating adds about 5% more agents in total, all of it spent giving small production changes more lenses rather than fewer.fetch-prgains fields; nothing is removed. If the merge-base cannot be resolved the report carries a null diff path and the review degrades to the old command-based flow with a warning.Linked Issues
None.
中文说明
这个 PR 做了什么
/review过去把 diff 命令交给每个 review agent,让它自己去跑。Shell 工具的输出被截断在 30 000 字符,且按 1/5 头部、4/5 尾部切分,所以在大改动上每个 agent 只拿到第一个文件开头的几百行、最后一个文件的尾部,中间全部被一个截断标记取代。这个 PR 把 diff 落盘,切分成每块都能被一次完整读取的分块,并让每个分块由唯一一个 agent 负责、必须返回覆盖回执。没有回执的分块会在流程继续前重新审查,因此 review 再也不可能对没人看过的代码给出「无阻塞」的结论。拓扑的选择依据是 diff 中的源码行数,而不是它的原始体量。测试代码主导了 diff 的体量——本仓库最近 40 个合并的 PR 中位数有 41% 是测试,而促成这项工作的那个 PR 本身就有 58% 是测试——所以按原始体量设门控,会仅仅因为一个 173 行的生产代码改动附带了 489 行新测试,就把它切成领地,让那段生产代码只剩一个审查者而不是八个视角。无论走哪条路,分块都会覆盖每一行;门控决定的只是审查者的数量和各自被要求做什么。
只解决覆盖是不够的。被大幅重写的源码文件现在还会额外获得三个通读全文的 agent,它们走一张固定的不变量清单:每个可变字段是否在所有退出路径被清理、每个定时器是否在所有关闭路径被取消且取消时不会丢弃回调已捕获的数据、每个 map 插入是否有对应的删除、每个重试计数器是否在所有入口自增、返回状态是否真的被检查、错误码是否被穷举地分为永久性与瞬时性、配置项是否在所有应当生效的路径上生效、以及提前返回是否跳过了后续路径依赖的副作用。清单被有意拆成三份——让一个 agent 在 2 400 行的文件上同时跑完八项检查,它只会认真做完其中一项。
另有三处较小的改动出自同一份证据。验证按每个 agent 至多八条发现分片,因为单个 verifier 为六十条发现逐一重读代码时,在列表尾部的质量会严重下滑。verifier 现在可以把 Critical 降级,但永远不能删除它——被否决的 Critical 对后续所有阶段都不可见,而被降级的仍会呈现给人类。reverse audit 改为按分块扇出,而不是让一个上下文饥饿的 agent 重读整份 diff;它不再免于验证;并且要连续两轮无新增才停止,而不是一轮。
为什么需要它
大 PR 要审十几轮,而且仍在冒出阻塞性缺陷。原因是可测量的,与 prompt 写得好不好无关。在一个真实的 211 000 字符改动上,截断让每个 agent 只看到 diff 的 14.4%——而且十个 agent 看到的是同一个 14.4%,所以沿评审维度的十路扇出只是把同一小片可见区域重复读了十遍,并没有增加覆盖。维护者最终确认的二十个缺陷里,十九个落在被隐藏的 85.6% 中。那些 review 之所以还能找到一些东西,是因为 agent 自作主张去打开了源文件,这也解释了为什么每一轮返回的都是一个看似随机的不同子集,以及为什么这个过程永远不收敛。
把 diff 写进文件是必要的,但并不充分:对同一份 diff 做一次整文件读取,只会返回它的前 611 行。这就是为什么分块同时受行数预算(关乎注意力)和字符预算(关乎一次读取实际能返回多少)的约束,也是为什么要求分块精确铺满整个 diff。精确铺满把「这段 hunk 到底有没有人看过」从一个无法回答的问题,变成了 orchestrator 可以断言的事实。
不变量 agent 之所以存在,是因为可见性是必要条件而非充分条件。在同一个 PR 上,分块 agent 的领地内包含了每一个状态机缺陷,却一个都没报出来。那些 bug 不在任何单个 hunk 里,而是在相隔两千行的新代码之间——文件顶部启动的定时器,和文件底部的销毁路径。这些 agent 缺的不是代码行,而是问题本身。「审查这段 diff 找 bug」和「列出每一个重试计数器,然后逐个调用点检查自增」不是同一条指令,只有后者能发现一个永远无法达到的上限。
Reviewer Test Plan
如何验证
对任意一个大 PR 运行
qwen review fetch-pr,检查它写出的报告。报告中现在应包含diffPath、diffPathAbsolute、diffLines、一个chunks数组,以及一个携带改写指标的按文件files数组。确认落盘的 diff 与git diff <mergeBaseSha>..<fetchedSha>逐字节一致,确认分块范围能逐字重建它且无空洞无重叠,确认没有任何分块超出字符预算。用read_file(file_path=diffPathAbsolute, offset=startLine-1, limit=lines)读取一个分块应完整返回该范围且不省略任何内容;而一次性读取整份 diff 则不会。对源码改动超过 500 行(或 diff 总行数超过 2400)的 PR,review 现在应当每个分块启动一个 agent,而不是十个 agent 面对整份 diff;每个 agent 都应以一行
Covered:回执结束;这些回执应恰好覆盖每一个分块 id 一次。对大幅重写了某个既有文件的 PR,应额外针对该文件运行三个通读全文的 agent,且 fetch 报告的files数组应把它标记为heavy。全新文件不应被标记为 heavy,尽管它的改写比例按定义就是 1.0。单元覆盖:在
packages/cli下运行npx vitest run src/commands/review(70 个测试,其中 7 个在恶意 git 配置下驱动真实仓库)。diff-plan 的测试断言了精确铺满、逐字重建、分块边界永不落在函数内部,以及行数与字符两个预算都会生效。fetch-pr 的测试固定了重写级判定规则,包括早先草稿里判错的两种情形——新文件不能算作重写,以及比例阈值必须用精确比值而非四舍五入后的值比较,否则 1 000 行文件里改动 399 行会混过一个它其实没达到的 0.40 门槛。行为证据,在一个既有 PR 的首个 commit 上、针对维护者后来在该 commit 中确认的九个缺陷测量:今天的 review 单轮找到九分之二,需要跨越两天、八轮才凑齐全部九个。分块拓扑找到九分之二。不变量 agent 单独找到九分之三到九分之五,且全部落在该清单所针对的缺陷类别内——没有一个落在它不针对的测试覆盖类或净化类,而这一点是在运行之前就写下的预测。两项改动合在一起,单轮找到九分之五到九分之七。区间来自两种记分口径:有三个 agent 各产出了两份答案,下界取每个 agent 的最终答案,上界取两次的并集。
Evidence (Before & After)
N/A —— 没有用户可见界面或 TUI 变更。
Tested on
Environment (optional)
单元测试,加上对一个真实 PR 实跑
qwen review fetch-pr,以及直接驱动生产环境的truncateAndSaveToFile与processSingleFileContent函数处理该 PR 真实的 211 000 字符 diff,以测量每种拓扑实际交付给 agent 的内容。Risk & Scope
ceil(N/8)个 verifier 和按分块的 reverse-audit 轮次。每个 agent 的上下文小得多,而且要对比的不是 26 次调用对 14 次——促成这次改动的那个 PR 跑了八轮、每轮 12 到 14 次调用,仍未收敛。源码改动较小的 PR 继续沿用现有的十 agent 拓扑;在最近 40 个合并的 PR 上,改用源码行数门控合计只多出约 5% 的 agent,且全部花在让小的生产代码改动获得更多视角上。fetch-pr只新增字段,没有移除任何东西。若无法解析 merge-base,报告中的 diff 路径为 null,review 会带一条警告降级为原来基于命令的流程。Linked Issues
无。