Code Review, Refactoring and Quality Measures
Agents make code cheap to produce. The scarce resource is justified confidence, so spend automation on the checkable and people on judgment.
Review in layers: automated gates first, an optional AI reviewer for a second look, then a person who asks whether this is the right change. Keep proposals small, refactor behind tests that pin current behavior, and judge the program by outcomes such as defects and rework, not by lines written. Public benchmark scores are a weak guide to your own repository.
What you will learn: a layered review process, a runnable pre-review gate, what to look for in agent changes, safe refactoring, useful measures and the limits of benchmarks.
Prerequisites: Issue-to-Pull-Request, Debugging and TDD Workflows.
Written in November 2026; benchmark notes reflect public statements up to that date. The examples use only the Python standard library. Their change sets and records are invented.
Who checks what
| Layer | Reliable for | Not reliable for |
|---|---|---|
| Build, types, tests, scanners | What they were written to detect | Anything else |
| Rule gate | Size, protected paths, obvious weakening | Meaning |
| AI reviewer | Suggestions and missed cases to investigate | Final approval; it can be wrong or persuaded |
| Person | Intent, design, risk, accountability | Careful attention to very large diffs |
Why agent changes need particular care
| Pattern | What to look for |
|---|---|
| Plausible but invented | Functions, options or packages that do not exist or behave differently |
| Satisfying the check | Special cases for test inputs; weakened assertions; skipped tests |
| Over-building | New layers, options and handlers nobody asked for |
| Silent removal | Deleted validation, logging or comments |
| Swallowed errors | Broad exception handlers that hide failure |
| Duplication | A new helper beside an existing one |
| Confident description | A summary that does not match the diff |
A gate before review
Deterministic rules are cheap, consistent and hard to argue with. This script examines three invented changes.
"""Cheap, deterministic checks on a proposed change, before anyone reviews it."""
import re
LIMIT_LINES = 200
PROTECTED = (".github/", "deploy/", "migrations/")
SECRET = re.compile(r"(api[_-]?key|secret|password|token)\s*=\s*['\"][^'\"]{8,}", re.I)
WEAKENING = re.compile(r"@unittest\.skip|pytest\.mark\.skip|# *noqa|verify=False|assert True")
# Each change: path -> (added lines, removed lines)
CHANGES = {
"small fix with a test": {
"shop/money.py": ([" return round(amount * 100)"], [" return int(amount * 100)"]),
"tests/test_money.py": ([" self.assertEqual(to_cents(19.99), 1999)"], []),
},
"quietly skips a test": {
"tests/test_cart.py": ([" @unittest.skip('flaky')"], []),
},
"touches the pipeline": {
".github/workflows/ci.yml": ([" run: ./publish.sh"], []),
"shop/config.py": (['API_KEY = "sk-demo-0000000000"'], []),
},
}
def review(change):
findings = []
added = sum(len(a) for a, _ in change.values())
removed = sum(len(r) for _, r in change.values())
if added + removed > LIMIT_LINES:
findings.append(("split", f"{added + removed} changed lines"))
code = [p for p in change if p.startswith("shop/")]
if code and not any(p.startswith("tests/") for p in change):
findings.append(("ask", "code changed without any test change"))
for path, (new, old) in change.items():
if path.startswith(PROTECTED):
findings.append(("block", f"{path} needs its owner"))
if path.startswith("tests/") and sum("assert" in l for l in old) > \
sum("assert" in l for l in new):
findings.append(("block", f"assertions removed from {path}"))
for line in new:
if SECRET.search(line):
findings.append(("block", f"possible secret in {path}"))
if WEAKENING.search(line):
findings.append(("block", f"check weakened in {path}"))
return findings
for title, change in CHANGES.items():
findings = review(change)
verdict = "block" if any(k == "block" for k, _ in findings) else \
"needs attention" if findings else "ready for human review"
print(f"{title}: {verdict}")
for kind, text in findings:
print(f" [{kind}] {text}")
Output:
small fix with a test: ready for human review
quietly skips a test: block
[block] check weakened in tests/test_cart.py
touches the pipeline: block
[ask] code changed without any test change
[block] .github/workflows/ci.yml needs its owner
[block] possible secret in shop/config.py
These are pattern checks, and patterns can be sidestepped: a secret can be split across lines, and a test can be weakened without any of these words. Use dedicated secret and code scanners for real protection, and treat the gate as a way to route attention. Run it from a protected pipeline that the proposed change cannot modify.
The reviewer's reading order
- Read the request, then the description. Do they match?
- Read the tests. Do they describe the required behavior, including failure?
- Look at what was deleted.
- Check boundaries: input handling, permissions, data changes, external calls.
- Check new dependencies one by one.
- Only then read for style and clarity.
- For risky changes, run it yourself.
If a proposal is too large to review properly, send it back to be split. Approving what you did not read is the most expensive habit a team can form.
Using an AI reviewer
- Give it the task, the diff and your rules, not only the diff.
- Ask for findings with a file, a line and a concrete failing case.
- Prefer a reviewer with a fresh context to the session that wrote the code.
- Track which comments lead to changes, and tune or drop noisy categories.
- Remember that text inside the diff or description can try to influence it.
- Never count its approval as the required human approval.
Findings worth writing
| Vague | Actionable |
|---|---|
| "Handle errors better." | "If the payment service times out, line 40 returns success. Return a retryable error." |
| "This could be slow." | "This queries once per order line; 500 lines means 500 queries. Fetch them together." |
| "Security issue?" | "Any signed-in user can pass another customer's id here. Check ownership." |
| "Not our style." | "We keep money as whole cents; add this to the lint rules." |
A good finding names the place, the condition and the consequence. Ask the same of human reviewers and AI reviewers. When you send findings back to an agent, include them verbatim and require a test for each defect, so the fix can be checked without rereading everything.
Refactoring safely
Refactoring changes structure while keeping behavior. Agents are quick at it, which makes proof of unchanged behavior essential.
- Write characterization tests that record what the code does now, odd cases included.
- Freeze those tests for the duration.
- Change one thing at a time: rename, extract, move.
- Run checks after each step and commit.
- Compare public interfaces, outputs and performance before and after.
- Keep behavior fixes in separate proposals.
| Hidden dependency | Why tests may miss it |
|---|---|
| Names used as strings | Reflection, configuration, serialized data |
| Other repositories | They are not in your test run |
| Ordering and timing | Tests rarely assert them |
| Log formats and error text | Dashboards and scripts may parse them |
Watch the slow damage
Single proposals can each look reasonable while the codebase gets harder to change. Check periodically for repeated helpers, growing files, unused code, rising build time and tests that assert little. Schedule clean-up as ordinary work, with the same review rules. If people can no longer explain how an area works, pause new features there until someone can.
Measure outcomes
This calculation compares two sets of invented records. It shows the method, not a finding about agents.
"""Outcome measures for agent-written changes. The records are invented."""
from statistics import median
# (merged, review minutes, rework commits, reverted or caused a defect)
RECORDS = {
"agent": [(True, 12, 0, False), (True, 35, 2, False), (False, 20, 0, False),
(True, 8, 0, False), (True, 50, 3, True), (False, 15, 1, False),
(True, 10, 0, False), (True, 22, 1, False)],
"people": [(True, 18, 1, False), (True, 25, 1, False), (True, 9, 0, False),
(True, 40, 2, True), (True, 14, 0, False), (False, 30, 1, False),
(True, 16, 0, False), (True, 21, 0, False)],
}
print(f"{'':8}{'merged':>8}{'review min':>12}{'rework':>8}{'escaped':>9}{'min per merge':>15}")
for who, rows in RECORDS.items():
merged = [r for r in rows if r[0]]
print(f"{who:8}{len(merged) / len(rows):8.0%}"
f"{median(r[1] for r in rows):12.1f}"
f"{sum(r[2] for r in merged) / len(merged):8.2f}"
f"{sum(r[3] for r in merged) / len(merged):9.0%}"
f"{sum(r[1] for r in rows) / len(merged):15.1f}")
Output:
merged review min rework escaped min per merge
agent 75% 17.5 1.00 17% 28.7
people 88% 19.5 0.57 14% 24.7
In this made-up data the agent's median review time is lower, yet the review time spent per merged change is higher, because rejected work still had to be read. One flattering number can hide the cost.
| Measure | Question it answers | Way it misleads |
|---|---|---|
| Merge rate | Is proposed work usable? | Rises if reviewers get lax |
| Review time per merged change | What does acceptance cost? | Falls when review is skipped |
| Rework before merge | How far off were first attempts? | Depends on reviewer style |
| Reverts and escaped defects | Did bad work get through? | Slow to appear; small numbers |
| Lead time from request to release | Is delivery faster overall? | Moved by many other things |
| Cost per merged change | Is it worth it? | Omits people's time unless added |
Compare similar kinds of task, state the sample size, and be wary of conclusions from a handful of records. Eight per group, as above, is far too few to decide anything.
Reading coding benchmarks
Benchmarks help compare systems under fixed conditions, and they have faults. In February 2026, OpenAI said it had stopped reporting SWE-bench Verified, citing problems including contamination, where models have seen the answers during training. In July 2026 it published an audit estimating that about 30% of SWE-bench Pro tasks were broken. Epoch AI's review also reports flaws.
- Check which tools, attempts, time limits and prompts produced a score.
- Do not compare scores from different setups.
- Treat small differences as noise unless repeated runs say otherwise.
- Build a private set of tasks from your own history, with checks you trust.
- Rerun it when you change the model, tool or instructions.
Agent Benchmarks and Datasets and Golden Datasets, Synthetic Data and Simulation go further.
Building your own task set
| Step | Detail |
|---|---|
| Collect | Past changes of different sizes, including some that were hard |
| Prepare | Check out the earlier state; write the request without revealing the answer |
| Judge | Tests that fail before and pass after, plus a short human rubric |
| Verify the judge | Confirm the real solution passes and a wrong one fails |
| Isolate | Hide the later history from the agent |
| Maintain | Remove tasks that become ambiguous or leak |
Team rules worth writing down
- Who may approve, and that authors cannot approve their own agent's work alone.
- A maximum proposal size.
- Paths that always need a named owner.
- How agent involvement is recorded on a change.
- What happens after an escaped defect: which check will catch it next time.
Managing review load
Faster writing moves the queue to review. Treat reviewer time as a limited resource and plan for it.
| Practice | Effect |
|---|---|
| Limit open proposals per person | Work finishes before more starts |
| Route by risk | Experts spend time where a mistake is expensive |
| Require evidence before review is requested | Broken work never reaches a person |
| Ask the author to review first | Obvious faults are caught by whoever has the context |
| Set a response time and a size limit | Branches do not grow stale |
| Close abandoned proposals | The queue shows real work |
The person who asked the agent for a change is its first reviewer. Passing an unread proposal to a colleague moves the effort to someone with less knowledge of the request.
Review depth by risk
| Change | Suggested depth |
|---|---|
| Documentation and comments | Check accuracy; run examples |
| Isolated feature with tests | One reviewer, normal reading order |
| Shared library or public interface | Reviewer who knows the callers |
| Authentication, payments, personal data | Named specialist, security checks, run it |
| Data migration or deletion | Two people, rehearsal, a way back |
Common mistakes
| Mistake | Better |
|---|---|
| Counting lines or proposals as productivity | Measure delivered, working outcomes |
| Mixing refactoring and new behavior | Separate them |
| Letting the change edit its own checks | Protect pipeline and test configuration |
| Choosing a tool from a leaderboard | Trial it on your own tasks |
| Adding reviewers without reading time | Limit work in progress |
Questions people ask
Does AI-written code need a different standard?
The standard stays the same. The process should account for higher volume and for the particular mistakes listed above.
Can we skip human review for trivial changes?
Some teams allow it for tightly defined cases with strong checks. Decide it as a written risk decision, restrict the allowed paths and sample the results.
Should we label agent-written changes?
A label makes it possible to compare outcomes and investigate patterns. Accountability still rests with the people who approve.
How big should our private task set be?
Start with a few dozen varied tasks and grow it from real failures. Report results with the count so readers can judge the uncertainty.
References
- OpenAI: why it no longer evaluates SWE-bench Verified
- OpenAI: separating signal from noise in coding evaluations
- Epoch AI: SWE-bench Pro review
- Google engineering practices: code review
Next steps
Sandboxes, Safety and Security for Coding Agents
Limit what the agent can touch.
Agent Evaluation Framework
Evaluate agents systematically.
Agent Dev Teams, OpenHands and Private Coding Agents
Scale to teams and organizations.