從程式碼審查到智能體集羣:管理 AI 輔助開發的新操作指南
From Code Review to Agent Fleets: The New Playbook for Managing AI-Assisted Development
Tamiz Uddin提出管理 AI 編碼智能體集羣的操作指南,建議以編排器、自動化審查閘門和分級人工審查,處理智能體並行產生的 PR。指南建議以三層審查處理 PR,並以缺陷逃逸率低於 3% 作為健康訊號之一;智能體亦應在沙箱及最小權限下運行,且不得自行合併 PR。
Originally published on tamiz.pro.
Code review used to be the quiet bottleneck of software delivery. A human reviewer, a diff, a few comments, a merge. Today that bottleneck has been replaced by something far more interesting — and far more dangerous. AI coding agents don't just suggest diffs; they open pull requests, run tests, fix their own failures, and, in some setups, merge their own work. When you scale that from one agent to a fleet of dozens working in parallel across a monorepo, the problem shifts from "how do I review code?" to "how do I govern an autonomous workforce I can barely observe?"
This is the new playbook — and it demands a different kind of engineering discipline. The tools that made agents possible are not the same tools that will keep a codebase healthy. You need an architecture, a review ladder, hard guardrails, and a metrics model that tells you when the fleet is lying to you.
- 1. The New Reality: Agents Are Contributors, Not Tools
- 2. Anatomy of an Agent Fleet
- 3. Code Review in the Age of AI
- 4. The Playbook: Operating an Agent Fleet
- 5. Guardrails: Permissions, Sandboxing, and Blast Radius
- 6. Measuring What Matters
- 7. Reference Configuration
- 8. Common Pitfalls
- 9. Frequently Asked Questions
1. The New Reality: Agents Are Contributors, Not Tools
The first generation of AI-assisted development was autocomplete. Copilot-style tools predicted the next line; the human was still the author, and the review process barely changed. The second generation — agentic coding — is a different animal. An agent takes a ticket, reads the codebase, writes a plan, implements it across multiple files, runs the test suite, fixes its own regressions, and opens a pull request. It does not assist. It produces.
That inversion has three consequences that most teams underestimate:
- Review bandwidth becomes the constraint. A single human reviewer used to gate a handful of PRs per day. An agent can emit dozens of PRs per hour. You cannot review your way out of that gap; you have to change what "review" means.
- Trust calibration is now a skill. The old assumption — the reviewer knows more than the author — is dead. A human reviewer often knows less about the diff than the agent that wrote it, especially in unfamiliar modules. If you review for correctness you will fail; you have to review for intent, risk, and architecture.
- Failure modes are systemic, not individual. A human who writes bad code is a bug. A fleet that shares a flawed prompt template or a misconfigured sandbox is a systemic defect generator. You are no longer debugging code; you are debugging the agent's environment.
This is why the playbook is not "how to prompt better" — it is how to build an operational layer around the agents so that their output is trustworthy by construction.
2. Anatomy of an Agent Fleet
Before you can govern a fleet, you need to know what one is. An agent fleet is not a bunch of terminals running claude in a loop. It is a distributed system with a dispatcher, workers, storage, gates, and telemetry. Here is the minimal architecture that works in production:
┌─────────────────────────────────────────────────────────────┐
│ Orchestrator / Dispatcher │
│ (task queue, priority, retries, concurrency limits) │
└──────────────┬──────────────────────────────┬───────────────┘
│ │
┌─────────▼─────────┐ ┌─────────▼─────────┐
│ Agent Worker A │ │ Agent Worker B │
│ (sandboxed) │ │ (sandboxed) │
└─────────┬─────────┘ └─────────┬─────────┘
│ │
┌─────────▼─────────┐ ┌─────────▼─────────┐
│ Artifact Store │ │ Review Gates │
│ (diffs, logs) │ │ (CI, SAST, tests)│
└─────────┬─────────┘ └─────────┬─────────┘
│ │
┌─────────▼─────────┐ ┌─────────▼─────────┐
│ Telemetry / │ │ Human Review │
│ Audit Trail │ │ (exception) │
└───────────────────┘ └───────────────────┘
Each component has a specific job:
- Orchestrator — the control plane. It holds the task queue, assigns tickets to workers, enforces concurrency caps, handles retries, and applies priority. This is where you set "max parallel agents" and "max retries per task." It is also where you enforce file ownership: an agent may only touch files within its assigned module.
- Agent Workers — the execution units. Each worker runs in an isolated sandbox (container, VM, or at minimum a clean working directory) with a scoped token. The worker is the LLM plus its tooling: shell access, file edit, test runner, git.
- Artifact Store — every agent run produces a diff, a plan, logs, and test output. Store all of it. This is your audit trail and your training data for evaluating agent quality.
- Review Gates — a pipeline that runs before any human sees the diff: build, unit tests, lint, type-check, SAST, dependency scan, secret scan, and a policy check. A gate that fails returns the task to the agent with the failure output. This is the single highest-leverage component.
- Human Review — now an exception path, not the default. Humans review the delta that the gates could not validate: architectural fit, API compatibility, security-sensitive changes, and anything touching production config or credentials.
- Telemetry / Audit Trail — immutable logs of every action: which agent, which prompt, which files touched, which commands ran, which gates passed. Without this you are flying blind.
A fleet without a review gate is just a code generator with a merge button. A fleet without an orchestrator is a stampede.
3. Code Review in the Age of AI
Code review is the part of the playbook that changes the most — and the part teams get wrong first. The naive move is to keep the old review process and point it at agent output. That fails because the volume is unmanageable and the signal-to-noise ratio is inverted.
The workable model is a three-tier review ladder, where each tier is cheaper and faster than the one below it, and escalation happens only when a tier cannot certify the change.
| Tier | Who runs it | What it catches | Escalate when |
|---|---|---|---|
| T1 — Automated gates | CI pipeline | Syntax errors, failing tests, lint violations, type errors, known CVEs, hardcoded secrets, policy violations | Any gate fails → return to agent |
| T2 — Agent self-review + static analysis | Agent + SAST tools | Logic errors, dead code, missing edge cases, security smells, API misuse | Heuristics flag risk → escalate to human |
| T3 — Human review | Senior engineer | Intent mismatch, architectural drift, API contract breaks, security-sensitive logic, prod config | Always required above a risk threshold |
This ladder works because it spends human attention where it matters. In practice, for a well-tuned fleet, roughly 70–80% of PRs should merge through T1 + T2 alone. If your human reviewers are touching more than 30% of agent PRs, your gates are too weak or your agents are too unconstrained.
What human review should actually check
When you do sit down to review an agent's PR, do not read it like a diff. Read it like a design document. Ask these four questions:
- Does this change belong here? Is the agent solving the right problem in the right module, or did it patch a symptom in an unrelated file? Agents are notorious for fixing a test failure by editing the test.
- Is the public contract intact? Did the agent change a function signature, a database schema, or an API response shape without updating callers? This is the highest-cost failure mode.
- Is there a hidden side effect? Did the agent add a network call, a file write, a config mutation, or a new dependency? Read for side effects, not for logic.
- Is the change reversible? If this ships and breaks, can you roll it back cleanly? If the agent touched a migration or a data transform, the answer is no — and that needs a human.
4. The Playbook: Operating an Agent Fleet
This is the operational core. These are the practices that separate teams that ship reliably with agents from teams that get burned.
4.1 Keep PRs small and semantically atomic
An agent will happily produce a 4,000-line PR that refactors a module, adds a feature, and upgrades a dependency — all at once. That is a review nightmare and a rollback hazard. Enforce a hard diff-size limit (e.g., 400–600 lines) and require one ticket per PR. The orchestrator should split large tasks automatically.
4.2 Use spec-first development
Do not give an agent a vague ticket like "improve performance." Give it a failing test, a type signature, or a written acceptance criterion. The agent's job is to make the test pass, not to interpret intent. Spec-first is the single most effective way to constrain agent behavior without micromanaging it. If you cannot write a test for it, you should not hand it to an agent.
4.3 Enforce a review ladder with hard thresholds
Agents may merge only through the ladder. Configure the orchestrator so that:
- T1 gates must pass — no exceptions.
- T2 must not flag high-severity issues.
- T3 (human review) is mandatory for any PR touching production config, migrations, auth, payments, or >200 lines.
- No agent may merge its own PR without a human sign-off. This is non-negotiable, even if it slows things down.
4.4 Make verification non-negotiable
Every agent PR must pass build + test + lint + type-check + SAST + secret scan before it can be considered. If a gate fails, the orchestrator returns the task to the agent with the failure output and a retry budget. After N retries (typically 2–3), the task is escalated to a human. This converts the agent from a guesser into a solver.
4.5 Rotate human reviewers
Agents learn the codebase. A single human reviewer will develop a blind spot for a specific agent's recurring mistakes. Rotate reviewers across agent outputs weekly, and periodically run a "red team" review on a random sample of merged agent PRs to measure defect escape rate.
4.6 Cap concurrency and stagger workloads
A fleet of 50 agents all touching the same module will create merge conflicts and thrash the CI. Cap concurrency per module (e.g., 2–3 agents per directory) and globally (e.g., 10–20). Use a priority queue so critical-path work preempts background refactors.
4.7 Treat agent code as new-hire code for the first N weeks
When you first deploy a fleet, do not trust it. For the first 2–4 weeks, require human review on 100% of agent PRs. Use that period to calibrate your gates, learn the agent's failure modes, and build a baseline of rework rate. Only relax to the tiered model once the defect escape rate drops below your threshold.
5. Guardrails: Permissions, Sandboxing, and Blast Radius
An agent with a production token and a shell is a security incident waiting to happen. The guardrails below are not optional; they are the difference between a fleet and a liability.
5.1 Least-privilege tokens
Every agent worker gets a short-lived, scoped token. It can read the repo, write to a branch, and push — nothing else. No access to production secrets, no admin permissions, no ability to create releases. The orchestrator holds the only token that can merge, and even that is gated.
5.2 Sandboxed execution
Each worker runs in a container with:
- No network egress except to the package registry and the agent API.
- A read-only filesystem except for a temp working directory.
- A memory and CPU limit.
- No access to the host's Docker socket, SSH keys, or cloud credentials.
5.3 File ownership and blast radius
The orchestrator assigns each agent a set of files it may modify. An agent working on src/orders/ cannot touch src/payments/ or infra/. This prevents the worst failure mode: an agent "fixing" a bug in an unrelated module it barely understands. Blast radius is the product of file ownership and token scope — keep both tight.
5.4 Audit logging
Every action is logged: agent ID, prompt hash, files touched, commands run, gates passed/failed, and the final diff. Store these logs immutably for at least 90 days. When something breaks, you will need to reconstruct exactly what the agent did.
5.5 Policy as code
Encode the guardrails as a policy file that the orchestrator reads. Here is a minimal example:
# fleet-policy.yaml
fleet:
max_concurrent_agents: 12
max_retries_per_task: 3
max_diff_lines: 600
permissions:
agent_token_scope: "repo:read, branch:write"
allow_network_egress: ["registry.npmjs.org", "api.agent-provider.com"]
allow_file_glob:
- "src/**/*.{ts,tsx}"
- "tests/**/*.{ts,tsx}"
deny_file_glob:
- "infra/**"
- "*.tf"
- "**/*.pem"
review_ladder:
t1_gates:
- "build"
- "test"
- "lint"
- "typecheck"
- "sast"
- "secret-scan"
t2_required: true
t3_human_review:
always_for:
- "**/migrations/**"
- "**/auth/**"
- "**/payments/**"
- "**/infra/**"
min_diff_lines_for_review: 200
merge_requires_human_signoff: true
This file is the contract between you and the fleet. It is version-controlled, reviewed like code, and enforced by the orchestrator. If the policy says an agent cannot touch infra/, then the orchestrator rejects the task before the agent ever runs.
6. Measuring What Matters
If you cannot measure it, you cannot govern it. But the naive metrics — "PRs merged per day" — will actively hurt you. Optimizing for throughput without measuring quality is how teams get a million lines of plausible-looking garbage.
Here is the metric set that matters, and what each one signals:
| Metric | What it measures | Healthy signal |
|---|---|---|
| Defect escape rate | % of merged agent PRs that later need a revert or hotfix | < 3% |
| Rework rate | % of agent PRs that require changes after first review | < 15% |
| Review latency | Time from PR open to merge | Decreasing over time |
| Human intervention rate | % of agent PRs that escalate to T3 | 20–30% |
| Gate pass rate on first attempt | % of agent PRs that pass all T1 gates without retry | > 60% |
| Agent success rate | % of assigned tasks that produce a mergeable PR | > 70% |
| Rollback time | Time to revert a bad agent PR | < 5 minutes |
Two metrics deserve special attention:
- Defect escape rate is your north star. It is the only metric that measures whether the fleet is actually producing trustworthy code. If it climbs above 3%, stop the fleet, tighten the gates, and recalibrate.
- Gate pass rate on first attempt tells you whether your agents are getting better or just getting luckier. If it is flat while agent success rate climbs, your gates are too permissive.
Track these per agent, per module, and per prompt template. If one agent has a 40% rework rate and another has 5%, you have a prompt or context problem, not a code problem.
7. Reference Configuration
Here is a working end-to-end example. First, the orchestrator config that ties the policy to the pipeline:
# orchestrator.yaml
apiVersion: fleet/v1
kind: Orchestrator
spec:
queue:
maxDepth: 200
priority: ["critical", "feature", "refactor"]
workers:
image: "ghcr.io/your-org/agent-worker:latest"
resources:
cpu: "2"
memory: "4Gi"
env:
- name: AGENT_API_KEY
valueFrom:
secretKeyRef: { name: agent-creds, key: api-key }
gates:
pipeline:
- name: build
cmd: "npm run build"
- name: test
cmd: "npm test -- --coverage"
- name: lint
cmd: "npm run lint"
- name: typecheck
cmd: "tsc --noEmit"
- name: sast
cmd: "semgrep ci --config=auto"
- name: secret-scan
cmd: "gitleaks detect --no-git"
mergePolicy:
requireHumanSignoff: true
requireAllGates: true
minApprovals: 1
Second, the CI gate script that the orchestrator runs on every agent PR. This is the code that actually stops bad code from reaching your main branch:
#!/usr/bin/env bash
# review-gate.sh — runs on every agent PR
set -euo pipefail
echo "[gate] Running T1 pipeline..."
# 1. Build
npm run build || { echo "[gate] BUILD FAILED"; exit 1; }
# 2. Tests
npm test -- --coverage || { echo "[gate] TESTS FAILED"; exit 1; }
# 3. Lint
npm run lint || { echo "[gate] LINT FAILED"; exit 1; }
# 4. Type-check
npx tsc --noEmit || { echo "[gate] TYPECHECK FAILED"; exit 1; }
# 5. Security scan
npx semgrep ci --config=auto || { echo "[gate] SAST FAILED"; exit 1; }
# 6. Secret scan
npx gitleaks detect --no-git || { echo "[gate] SECRETS FOUND"; exit 1; }
# 7. Diff size guard
DIFF_LINES=$(git diff --numstat origin/main...HEAD | awk '{s+=$1+$2} END {print s}')
if [ "$DIFF_LINES" -gt 600 ]; then
echo "[gate] DIFF TOO LARGE: $DIFF_LINES lines (max 600)"
exit 1
fi
# 8. File ownership check
if git diff --name-only origin/main...HEAD | grep -qE '^(infra/|.*\.tf$|.*\.pem$)'; then
echo "[gate] FORBIDDEN FILE TOUCHED — requires human review"
exit 2
fi
echo "[gate] ALL T1 GATES PASSED"
exit 0
Note the exit codes: 1 for a hard failure (return to agent), 2 for a policy escalation (route to human). This distinction is what makes the ladder work — the orchestrator knows whether to retry the agent or hand the task to a person.
8. Common Pitfalls
These are the mistakes I see teams make over and over. Each one is survivable on its own; together they are fatal.
- Over-trusting the agent. Assuming that because the agent wrote tests, the tests are meaningful. Agents will happily write tests that pass for the wrong reasons. Always spot-check test quality.
- Letting agents self-merge. The fastest way to lose a codebase. No agent should ever have merge rights. The orchestrator merges, and only after a human sign-off.
- No sandboxing. Running agents with full access to the developer's machine is a supply-chain and credential risk. Containerize or die.
- Treating review as a formality. If your human reviewers are rubber-stamping agent PRs, you are not reviewing — you are just merging. Enforce the ladder.
- Ignoring telemetry. If you cannot see which agent wrote the buggy code, you cannot fix the root cause. Log everything.
-
Allowing agents to touch production config. One agent with access to
infra/can take down prod. Deny it at the policy layer, not at review time. - No rollback plan. Agent PRs ship fast. If you do not have a one-command revert, you will be debugging at 2 AM. Build the revert path before you build the fleet.
- Optimizing for throughput. "More PRs merged" is a vanity metric. Optimize for defect escape rate and rework rate, and throughput will follow.
9. Frequently Asked Questions
Q: How many human reviewers do I need for a fleet of 20 agents?
You do not need 20 reviewers. You need 2–3 senior engineers who focus on the T3 exception path. The goal is not to review every PR — it is to review the ~20–30% that the gates cannot certify. If your humans are reviewing more than that, fix your gates first. For a deeper look at how to structure these workflows, check out Tamiz's Insights on AI-assisted engineering.
Q: What is the single most effective thing I can do to improve agent output quality?
Spec-first development. If you give an agent a failing test or a precise type signature as the acceptance criterion, you constrain its search space dramatically and make its output verifiable. A vague ticket is an invitation for the agent to guess.
Q: How do I know if my agent fleet is actually saving time?
Compare the metric set in Section 6 before and after fleet deployment. The two numbers that matter most are cycle time (PR open to merge) and defect escape rate. If cycle time drops but defect escape rate rises, you are trading quality for speed — and you should tighten the gates. If both improve, your fleet is working. See tamiz.pro for more on engineering workflow measurement.
來源:DEV Community · dev.to