Guides

Understanding unfamiliar code with Grok Build

View as Markdown

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.

Ask mode example: Understanding infrastructure
How does logging work in this project? Where are logs configured and where do they go?
See the agent's response
Searched codebase logging configuration and infrastructure
Read src/utils/logger.ts
Read src/config/logging.ts
Logging Infrastructure
Configuration: src/config/logging.ts
•Uses Winston with multiple transports
•Log level controlled by LOG_LEVEL env var (default: 'info')
Transports
1.Console - JSON format in production, pretty-print in dev
2.File - Rotated daily, kept for 14 days in logs/
3.Datadog - Production only, via dd-trace integration
Usage Pattern
import { logger } from '@/utils/logger';
logger.info('message', { userId, action });
Where Logs Go
•Development: Console + logs/app.log
•Production: Datadog (searchable at app.datadoghq.com)
Ask mode example: Tracing a flow
What happens when a user submits a payment? Trace the flow from the frontend to the database.
See the agent's response
Searched codebase payment submission flow
Read src/pages/Checkout.tsx
Read src/api/routes/payments.ts
Read src/services/PaymentService.ts
Read src/repositories/OrderRepository.ts
Payment Flow: Frontend → Database
1.Frontend (Checkout.tsx)
•User clicks "Pay Now" → handleSubmit()
•Validates form, creates Stripe PaymentMethod
•POST to /api/payments/charge
2.API Route (payments.ts:45)
•Validates JWT, extracts userId
•Calls PaymentService.processPayment()
3.Service Layer (PaymentService.ts)
•Creates Stripe PaymentIntent
•Handles 3D Secure if required
•On success: calls OrderRepository.create()
4.Database (OrderRepository.ts)
•Transaction: creates Order + OrderItems
•Updates inventory counts
•Returns order confirmation
Error Handling: Each layer catches and wraps errors. Failed payments logged to payment_errors table with Stripe error codes.
Ask mode example: Summarizing large files
The PaymentGateway class has 2000 lines. Give me a summary of its responsibilities and main methods.
See the agent's response
Read src/services/PaymentGateway.ts
Thought for 2s
This is a large class - 2000+ lines. I'll identify the main sections and public methods to give a useful overview.
PaymentGateway Class Summary (2,147 lines)
Core Responsibilities
1.Payment processing (Stripe, PayPal, Apple Pay)
2.Refund handling
3.Subscription management
4.Webhook processing
Main Public Methods
MethodPurposeLines
charge()Process one-time payment89-156
refund()Full or partial refund245-312
subscribe()Create subscription401-489
cancelSubscription()Cancel with proration567-623
handleWebhook()Process Stripe events1204-1456
Internal Helpers (private):
•_validateCard() - Card validation before charge
•_calculateProration() - Subscription proration math
•_retryWithBackoff() - Retry failed API calls
Dependencies: Stripe SDK, PayPal SDK, our AuditLogger, NotificationService
Note: The webhook handler (250+ lines) could probably be extracted to its own class.

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

Agent example: Generate sequence diagram
Create a sequence diagram showing what happens when a user logs in. Include the frontend, API, auth service, and database.
See the agent's response
Searched codebase login authentication flow
Read src/pages/Login.tsx
Read src/api/routes/auth.ts
Read src/services/AuthService.ts
Here's how the login flow works:
Mermaid diagram source
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
Summary:
1.User enters credentials in Login form
2.Frontend validates locally, then POSTs to /auth/login
3.Auth API calls AuthService.validateCredentials()
4.AuthService queries database for user by email
5.Bcrypt compares password hash
6.On success: creates session, generates JWT (15min) + refresh token (7d)
7.Tokens set as HTTP-only cookies
8.User redirected to dashboard
Agent example: Generate flowchart
Draw a flowchart of the order processing pipeline, from order creation to fulfillment.
See the agent's response
Searched codebase order processing pipeline
Read src/services/OrderService.ts
Read src/workers/FulfillmentWorker.ts
Here's the order processing pipeline:
Mermaid diagram source
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]
Stages:
1.Order Created - Initial state after checkout
2.Payment Verification - Stripe charge confirmation
3.Inventory Reserve - Soft lock on items
4.Fulfillment Queue - Async job via Redis queue
5.Pick & Pack - Warehouse processing
6.Ship - Carrier handoff + tracking
7.Complete - Final state
Edge Cases:
•Payment failure → Order Failed state
•Out of stock → Backorder state (customer notified)

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.

Ask mode example: Request tracing
Trace a request from the /api/orders endpoint to the database. What middleware does it pass through? What validations happen along the way?
See the agent's response
Searched codebase /api/orders endpoint middleware chain
Read src/api/routes/orders.ts
Read src/middleware/auth.ts
Read src/middleware/validation.ts
Read src/middleware/rateLimit.ts
Request Trace: POST /api/orders
Middleware Chain (in order):
1.rateLimiter - 100 req/min per IP (429 if exceeded)
2.authenticate - Validates JWT, attaches req.user
3.validateBody(OrderSchema) - Zod validation of request body
4.checkInventory - Verifies all items in stock
5.Route Handler - Creates order
Validations
•JWT must be valid and not expired
•Body must match OrderSchema:
•items[] - Array of {productId, quantity}
•shippingAddress - Required object
•paymentMethodId - Stripe payment method
•Each item quantity must be ≤ available inventory
Database Writes
1.orders table - Main order record
2.order_items table - Line items
3.inventory table - Decrement counts
4.audit_log table - Record of creation
Response: Order object with id, status: 'pending', estimatedDelivery
Ask mode example: Impact analysis
I want to rename the Customer class to Account. Find everywhere this would affect and list the files that would need to change.
See the agent's response
Searched codebase Customer class usages and references
Grepped Customer
Thought for 2s
Found 47 files referencing Customer. Let me categorize them by type of reference.
Impact Analysis: Renaming Customer → Account
Files Affected: 47 total
Models (3 files)
•src/models/Customer.ts - Main model definition
•src/models/index.ts - Export statement
•src/types/entities.ts - Type definition
Services (8 files)
•CustomerService.ts - Primary service (rename to AccountService)
•OrderService.ts - References Customer type
•BillingService.ts - Customer billing methods
•... 5 more
API Routes (6 files)
•routes/customers.ts - Rename to accounts.ts
•routes/orders.ts - Import reference
•... 4 more
Tests (18 files)
•All files in __tests__/customers/
•Various integration tests
Database (2 files)
•Migration needed: customers table → accounts
•prisma/schema.prisma - Model rename
Config (1 file)
•src/config/permissions.ts - Role definitions
Recommendation: Create a migration plan. Start with types/models, then services, then routes. Update database last with a proper migration script.

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

Ask mode example: External documentation
Look up the Web Stripe API documentation for payment intents. How does our src/services/PaymentService.ts implementation compare to their recommended patterns?
See the agent's response
Searched Stripe payment intents best practices
Read src/services/PaymentService.ts
Comparison: Our Implementation vs Stripe Best Practices
We Follow
•Using PaymentIntents (not legacy Charges API)
•Server-side confirmation for security
•Idempotency keys for retry safety
•Webhook verification with signing secret
Could Improve
1.3D Secure: We handle it, but Stripe now recommends automatic_payment_methods instead of manually specifying card
2.Error Handling: We catch generic errors; Stripe recommends handling specific error codes (card_declined, expired_card, etc.)
3.Metadata: We don't attach metadata to PaymentIntents - useful for reconciliation
Missing
1.Radar Rules: Not using Stripe Radar for fraud detection
2.Customer Portal: Could use Stripe's hosted billing portal instead of custom UI
Code Reference: PaymentService.ts lines 67-89 for PaymentIntent creation

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

Ask mode example: Understanding evolution
Why is the PaymentGateway API shaped this way? Look through git history and summarize how it evolved.
See the agent's response
Ran git log --oneline src/services/PaymentGateway.ts | head -20
Ran git show abc123 --stat
PaymentGateway Evolution
Timeline
•2022-03: Initial implementation (single payment provider)
•2022-06: Added PayPal support (commit: abc123)
•"Add PayPal as alternative payment method per enterprise request"
•2022-09: Subscription billing added
•2023-01: Major refactor for PCI compliance
•"Remove card data from logs, add tokenization"
•2023-06: Apple Pay integration
•2023-11: Webhook handler rewrite
•"Fix race condition in webhook processing (PROD-4521)"
Key Insights
1.The complex multi-provider structure came from incremental additions, not upfront design
2.The large webhook handler (line 1204-1456) was rewritten after a production incident
3.Some "weird" code paths exist for backwards compatibility with PayPal v1 API
Original Authors: @sarah (payments), @mike (subscriptions)
Ask mode example: Finding intent
This function has a weird edge case handler. Check git blame to find when it was added and look at the commit message or related commits for context.
See the agent's response
Ran git blame -L 234,250 src/services/OrderService.ts
Ran git show def456
Context for Edge Case Handler (lines 234-250)
Commit: def456 (2023-03-15)
Author: @alex
Message: "Handle edge case where order total is $0 after discounts"
Related Issue: JIRA-2341
"Customer applied 100% discount code but checkout still tried to charge card"
Why It Exists
When order total equals $0 after discounts:
1.Skip Stripe PaymentIntent creation entirely
2.Still create order record
3.Mark as payment_status: 'not_required'
4.Send confirmation email (different template)
Safe to Change?
•The $0 order flow is tested in order.test.ts lines 456-489
•3 other places check for payment_status: 'not_required'
•Changing this would need to update email templates too
Verdict: Keep the logic, but the implementation could be cleaner.

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.

Ask mode example: Architecture overview
Give me an overview of this codebase. What are the main modules and how do they interact?
See the agent's response
Listed src/
Read package.json
Searched codebase main application architecture
Codebase Overview
Tech Stack
•Runtime: Node.js 18 + TypeScript
•Framework: Express.js
•Database: PostgreSQL (via Prisma ORM)
•Cache: Redis
•Queue: BullMQ for background jobs
Main Modules
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 config
Key Patterns
1.Layered Architecture: Routes → Services → Repositories
2.Dependency Injection: Via tsyringe container
3.Repository Pattern: All DB access through repositories
4.Event-Driven: Domain events trigger side effects
Entry Points
•src/index.ts - Main server
•src/workers/index.ts - Job processors
Tests: Jest, located in __tests__/ directories
Ask mode example: Learning patterns
How do I add a new API endpoint? Show me an example of an existing one I can follow as a pattern.
See the agent's response
Read src/api/routes/users.ts
Read src/services/UserService.ts
Read src/repositories/UserRepository.ts
How to Add a New API Endpoint
Example: GET /api/users/:id (from users.ts)
1. Define Route (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;
2. Create Service (src/services/YourService.ts):
•Business logic lives here
•Inject repository via constructor
•Handle validation and business rules
3. Create Repository (src/repositories/YourRepository.ts):
•Data access only
•Use Prisma client
•Return typed entities
4. Register Route (src/api/index.ts):
app.use('/api/yourResource', yourResourceRouter);
5. Add Tests (src/api/routes/__tests__/yourResource.test.ts)
Pattern to Follow: Look at 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:

Rules example: Codebase Context

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.

Agent example: Extended investigation
Map out our entire authentication system. Document every auth-related file, how they connect, what tokens we use, how sessions are managed, and any security concerns you identify.
See the agent's response
Searched codebase authentication system architecture
Found files src/**/auth/**
Read src/services/AuthService.ts
Read src/middleware/authenticate.ts
Read src/utils/jwt.ts
Thought for 3s
Found 12 auth-related files. Let me document the token flow, session management, and identify any security concerns.
Createdauth-system.md+85
# Authentication System Documentation

## Token Types
- **Access Token**: JWT, 15-minute expiry
- **Refresh Token**: Opaque, 7-day expiry, stored in DB
Authentication System Documentation
Created comprehensive doc at docs/auth-system.md:
Auth-Related Files (12 total)
•AuthService.ts - Core auth logic
•authenticate.ts - JWT verification middleware
•refreshToken.ts - Token refresh endpoint
•sessions.ts - Session management
•... 8 more
Token Flow
1.Login → Access JWT (15min) + Refresh token (7d)
2.Access token in Authorization header
3.Refresh token in HTTP-only cookie
4.Token refresh at /auth/refresh
Session Management
•Sessions stored in sessions table
•Redis cache for active session lookup
•Logout invalidates all devices option available
Security Concerns Identified
1.Refresh tokens not rotated on use (should be)
2.No rate limiting on /auth/refresh
3.Passwords hashed with bcrypt (cost 12)
4.JWT signed with RS256

Cloud 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

  1. Open your project. Agent can search and read the workspace as soon as it is open.

  2. Start with broad questions. Ask about architecture, main modules, and how things connect. Build a mental model before diving into specifics.

  3. Use Ask mode for exploration. When you are trying to understand rather than change, Ask mode keeps Grok Build focused on explaining. Press Shift+Tab to switch.

  4. Generate diagrams for complex flows. Visual representations help you understand systems faster. Ask Grok Build to create Mermaid diagrams of architectures and data flows.

  5. Capture what you learn. Add useful context to rules files so it persists across sessions and benefits your team.


Last updated: November 23, 2026