Writing Effective Engineering Prompts for Complex Refactors and Migrations
Prerequisites: The AI Coding Landscape.
Key Takeaway: Prompting an AI coding assistant is not casual conversation; it is software specification. Vague prompts ("refactor this code") yield generic, hallucinated rewrites. High-leverage engineering prompts use the Spec-First Framework: declaring explicit TypeScript interfaces, defining strict non-goals, and breaking complex migrations into atomic, testable passes.
The Anti-Pattern: Lazy Monolithic Prompting
Observe the typical low-velocity prompt:
// Bad, low-leverage prompt:
"Refactor our user profile page to use Server Actions and make it look modern."Why this prompt fails:
- Unbounded Scope: The model tries to redesign the CSS, modify database schemas, rewrite auth logic, and create Server Actions all in one pass.
- Missing Constraints: It introduces external libraries you don't use (e.g. installing Redux or Axios).
- Lost Edge Cases: It drops subtle legacy behavior: loading states, error boundaries, optimistic UI updates, and accessibility tags.
The Spec-First Prompting Framework
Senior engineers structure AI engineering prompts using the Five-Pillar Specification Pattern:
graph TD
Prompt["Senior Engineering Prompt"] --> P1["1. Objective & Role: Senior Next.js Architect"]
Prompt --> P2["2. Context & Constraints: Existing schemas, Next.js 15 App Router, zero new npm dependencies"]
Prompt --> P3["3. Interface Contract: Define TypeScript types & Zod schemas first"]
Prompt --> P4["4. Explicit Non-Goals: What the model MUST NOT touch"]
Prompt --> P5["5. Acceptance Criteria: Pass tsc, verify tests, return unified diff"]Exemplary Engineering Prompt: Complex State Migration
Here is a real-world prompt refactoring a messy 500-line client component into modular Server Actions:
### TASK: Migrate User Billing State to Next.js 15 Server Actions
#### 1. OBJECTIVE
Refactor `components/billing/PaymentPlanSelector.tsx` from client-side `fetch('/api/billing')` to a Next.js 15 Server Action architecture with optimistic UI updates.
#### 2. ARCHITECTURAL CONSTRAINTS
- Target runtime: Next.js 15 App Router (Node.js runtime).
- Do NOT install any third-party libraries. Use native `useActionState` and `useOptimistic`.
- All database operations must be isolated in `app/actions/billing.ts`.
- Retain exact existing Tailwind CSS styles. Do not redesign layout.
#### 3. TYPE CONTRACT
Implement and export the following interface in `types/billing.ts`:
```typescript
export interface PlanUpdatePayload {
tier: "starter" | "pro" | "enterprise";
billingCycle: "monthly" | "annual";
}
export type ActionResponse<T> =
| { success: true; data: T }
| { success: false; error: string; code: "UNAUTHORIZED" | "PAYMENT_FAILED" | "VALIDATION_ERROR" };4. EXPLICIT NON-GOALS
- Do NOT touch
lib/stripe.tsor payment webhook handlers. - Do NOT remove existing data-testid attributes used by Playwright tests.
5. STEP-BY-STEP EXECUTION PLAN
- Author the server action
updateSubscriptionPlaninapp/actions/billing.tsvalidating arguments with Zod. - Refactor
PaymentPlanSelector.tsxto bind form state usinguseActionState. - Wrap plan cards in
useOptimisticto eliminate UI latency.
---
### The Atomic Three-Pass Technique for Large Refactors
When refactoring a large module (1,000+ lines), **never ask the model to do everything in a single turn**. Decompose into three sequential passes:
```mermaid
sequenceDiagram
participant Dev as Senior Engineer
participant AI as AI Coding Assistant
Dev->>AI: Pass 1: Types & Schemas Only ("Generate interfaces and Zod schemas")
AI-->>Dev: Returns types.ts
Dev->>Dev: Reviews & approves types
Dev->>AI: Pass 2: Core Business Logic ("Implement handler matching types.ts")
AI-->>Dev: Returns actions.ts
Dev->>Dev: Runs npx tsc --noEmit
Dev->>AI: Pass 3: UI Integration ("Update React component to consume actions.ts")
AI-->>Dev: Returns Component.tsx
Dev->>Dev: Runs npm testCommon Pitfalls & Anti-Patterns
- Omitting Negative Constraints: Models default to what was popular in their training data. If you don't explicitly command "Do NOT use class components, do NOT install axios", the model will happily introduce legacy patterns.
- Pasting Truncated Snippets Without Surrounding Types: Giving the model a 20-line snippet without the import headers or type declarations forces it to invent placeholder types that break your build.
- Accepting Changes Without Running TypeScript: Always run
npx tsc --noEmitimmediately after applying an AI patch. Fix compilation errors before proceeding to the next step.
Senior Engineer Interview Angle
Staff Engineer Question: "How do you prompt an AI coding tool to perform a framework migration (e.g. Pages Router to App Router) across 20 files without introducing regressions?"
Exemplary Answer:
*"We apply The Specification-First Scaffold Pattern:
- Interface Freeze: We freeze existing TypeScript interfaces and write end-to-end integration tests that record current input/output behavior for all 20 routes.
- Golden Reference File: We manually migrate one representative route by hand, establishing the gold-standard architecture (Server Component layout, error boundary, loading skeleton, server actions).
- Micro-Batch Prompting: We prompt the AI tool on one route at a time, providing the legacy file and the golden reference file as a few-shot exemplar. The prompt explicitly commands: 'Transform Route X to match the structural patterns of GoldenRoute.tsx. Do NOT alter response payload schemas.'
- Verification: After each route is generated, our CI runs integration tests. If tests pass, we commit; if tests fail, we feed the error diff back to the model for bounded correction."*
Quick Self-Check
- What are the five pillars of the Spec-First prompting framework?
- Why should large refactors be broken into the Atomic Three-Pass technique?
- What is an explicit non-goal in an engineering prompt?