Guides
Modernizing legacy code with Grok Build
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:
See the agent's response
See the agent's response
See the agent's response
uglifyjs-webpack-plugin [removed]TerserPluginwebpack.prod.jsoptimize-css-assets-webpack-plugin [removed]css-minimizer-webpack-pluginwebpack.prod.jsfile-loader [deprecated]type: 'asset')webpack.common.js (3 rules)url-loader [deprecated]type: 'asset')webpack.common.js (2 rules)node-sass → should migrate to sass (Dart Sass)webpack-dev-server v3 → needs v4 for Webpack 5nth-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:
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:
See the agent's response
Thought for 2s
EditedHome.tsx+1-1
import { Button } from '../components/Button.js';
import { Button } from '../components/Button.jsx';.jsx.jssrc/components/Button.js → Button.jsx
src/components/Card.js → Card.jsx
src/components/Modal.js → Modal.jsx
... (25 more)src/components/utils/formatters.js
src/components/utils/validators.js
src/components/constants.js
... (3 more)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:
See the agent's response
Thought for 2s
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');| Moment API | Day.js Equivalent | Count |
|---|---|---|
moment() | dayjs() | 45 |
.format() | .format() | 38 |
.fromNow() | .fromNow() (plugin) | 12 |
.diff() | .diff() | 8 |
.add()/.subtract() | Same API | 15 |
.isValid() | .isValid() | 4 |
relativeTime - for .fromNow() supportcustomParseFormat - for parsing specific formatsGrok 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:
See the agent's response
Thought for 3s
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) => {webapp/WEB-INF/views/checkout.jsp (287 lines)src/pages/Checkout.tsx (145 lines)| JSP Pattern | React 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) |
Button from @/components/uiInput from @/components/uiCard from @/components/uiWhen 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.
See the agent's response
Thought for 3s
ACCT-RECORD - 150-byte fixed-width account recordTRANS-RECORD - 80-byte transaction inputERROR-RECORD - Error output formatStart 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.
See the agent's response
Thought for 2s
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/copybooks/ACCT-REC.cpysrc/types/Account.ts| COBOL Definition | TypeScript | Notes | ||
|---|---|---|---|---|
PIC 9(10) | string | Preserve leading zeros | ||
PIC X(30) | string | Right-padded in COBOL | ||
PIC S9(9)V99 COMP-3 | Decimal | Use decimal.js for precision | ||
PIC X(1) | `'A' \ | 'S' \ | 'C'` | Union type for status |
PIC 9(8) (date) | string | YYYYMMDD format |
import { Decimal } from 'decimal.js';Data structure conversion is often the foundation: convert COBOL copybooks, which define record layouts, to modern type definitions.
See the agent's response
Thought for 3s
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
});
});
});cobol/ACCTUPDT.cbl (580 lines)src/services/AccountUpdateService.ts (187 lines)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:
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.
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:
See the agent's response
Thought for 2s
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' });logger.error('Payment failed', { error, userId });
res.status(400).json({ error: error.message });res.status(400).send({ message: 'Error' }); // Different key
res.status(400).json({ err: error }); // Abbreviated// 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' });
}
};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:
See the agent's response
Thought for 2s
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);
}| Method | Before | After | |
|---|---|---|---|
getUser | throws NotFoundError | Result<User, NotFoundError> | |
createUser | throws ValidationError | Result<User, ValidationError> | |
updateUser | throws NotFoundError | `Result<User, NotFoundError \ | ValidationError>` |
deleteUser | throws NotFoundError | Result<void, NotFoundError> | |
verifyEmail | throws InvalidTokenError | Result<void, InvalidTokenError> | |
| ... 3 more |
result.match() or result.unwrapOr()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:
See the agent's response
StripeClient - Stripe API wrapperPayPalClient - PayPal API wrapperAuditLogger - Logs all payment eventsNotificationService - Sends receipts/alertsMetricsCollector - Payment metricsOrderService.ts - checkout flowSubscriptionService.ts - recurring billingRefundController.ts - manual refundsWebhookHandler.ts - payment eventsGrok 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
-
Start with Plan Mode. Use Plan Mode to have Grok Build research your codebase and create a structured migration plan before making any changes.
-
Pick a contained migration first. A single library upgrade or one module's conversion. Develop your workflow before tackling larger migrations.
-
Create a rules file. Document your target patterns and point to good examples. This investment pays off across every file Grok Build touches.
-
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