#### Guides

# Debugging with Grok Build

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](/build/agents-window/agent/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](/build/agents-window/agent/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

**Agent 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 test@example.com and adding 3 items to the cart.

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.

**Agent 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.

## 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.

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.

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.

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: user@company.com, Org ID: org\_789. Check the team membership logic, permission checks, and any caching that might delay visibility.

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.

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:

**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.

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.

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

## Debugging frontend issues

Grok Build's [browser tool](/build/agents-window/agent/tools/browser) 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.

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.

## 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?

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.

**Agent 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?

Use [Ask mode](/build/agents-window/agent/plan-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.

**Agent 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?

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:

**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.
