How to Ship 5,000 Lines of Reliable Code a Day With a Multi-Agent Architecture
About two weeks after I started running multiple coding agents in real repositories, my normal PR workflow fell apart.
I'd wake up to diffs over a thousand lines that froze the GitHub tab, AI reviewers and AI authors bouncing the same PR back and forth five times over variable names, green CI runs hiding silently skipped tests, and an agent changing a default product threshold without mentioning it anywhere in the PR.
Reading 5,000 lines of diff by hand every day doesn't work. What fixed it for me was tightening both ends of the loop: capping every task at 800 lines before review starts, then running two automated gates so I only have to sign off on a handful of plain-language behavior changes before merging to main . Here's the setup I'm running now, including the 3-role split on a dev branch, the six rules that stopped review loops, and the small Python check I wrote to catch fake-green pytest runs.
Splitting the Work Before Review
When an agent hands over a huge diff touching dozens of files across unrelated modules, tweaking the review prompt won't help much. The review problem usually starts upstream.
Cutting Six Roles Down to Three
My first attempt copied a standard team chart: PM, architect, frontend, backend, QA, and a separate observer agent all talking in the same issue thread. I ripped it out after a week.
Every handoff added another round of summarization, so by the time code reached QA the original acceptance criteria had drifted. Agents kept @ -mentioning each other in the same comment thread, waking up three sessions at once just to acknowledge messages and re-read the repo.
I stripped it down to three roles with hard file and branch boundaries:
- Leader Owns Task splitting, 500/800-line caps, boundary counterexamples for risky tasks, merging into dev. Not allowed to running full Tier 2 regression, Write feature code, open feature PRs, merge straight to main
- Dev Owns Coding in an isolated branch or worktree, writing tests, running Tier 0/1 checks, pasting
--shortstatcounts, self-review. Not allowed to Push to dev or main , run amend , rebase , or force push after review starts - Reviewer Owns Cross-model read-only checks at Gate 1 (sub-issue into dev ) and Gate 2 (release check on dev ). Not allowed to Edit files, commit, push, or open feature sub-issues
Dropping the standalone observer meant moving "check for silent product changes" into Reviewer's Gate 2 pass. Gate 2 carries a bit more context now, but I don't have to pay for another agent wake-up cycle on every epic.
Using dev as a Buffer Between Two Gates
Sub-issues never merge straight into main (or master ). Everything lands on dev first.
Gate 1 guards each sub-issue going into dev . Dev branches off dev , runs local static checks and targeted module shards (1 to 2 minutes), and gets a read-only pass from Reviewer. Sub-issues merge into dev automatically (via PR auto-merge or Leader --no-ff ) with zero human sign-off, leaving only a ticket record if you want to check what changed. Parallel tasks don't stall behind each other waiting on slow full-suite runs.
Gate 2 runs once all sub-issues for an epic have landed on dev . Leader runs the full regression suite and baseline check on dev , then hands the combined diff to Reviewer. My job is just the final dev -> main merge.
Event-Driven Scheduling and Three Config Layers
Running agents concurrently exposed two fast ways to burn budget: polling loops waiting on CI, and copy-pasting workflow instructions into every repo until they drift apart.
For scheduling, sub-issues declare native dependencies with --blocked-by <id> so downstream tasks unblock automatically when upstream ones close. Waiting on GitHub CI uses event wake-ups ( --until-pr checks ) instead of gh pr checks --watch or sleep loops. Every handoff comment @ -mentions exactly one next owner, never @Reviewer and @Leader together.
For configuration, I keep three layers:
- One shared workflow skill for the 3-role rules, review checklist, and test standards.
- Golden agent templates cloned per repo so cross-model pairings and concurrency caps stay consistent.
- A 6-section Project Context per repo. Section 1 defines how merges work, which lets the exact same workflow drive GitHub PRs (
--auto --merge --match-head-commit) on a full-stack Web repo and local worktree merges (git merge --no-ff) on a private compute-heavy Python repo.
Keeping Diffs Small Before Review
Coding agents don't naturally slice work into reviewable commits. Give one a medium-sized feature and it'll happily refactor twenty adjacent files along the way.
Each sub-issue targets <= 500 handwritten lines of app and test code, with a hard cap of 800 lines (generated clients, lockfiles, and frozen data snapshots don't count). Before pinging Reviewer, Dev runs git diff --shortstat <base>..HEAD and pastes the handwritten count into the comment. If the change is clearly going to cross 800 lines and the ticket doesn't have an explicit Leader exemption (which requires a reason and a commit-by-commit reading guide), Dev stops and asks Leader to split the task. If an unexempted >800-line diff still shows up at Gate 1, Reviewer rejects it immediately without reading the code.
I also enforce a quick YAGNI pass. Leader writes down what's explicitly out of scope during planning, dead paths get deleted rather than wrapped in compatibility shims, and Dev reads its own full git diff <start_sha>..HEAD to trim speculative abstractions before opening review.
Gate 1: Stopping Review Loops
Once PRs stay small, Gate 1 focuses on three recurring headaches: same-model blind spots, weak tests, and infinite nitpick threads.
Different Model Families and Read-Only Reviews
When the same model family writes the implementation, writes the tests, and reviews the diff, it tends to miss the exact same edge cases twice. Pairing Dev and Reviewer on different model families breaks that pattern. Making Reviewer strictly read-only keeps it from quietly patching code mid-review and forces every defect into a concrete comment.
Reading the Tests First
At Gate 1, Reviewer checks the tests before looking at business logic. It looks for mock-only tests ( mock.assert_called_once() with no state or output assertion), missing fail-before-fix proof on bug fixes, quiet edits to frozen golden fixtures, and scattered one-off test_fix_*.py files that belong as pytest.mark.parametrize rows in the module's main test file.
On risky tasks (numerical core code, auth rules, schema migrations, or dual-path refactors), Leader writes a short table of boundary counterexamples upfront. Reviewer then runs 1 or 2 edge cases in a quick read-only script to make sure the code and tests aren't sharing the same wrong assumption.
Three Rules That Ended Review Ping-Pong
Early AI reviewers wasted hours rejecting PRs over naming preferences, or finding new complaints in untouched code on round three. Three rules cleared that up:
- Only six classes of bugs can block a PR :
- Correctness and contract bugs (logic errors, null/numeric/concurrency/idempotency edge cases, schema mismatches)
- Security and repo redlines (auth bypass, leaked secrets, data-boundary leaks)
- Irreversible database migrations (missing downgrade or multiple Alembic heads)
- Test defects (missing required counterexamples, mock-only assertions, missing fail-before-fix proof, edited golden fixtures)
- Scope and integration breakage (unrequested dependencies, broken cross-module contracts)
- Severe Gate 2 test debt (deleted or skipped tests bypassing the baseline, or untagged >2s slow tests)
- Naming tweaks, minor readability nits, and optional helper extractions go into a non-blocking list and still approve.
- All blockers in round one : Round 1 has to list every blocker with four fields ( category , file:line , repro evidence , expected fix ). Round 2+ only checks whether those blockers were fixed and whether new commits introduced new bugs. No dredging up fresh nits from old unchanged lines.
- Hard round caps : At Gate 1, if the same root cause fails to converge for 2 rounds in a row , or total rejections hit 3 rounds , Reviewer marks the sub-issue blocked and hands it to Leader. Gate 2 stops at 2 rounds and comes to me.
Gate 2: Checking the Integration Branch
Landing sub-issues on dev is only halfway to production. Gate 2 checks how everything fits together before I merge to main .
Comparing Two Diffs ( main..dev and base_sha..dev )
When two epics are active on dev at once, main..dev includes commits from the other epic. Looking only at main..dev blames the wrong task, while looking only at individual PRs misses integration seams. Leader records base_sha when an epic starts, so Reviewer checks both views at Gate 2: main..dev for the full release candidate (cross-module contracts, migration chain, security redlines), and base_sha..dev to isolate what this epic actually changed. Anything left over from another in-flight epic gets flagged as a warning rather than blocking the current one.
Making Sure Green Tests Are Actually Green
Across both the compute-heavy Python repo and the full-stack Web repo, I split test execution into four tiers:
- Tier 0 (local, 10 to 30s) : lint, typecheck, build, and pure unit tests with no external IO. Must be green before touching the cloud runner.
- Tier 1 (cloud Gate 1, 1 to 2m) : changed-file routing (
--changed), domain shards (--shard), and 20 quick property-test cases. - Tier 2 (cloud Gate 2, 3 to 6m) : full dev regression using saved
.test_durationswith Longest Processing Time (LPT) bin-packing and worksteal ,--durations=20reporting (holding default unit tests under 2s ), plus the baseline check. - Tier 3 (nightly) : 500+ fuzz cases, mutation testing on the critical 5% to 10% core directories, and heavy E2E runs. Only triggers when dev got new commits, stays quiet on pass, and files an issue on failure.
Multiple repos share one 8-slot cloud VM via cloud-test-queue . Each lease is tied to an open file descriptor locked with kernel flock , so if a worker dies or SSH drops, the kernel frees the slot right away with no brittle TTL cleanup cron. slots and min_slots flex capacity across jobs, and CLOUD_TEST_QUEUE_SLOTS caps worker concurrency so runs don't OOM each other.
Even with that in place, pytest can still exit 0 when something goes wrong: a command aimed at an empty folder, an xdist worker crashing and dropping a batch of tests, or an agent adding @pytest.mark.skip to get past a failure. I wrote a small stdlib-only gate called test-baseline-gate that runs --collect-only independently, verifies the baseline's canonical set_sha256 , and compares every collected node against actual outcomes:
def evaluate ( baseline : Baseline , expected : set [ str ] , outcomes : Mapping [ str , str ] , * , scoped_nodes : Collection [ str ] , ) -> GateVerdict : failures = { node for node , outcome in outcomes . items ( ) if outcome in FAILURES } scoped = baseline . entries . keys ( ) & scoped_nodes return GateVerdict ( unreported = tuple ( sorted ( expected - outcomes . keys ( ) ) ) , # crashed worker dropped tests unexpected_failures = tuple ( sorted ( failures - scoped ) ) , # new regression outside baseline outcome_changed = tuple ( sorted ( # failed <-> error flip n for n in scoped & failures if outcomes [ n ] != baseline . entries [ n ] [ "outcome" ] ) ) , missing_from_run = tuple ( sorted ( # deleted, skipped, or xfailed n for n in scoped if n not in expected or ( n not in failures and outcomes . get ( n ) != "passed" ) ) ) , resolved_baseline = tuple ( sorted ( # fixed baseline needs explicit refresh n for n in scoped & expected if outcomes . get ( n ) == "passed" ) ) , empty_collection = not expected , # ran against 0 tests )
If any of those six tuples isn't empty, Gate 2 fails. Reviewer also runs a short Test GC pass at Gate 2: deleting retired tests for removed features, dropping brittle mock-call-count checks, and folding one-off regression files into parametrize tables.
Catching Silent Behavior Changes
Once tests and static checks cover correctness, the biggest surprise left is an agent making a product call you never asked for: picking a default threshold, turning a manual suggestion into an auto-apply action, or loosening notification rules.
At Gate 2, Reviewer scans for user-visible behavior changes and groups them by effect (if a dozen files implement one new default, that's one item). Anything crossing a redline, like irreversible deletes or flipping "suggest" to "auto-run", blocks the release. Everything else gets summarized into at most 3 plain-language bullets ( when X happens -> system does Y -> how to change it ) for me to approve or tweak before merging.
Where This Is Too Heavy
Maintaining a dev branch, a 6-section Project Context, a shared flock test queue, and baseline hashes is way too much machinery for a 300-line one-off script or a weekend prototype. It only starts making sense when you're running concurrent agents week after week across real repos, like a compute-heavy Python codebase and a full-stack Web app (or keeping public tooling like GSX-Eis/jq-factor-lab alongside private workspaces).
One rough edge I'm still working out: on the rare 20-file interface rename that genuinely crosses 800 lines, getting Leader to write a short, useful commit-by-commit review guide without blowing up Reviewer's context still takes manual nudging.
My daily role is much narrower now: set the redlines, settle escalated deadlocks, check those <= 3 behavior notes, and merge dev -> main . If you're running multiple coding agents in parallel, what's been the hardest part to keep under control in your review flow?
Disclosure: I built and run this multi-agent engineering workflow myself, verified every architecture rule, threshold, and code snippet against the actual implementation, and used AI tools to help draft and tighten the English prose.
Comments
@D-04got10-01 5k? What a cutie. I do that in a toilet break. 2k when I sleep.