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.

BeginnerIntermediateExpert · 11 min read · Last updated:

In short

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.

Versions used

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.

Beginner Review in layers

Who checks what

Build and testsdoes it work?
Rule gateis it allowed?
AI reviewerwhat looks suspicious?
Personshould we?
LayerReliable forNot reliable for
Build, types, tests, scannersWhat they were written to detectAnything else
Rule gateSize, protected paths, obvious weakeningMeaning
AI reviewerSuggestions and missed cases to investigateFinal approval; it can be wrong or persuaded
PersonIntent, design, risk, accountabilityCareful attention to very large diffs

Why agent changes need particular care

PatternWhat to look for
Plausible but inventedFunctions, options or packages that do not exist or behave differently
Satisfying the checkSpecial cases for test inputs; weakened assertions; skipped tests
Over-buildingNew layers, options and handlers nobody asked for
Silent removalDeleted validation, logging or comments
Swallowed errorsBroad exception handlers that hide failure
DuplicationA new helper beside an existing one
Confident descriptionA summary that does not match the diff
Intermediate Gates and judgment

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

  1. Read the request, then the description. Do they match?
  2. Read the tests. Do they describe the required behavior, including failure?
  3. Look at what was deleted.
  4. Check boundaries: input handling, permissions, data changes, external calls.
  5. Check new dependencies one by one.
  6. Only then read for style and clarity.
  7. For risky changes, run it yourself.
Small enough to read

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

VagueActionable
"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.

  1. Write characterization tests that record what the code does now, odd cases included.
  2. Freeze those tests for the duration.
  3. Change one thing at a time: rename, extract, move.
  4. Run checks after each step and commit.
  5. Compare public interfaces, outputs and performance before and after.
  6. Keep behavior fixes in separate proposals.
Hidden dependencyWhy tests may miss it
Names used as stringsReflection, configuration, serialized data
Other repositoriesThey are not in your test run
Ordering and timingTests rarely assert them
Log formats and error textDashboards 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.

Advanced Measuring quality

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.

MeasureQuestion it answersWay it misleads
Merge rateIs proposed work usable?Rises if reviewers get lax
Review time per merged changeWhat does acceptance cost?Falls when review is skipped
Rework before mergeHow far off were first attempts?Depends on reviewer style
Reverts and escaped defectsDid bad work get through?Slow to appear; small numbers
Lead time from request to releaseIs delivery faster overall?Moved by many other things
Cost per merged changeIs 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

StepDetail
CollectPast changes of different sizes, including some that were hard
PrepareCheck out the earlier state; write the request without revealing the answer
JudgeTests that fail before and pass after, plus a short human rubric
Verify the judgeConfirm the real solution passes and a wrong one fails
IsolateHide the later history from the agent
MaintainRemove 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.

PracticeEffect
Limit open proposals per personWork finishes before more starts
Route by riskExperts spend time where a mistake is expensive
Require evidence before review is requestedBroken work never reaches a person
Ask the author to review firstObvious faults are caught by whoever has the context
Set a response time and a size limitBranches do not grow stale
Close abandoned proposalsThe 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

ChangeSuggested depth
Documentation and commentsCheck accuracy; run examples
Isolated feature with testsOne reviewer, normal reading order
Shared library or public interfaceReviewer who knows the callers
Authentication, payments, personal dataNamed specialist, security checks, run it
Data migration or deletionTwo people, rehearsal, a way back

Common mistakes

MistakeBetter
Counting lines or proposals as productivityMeasure delivered, working outcomes
Mixing refactoring and new behaviorSeparate them
Letting the change edit its own checksProtect pipeline and test configuration
Choosing a tool from a leaderboardTrial it on your own tasks
Adding reviewers without reading timeLimit 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

Next steps