Refactoring prompts for AI-generated code are how you salvage a vibe-coded project when the demo works but the repo reads like six interns pair-programmed with no standup — duplicate utilities, god components, and env vars spelled three different ways. This prompt pack and workflow turns cleanup into repeatable passes instead of one desperate “refactor everything” message that breaks auth. Updated October 2026.

You are not alone if your Lovable export “works” and terrifies you in VS Code. Before cleanup, read how to review AI-generated code for a security and architecture lens. For the broader refactor philosophy, see prompt chains for multi-file refactors and anchor your stack against the Vibe Coding Roadmap.
Table of contents
- Signals you have AI spaghetti (not just MVP debt)
- Golden rules for safe AI refactors
- Refactoring prompt library by category
- Multi-step prompt chains that work
- Folder structure recovery prompts
- Testing gates between passes
- When to stop prompting and hand off
- FAQ
Signals you have AI spaghetti (not just MVP debt)
Every MVP carries debt. Clean up vibe coded spaghetti when debt blocks the next feature, not when pedants dislike your file names.
- Same function in three files —
formatDate,formatDate2, inlinetoLocaleDateString - Components over 300 lines with fetch, UI, and business rules intertwined
- Inconsistent data fetching — React Query in one screen, raw
useEffectfetch in another - Env var schizophrenia —
NEXT_PUBLIC_APIvsAPI_URLvs hardcoded localhost - Auth checks only in UI — buttons hidden but routes still public
- No shared types —
anyand duplicated interfaces for the same Supabase row - Dead code from prompt retries —
DashboardOld.tsx, commented blocks half the file
If two or more apply, you are in refactor territory — not shame, just phase two of vibe coding.
Spaghetti vs acceptable MVP shortcuts
| Acceptable for launch | Fix before next feature |
|---|---|
| Inline Tailwind without design tokens | Duplicated Supabase clients with different keys |
| Missing unit tests on UI | Client-only route protection |
Single utils.ts junk drawer | Three junk drawers with overlap |
| Console.log debugging left in | Service role key imported in client component |
Golden rules for safe AI refactors
Refactor AI generated code prompts fail when they violate constraints humans learn in code review:
- One concern per prompt. Extract hooks today; rename folders tomorrow.
- Name files explicitly. “Refactor auth” becomes a repo-wide rewrite. List paths.
- Require diff summary. Agent must list files touched and behavior unchanged.
- Preserve public API. Exports and route URLs stable unless prompt says otherwise.
- Run build between passes.
npm run buildis your cheap integration test. - Git commit per pass. Rollback beats debugging a 40-file agent diff.
Load system prompt templates with: “Prefer smallest diff; no new dependencies without asking.”
Refactoring prompt library by category
1. Extract duplicated utilities
Prompt: “Scan src/ for duplicate date/string/format helpers. Consolidate into lib/format.ts. Update imports. Do not change function behavior. List removed duplicates. No other files modified except import paths.”
2. Split god components
Prompt: “Split components/Dashboard.tsx into: DashboardLayout, DashboardStats, DashboardTable. Move data fetching to a useDashboardData hook in hooks/. Preserve all existing props and routes. Max 120 lines per new file.”
3. Unify Supabase access
Prompt: “Replace direct createClient calls outside lib/supabase/ with imports from server/client helpers. Align env var names to NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY. Reference patterns in Supabase auth setup prompts mentally — one client factory only.”
4. Remove dead code
Prompt: “Find files ending in Old, Backup, Copy, or suffix 2. Confirm zero imports via search. Delete unreferenced files. Remove commented-out blocks over 10 lines in app/ and components/. Report deletions.”
5. Standardize error handling
Prompt: “Add consistent try/catch with user-safe messages on all server actions in app/actions/. Log errors server-side only. Do not expose stack traces. Match existing toast pattern in components/ui/toast.”

Multi-step prompt chains that work
Chains from our dedicated guide apply directly to spaghetti cleanup:
Chain A — Read-only audit (no edits):
- “List top 10 maintainability issues in this repo by severity. Files and line ranges only. No code changes.”
- “Propose a 4-pass refactor plan with estimated files per pass. Dependencies between passes noted.”
- Human picks passes; execute one at a time.
Chain B — Data layer first:
- Unify Supabase clients and types.
- Extract hooks from components using those types.
- Split UI components last — they now import stable hooks.
Chain C — Auth hardening after feature refactors:
- Never refactor auth in the same pass as UI moves.
- After structure stable, run middleware audit prompt from auth tutorials.
When chains stall, switch to debugging prompts for vibe coding — often the agent lost stack context, not architecture.
Folder structure recovery prompts
AI projects drift into flat components/ swamps. Recovery prompt:
“Reorganize without changing imports’ public behavior: move feature code to features/{name}/components, features/{name}/hooks, shared UI stays in components/ui. Update all import paths. Run typecheck. Provide migration map.”
Target structure for Next.js App Router vibe apps:
app/— routes only, thin pagesfeatures/— domain modulescomponents/ui/— buttons, inputs, design systemlib/— clients, env, pure utilitiestypes/— shared DB and API types
Testing gates between passes
Refactor prompts without verification invite regressions:
| Gate | Command / action | When |
|---|---|---|
| Build | npm run build | After every pass |
| Lint | npm run lint | After structure passes |
| Smoke | Login, create, read, delete one entity | After data layer passes |
| Diff review | Human read agent summary | Before merge to main |
Compare IDE assistance levels in Copilot vs Cursor vs Windsurf — refactors benefit from repo-wide context Cursor provides.
When to stop prompting and hand off
Prompts cannot replace architectural decisions forever. Stop vibe refactoring when:
- Passes repeatedly break auth or payments — hire review
- You need real test coverage for compliance — prompts write shallow tests
- Performance requires profiling, not guesswork refactors
- Three consecutive passes fail build — reset branch and narrow scope
Tooling comparison: Claude Code vs Cursor for agentic multi-file work; Cursor vs Lovable when export + local refactor beats in-builder retries.
Type safety recovery prompts
AI spaghetti often means any everywhere and three interfaces for the same Supabase row. Run a dedicated type pass before feature work:
Prompt: “Generate TypeScript types from Supabase schema for tables users, projects, tasks. Single source in types/database.ts. Replace inline object types in app/ and components/ with imports. No behavior changes. Run tsc and fix errors.”
Strong types make subsequent refactor prompts safer — agents infer breaking changes when props mismatch. Export types from one file; forbid duplicate interface User declarations in feature folders.
Performance cleanup prompts
Spaghetti code ships with performance debt: fetch waterfalls, missing React.memo on heavy lists, images without dimensions. After structure refactors, run:
- “Identify client components that fetch data — move fetch to server components or hooks with single query per screen.”
- “Add loading.tsx and Suspense boundaries for routes over 200ms TTFB in dev.”
- “Replace raw img tags with Next.js Image where files exist in public/.”
Performance passes are lower priority than auth and RLS fixes — but cheap wins before launch reduce support tickets.
Anti-patterns to forbid in system rules
Add these to Cursor rules or Continue config to prevent respaghetti after cleanup:
- No new files named utils2, helpers_backup, or componentCopy.
- No fetch in useEffect when server component or React Query already used elsewhere.
- No inline Supabase service role key — ever.
- No refactor prompt without listing allowed file paths.
- Max one new dependency per PR unless prompt explicitly requests library X.
These guardrails align with system prompt templates — customize for your stack.
Mini case study: Lovable export cleanup
Typical Lovable export arrives with working demo and 40 components in flat structure. Pass one: delete dead files. Pass two: unify Supabase client. Pass three: extract hooks from three largest components. Pass four: folder restructure to features/. Pass five: auth middleware audit. Total time with Cursor: one weekend versus two weeks of re-prompting Lovable for refactors that never land cleanly.
Export first per Vercel deploy guide, then refactor locally with git commits — in-builder cleanup lacks rollback discipline.
Logging and error boundary prompts
Spaghetti apps swallow errors. After data layer cleanup, prompt: “Add error.tsx boundaries for app routes; log server errors with structured JSON; user-facing message generic; no stack traces in client.” Centralize client error reporting later — Sentry optional for MVP — but never silent catch blocks in server actions.
Import path and alias cleanup
AI projects mix ../../../components with @/components. Single pass prompt: “Standardize all imports to @/ alias per tsconfig paths; no relative imports crossing feature boundaries; run eslint fix.”
Consistent aliases make subsequent refactor prompts reliable — agents parse @/ paths predictably in large repos.
Pre-merge refactor review checklist
- git diff –stat under 500 lines per pass ideally
- npm run build green
- Auth smoke test on two accounts
- No new any types without comment justification
- Agent summary matches actual files changed
- Compare against review guide security section
Naming and convention recovery
Inconsistent naming — fetchUser, get_user, loadUserData for the same operation — confuses humans and LLMs alike. Run a naming pass after structure stabilizes: “Standardize async data functions to getX fetch pattern in lib/data/; components PascalCase; hooks useX; server actions verbNoun; document in CONTRIBUTING.md.” Boring conventions beat clever abstractions in AI-maintained repos.
Third-party integration spaghetti
Stripe, webhooks, and email SDKs pasted inline in page components are security and maintenance hazards. Extract to lib/stripe/ and route handlers; never import secret keys outside server files. Prompt: “Move all Stripe calls from components to app/api/webhooks/stripe/route.ts and lib/stripe/server.ts; verify build.” Same pattern for Resend, Postmark, or OpenAI server calls — one gateway folder per vendor.
Keep a refactor log in CHANGELOG.md — future you and future agents need context on why folders moved.
FAQ
Can one prompt clean my entire AI codebase?
Technically sometimes; reliably no. Single-shot refactors miss edge cases and blend concerns. Use chained passes with commits between them.
Should I refactor before or after deploying?
Deploy a secure MVP first if users wait — then refactor on main with preview deploys. Never refactor auth and deploy Friday same day.
What if the agent keeps adding new abstractions?
Add to system rules: “No new design patterns, classes, or folders unless prompt explicitly requests. Prefer inline extraction over enterprise patterns.”
How do I refactor Bolt or Lovable exports specifically?
Export to GitHub first per Vercel deploy guide, run build locally, then Chain B (data layer). In-builder refactors lack git discipline.
Refactoring prompts for AI-generated code turn spaghetti into maintainable MVPs when you audit first, refactor in small committed passes, and gate with builds — not hope. Combine this library with multi-file prompt chains, review with AI code review habits, and debug stuck agents using debugging prompts before you rage-quit the repo.
