Guides
Understanding unfamiliar code with Grok Build
Every codebase has knowledge locked inside it: how authentication works, why that API is shaped the way it is, and what breaks if you change a function. Grok Build lets you ask these questions directly and get answers grounded in your code. See how Agent searches your codebase for details.
Asking questions about your codebase
Think of Grok Build as a teammate who has read every file in the project. You can ask the same questions you would ask a senior engineer who knows the codebase well.
See the agent's response
src/config/logging.tsLOG_LEVEL env var (default: 'info')logs/dd-trace integrationimport { logger } from '@/utils/logger';
logger.info('message', { userId, action });logs/app.logSee the agent's response
Checkout.tsx)handleSubmit()/api/payments/chargepayments.ts:45)PaymentService.processPayment()PaymentService.ts)OrderRepository.create()OrderRepository.ts)payment_errors table with Stripe error codes.See the agent's response
Thought for 2s
| Method | Purpose | Lines |
|---|---|---|
charge() | Process one-time payment | 89-156 |
refund() | Full or partial refund | 245-312 |
subscribe() | Create subscription | 401-489 |
cancelSubscription() | Cancel with proration | 567-623 |
handleWebhook() | Process Stripe events | 1204-1456 |
_validateCard() - Card validation before charge_calculateProration() - Subscription proration math_retryWithBackoff() - Retry failed API callsAuditLogger, NotificationServiceWhen you want to understand without making changes, use Ask mode. Grok Build explores and explains without editing files. Press Shift+Tab and select Ask to switch modes. This is the right choice when you are building mental models, not shipping code.
Grok Build maintains context within a conversation, so you can start broad and drill into specifics with follow-up questions. If you are looking at a specific file and want to understand it better, reference it directly: "Explain what @src/services/PaymentProcessor.ts does and what calls it."
Visualizing with diagrams
Complex systems are often easier to understand visually. Grok Build can generate Mermaid diagrams to show how components interact, how data flows, or how requests move through your system.
See the agent's response
sequenceDiagram
participant U as User
participant F as Frontend
participant A as Auth API
participant S as Auth Service
participant D as Database
U->>F: Enter credentials
F->>A: POST /auth/login
A->>S: validateCredentials()
S->>D: SELECT user WHERE email
D-->>S: User record
S->>S: bcrypt.compare()
S->>D: INSERT session
S-->>A: JWT + refreshToken
A-->>F: Set cookies
F-->>U: Redirect to dashboard/auth/loginSee the agent's response
flowchart TD
A[Order Created] --> B{Payment OK?}
B -->|Yes| C[Reserve Inventory]
B -->|No| D[Order Failed]
C --> E{Stock Available?}
E -->|Yes| F[Queue for Fulfillment]
E -->|No| G[Backorder]
F --> H[Pick & Pack]
H --> I[Ship]
I --> J[Order Complete]Diagrams render directly in Grok Build and are useful for onboarding, documentation, and debugging. They help you and your team see the bigger picture.
Tracing how code connects
Understanding individual files is one thing. Understanding how data flows through a system requires seeing the whole picture: what calls what, what depends on what, what breaks if you change something.
See the agent's response
rateLimiter - 100 req/min per IP (429 if exceeded)authenticate - Validates JWT, attaches req.uservalidateBody(OrderSchema) - Zod validation of request bodycheckInventory - Verifies all items in stockOrderSchema:items[] - Array of {productId, quantity}shippingAddress - Required objectpaymentMethodId - Stripe payment methodorders table - Main order recordorder_items table - Line itemsinventory table - Decrement countsaudit_log table - Record of creationid, status: 'pending', estimatedDeliverySee the agent's response
Thought for 2s
src/models/Customer.ts - Main model definitionsrc/models/index.ts - Export statementsrc/types/entities.ts - Type definitionCustomerService.ts - Primary service (rename to AccountService)OrderService.ts - References Customer typeBillingService.ts - Customer billing methodsroutes/customers.ts - Rename to accounts.tsroutes/orders.ts - Import reference__tests__/customers/customers table → accountsprisma/schema.prisma - Model renamesrc/config/permissions.ts - Role definitionsFor microservices architectures, open multiple repositories in the same workspace. Grok Build can search across them and trace dependencies across service boundaries. This makes understanding upstream and downstream impacts practical when working across multiple services.
Context beyond the codebase
Sometimes understanding code requires context that is not in your repository: API documentation, framework guides, or information from external systems.
Web search lets Grok Build look up current documentation when it encounters unfamiliar APIs or needs to understand how a library works. This is automatic when the agent needs external information.
MCP integrations connect Grok Build to external tools and data sources. If you need to understand how your code interacts with production data, a connected database MCP can provide that context. If you need to reference design specs, a Figma MCP can pull in relevant frames. Browse the Marketplace for available integrations.
See the agent's response
automatic_payment_methods instead of manually specifying cardmetadata to PaymentIntents - useful for reconciliationPaymentService.ts lines 67-89 for PaymentIntent creationUnderstanding why code is the way it is
Sometimes you inherit code that seems strange and want to know if there is a reason before changing it. Git history provides context about how code evolved and why decisions were made.
See the agent's response
See the agent's response
payment_status: 'not_required'order.test.ts lines 456-489payment_status: 'not_required'This is about understanding intent and history, not only current state. Code that looks wrong often has a reason: a bug it fixed, a constraint it worked around, or a migration it supported. Knowing that history helps you decide whether to preserve the behavior or safely change it.
Onboarding to a new codebase
When you join a team or start working with an unfamiliar project, the first days are often spent hunting through files and asking teammates basic questions. Grok Build compresses this ramp-up time.
See the agent's response
src/
├── api/ # Express routes + middleware
├── services/ # Business logic layer
├── repositories/ # Data access (Prisma)
├── models/ # Type definitions
├── workers/ # Background job processors
├── utils/ # Shared utilities
└── config/ # Environment + app configtsyringe containersrc/index.ts - Main serversrc/workers/index.ts - Job processors__tests__/ directoriesSee the agent's response
GET /api/users/:id (from users.ts)src/api/routes/yourResource.ts):import { Router } from 'express';
import { authenticate } from '@/middleware/auth';
import { YourService } from '@/services/YourService';
const router = Router();
router.get('/:id', authenticate, async (req, res) => {
const result = await YourService.getById(req.params.id);
res.json(result);
});
export default router;src/services/YourService.ts):src/repositories/YourRepository.ts):src/api/index.ts):app.use('/api/yourResource', yourResourceRouter);src/api/routes/__tests__/yourResource.test.ts)users.ts - it's the cleanest example with full CRUD.Get the big picture first, then drill into specifics about common tasks, testing strategies, and configuration.
Capture what you learn in rules files
As you learn things about your codebase, add them to rules files so Grok Build has that context in future sessions and for other team members.
Create a .cursor/rules/codebase-context.mdc file:
Text
# Codebase Context
## Architecture
- This is a monorepo with three main packages: api, web, and shared
- The API uses Express with TypeORM
- The web client is Next.js
## Common patterns
- To add a new API endpoint, see src/api/routes/users.ts as an example
- Database migrations are in src/api/migrations
- Services handle business logic, repositories handle data access
## Gotchas
- The legacy auth system is in src/api/auth/legacy. Don't modify it.
- Some older services use callbacks instead of async/await
- The UserDAO exists for backwards compatibility; prefer UserRepository
This file serves double duty: it helps Grok Build give better answers, and it is documentation that new team members can read directly.
Deep investigations with Cloud Agents
Some questions require extended exploration: understanding a complex subsystem, mapping all the places a pattern is used, or tracing an issue through multiple services. For these, Cloud Agents can run longer investigations while you do other work.
See the agent's response
Thought for 3s
Createdauth-system.md+85
# Authentication System Documentation
## Token Types
- **Access Token**: JWT, 15-minute expiry
- **Refresh Token**: Opaque, 7-day expiry, stored in DBdocs/auth-system.md:AuthService.ts - Core auth logicauthenticate.ts - JWT verification middlewarerefreshToken.ts - Token refresh endpointsessions.ts - Session management/auth/refreshsessions table/auth/refreshCloud Agents run autonomously in isolated environments. You can check their progress, send follow-up questions, or take over at any point. This is useful for thorough investigations that would take too long interactively.
Getting started
-
Open your project. Agent can search and read the workspace as soon as it is open.
-
Start with broad questions. Ask about architecture, main modules, and how things connect. Build a mental model before diving into specifics.
-
Use Ask mode for exploration. When you are trying to understand rather than change, Ask mode keeps Grok Build focused on explaining. Press
Shift+Tabto switch. -
Generate diagrams for complex flows. Visual representations help you understand systems faster. Ask Grok Build to create Mermaid diagrams of architectures and data flows.
-
Capture what you learn. Add useful context to rules files so it persists across sessions and benefits your team.
Last updated: November 23, 2026