Guides

Reviewing code with Grok Build

View as Markdown

Codebase search lets Grok Build see how changed code connects to the rest of your project. It can check whether a change duplicates existing logic, violates patterns your team uses elsewhere, or misses edge cases that similar code handles.

Self-review before submitting PRs

The most effective reviews happen before you push. When you review your own changes with Grok Build, you catch issues while the context is fresh and before you've context-switched to something else.

Ask mode example: Self-review changes
I'm about to commit changes to the checkout flow. Review them for bugs, edge cases, and anything that might surprise a reviewer.
See the agent's response
Ran git diff --staged
Read src/pages/Checkout.tsx
Searched codebase similar checkout error handling patterns
Review of Checkout Flow Changes
Potential Issues Found:
1.Race Condition (line 45)
•setLoading(false) called before await processPayment() completes
•User could click Submit again while payment processes
2.Missing Error Handling (line 67)
•fetchShippingRates() can throw but isn't wrapped in try/catch
•Other checkout endpoints handle this - see CartService.ts:89
3.Inconsistent Validation (line 23)
•Email validated client-side only
•Other forms in codebase also validate server-side
Looks Good:
•Cart total calculation is correct
•Stripe PaymentIntent creation follows existing pattern
•Loading states properly managed
Suggested Fix for Race Condition:
setLoading(true);
try {
  await processPayment();
} finally {
  setLoading(false);
}
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 --stat
Searched codebase related code and conventions
Likely Reviewer Questions:
1."Why a new service instead of extending OrderService?"
•Answer: OrderService is 800+ lines; this keeps refund logic isolated
•Add to PR description: "Extracted to follow single-responsibility principle"
2."Why not use the existing Result pattern?"
•You're throwing exceptions here but team uses Result elsewhere
•Consider: Convert to Result or explain why exceptions fit better
3."Where are the tests?"
•No test file added - reviewers will ask
•Add: RefundService.test.ts or note that tests are coming in follow-up PR
4."What about partial refunds?"
•Current implementation only handles full refunds
•Clarify scope in PR description
Suggested PR Description:
## Summary
Extracts refund logic from OrderService into dedicated RefundService.

## Why
- OrderService is becoming too large (800+ lines)
- Refund logic has different error handling needs

## Scope
- Full refunds only (partial refunds tracked in JIRA-456)

## Testing
- Unit tests in follow-up PR
- Manually tested with Stripe test mode

Grok Build can compare your changes against patterns elsewhere in the codebase. If you're adding error handling to one endpoint, it can check whether similar endpoints handle errors the same way. This consistency check is tedious to do manually but natural for Grok Build.

If you develop prompts that work well for your codebase, turn them into custom commands. A /review command that runs your standard checks before every PR saves time and ensures consistency.

Automated review with Bugbot

Bugbot reviews PRs automatically when you push. It reads the full context of your change, including how the changed code interacts with the rest of your codebase, and looks for bugs that would reach production.

This is different from linters. Linters catch formatting issues and simple patterns. Bugbot looks for logic errors: null pointer exceptions waiting to happen, race conditions, missing error handling, security issues. It understands code semantically, not only syntactically.

What Bugbot catches

The specific issues Bugbot surfaces depend on your codebase. It tends to find null reference errors, missing error handling, race conditions, and security issues. Teams with strong typing see fewer null errors flagged; teams with async code see more race condition warnings.

See the Bugbot documentation for setup and configuration.

Reviewing others' PRs

When you're the reviewer, Grok Build helps you understand unfamiliar code quickly and check things you might miss.

Understanding what changed

Start by getting oriented. Use Ask mode (Shift+Tab, then select Ask) to explore without making changes:

Ask mode example: Understand a PR
Walk me through this PR. What's it trying to accomplish, and what's the approach?
See the agent's response
Ran git diff main...feature/auth-refactor --stat
Read src/services/AuthService.ts
Read src/middleware/authenticate.ts
PR Summary: Auth Refactor
What It Does:
Refactors authentication from session-based to JWT tokens.
Files Changed (12):
•AuthService.ts - Core changes (JWT generation)
•authenticate.ts - Middleware now validates JWT
•login.ts, logout.ts - Route handlers updated
•User.ts - Added refreshToken field
•7 test files
Approach:
1.Replaces express-session with JWT in HTTP-only cookies
2.Adds refresh token rotation for security
3.Keeps backwards compatibility via X-Legacy-Session header
Key Changes:
•Login returns JWT (15min) + refresh token (7d)
•/auth/refresh endpoint for token renewal
•Session table deprecated, data moved to JWT claims
What to Watch For:
•Logout invalidation (uses token blacklist in Redis)
•Refresh token rotation (old token invalidated on use)
•Migration path for existing sessions
Ask mode example: Trace connections
This PR touches the payment flow. Show me how the changed code connects to the rest of the payment system.
See the agent's response
Searched codebase payment flow connections
Read src/services/PaymentService.ts
Grepped PaymentService
Payment Flow Connection Map
Changed File: PaymentService.ts
Direct Callers (5 files):
src/routes/checkout.ts → PaymentService.charge()
src/routes/subscriptions.ts → PaymentService.subscribe()
src/workers/BillingWorker.ts → PaymentService.renewSubscription()
src/services/OrderService.ts → PaymentService.refund()
src/services/RefundService.ts → PaymentService.refund()
Downstream Effects:
•charge() triggers → InventoryService.reserve()
•charge() triggers → NotificationService.sendReceipt()
•refund() triggers → InventoryService.release()
Webhook Dependencies:
•WebhookController.ts listens for Stripe events
•Calls PaymentService.handleWebhook() for reconciliation
Impact Assessment:
The changes to charge() affect:
•Checkout flow (direct)
•Subscription renewals (via BillingWorker)
•Inventory reservations (downstream)
Note: The PR doesn't update BillingWorker.ts - verify it still works with new charge() signature.

Grok Build traces through callers and callees to show you the impact of changes. A two-line change might have implications across multiple files, and Grok Build can surface those connections.

Checking edge cases

Domain-specific edge cases are easy to miss in review. If you know the area is tricky, ask Grok Build to enumerate what could go wrong:

Ask mode example: Check edge cases
This PR modifies how we handle refunds. What edge cases should I verify? Think about partial refunds, currency conversion, and timing issues.
See the agent's response
Read src/services/RefundService.ts
Searched codebase refund edge cases in similar code
Searched Stripe refund edge cases
Refund Edge Cases to Verify
1. Partial Refunds
•Current code assumes full refund
•What happens if amount < order.total?
•Stripe supports partial refunds - does the code?
2. Currency Conversion
•Order placed in EUR, refund requested in USD?
•Stripe handles conversion but at current rate
•Customer may get different amount - is that documented?
3. Timing Issues
•Refund requested while payment still pending?
•Refund requested after Stripe's 180-day window?
•What if webhook for original charge hasn't arrived yet?
4. Duplicate Refunds
•No idempotency key visible in the code
•User double-clicks refund button → two refunds?
•Other endpoints use Idempotency-Key header
5. Subscription Refunds
•Refunding a subscription payment?
•Does it cancel the subscription or just refund one period?
Recommendation: Add tests for cases 1, 3, and 4 at minimum.
Ask mode example: Find missing error handling
The PR adds a new API endpoint. What error conditions should it handle that it currently doesn't?
See the agent's response
Read src/routes/products.ts
Searched codebase error handling in similar API endpoints
Missing Error Handling Analysis
Comparing POST /api/products to existing endpoints:
Error ConditionSimilar EndpointsThis PR
Invalid body schema400 + detailsMissing
Duplicate SKU409 ConflictMissing
DB connection error503 + retry-afterMissing
Unauthorized401Handled
Not found (for updates)404Handled
Missing Handlers:
1.No Input Validation
// Current:
const product = req.body; // No validation

// Should be:
const product = validateBody(req.body, ProductSchema);
2.No Duplicate Check
// Other endpoints check uniqueness:
const existing = await repo.findBySku(sku);
if (existing) throw new ConflictError('SKU exists');
3.No Database Error Handling
// Other endpoints wrap DB calls:
try {
  await repo.create(product);
} catch (e) {
  if (isConnectionError(e)) throw new ServiceUnavailable();
  throw e;
}

This works because Grok Build can see similar code elsewhere in your codebase. If other endpoints handle certain errors, it notices when this one doesn't.

Checking against team standards

If your team has documented standards in rules files, Grok Build can check compliance:

Ask mode example: Check against standards
Review this PR against the patterns in .cursor/rules/. Does anything violate our conventions?
See the agent's response
Read .cursor/rules/review.mdc
Ran git diff main...HEAD
Searched codebase referenced pattern files
Standards Compliance Check
Checking Against: .cursor/rules/review.mdc
Error Handling [violation]
•Rule: "All async operations should use try/catch or Result pattern"
•Found: 3 unhandled async calls in OrderController.ts
•Line 45: await orderService.create() - no try/catch
•Line 67: await paymentService.charge() - no try/catch
•Line 89: await emailService.send() - no try/catch
•Reference: src/utils/errors.ts shows expected pattern
Validation [violation]
•Rule: "Public API endpoints must validate input"
•Found: POST /api/orders accepts body without validation
•Reference: src/middleware/validation.ts shows how to add
Logging [warning]
•Rule: "Operations that can fail should log with correlation IDs"
•Found: Logging present but missing correlation ID
•Current: logger.info('Order created')
•Expected: logger.info('Order created', { correlationId, orderId })
Summary:
•2 violations requiring changes
•1 warning (nice to have)

The more specific your rules files, the more useful this check becomes. "Follow best practices" produces vague feedback. "Use the Result pattern for operations that can fail" produces specific feedback.

Encoding review standards

The knowledge that makes senior engineers good reviewers can be captured in rules files. When you encode this knowledge, Grok Build (and Bugbot) apply it consistently across every review.

Bugbot rules (BUGBOT.md)

Create a BUGBOT.md file in your repository root:

Bugbot rules example: Review Standards

Text

# Review Standards

## Test coverage
If the PR modifies files in {server/**, api/**} and there are no changes
in {**/*.test.*, tests/**}, flag as needing tests.

## Security-sensitive areas
If the PR modifies files in {auth/**, payments/**, security/**},
add a comment requesting security review.

## Common patterns to enforce
- Flag .Result or .Wait() in async code (use await instead)
- Flag TODO comments without linked issues
- Flag new dependencies without justification in PR description

Agents Window rules (.cursor/rules/)

Create a .cursor/rules/review.mdc file for reviews in the Agents Window:

Rules example: Review Context

Text

# Review Context

## Patterns to check
- Error handling: All async operations should use try/catch or the Result pattern
- Validation: Public API endpoints must validate input before processing
- Logging: Operations that can fail should log before and after with correlation IDs

## Files to reference
- src/utils/errors.ts shows our error handling pattern
- src/middleware/validation.ts shows our validation approach

## Known areas of risk
- The legacy UserService has implicit null returns; always check for null
- Payment operations must be idempotent; check for duplicate handling

Start with the issues that come up repeatedly in your reviews. Each rule you add is a review that future PRs get automatically.

Connecting external context

MCP integrations can pull context from GitHub, GitLab, Linear, and other tools directly into your review workflow. If you need to understand why a change was made, you can reference the linked issue. If you need to check related PRs, you can query your repository.

Ask mode example: Check against requirements
Pull the linked issue for this PR and check whether the implementation matches what was requested.
See the agent's response
Github MCP get_issue 234
Ran git diff main...HEAD
Requirements Check: Issue #234
Issue Title: "Add bulk export for admin users"
Acceptance Criteria vs Implementation:
RequirementStatusNotes
Export up to 10,000 recordsDoneImplemented with pagination
CSV formatDoneUsing csv-stringify
Include all user fieldsPartialMissing lastLoginAt field
Admin-only accessDonerequireAdmin middleware
Progress indicatorMissingNot implemented
Email when completeMissingNot implemented
Missing from Implementation:
1.Progress Indicator
•Issue says: "Show progress for large exports"
•Not found in PR - intentional deferral or oversight?
2.Email Notification
•Issue says: "Email download link when ready"
•Not implemented - async export pattern not used
3.Field Missing
•lastLoginAt mentioned in issue but not in export
Recommendation:
Clarify with product whether progress + email are MVP or can be follow-up. The lastLoginAt field should probably be added.

Browse the Marketplace for available integrations with your tools.

Getting started

  1. Try self-review first. Before your next PR, ask Grok Build to review your changes. Notice what it catches that you missed, and what feedback is useful versus noise.

  2. Enable Bugbot on a repository. After a week of running, you'll have a sense of which comments are valuable and which to dismiss, and you can tune the rules accordingly.

  3. Start a rules file. Pick one or two issues that come up repeatedly in your reviews and encode them. Add more as patterns emerge.

  4. Use Ask mode for understanding. When reviewing unfamiliar code, explore with Ask mode before forming opinions.

For related workflows, see Understanding Unfamiliar Code for exploring codebases and Debugging for investigating issues discovered in review.


Last updated: November 23, 2026