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 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
See the agent's response
-
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.
-
Agent explores and hypothesizes: Grok Build reads your codebase and generates multiple hypotheses about what could be wrong.
-
Agent adds instrumentation: Grok Build adds logging statements designed to test its hypotheses, capturing variable states, execution paths, and timing information.
-
You reproduce the bug: Go to your application and trigger the bug while the agent collects runtime logs.
-
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.
-
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.
See the agent's response
Thought for 2s
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.
See the agent's response
Thought for 2s
findUser query in AuthMiddleware.ts doesn't include the profile relation:// Line 45 - missing profile include
const user = await prisma.user.findUnique({ where: { id } });const user = await prisma.user.findUnique({
where: { id },
include: { profile: true }
});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:
See the agent's response
Thought for 2s
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
]);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.
See the agent's response
Thought for 2s
plan_type, but uses 'pro' (lowercase) while the DB stores 'Pro'startDate < endDateplan_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:
See the agent's response
orgContext middleware sets org_id from the JWT, but:/api/auth/refresh-tokenWhen you have access to logs or monitoring dashboards, share what you find:
See the agent's response
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)AuthService.ts:67):// JWT claims set at login, not refreshed on org change
const token = jwt.sign({ userId, org_id: user.org_id }, secret);org_changed_at timestamp, validate JWT against itGrok 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:
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.
See the agent's response
Thought for 1s
EditedUserService.test.ts+3-1
const mockUser = { id: '1', email: '[email protected]' };
const mockUser = {
id: '1', email: '[email protected]',
profile: { name: 'Test', avatar: null }
};profile relation that getProfile() expects. Added the profile object to the mock user.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:
See the agent's response
Thought for 1s
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' });
});
});Thought for 1s
CreatedNotificationService.ts+4
async function sendWelcomeEmail(user: User) {
if (!user.email) {
return { skipped: true, reason: 'no_email' };
}sendWelcomeEmail when email is null{ skipped: true, reason: 'no_email' } instead of throwingA 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.
See the agent's response
Thought for 1s
Uncaught TypeError: Cannot read property 'addEventListener' of null
at CheckoutForm.js:45DOMContentLoaded wrapper or defer attribute on script tag.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:
See the agent's response
Thought for 2s
| Request | Time | Status |
|---|---|---|
| /api/orders | 3,450ms | 200 |
| /api/user | 89ms | 200 |
| /api/notifications | 156ms | 200 |
/api/orders takes 3.4 secondsuser_id column.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.
See the agent's response
Thought for 3s
await checkout();
expect(cart.items).toHaveLength(0); // Fails intermittentlycheckout() function clears the cart asynchronously via a background job, but the test expects it to be cleared immediately.await checkout();
await waitFor(() => {
expect(cart.items).toHaveLength(0);
}, { timeout: 1000 });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.
See the agent's response
InventoryService - stock checksPricingService - tax and discount calculationPaymentService - payment processingNotificationService - emails and webhooksAuditLogger - compliance loggingCheckoutController.submit() - web checkoutAPIController.createOrder() - API ordersSubscriptionWorker.renew() - subscription renewalsrollback() 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.
See the agent's response
abc123 (March 15)status: 'pending' SELECT COUNT(*) FROM users
WHERE id NOT IN (SELECT user_id FROM profiles);getProfile() assumes profile always existsgetProfile()user.settings - same assumptionuser.subscription - has null checkAfter 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:
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