Coding agents

Reviewing and testing code

View as Markdown

Coding agents produce a lot of code, and with it, tech debt. Keep your quality bar the same whether code was written by hand or by an agent.

AI-generated code can look correct and still be subtly wrong. It might compile and pass your tests, yet miss edge cases, have security issues, or duplicate logic that exists elsewhere. Code review catches these before they reach production.

Self-review

Review your code before you ask others to look at it.

Watch the agent work. The diff view shows changes as they happen. If you see the agent heading in the wrong direction, click Stop or press Cmd Shift Backspace / Ctrl Shift Backspace to cancel and redirect. You don't have to wait until it finishes. For larger course corrections, revert the changes and refine your plan before running it again, as covered in developing features.

Ask the agent to review all changes at once. Tag @Branch in your prompt to give the agent the full diff of your current branch. Say something like "review the changes on this branch" or "what am I working on right now?" to give the agent rich context and catch issues across many different files.

For example, you can ask the agent to review its own work:

Ask mode example: Self-review
Review the changes I've made to the discount code feature. Look for bugs, missing error handling, and anything that doesn't match our patterns in src/services/PricingService.ts
See the agent's response
Ran git diff --staged
Read src/services/DiscountService.ts
Searched codebase similar discount and pricing patterns
Review of discount code changes:
Potential issues:
1.Missing input validation (DiscountService.ts:23) — applyDiscount() doesn't check if price is negative. Other pricing functions in PricingService.ts validate this at the top.
2.No rate limiting — The /api/discount/validate endpoint can be called unlimited times. An attacker could brute-force valid codes. Other auth-adjacent endpoints use rateLimit(10, '1m').
3.Inconsistent error codes — Returns 400 for expired codes but 404 for invalid codes. The checkout frontend expects all discount errors to be 422.
Looks good:
•Percentage discounts applied before fixed-amount (correct ordering)
•Price floor at $0 prevents negative totals
•Test coverage for all discount types
•Follows existing service patterns from PricingService.ts
Ask mode example: Anticipate reviewer questions
What questions will reviewers have about these changes? What context should I include in the PR description?
See the agent's response
Ran git diff HEAD~1
Searched codebase related code and conventions
Likely reviewer questions:
1."Why a new DiscountService instead of adding to PricingService?"
•Answer: PricingService is 600+ lines; this keeps discount logic isolated
•Add to PR description: "Extracted to follow single-responsibility pattern"
2."Where are the integration tests?"
•Unit tests exist but no API-level tests
•Consider adding: POST /api/discount/validate with valid/expired/invalid codes
3."Does the discount apply before or after tax?"
•Current: before tax (discount reduces subtotal, then tax applies to the discounted amount)
•Add to PR description so reviewers don't have to read through the code
Suggested PR description:
> Adds discount code support to checkout. Users can enter codes for percentage or fixed-amount discounts. Codes validate against expiry dates and usage limits. Discounts apply before tax.
>
> Extracted into DiscountService (separate from PricingService) since discount logic has different validation needs. Integration tests in follow-up PR.

Prepare for peer review

Agents can produce one large commit with hundreds of changed lines, which is hard for anyone to review. Use small, semantic commits instead, each one logical change with a clear description, so a reviewer can step through the history.

This housekeeping is tedious by hand, but agents handle it well:

  1. Build the feature freely. Don't worry about commit hygiene while you're iterating.
  2. Once everything works, ask the agent to rework the commit history into reviewable pieces.
  3. The agent resets to main, reads through all the changes, and plans a logical sequence to create clean commits with descriptive messages.
  4. It validates the final diff matches the original, so none of your changes are lost.

Use this prompt to create a skill so anyone on your team can run /rework-commits after finishing a feature:

Create a skill file at .cursor/skills/rework-commits/SKILL.md with this content: # Split Branch into Reviewable Commits Rework a branch into a sequence of small, semantic commits for review. ## Important - Prepend `GIT_EDITOR=true` to all git commands you run, especially ones looking at diffs, so you avoid getting blocked ## Instructions 1. **Check for uncommitted changes**: Abort if there are any. 2. **Check rebase status**: Verify the branch is rebased on top of `main`. Abort if not. 3. **Save recovery point**: Tell the user the current commit hash in case they need to `git reset --hard` to it later. 4. **Save the original diff**: Save the full git diff to `/tmp/original-diff.patch` before making changes. 5. **Reset to main**: Run `git reset main` to unstage all changes. 6. **Plan the commits**: Read through ALL changes carefully. Plan a logical breakdown into small, sequential, semantic commits. Write a TODO for each in `/tmp/split-todos.md`. Order: database/schema changes first, backend second, frontend last. 7. **Create the commits**: Work through the TODOs one by one. Write excellent commit descriptions for human reviewers. 8. **Validate**: Compare the current diff against `/tmp/original-diff.patch` to ensure no changes were lost or altered. 9. **Cleanup**: Delete temporary files once validation passes. ## Notes - If validation fails, tell the user and provide the original commit hash for recovery - Each commit should be self-contained and represent a logical unit of work - Commit messages should explain the "why" behind the changes

Try in the Agents Window

Agent review

After the agent finishes a task, click Review then Find Issues to run a dedicated code review. The agent analyzes proposed edits line by line and flags potential problems.

For all local changes, open the Source Control tab and run Agent Review to compare against your main branch. This catches issues across your full set of changes.

Bugbot for pull requests

Bugbot reviews pull requests in your source control provider when you push. It reads how the change connects to the rest of your codebase and looks for logic errors that linters miss: null pointer exceptions, race conditions, missing error handling, and security issues.

When Bugbot finds an issue, it can also propose a fix. With autofix enabled, you can commit the fix directly from a comment on the pull request.

You can also customize Bugbot by providing additional rules, which the customizing agents chapter covers.

Verifiable goals

To help ensure the correctness of your code, you want to give the agent clear signals to validate its own work:

  • Tests catch behavioral regressions
  • Type checking catches structural errors
  • Linting catches style and pattern violations

The more of these checks you have in place, the more confidently you can delegate work to agents. Use typed languages with test coverage and linting rules alongside your agent.

Which combination provides the strongest safety net for AI-generated code?

Let agents write your tests

Thorough test coverage used to take significant effort, so many teams added tests only after something broke. Agents make it approachable: ask the agent to write tests, then verify they're correct. The agent can also do manual testing for you through the browser, checking UI states or flows you'd otherwise verify by hand.

Agent example: Agent-written tests
Write integration tests for the discount code API endpoint and e2e tests for the checkout discount flow. Look at our existing test patterns and match them.
See the agent's response
Searched codebase existing test patterns and frameworks
Read src/services/DiscountService.ts
Grepped describe.*discount|test.*discount
Thought for 2s
The project uses Vitest for unit tests and Playwright for e2e. DiscountService has unit tests for applyDiscount() but no integration tests for the API endpoint and no e2e tests for the checkout flow with discount codes.
Createddiscount.test.ts+42
describe('POST /api/discount/validate', () => {
  it('returns discount details for a valid code', async () => {
    const res = await request(app).post('/api/discount/validate')
      .send({ code: 'SAVE20' })
    expect(res.status).toBe(200)
    expect(res.body.discount).toBe(20)
  })

  it('returns 422 for an expired code', ...)
  it('returns 422 for a code exceeding usage limit', ...)
  it('returns 422 for an invalid code', ...)
  it('rate limits after 10 requests per minute', ...)
})
Createdcheckout-discount.spec.ts+38
test('user applies a valid discount code during checkout', async ({ page }) => {
  await page.goto('/checkout')
  await page.fill('[data-testid="discount-input"]', 'SAVE20')
  await page.click('[data-testid="apply-discount"]')
  await expect(page.locator('.discount-applied')).toBeVisible()
  await expect(page.locator('.total')).toContainText('$80.00')
})
Test coverage added:
•Integration tests (api/discount.test.ts): 5 tests covering the /api/discount/validate endpoint — valid codes, expired codes, usage limits, invalid codes, and rate limiting
•E2E tests (checkout-discount.spec.ts): 3 tests covering the full checkout flow — applying a valid code, trying an expired code, and removing a discount
Previously untested: The rate limiting and the full user flow from entering a code to seeing the updated total. Unit tests only covered the applyDiscount() math, not the API layer or the UI.

High-quality tests give you the confidence to let the agent work on its own without introducing regressions.

Good prompts for generating tests:

  • "Plan how to get e2e coverage for our checkout flow. What scenarios should we test?"
  • "Set up integration tests for the payments API. Use our existing test infrastructure in src/__tests__/."
  • "What edge cases aren't covered by our current tests for the discount feature?"
  • "Write regression tests for the bug we fixed in PaymentService.ts."

The agent can also set up testing infrastructure from scratch, such as configuring Playwright and writing your first test.

Cloud Agents

Cloud agents run in remote sandboxes, so you can close your laptop and check results later:

  1. Describe the task and provide relevant context
  2. The agent clones your repo and creates a branch
  3. It works on its own, opening a pull request when finished
  4. You get notified when it's done (via Slack, email, or the web interface)
  5. Review the changes and merge when ready

They suit to-do list tasks: side bug fixes, test coverage for existing code, documentation updates, and refactors. They can also test many variations in parallel. For a new discount code feature, launch several to test every discount type, invalid inputs, stacked discounts, and boundary values. Each creates a branch with its results, and you turn the failures into local test cases before merging.

Speed up your feedback loops

With more agents, the bottleneck moves to the slowest part of your system: the test suite, type and lint checks, or CI. Every agent pays these costs. If tests take 10 minutes and you run 10 agents, that's nearly two hours of waiting; make them 50% faster and you save almost an hour each time.

Faster tests, a smaller dependency tree, a quicker CI pipeline, type checking, and builds all compound when agents run them dozens of times a day. Agents can do this work too: ask one to profile your tests and fix the slowest, or audit your dependencies and remove what's unused.

Common failure pattern

Passing tests don't guarantee the code works correctly. It's possible the tests are checking the wrong behavior. The agent might have written code that works for the happy path but doesn't consider all of the edge cases.

Understand the code changes yourself. If a change is too large to review comfortably, break it into smaller pieces.

What's next

You now understand how to ship new features, debug when things go wrong, and review code to ensure it's high quality. The last piece is making your workflow faster by customizing agents to work with your specific codebase.

You've completed this chapter

Next: Customizing agents

Last updated: November 23, 2026