Guides

Debugging with Grok Build

View as Markdown

Debugging is detective work: trace the error, understand the context, form a hypothesis, test it. Grok Build does much of this work for you. It reads stack traces, searches your codebase for relevant code, proposes fixes, and runs tests to verify them.

For tricky bugs that need runtime information, Debug Mode takes this further: it generates hypotheses, instruments your code with logging, and uses the actual runtime data to pinpoint root causes.

Debug mode: runtime-driven debugging

Debug Mode is for bugs that are hard to reproduce or understand. Instead of writing a fix right away, the agent forms hypotheses, adds logging to test them, then asks you to reproduce the bug so it can see what happens at runtime. Race conditions, memory leaks, and intermittent failures need that real execution data.

When to use debug mode

Debug Mode works best for:

  • Challenging bugs or regressions that can be reproduced
  • Performance problems and memory leaks
  • Issues where reading the code does not reveal the cause

For straightforward errors with clear stack traces, regular Agent mode is faster.

Switch to Debug Mode with Shift+Tab and select Debug.

The debug mode workflow

Debug mode example: Debug a reproducible issue
The checkout flow is failing for some users but not others. I can reproduce it by logging in as user [email protected] and adding 3 items to the cart.
See the agent's response
Read src/services/checkout/CartService.ts
Searched codebase cart session handling
I've identified 3 hypotheses for why checkout fails for some users:
H1: Session expiry - Cart sessions expire after 30 min, but users on slow connections may exceed this
H2: Race condition - Concurrent cart updates when user has multiple tabs open
H3: Inventory sync - Items removed from inventory but not cleared from cart
I'll add logging to test these. Please reproduce the issue with the test account and I'll analyze the logs.
  1. Describe the bug: Tell Grok Build what is happening and how to reproduce it. Include specific steps, user accounts, or data that triggers the issue.

  2. Agent explores and hypothesizes: Grok Build reads your codebase and generates multiple hypotheses about what could be wrong.

  3. Agent adds instrumentation: Grok Build adds logging statements designed to test its hypotheses, capturing variable states, execution paths, and timing information.

  4. You reproduce the bug: Go to your application and trigger the bug while the agent collects runtime logs.

  5. Agent analyzes and fixes: With real data about what happened, Grok Build pinpoints the root cause and generates a targeted fix. The fix is often only a few lines.

  6. You verify: Reproduce one more time to confirm the fix works. If not, the agent adds more logging and refines its approach.

You make the final call: a fix can work technically yet only treat the symptom.

Debug mode example: Race condition
There's a race condition somewhere in the order processing. Orders occasionally get duplicated. I can reproduce by rapidly clicking the submit button.
See the agent's response
Searched codebase order submission handling
Read src/services/OrderService.ts
Thought for 2s
The submit handler doesn't disable the button during processing, and there's no idempotency check. Multiple rapid clicks could create duplicate orders.
Hypothesis: Missing idempotency protection
I'll add logging to capture:
1.Button click timestamps
2.Order creation attempts with request IDs
3.Database transaction timing
Please rapidly click the submit button 5 times and I'll analyze the sequence. Looking for overlapping transaction windows.

Starting from an error

The most common debugging scenario: you have an error and need to find the cause. Grok Build works best when you give it everything you have.

Agent example: Debug from error
I'm seeing 'TypeError: Cannot read property id of undefined' at UserService.getProfile (line 45). Find the root cause and fix it.
See the agent's response
Read src/services/UserService.ts
Searched codebase ProfileController.show callers
Thought for 2s
The error occurs in getProfile() when user.profile is undefined. Looking at callers to find where this state originates.
Grepped findUser.*include.*profile
Found the root cause. The findUser query in AuthMiddleware.ts doesn't include the profile relation:
// Line 45 - missing profile include
const user = await prisma.user.findUnique({ where: { id } });
Should be:
const user = await prisma.user.findUnique({
  where: { id },
  include: { profile: true }
});
This only fails for users created before we added profile onboarding - they have users without profiles.

Stack traces tell Grok Build where to look, but the root cause is often upstream. The error occurs at line 45, but the problem might be in whatever called that function with bad data. Grok Build traces through callers to find where things went wrong, not only where the error surfaced.

For log-based debugging, paste the relevant output and let Grok Build correlate timestamps and events:

Agent example: Debug from logs
Order processing is failing for order 12345. Logs show inventory check passed, then payment authorization started, then the error. Find where it fails after payment auth.
See the agent's response
Read src/services/OrderService.ts
Searched codebase payment authorization flow
Thought for 2s
The logs show inventory check passed at 10:23:44, payment auth started at 10:23:45, then failure. The error happens between payment start and completion.
Read src/services/PaymentService.ts
Found it. The processPayment function has a 5-second timeout, but the Stripe webhook handler doesn't account for network latency:
// PaymentService.ts:89
const result = await Promise.race([
  stripe.paymentIntents.create(params),
  timeout(5000) // Too aggressive
]);
For order_id=12345, the payment likely succeeded on Stripe's side but we timed out before receiving confirmation. Check your Stripe dashboard - the charge probably went through.

Error messages alone are often ambiguous. Stack traces narrow the search, timestamped logs show the sequence of events, and steps to reproduce let Grok Build verify the fix.

Debugging from support tickets

Support reports often arrive with incomplete information: a description, maybe a screenshot, sometimes account details.

Agent example: Investigate support ticket
A customer reports: 'I tried to export my data but got a blank file. I'm on the Pro plan, account ID 12345.' Find the export functionality, check what could cause blank exports, and identify likely causes for this user's issue.
See the agent's response
Searched codebase data export functionality
Read src/services/ExportService.ts
Read src/jobs/ExportJob.ts
Thought for 2s
Export has three stages: query data, transform to CSV, upload to S3. A blank file could mean: empty query results, transform failure, or partial upload.
Found several potential causes for blank exports:
1.Pro plan filter - Line 67 in ExportService filters by plan_type, but uses 'pro' (lowercase) while the DB stores 'Pro'
2.Empty date range - No validation that startDate < endDate
3.S3 timeout - Large exports can timeout at 30s, producing truncated files
For account 12345, check their plan_type value in the database. If it's 'Pro' with capital P, that's the bug.

Customer descriptions are symptoms, not root causes. A "blank file" could mean the export found no data, timed out, failed silently, or produced a corrupted download. Grok Build maps out these possibilities and suggests what to check first.

For issues that require account-specific investigation, give Grok Build the context it needs:

Agent example: Account-specific investigation
Support ticket: User can't see their team members after being added to an organization. Account: [email protected], Org ID: org_789. Check the team membership logic, permission checks, and any caching that might delay visibility.
See the agent's response
Searched codebase team membership and organization logic
Read src/services/TeamService.ts
Read src/middleware/orgContext.ts
Investigation: User can't see team members
Found the issue. The orgContext middleware sets org_id from the JWT, but:
1.JWT is issued at login and cached for 15 minutes
2.User was added to org_789 via admin panel
3.Their JWT still contains old org_id (org_456 or null)
Solution paths:
•User logs out and back in (refreshes JWT)
•Admin triggers token refresh via /api/auth/refresh-token
•We add org membership check that bypasses JWT cache
Root cause: Org membership changes don't invalidate existing JWTs.

When you have access to logs or monitoring dashboards, share what you find:

Agent example: Debug with logs
User was added to org_789 via admin panel but their JWT still shows org_456. They're getting an empty team members list. Find where we set org_id in the token and why it's not updating after org changes.
See the agent's response
Read src/services/AuthService.ts
Searched codebase JWT org_id assignment
Read src/middleware/authenticate.ts
Found the stale JWT issue
The logs show exactly what's happening:
14:22:45 - User added to org_789 (admin panel)
14:23:01 - JWT org_id: org_456 (stale)
14:23:01 - GET /api/team/members returns empty (wrong org)
Root cause (AuthService.ts:67):
// JWT claims set at login, not refreshed on org change
const token = jwt.sign({ userId, org_id: user.org_id }, secret);
Fix options:
1.Add org_changed_at timestamp, validate JWT against it
2.Query org_id from DB instead of trusting JWT
3.Force token refresh when admin changes org membership
Recommend option 3 - add webhook from admin panel to invalidate user sessions.

Grok Build can correlate timestamps, identify the discrepancy, and trace through your authentication and session code to find where the stale data originates.

Building a support debugging workflow

For teams handling regular support escalations, create a rules file that captures your debugging patterns:

Rules example: Support Debugging Context

Text

# Support Debugging Context

## Common issue categories
- "Can't log in" -> Check auth provider status, then session/token issues
- "Missing data" -> Check permissions first, then sync status, then data integrity
- "Slow performance" -> Get timestamp range, check for N+1 queries or missing indexes

## Useful queries
- Find user by email: SELECT * FROM users WHERE email = ?
- Check org membership: SELECT * FROM org_members WHERE user_id = ?
- Recent errors for user: Check error_logs table with user_id filter

## Access notes
- Production logs in Datadog, filter by user_id tag
- Admin panel at /internal/admin for account lookups
- Feature flags checked via LaunchDarkly dashboard

This context helps Grok Build suggest relevant investigation steps and know where to look for information specific to your infrastructure.

The iterative debugging loop

Grok Build can run your code, see the results, and iterate. This closed-loop debugging is where Grok Build is most effective.

Agent example: Run and fix
Run the test for UserService.getProfile. If it fails, fix the issue and run it again. Keep going until it passes.
See the agent's response
Ran npm test UserService.getProfile
Thought for 1s
Test failed: 'Cannot read property profile of undefined'. The mock user doesn't have a profile object.
EditedUserService.test.ts+3-1
const mockUser = { id: '1', email: '[email protected]' };
const mockUser = {
  id: '1', email: '[email protected]',
  profile: { name: 'Test', avatar: null }
};
Ran npm test UserService.getProfile
Test passing now.
The mock was missing the profile relation that getProfile() expects. Added the profile object to the mock user.
All 5 UserService tests now pass.

The first fix often reveals a second issue. Run, observe, fix, and repeat.

For bugs that only occur under specific conditions, have Grok Build write a test that reproduces the scenario:

Agent example: Reproduce and fix
This bug happens when a user has no email set. Write a test case that reproduces this scenario, then fix the code to handle it gracefully.
See the agent's response
Thought for 1s
I'll write a test that creates a user with no email, then calls the function that's failing. This will reproduce the bug in a controlled way.
CreatedNotificationService.test.ts+15
describe('sendWelcomeEmail', () => {
  it('handles users with no email gracefully', async () => {
    const userWithoutEmail = { id: '1', email: null };
    
    // Should not throw, should return early
    await expect(sendWelcomeEmail(userWithoutEmail))
      .resolves.toEqual({ skipped: true, reason: 'no_email' });
  });
});
Ran npm test sendWelcomeEmail
Thought for 1s
Test fails as expected - the function throws when email is null. Now I'll fix the code.
CreatedNotificationService.ts+4
async function sendWelcomeEmail(user: User) {
  if (!user.email) {
    return { skipped: true, reason: 'no_email' };
  }
Ran npm test sendWelcomeEmail
Test passes. Fixed the null email handling.
Changes:
1.Added test case for user without email
2.Added early return in sendWelcomeEmail when email is null
3.Returns { skipped: true, reason: 'no_email' } instead of throwing
This gracefully handles the edge case without breaking the notification flow.

A failing test confirms the bug exists and tells you when it's fixed.

Debugging frontend issues

Grok Build's browser tool lets it see what users see: the rendered UI, console errors, network requests, and application state.

Agent example: Visual debugging
Open the checkout page and click 'Submit Order'. The button doesn't respond. Take a screenshot, check console errors, and identify the issue.
See the agent's response
Browsed localhost:3000/checkout
Thought for 1s
Page loaded. I can see the Submit Order button. Let me click it and check what happens.
Browsed clicked Submit Order button
Browsed checking console for errors
Found the issue
Console error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
    at CheckoutForm.js:45
The button click handler is trying to attach to an element that doesn't exist yet. The form JavaScript runs before the DOM is fully loaded.
Root cause: Missing DOMContentLoaded wrapper or defer attribute on script tag.
Fix: Add defer to the script tag in checkout.html, or wrap the handler setup in:
document.addEventListener('DOMContentLoaded', () => {
  // button setup here
});

A button that does not respond could be a JavaScript error, an element covered by CSS, a failed API call, or state that never updated. Grok Build checks the actual browser state rather than guessing from code.

For performance issues, Grok Build can profile network requests:

Agent example: Network debugging
The orders page is loading slowly. Check what API calls it makes, how long each takes, and identify any that are slow or failing.
See the agent's response
Browsed localhost:3000/orders - checking network tab
Thought for 2s
Page took 4.2 seconds to load. Let me check the network waterfall to see which requests are slow.
Network Analysis: /orders page
RequestTimeStatus
/api/orders3,450ms200
/api/user89ms200
/api/notifications156ms200
Problem: /api/orders takes 3.4 seconds
Likely causes:
1.N+1 query - fetching order items separately for each order
2.Missing database index on user_id column
3.No pagination - loading all orders at once
Next step: Check the OrderController to see the query. Look for .include() with nested relations or missing where clauses.

Long-running investigations

Some bugs require extended investigation: flaky tests, memory leaks, race conditions that only appear under load. Grok Build can work on these while you do other things.

Agent example: Debug flaky test
This test is flaky. It passes sometimes and fails others. Run it 20 times, collect the failures, and find the pattern. What's causing the inconsistency?
See the agent's response
Ran for i in {1..20}; do npm test checkout.test.ts 2>&1 | tail -1; done
Thought for 3s
Ran 20 times: 14 passed, 6 failed. Failures all on 'should clear cart after checkout'. Looking for timing or state issues.
Read tests/integration/checkout.test.ts
Flaky Test Analysis
Pattern found: Failures occur when tests run in quick succession.
Root cause (line 89):
await checkout();
expect(cart.items).toHaveLength(0); // Fails intermittently
The checkout() function clears the cart asynchronously via a background job, but the test expects it to be cleared immediately.
Fix:
await checkout();
await waitFor(() => {
  expect(cart.items).toHaveLength(0);
}, { timeout: 1000 });
Or mock the cart clearing to be synchronous in tests.

For long debugging sessions, give clear success criteria ("the test should pass consistently 20 times in a row"), make sure Grok Build can run the relevant tests, and check in periodically. The agent will keep iterating until it meets the criteria or gets stuck.

Understanding before fixing

In unfamiliar code, a quick fix often creates new bugs or treats only the symptom.

Ask mode example: Understand before debugging
Before we try to fix this bug, explain how the OrderProcessor class works. What are its main responsibilities? What other services does it depend on? What calls it?
See the agent's response
Read src/services/OrderProcessor.ts
Searched codebase OrderProcessor dependencies and callers
OrderProcessor Overview
Responsibilities:
1.Validate order data (items, quantities, prices)
2.Check inventory availability
3.Calculate totals with tax and shipping
4.Create order record in database
5.Trigger payment processing
6.Send confirmation notifications
Dependencies:
•InventoryService - stock checks
•PricingService - tax and discount calculation
•PaymentService - payment processing
•NotificationService - emails and webhooks
•AuditLogger - compliance logging
Callers:
•CheckoutController.submit() - web checkout
•APIController.createOrder() - API orders
•SubscriptionWorker.renew() - subscription renewals
State machine: pending → validated → paid → fulfilled → completed
Warning: The rollback() method (line 234) is complex and has known issues with partial refunds.

Use Ask mode for this exploration. Ask Grok Build to explain the flow, identify the components involved, and map out what could go wrong. Then switch back to Agent mode with a clearer picture of where to focus.

Root cause analysis

Finding the immediate fix is often not enough. Without understanding why the bug happened, similar bugs will keep appearing.

Ask mode example: Find root cause
You fixed the null reference error. Now explain why this happened. How did we get into a state where user.profile was undefined? What sequence of events leads here?
See the agent's response
Searched codebase user.profile undefined scenarios
Ran git log --oneline src/models/User.ts | head -10
Root Cause Analysis: undefined user.profile
Why it happened:
1.Historical: Users created before March 2024 don't have profiles
•Profile model added in commit abc123 (March 15)
•Migration created profiles for existing users
•But migration had a bug: skipped users with status: 'pending'
2.Current: 847 users have no profile record
   SELECT COUNT(*) FROM users 
   WHERE id NOT IN (SELECT user_id FROM profiles);
3.Code assumption: getProfile() assumes profile always exists
Prevention:
1.Add database constraint: profiles required for active users
2.Add defensive check in getProfile()
3.Run data migration to create missing profiles
Similar patterns to check:
•user.settings - same assumption
•user.subscription - has null check

After fixing a bug, ask Grok Build to find other places with the same pattern. If the bug was a missing null check, there may be similar missing checks elsewhere. If it was a race condition, the same race might exist in related code.

Document significant findings in your rules files or team documentation. The best debugging session is the one you do not have to repeat.

Building a debugging knowledge base

Capture what you learn so debugging knowledge persists across sessions and team members.

Create a .cursor/rules/debugging.mdc file:

Rules example: Debugging Context

Text

# Debugging Context

## Common issues
- Null user.profile: Usually means the user was deleted but sessions weren't cleared
- Payment timeout errors: Check the payment gateway status page first
- Slow API responses: Often caused by N+1 queries, check the query logs

## Useful commands
- npm run debug:payments - Runs payment service with verbose logging
- docker logs worker -f - Follow worker logs for background job issues
- npm run db:query-log - Shows recent slow queries

## Known flaky tests
- tests/integration/checkout.test.ts - Race condition in cart clearing, fix in progress
- tests/e2e/notifications.test.ts - Timing dependent on email service mock

## Debugging tips
- Always check if the issue reproduces locally before diving in
- The staging database resets nightly; check if data-dependent bugs are timing related
- Payment sandbox credentials expire monthly; check if payment tests suddenly fail

Update this file as you learn. When you solve a tricky bug, add the symptoms and solution. This file helps Grok Build and your team debug faster over time.


Last updated: November 23, 2026