Invite & Earn

How invite rewards work

Share your invite link. When a friend registers through it and tops up, you receive the displayed reward on their subsequent top-ups.

How to Review an AI Agent PR and Remove Unneeded Changes

A practical pre-merge workflow for AI-generated pull requests: define an acceptance contract, inspect the complete diff, use a fresh-context reviewer, trim changes in small batches, rerun evidence-based checks, and require human sign-off.

Contents
How to Review an AI Agent PR and Remove Unneeded Changes

An AI coding agent can fix errors and deliver a feature quickly, yet also reformat unrelated files, introduce abstractions, change configuration, or rewrite more of the codebase than the task requires. Before merging, the goal is not the fewest possible lines. The goal is a change set in which every important edit maps to an accepted requirement, a maintainer can explain it, and the team can verify it with tests or other evidence.

One developer described a personal workflow on X: after an agent opens a pull request, they start a second agent in a fresh context and ask it to identify what can be cut. The author explicitly called this extra work and extra tokens, not a guaranteed or optimal solution. A separate user reported that Codex fixed many errors while changing so much code that they no longer understood it. These reports define the problem; they do not prove that a second agent always improves a PR.

The workflow below treats the second agent as a skeptical reviewer, not an authority. The human maintainer remains responsible for scope, evidence, risk, and the merge decision.

The workflow in seven steps

  1. Write an acceptance contract: intended behavior, behavior that must not change, allowed scope, risks, and validation commands.
  2. Build an exact inventory using the PR conversation, commits, checks, Files changed, and local Git commands.
  3. Give a fresh-context agent a review-only task; do not let it edit on the first pass.
  4. Classify every finding as keep, simplify, remove, split, or escalate, with evidence for the recommendation.
  5. Apply only human-approved reductions in small, reversible batches.
  6. Run the same relevant tests and checks before and after trimming.
  7. Review the final diff from the beginning and merge only when a maintainer can explain the whole change.

1. Write an acceptance contract before asking for another review

“Make this PR cleaner” is not a sufficient objective. It invites another subjective rewrite. Create a short contract that states:

  • Problem and observable outcome: what the user or caller should see when the change works.
  • Behavior to preserve: existing interfaces, failure behavior, compatibility, and data semantics that must remain unchanged.
  • Allowed scope: the modules, APIs, schemas, configuration, or tests expected to change.
  • Explicit non-goals: no framework upgrade, global formatting, unrelated rename, speculative abstraction, or configuration migration unless required.
  • Risk constraints: security, permissions, migrations, performance, observability, rollback, and backward compatibility.
  • Validation: the repository’s actual formatting, lint, type-check, test, build, migration, or end-to-end commands.

If the team cannot describe the correct result, it cannot reliably decide which code is unnecessary. Clarify the contract before deleting anything.

2. Establish the complete diff, not just the agent’s summary

GitHub organizes PR evidence across several views. Conversation contains the description and discussion; Commits shows how the branch evolved; Checks shows automated validation; Files changed shows the diff reviewers must understand. GitHub’s review flow supports line comments, suggestions, per-file Viewed markers, and a final Comment, Approve, or Request changes decision.

When you need to run or modify the PR locally, GitHub documents this checkout flow:

gh pr checkout <PR_NUMBER>
git fetch origin

Replace origin/main with the real base branch, then inventory the change from the common ancestor to the PR head:

git diff --stat origin/main...HEAD
git diff --name-status origin/main...HEAD
git log --oneline origin/main..HEAD

Git defines git diff A...B as the changes from the merge base of A and B to B. Start with the summary and file statuses, then inspect the full diff and suspicious paths:

git diff origin/main...HEAD
git diff origin/main...HEAD -- path/to/suspicious-file

Do not delete during this inventory pass. Sort files into five groups:

GroupQuestion to answer
Core implementationDoes it directly implement an item in the acceptance contract?
Necessary supportAre tests, docs, migration, or configuration required by the implementation?
Suspected scope expansionDid the PR add global formatting, broad renames, unrelated abstractions, or dependency upgrades?
Generated outputMust the generated file be committed with its source, or was it included accidentally?
Uncertain/high riskDoes the edit touch security, data, compatibility, or a domain the reviewer does not understand?

Complexity alone is not proof of redundancy. Defensive checks, migrations, and compatibility paths may be longer than the happy path and still be necessary.

3. Use a fresh context for a review-only first pass

A fresh context is useful because it can receive a different objective from the implementation session: challenge scope and evidence instead of finishing the feature. That is a reasoned review technique and a practitioner report, not an official GitHub requirement or a measured guarantee.

Give the reviewer the acceptance contract, the complete PR diff, relevant call sites, tests, and repository instructions. Use a prompt such as this:

You are the second-pass maintainer reviewer for this pull request. Your goal is not to rewrite the code. Find the smallest explainable change set that still satisfies the acceptance contract.

First pass: review only. Do not modify any file.
Read the PR goal, complete diff, relevant callers, tests, and repository constraints.

For every finding, return:
1. file and exact hunk or symbol;
2. requirement served by the change;
3. evidence: caller, test, interface contract, documentation, or missing evidence;
4. risk of removing or simplifying it;
5. recommended action: KEEP / SIMPLIFY / REMOVE / SPLIT / HUMAN DECISION;
6. exact validation to run after the change.

Rules:
- Do not recommend deletion merely because code is long or stylistically different.
- Passing tests are not the only proof that requirements are correct.
- Prioritize unrelated formatting, duplicate abstractions, unused helpers, out-of-scope refactors, and unexplained dependency or configuration changes.
- Preserve security, compatibility, migrations, error handling, and observability unless evidence shows they are unnecessary.
- State uncertainty; do not invent business rules.
- Finish with a low-to-high-risk trim plan. Do not write code yet.

A report-first pass prevents the reviewer from creating another large rewrite while supposedly reducing the first one. Every recommendation should point to a file, a hunk, and evidence.

4. Let a human classify each finding by evidence

Use a decision table instead of accepting the reviewer’s list wholesale:

DecisionWhen it appliesEvidence the maintainer should confirm
KeepThe code directly implements the contract or provides required security, compatibility, migration, or operational behaviorRequirement mapping, call path, test, interface, or documented constraint
SimplifyThe behavior is required but the implementation duplicates branches, wrappers, or layersBehavioral equivalence and coverage of important edges
RemoveThe edit is unrelated, unused, unsupported by a contract, or only an accidental format/rename changeRepository search plus build and relevant tests show no dependency
SplitThe work may be valuable but is outside this PR’s contractIt can be described, tested, reviewed, and reverted independently
EscalateThe change touches an unfamiliar domain, security boundary, migration, or hidden business ruleCode owner, domain maintainer, or characterization tests are needed

Investigate these common signals, but do not treat them as automatic deletion rules:

  • multiple generic layers around one call site;
  • old and new paths retained without a documented compatibility period;
  • unrelated formatting, import ordering, renaming, or file movement;
  • a new dependency, lockfile change, permission, or configuration with no PR explanation;
  • tests that assert implementation shape rather than observable behavior;
  • broad exception handling that hides failures;
  • generated helpers with no callers;
  • “we may need this later” code added to the current task.

The reverse warning matters too: no test does not mean no use. It may indicate missing coverage. Add a characterization test or ask the module owner before removing uncertain behavior.

5. Trim in small batches and keep a recovery point

Before editing, confirm the working tree state and create a local backup reference:

git status --short
git branch backup/ai-pr-before-trim

When an entire file should match the base version, you can restore it from the merge base:

BASE=$(git merge-base origin/main HEAD)
git restore --source="$BASE" -- path/to/unrelated-file

For selected hunks, use interactive restore:

git restore -p --source="$BASE" -- path/to/file

Git’s documentation notes that if a tracked path does not exist in the restore source, restoring it removes the path to match that source. Verify $BASE and the path before running the command, then inspect the diff immediately. Editing manually is equally valid; the important constraint is to avoid introducing another unrelated refactor.

Process one approved group at a time:

git diff
git add -p
git diff --cached
git commit -m "Remove unrelated changes from AI-generated PR"

Small commits make the review legible: reviewers can see what was removed, why it was removed, and which validation belongs to that decision. Do not hide the work with destructive history rewriting during review; any final squashing should follow the team’s normal policy.

6. Use comparable validation before and after trimming

The purpose of testing is not to prove that the diff is smaller. It is to show that the accepted behavior survived. Record a baseline for the original PR when practical, then run the same relevant checks after each trim batch:

<format-check-command>
<lint-command>
<typecheck-command>
<targeted-unit-test-command>
<relevant-integration-test-command>
<build-or-e2e-command>

Use commands from repository documentation or CI configuration instead of asking the agent to guess. Cover the following where relevant:

  • the normal path and important boundary cases for the changed feature;
  • failure, permission, empty-value, concurrency, timeout, and retry behavior;
  • public interfaces, serialized formats, database or data migrations;
  • build, type checks, lint, dependency and security checks;
  • repository-required checks shown on the latest PR commit.

If a trim breaks a test, revert that batch or recover it from the backup, then investigate. Do not make both tests and implementation green by changing them together unless the acceptance contract explicitly says the old expectation is wrong and a human has approved the new behavior.

Tests are necessary evidence, but not sufficient on their own. A green suite may be incomplete; the maintainer must still understand the design and risk.

7. Re-review the final diff and make an explicit decision

After trimming, reopen Files changed and review from the top. GitHub removes the Viewed mark when a viewed file changes, which helps identify files that need another pass. Check Commits and Checks again so the validation belongs to the latest revision.

You may run one final fresh-context review against only the acceptance contract and final diff, but define a stop condition: it may report evidence-backed issues, not begin an endless style-refactoring loop. Then submit a human review:

  • Approve when the contract is met, every important change is explainable, risks are addressed, and required validation passes.
  • Request changes when scope expansion, unexplained logic, or failed checks remain. Whether this blocks merging depends on repository rules and branch protection.
  • Comment when feedback is useful but you are neither approving nor formally requesting changes.

Pre-merge checklist

  • Every changed file maps to the current requirement, a necessary test, or explicit supporting work.
  • A maintainer can explain each important hunk without repeating the agent’s summary.
  • Unexplained dependency, configuration, permission, migration, and generated-file changes were removed, split, or escalated.
  • The original and trimmed PR were evaluated with a comparable validation set.
  • Relevant local tests, build steps, and checks on the latest commit meet the project’s requirements.
  • Security, data, and compatibility uncertainty was reviewed by an appropriate owner.
  • The final diff is focused; if it is still too broad, independent work has been split instead of forced through one review.
  • The review decision and any follow-up work are recorded.

Failure modes and recovery

The second agent starts rewriting the module

Stop the run. Return to a review-only report, limit the files it can touch, and require a hunk, requirement, and validation for every recommendation. Reject aesthetic rewrites without evidence.

Two agents disagree about a piece of code

Do not vote. Compare callers, interface contracts, failure paths, tests, and historical constraints. If evidence remains weak, keep the code temporarily, add coverage, or ask a domain maintainer.

Tests pass, but the maintainer still cannot explain the code

Test coverage is not the same as understandable design. Split the PR, add documentation, or require an explanation of the critical path. Do not merge opaque code only because CI is green.

The repository has no reliable tests

Add a minimal characterization test for the behavior being preserved, or perform a repeatable manual check and record its result. For high-risk code, missing evidence is a reason to pause, not permission for an agent to guess.

The PR is too large for a complete review

Separate core behavior, refactoring, dependency upgrades, formatting, and migrations into independently reviewable changes. Smaller review units are easier to verify and revert than one broad “cleanup.”

Execution prompt for approved findings

Only after a human accepts specific findings should an agent edit the PR:

Implement only these approved finding IDs: [LIST].
Do not modify any file outside the approved list and do not perform opportunistic refactoring.
For each logical group:
1. show the actual diff;
2. run the assigned validation commands;
3. report each command, exit status, and failure summary;
4. list remaining uncertainties.
Stop and request a human decision if an approved item would change the acceptance contract, a public interface, security behavior, or migration behavior.

The central idea is not “use more agents.” It is to separate generation from review: one context proposes an implementation, a second context challenges scope and evidence, and a human owns the decision. The right result is not the shortest diff; it is the smallest explainable, verified change that still satisfies the task.

Sources and scope

Ready to optimize your LLM workflow?

Join thousands of developers building faster, smarter, and more cost-effective AI applications with BetterToken.

Get Started for Free