Guides

Modernizing legacy code with Grok Build

View as Markdown

Large-scale code migrations are tedious. Framework upgrades, language conversions, and refactoring projects can take months of mechanical find-and-replace work. Grok Build handles these transformations across hundreds of files while you focus on the decisions that require developer judgment.

Framework and library upgrades

When you're a few versions behind on Angular, React, or any other framework, catching up means touching dozens or hundreds of files. Each version has breaking changes to navigate, and the work compounds when you've skipped multiple releases.

Grok Build can search your codebase for the patterns you're migrating from and to, run builds and tests in the terminal, and search the web for current migration guides.

How to approach it

Start with Plan Mode (Shift+Tab, then select Plan). Describe your migration and let Grok Build research your codebase:

Plan mode example: Framework upgrade
Upgrade from Angular 12 to Angular 16. Identify all breaking changes we need to address.
See the agent's response
Read package.json
Searched Angular 12 to 16 migration guide
Searched codebase Angular components and modules
Found 47 components and 23 files with RxJS operators. A few questions before I create the migration plan:
A) Migration approach - How should we handle the upgrade?
•a) Incremental (12→13→14→15→16, safest)
•b) Direct jump to 16 (faster, more risk)
•c) Parallel branch (new app, migrate features)
Default: Incremental
B) Standalone components - How to handle NgModules?
•a) Convert all to standalone (recommended for new projects)
•b) Keep NgModules for lazy routes only
•c) Minimal changes, keep existing structure
Default: Convert all to standalone
C) Testing strategy - How to verify each step?
•a) Run full test suite after each version bump
•b) Manual smoke test, fix issues as found
•c) Create migration-specific test checklist
Default: Full test suite after each bump
Plan mode example: API migration
Find everywhere we use the old React context API and plan migration to the new one.
See the agent's response
Searched codebase React context API usage
Grepped React.createContext|contextType
Found 15 context usages: 8 class components need migration, 7 already use hooks. Questions before I proceed:
A) Migration scope - Which components to convert?
•a) All 8 class components at once
•b) Start with high-traffic components (UserProfile, CartWidget)
•c) Only the ones blocking other work
Default: All 8 at once (they're isolated)
B) Component conversion - How to handle class → functional?
•a) Full rewrite to functional components
•b) Keep classes, just update context pattern
•c) Rewrite and add hooks for state management
Default: Full rewrite to functional
C) Testing approach - How to verify behavior preserved?
•a) Snapshot tests before/after
•b) Manual testing with existing E2E suite
•c) Add unit tests for each converted component
Default: Snapshot tests before/after
Agent example: Dependency audit
Audit our codebase for deprecated webpack plugins before upgrading to v5.
See the agent's response
Read package.json
Ran npm audit --json
Searched webpack 5 deprecated plugins list
Webpack 5 Compatibility Audit
Deprecated/Removed Plugins (4 found):
1.uglifyjs-webpack-plugin [removed]
•Removed in Webpack 5
•Replace with: built-in TerserPlugin
•Files: webpack.prod.js
2.optimize-css-assets-webpack-plugin [removed]
•Removed in Webpack 5
•Replace with: css-minimizer-webpack-plugin
•Files: webpack.prod.js
3.file-loader [deprecated]
•Deprecated (still works)
•Replace with: Asset Modules (type: 'asset')
•Files: webpack.common.js (3 rules)
4.url-loader [deprecated]
•Deprecated (still works)
•Replace with: Asset Modules (type: 'asset')
•Files: webpack.common.js (2 rules)
Other Issues:
•node-sass → should migrate to sass (Dart Sass)
•webpack-dev-server v3 → needs v4 for Webpack 5
Security Vulnerabilities: 3 moderate, 1 high
•High: nth-check via css-select (update postcss-svgo)

Grok Build searches your code, asks clarifying questions, and creates a structured plan that you can review and edit before executing. Save plans to .cursor/plans/ to share with your team or reference later.

Execute in phases so that if something breaks, you know exactly which change caused it.

Define your target patterns with rules

Migrations go more smoothly when Grok Build knows your conventions. Create a .cursor/rules/migration.mdc file that captures your decisions:

Rules example: Angular 16 Migration

Text

# Angular 16 Migration

When updating Angular code:
- Use standalone components, not NgModules
- Use the new inject() function instead of constructor injection
- Use signals for reactive state where possible
- Keep existing naming conventions for components and services

When updating RxJS:
- Import operators from 'rxjs' not 'rxjs/operators'
- Replace deprecated operators (switchMap stays, but pluck becomes map)

With rules files in place, Grok Build follows your conventions consistently across every file it touches. This consistency matters most when you're changing hundreds of files.

Large-scale file transformations

Sometimes you need to make the same change across hundreds of files: changing import paths after a folder restructure, converting file extensions, or updating a deprecated API call everywhere it appears.

These changes are repetitive but not trivial. Each file may have slight variations in how the pattern appears, and a missed file can cause bugs that surface much later.

How Grok Build handles bulk changes

When you ask Grok Build to make changes across many files, it uses several tools together:

  • Codebase search to find affected files by exact text or related usage
  • File editing to apply changes while preserving surrounding code and formatting
  • Terminal access to run your build and test suite after changes, catching errors immediately
  • Web search to look up current documentation when it encounters unfamiliar APIs or edge cases

Together, these let Grok Build find a deprecated call, look up how to convert it, make the change, and run your tests.

Bulk file changes

Consider changing file extensions across a project:

Agent example: Bulk file extension change
Go through all files in src/components/. For any file that contains React components, change the extension from .js to .jsx. Update any imports that reference these files.
See the agent's response
Found files src/components/**/*.js
Read src/components/Button.js
Thought for 2s
Found 34 .js files in components. I'll check each for JSX - if it contains JSX syntax, rename to .jsx and update imports.
Renamed Button.js → Button.jsx
Searched codebase imports referencing Button.js
EditedHome.tsx+1-1
import { Button } from '../components/Button.js';
import { Button } from '../components/Button.jsx';
Bulk Extension Change Complete
Files Renamed: 28 of 34
•28 files contained JSX → renamed to .jsx
•6 files were pure JS utilities → kept as .js
Imports Updated: 47 files
•Updated all import statements referencing renamed files
•Checked both relative and absolute imports
Files Changed:
src/components/Button.js → Button.jsx
src/components/Card.js → Card.jsx
src/components/Modal.js → Modal.jsx
... (25 more)
Not Renamed (no JSX):
src/components/utils/formatters.js
src/components/utils/validators.js
src/components/constants.js
... (3 more)
Build passing. All tests passing.

The key is being specific about scope and consequences:

  • Which files to look at
  • What condition triggers a change
  • What the change should be
  • What else needs updating as a result

Bulk API updates

When a library deprecates an API, you need to update every call site:

Agent example: API replacement
Find all uses of the deprecated moment() function. Replace them with dayjs() equivalents. The APIs are similar but not identical, so check each usage and convert it correctly.
See the agent's response
Searched codebase moment() function usages
Grepped moment\(
Searched moment.js to dayjs migration guide
Thought for 2s
Found 67 usages of moment() across 23 files. Most are simple formatting, but some use moment-specific methods. I'll convert each based on context.
Editeddates.ts+15-12
import moment from 'moment';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);

return moment(date).format('MMM D, YYYY');
return dayjs(date).format('MMM D, YYYY');
Ran npm test
Moment → Day.js Migration Complete
Files Updated: 23
Conversions Made:
Moment APIDay.js EquivalentCount
moment()dayjs()45
.format().format()38
.fromNow().fromNow() (plugin)12
.diff().diff()8
.add()/.subtract()Same API15
.isValid().isValid()4
Plugins Added:
•relativeTime - for .fromNow() support
•customParseFormat - for parsing specific formats
Bundle Impact:
•Before: moment.js = 67KB gzipped
•After: dayjs + plugins = 6KB gzipped
•Savings: 61KB
All 156 tests passing. Build successful.

Grok Build finds each usage, understands the context, and applies the appropriate conversion rather than doing a blind find-and-replace.

Language and platform migrations

Moving from one stack to another is one of the most time-consuming projects a team can take on. JSP to React. .NET Framework to .NET Core. PHP to Node. These migrations traditionally take months because every file needs developer attention.

Converting between frameworks

For a JSP to React migration, you might use a prompt like:

Agent example: Framework conversion
Convert this JSP file to a React functional component. Preserve all the business logic and user interactions. Use our existing component library for UI elements (see src/components/ui/ for examples).
See the agent's response
Read webapp/WEB-INF/views/checkout.jsp
Searched codebase existing React component patterns
Read src/components/ui/Button.tsx
Thought for 3s
The JSP has form handling, JSTL conditionals, and EL expressions for cart data. I'll convert to a React component with hooks for state management.
CreatedCheckout.tsx+145
import { useState } from 'react';
import { useCart } from '@/hooks/useCart';
import { Button, Input, Card } from '@/components/ui';

export function Checkout() {
  const { items, total } = useCart();
  const [shipping, setShipping] = useState({});

  // Converted from JSP form handling
  const handleSubmit = async (e) => {
Ran npm test Checkout
JSP → React Conversion Complete
Source: webapp/WEB-INF/views/checkout.jsp (287 lines)
Output: src/pages/Checkout.tsx (145 lines)
Conversions Made:
JSP PatternReact Equivalent
<c:forEach items="${cart.items}">items.map()
<c:if test="${not empty error}">{error && <Alert>}
${cart.total}{formatCurrency(total)}
<form:input path="email"><Input value={email} onChange={...}>
<spring:message code="...">t('checkout.title') (i18n)
Business Logic Preserved:
•Cart validation before submit
•Shipping cost calculation
•Promo code handling
•Error message display
Using Existing Components:
•Button from @/components/ui
•Input from @/components/ui
•Card from @/components/ui
Component renders correctly. Form validation working.

When Grok Build processes this, it reads the JSP file to understand its structure and logic, references your existing React components to match your patterns, and generates a new component that preserves the original behavior. It can then update any files that referenced the old JSP template and run your test suite to verify the conversion.

Mainframe and COBOL migrations

Enterprise teams often face the challenge of modernizing mainframe systems written in COBOL. These migrations are particularly complex because the code may be decades old, documentation is often incomplete, and the developers who wrote it may no longer be available.

Ask mode example: Understand COBOL business logic
Analyze this COBOL program and explain its business logic. What data structures does it use? What are the main processing steps? Create documentation that would help someone unfamiliar with COBOL understand what this code does.
See the agent's response
Read cobol/ACCTUPDT.cbl
Thought for 3s
This COBOL program processes account updates. Let me trace through the PROCEDURE DIVISION to understand the business logic.
COBOL Program Analysis: ACCTUPDT.cbl
Purpose: Process customer account updates from batch input file
Data Structures (COPYBOOKS):
•ACCT-RECORD - 150-byte fixed-width account record
•TRANS-RECORD - 80-byte transaction input
•ERROR-RECORD - Error output format
Main Processing Steps:
1.INIT-PROCESS (lines 100-120)
•Open input/output files
•Initialize counters and accumulators
2.PROCESS-TRANSACTIONS (lines 150-300)
•Read transaction record
•Validate account number (check digit algorithm)
•Lookup account in master file
•Apply update based on TRANS-TYPE:
•'A' = Address change
•'B' = Balance adjustment
•'S' = Status change
3.VALIDATE-ACCOUNT (lines 350-420)
•Check digit validation (modulus 10)
•Account status must be 'A' (Active)
•Balance must not go negative
4.ERROR-HANDLING (lines 500-580)
•Write to error file with reason code
•Increment error counter
•Continue processing (non-fatal)
Key Business Rules:
•Account numbers are 10 digits with check digit
•Negative balances not allowed (rejects transaction)
•Status codes: A=Active, S=Suspended, C=Closed
•Closed accounts cannot be updated

Start by having Grok Build document the existing system. COBOL code is often self-documenting in structure but opaque in purpose. Grok Build can read the code and explain the business rules it implements, the data it processes, and the edge cases it handles.

Agent example: Convert COBOL data structures
Convert this COBOL copybook to TypeScript interfaces. Preserve the field names and add comments explaining each field's purpose based on its usage in the codebase.
See the agent's response
Read cobol/copybooks/ACCT-REC.cpy
Thought for 2s
This copybook defines an account record with PIC clauses. I'll convert each field to TypeScript types.
CreatedAccount.ts+42
/**
 * Account record - converted from COBOL ACCT-REC.cpy
 * Original: 150-byte fixed-width record
 */
export interface Account {
  /** PIC 9(10) - Account number with check digit */
  accountNumber: string;
  
  /** PIC X(30) - Customer name */
  customerName: string;
  
  /** PIC S9(9)V99 COMP-3 - Balance in cents */
  balance: Decimal;
  
  /** PIC X(1) - A=Active, S=Suspended, C=Closed */
  status: 'A' | 'S' | 'C';
}
COBOL Copybook → TypeScript Conversion
Source: cobol/copybooks/ACCT-REC.cpy
Output: src/types/Account.ts
Field Mappings:
COBOL DefinitionTypeScriptNotes
PIC 9(10)stringPreserve leading zeros
PIC X(30)stringRight-padded in COBOL
PIC S9(9)V99 COMP-3DecimalUse decimal.js for precision
PIC X(1)`'A' \'S' \'C'`Union type for status
PIC 9(8) (date)stringYYYYMMDD format
Preserved from Original:
•Field names (converted to camelCase)
•Comments explaining each field's purpose
•Business constraints (status codes)
•Precision for monetary values
Added decimal.js Import:
import { Decimal } from 'decimal.js';
This type will be used by the converted account processing service.

Data structure conversion is often the foundation: convert COBOL copybooks, which define record layouts, to modern type definitions.

Agent example: Convert COBOL to modern service
This COBOL program processes customer account updates. Convert it to a Node.js service that implements the same business logic. Preserve all validation rules and error handling. Add tests that verify the new implementation matches the COBOL behavior.
See the agent's response
Read cobol/ACCTUPDT.cbl
Read src/types/Account.ts
Searched codebase existing service patterns
Thought for 3s
I'll convert the COBOL business logic to TypeScript, preserving all validation rules and error handling. The account validation with check digit is critical.
CreatedAccountUpdateService.ts+187
import { Account } from '@/types/Account';
import { Decimal } from 'decimal.js';

export class AccountUpdateService {
  /**
   * Validate account number using modulus 10 check digit
   * Converted from COBOL VALIDATE-ACCOUNT paragraph
   */
  validateAccountNumber(accountNum: string): boolean {
    // Check digit algorithm preserved from COBOL
  }
CreatedAccountUpdateService.test.ts+95
describe('AccountUpdateService', () => {
  describe('validateAccountNumber', () => {
    it('accepts valid account numbers', () => {
      // Test cases from COBOL test data
    });
  });
});
Ran npm test AccountUpdateService
COBOL → Node.js Service Conversion
Source: cobol/ACCTUPDT.cbl (580 lines)
Output: src/services/AccountUpdateService.ts (187 lines)
Business Logic Preserved:
Account Validation
•Modulus 10 check digit algorithm
•Status validation (Active accounts only)
•Balance validation (no negative)
Transaction Processing
•Address updates ('A' type)
•Balance adjustments ('B' type)
•Status changes ('S' type)
Error Handling
•Invalid account → reject with code 'E01'
•Closed account → reject with code 'E02'
•Negative balance → reject with code 'E03'
Test Coverage:
•23 test cases covering all transaction types
•Edge cases from original COBOL test data
•Comparison tests against COBOL output
All tests passing. Output matches COBOL reference implementation.

For the actual code conversion, work module by module rather than attempting the entire system at once. Each converted module can be tested against the original COBOL output to verify correctness. Create a rules file documenting COBOL-specific patterns and their modern equivalents:

Rules example: COBOL Migration Rules

Text

# COBOL Migration Rules

## Data type mappings
- PIC 9(n) -> number (or BigInt for n > 15)
- PIC X(n) -> string
- PIC S9(n)V9(m) COMP-3 -> Decimal (use decimal.js library)

## Common patterns
- PERFORM VARYING -> for loop
- EVALUATE TRUE -> switch statement or if-else chain
- 88-level conditions -> enum or boolean properties

## Business rules to preserve
- Account numbers are always validated with check digit (see validateAccountNumber)
- Date fields use YYYYMMDD format internally, convert to ISO 8601 for APIs
- Negative amounts use trailing sign convention in files

The code may look dated, but it encodes decades of domain knowledge and edge case handling that must survive the migration.

Why this works

Grok Build can find your existing patterns, your target patterns, and similar migrations elsewhere in your code.

When you convert the first few files and commit them, Grok Build learns from those examples. Subsequent conversions become more accurate because it has reference implementations to follow. The first 10% of a migration often takes longer than the remaining 90%.

Setting up context for migrations

For large migrations, a rules file helps Grok Build make consistent decisions across hundreds of files. Without explicit guidance, Grok Build might handle the same edge case differently in different files. A rules file ensures it follows your team's decisions everywhere.

Rules example: .NET Core Migration

Text

# .NET Core Migration Rules

## Patterns to follow
- Use dependency injection via IServiceCollection
- Replace HttpContext.Current with IHttpContextAccessor
- Use async/await throughout, no .Result or .Wait()
- Configuration via IOptions<T> pattern

## Files to reference
- src/Services/UserService.cs (already migrated, good example)
- src/Controllers/BaseController.cs (shows new controller pattern)

## Common gotchas
- Session state works differently. See SessionHelper.cs for our approach
- Our custom auth filter needs the new middleware pattern

The "files to reference" section is particularly useful: when Grok Build encounters an ambiguous case, it looks at these examples to see how you've handled similar situations. The "common gotchas" section prevents Grok Build from making mistakes you've already figured out how to avoid.

Refactoring at scale

Beyond version upgrades and language migrations, Grok Build's Agent mode handles structural refactoring across large codebases.

Extracting shared code

When you have duplicated logic scattered across your codebase, you can ask Grok Build to find it before proposing changes:

Agent example: Extract shared code
Look at how we handle API error responses across our codebase. Find all the places where we're doing similar error handling and extract a shared utility. Show me the patterns you find before making any changes.
See the agent's response
Searched codebase API error response patterns
Grepped res\.status\(\d+\)\.json
Thought for 2s
Found similar error handling in 14 route files. Most follow the same pattern but with slight variations. I'll identify the common structure.
Error Handling Pattern Analysis
Found 14 files with similar patterns:
Pattern 1: Direct response (8 files)
res.status(400).json({ error: 'Validation failed', details: errors });
res.status(404).json({ error: 'User not found' });
res.status(500).json({ error: 'Internal server error' });
Pattern 2: With logging (4 files)
logger.error('Payment failed', { error, userId });
res.status(400).json({ error: error.message });
Pattern 3: Inconsistent (2 files)
res.status(400).send({ message: 'Error' }); // Different key
res.status(400).json({ err: error }); // Abbreviated
Proposed Shared Utility:
// src/utils/apiResponse.ts
export const ApiError = {
  badRequest: (res, message, details?) => 
    res.status(400).json({ error: message, details }),
  notFound: (res, resource) =>
    res.status(404).json({ error: `${resource} not found` }),
  internal: (res, error) => {
    logger.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};
Shall I create this utility and update all 14 files?

Grok Build searches your code, identifies the duplicated patterns, and proposes a shared abstraction that you can review before executing the extraction.

Applying patterns retroactively

You established a pattern six months ago, but older code still uses the old approach:

Agent example: Apply pattern retroactively
Our newer services use the Result pattern for error handling. Find services that still throw exceptions for business logic errors and convert them to use Result instead. Start with the UserService.
See the agent's response
Searched codebase services throwing exceptions for business logic
Read src/services/UserService.ts
Read src/utils/Result.ts
Thought for 2s
UserService has 8 methods that throw exceptions. I'll convert each to return Result<T, E> instead.
EditedUserService.ts+25-18
import { Result, Ok, Err } from '@/utils/Result';

  async getUser(id: string): Promise<User> {
    const user = await this.repo.findById(id);
    if (!user) throw new NotFoundError('User not found');
    return user;
  }
  async getUser(id: string): Promise<Result<User, NotFoundError>> {
    const user = await this.repo.findById(id);
    if (!user) return Err(new NotFoundError('User not found'));
    return Ok(user);
  }
Ran npm test UserService
Result Pattern Migration: UserService
Methods Converted: 8
MethodBeforeAfter
getUserthrows NotFoundErrorResult<User, NotFoundError>
createUserthrows ValidationErrorResult<User, ValidationError>
updateUserthrows NotFoundError`Result<User, NotFoundError \ValidationError>`
deleteUserthrows NotFoundErrorResult<void, NotFoundError>
verifyEmailthrows InvalidTokenErrorResult<void, InvalidTokenError>
... 3 more
Callers Updated: 12 files
•Routes now use result.match() or result.unwrapOr()
•Controllers handle both Ok and Err cases explicitly
Benefits:
•Explicit error handling at compile time
•No uncaught exceptions in business logic
•Errors are values, not control flow
All 34 tests passing. TypeScript compilation successful.

This kind of retroactive cleanup becomes practical when the mechanical work of finding and changing files takes minutes rather than hours.

Understanding before changing

For legacy code, understanding often matters more than changing. Use Ask mode to explore without making changes:

Ask mode example: Understand before refactoring
I need to refactor the PaymentProcessor class. Before we start, explain how it works, what its dependencies are, and what would break if we changed it.
See the agent's response
Read src/services/PaymentProcessor.ts
Searched codebase PaymentProcessor dependencies and callers
Grepped PaymentProcessor
PaymentProcessor Analysis
What It Does:
•Handles all payment operations (charge, refund, subscription)
•Integrates with Stripe, PayPal, Apple Pay
•Manages retry logic and idempotency
Dependencies (imports):
•StripeClient - Stripe API wrapper
•PayPalClient - PayPal API wrapper
•AuditLogger - Logs all payment events
•NotificationService - Sends receipts/alerts
•MetricsCollector - Payment metrics
Who Calls It (15 files):
•OrderService.ts - checkout flow
•SubscriptionService.ts - recurring billing
•RefundController.ts - manual refunds
•WebhookHandler.ts - payment events
•... 11 more
What Would Break:
High Risk:
•Webhook signature verification (line 234)
•Idempotency key generation (line 89)
•Retry logic timing (lines 156-180)
Medium Risk:
•PayPal legacy API compat (lines 300-350)
•Currency conversion (line 412)
Recommendation:
Write tests for webhook handling and idempotency before refactoring. These are the most fragile parts with production implications.

Grok Build traces through the code and identifies dependencies, giving you a clear picture before you commit to any changes. This is particularly useful when documentation is sparse or outdated.

Getting started

  1. Start with Plan Mode. Use Plan Mode to have Grok Build research your codebase and create a structured migration plan before making any changes.

  2. Pick a contained migration first. A single library upgrade or one module's conversion. Develop your workflow before tackling larger migrations.

  3. Create a rules file. Document your target patterns and point to good examples. This investment pays off across every file Grok Build touches.

  4. Commit your examples. When you manually convert a file and get it right, commit it. Grok Build uses it as a reference for subsequent conversions.


Last updated: November 23, 2026