Ryz Labs/Rescue/Cursor codebase to production
Rescue

Cursor Codebase to Production: Cleanup and Hardening Runbook

How to turn an AI-generated codebase written with Cursor Agent into one a team can own: find the drift, lock down review, test the money paths and refactor in place.

Taking a Cursor codebase to production means turning a repo that grew through hundreds of agent edits into one where every change is reviewed, tested and consistent with written conventions. Our recommendation: keep what works, harden it in place, and replace only the modules that can't be pinned down by tests. What decides success with Cursor is not the editor, it's whether the team that keeps using it agrees on conventions and review gates before the next round of agent changes lands.

What Cursor gives you, and where production starts

A Cursor project is not a hosted app you export later. What you hand a new engineer is an ordinary Git repository in whatever stack you (or the Agent) picked: a Next.js app, a FastAPI service, a Rails monolith, a pile of Lambda functions. Nothing has to be migrated off a platform, which is good news, but the problems are harder to see: they live in the shape of the code, not in a settings page.

For a cleanup, what matters is how Cursor makes and reviews changes:

Production starts when the cost of a wrong change goes up. Real users turn a regression into an outage; a customer security review asks who approved each change, where secrets live and why each dependency is trusted. A repo where the Agent rewrote the same function in four files can't answer those yet.

Failure modes we find first in Cursor repos

Worst first. Each grows out of many fast agent sessions with no shared conventions and no gate in front of main, not from the editor itself.

1. Missing authorization in handlers

The Agent was asked to "add an endpoint that returns the invoice" and did exactly that: it checks that the caller is logged in, loads the invoice by id from the URL, and returns it. Nothing checks that the invoice belongs to the caller's account. This is OWASP API1:2023, Broken Object Level Authorization, and it shows up handler by handler because each one was generated in a separate session.

Detect: list every route and RPC handler, then for each one write down which identifier comes from the request and which query enforces ownership. Log in as user A, take an id that belongs to user B, and call every read, update and delete route with it. If the repo talks to Supabase, remember that the secret and service_role keys bypass Row Level Security, so any server code using them must do its own ownership check. Fix: one authorization layer (middleware, a policy module or database policies), applied by default, with a test per resource proving cross-account access fails.

2. Secrets in source, .env committed, keys in history

A key pasted into chat to "just make it work" ends up in a config file, or a .env file was committed early and deleted later, leaving the value in history.

Detect: enable GitHub secret scanning and run a history-wide scan locally; grep the built frontend bundle for key prefixes. Check mcp.json for tokens too. Fix: rotate every exposed credential first (deleting the file does nothing for history), move values to the host's secret store, add .env to .gitignore, and enable push protection so new hardcoded credentials are blocked at push time.

3. Migrations edited in place

The Agent was asked to add a column and rewrote the original migration file instead of adding a new one. Fresh local databases look fine; production, which ran the old version, drifts from what the code expects.

Detect: run git log on the migrations folder and flag any file modified after its first commit; dump the production schema and diff it against a fresh database built from migrations. Fix: freeze applied migrations, write forward-only corrective migrations for every drift, and add a CI check that fails if an already-merged migration file changes.

4. Dependencies added and never pinned or audited

Each Agent session grabs whatever package solves its problem: three date libraries, two HTTP clients, loose version ranges, and now and then a plausible-looking name nobody meant to install.

Detect: confirm a lockfile exists and is committed; run the ecosystem's audit command; find where each direct dependency is imported; anything used once or never is a removal candidate. Check unfamiliar names against the registry by hand. Fix: pin versions, delete unused packages, consolidate duplicates onto one choice, and add an automated dependency update and audit job in CI.

5. Duplicated logic and inconsistent patterns

This is the signature of an agent-grown repo. Price calculation exists in the checkout handler, the invoice email and an admin script, each slightly different. Error handling and data access follow a different pattern in every folder.

Detect: run a copy-paste detector over the source tree; search for the domain words that matter (price, total, discount, permission, role) and count how many places compute them. Fix: do not refactor yet. Pick the canonical implementation, write characterization tests around all copies, then collapse them into one module. Record the chosen pattern in a project rule so the Agent stops reintroducing the others.

6. Tests that assert the implementation, or were written to pass

Many Cursor repos do have tests. The problem is what they check. Tests generated alongside the code tend to mock every collaborator and assert that a function called another function, or they snapshot whatever the output happened to be. When an Agent was told "make the tests pass," it sometimes changed the assertion instead of the code.

Detect: introduce a deliberate bug in a money path (flip a discount sign, drop an ownership filter) and see whether any test fails. Run mutation testing on the core modules. Fix: write behavior-level tests on public interfaces against a real test database, and treat a test that survives an obvious mutation as missing.

7. Dead code and no module boundaries

Abandoned approaches stay in the tree: a second auth flow nobody calls, folders from a pivot, helpers duplicated three ways. Everything imports everything, so neither people nor the Agent can tell where new code belongs.

Detect: run an unused-exports tool and coverage from the end-to-end suite; generate an import graph and look for cycles. Fix: delete what nothing reaches, define a handful of modules with explicit public interfaces, and enforce the boundaries with a lint rule so both humans and the Agent get a failing check when they cross them.

Production readiness checklist

The hardening plan, step by step

Phase 0: Freeze and snapshot

Stop merging unreviewed Agent output. Tag the current production commit, back up the database, and export the production schema. Turn on branch protection for main so Cloud Agents and humans alike must open a pull request. Inventory who uses Agent, whether Cloud Agents are enabled, and which MCP servers are configured with what credentials. Exit criteria: nothing reaches main without a pull request, and you can restore today's state from a tag plus a backup.

Phase 1: Security

Rotate secrets, scrub what you can from history, and enable secret scanning plus push protection. Fix every handler on the authorization map that trusts a request id, and remove unexplained dependencies. Turn on Bugbot and Security Review for pull requests, and write BUGBOT.md with the specific things reviewers here should flag. Exit criteria: no live credential in source or history, every handler has an ownership test, and every pull request gets automated security review plus a human approval.

Phase 2: Data and performance

Reconcile production schema with migrations using forward-only fixes and add the CI check that rejects edited migrations. Profile the hot paths for queries inside loops and missing indexes. Exit criteria: schema drift is zero, slow queries on the top endpoints have indexes or batched loads, and one module owns data access.

Phase 3: Tests, conventions and CI/CD

Write characterization tests first: record what the money paths do today, including the odd parts, so any refactor that changes behavior fails loudly. Only then consolidate duplicated logic and delete dead code, one module per pull request. In parallel, write the project rules: one .mdc file per concern, each short and concrete ("all database access goes through src/data; never import the client elsewhere"), checked in and reviewed. Enable Agent Review after agent tasks so drift is caught before a pull request is even opened. CI runs lint with boundary rules, type checks, tests, the dependency audit and the migration check, then deploys to staging. Exit criteria: money paths are covered by behavior tests that catch deliberate mutations, rules exist for every agreed convention, and every merge deploys to staging automatically.

Phase 4: Operations

Add error tracking, structured logs with request and account ids, and alerts on payment failures and error-rate spikes. Write a runbook for the likeliest incidents, set up on-call, and run a restore drill. Exit criteria: an alert fires before a customer reports a problem, and someone other than the original author can follow the runbook.

Phase 5: Re-platform only what's left

A few modules may still resist testing. Rebuild those behind the interface the characterization tests define, one at a time. Exit criteria: each replaced module passes the same characterization suite as the one it replaced.

PhaseGoalKey techniqueExit criteria
0 Freeze and snapshotStop unreviewed changesBranch protection, tag, backup, inventory of Agent, Cloud Agents and MCP useEvery change arrives as a pull request; state is restorable
1 SecurityClose authz and secret gapsOwnership map per handler, rotation, push protection, Bugbot and Security Review with BUGBOT.mdNo live secrets; cross-account tests pass; automated plus human review
2 Data and performanceMake the schema trustworthyForward-only fixes, immutable migrations check, query profilingZero drift; hot paths indexed
3 Tests, conventions and CI/CDRefactor without regressionsCharacterization tests, .cursor/rules, Agent Review, boundary lintMutations caught; conventions written; CI to staging
4 OperationsSee problems firstError tracking, structured logs, alerts, runbook, restore drillAlerts before customers; runbook usable by others
5 Re-platform what's leftReplace the untestableRebuild behind characterized interfacesSame suite passes on the new module

What an AI pod on your team does in the first two weeks

Job one is understanding a codebase nobody designed as a whole; job two is agreeing how the team keeps using Cursor without regrowing the mess.

Week one

Week two

Our AI pod uses coding assistants, Cursor included, for the boring parts: test generation, policy drafts, codemods for consolidating duplicates, and log triage. Every change still goes through human review and the tests.

Keep, harden or rebuild?

A Cursor repo is already a normal codebase, so hardening wins far more often than founders expect.

SituationRecommendation
Stack is reasonable, the product works, issues are copies of logic, authz holes and weak assertionsHarden the existing repo
Frontend is fine but business logic is scattered through API routes and componentsExtract a backend service or domain module behind tests
The Agent mixed frameworks or runtimes and nothing can be tested without rewriting itRebuild those modules behind characterization tests, keep the rest
Pre-revenue and still testing the idea, or only internal staff log inHold off on a team; protect main, rotate secrets, keep iterating
A prototype a weekend of cleanup would coverFix it yourself with the checklist above

Typical team shape

A Cursor rescue needs engineers who read unfamiliar code quickly and know the stack the Agent chose. The usual roles: a tech lead responsible for the codebase map and conventions, 1–3 senior engineers fluent in that stack across front and back end (in a TypeScript repo, TypeScript developers), part-time security and DevOps help for authz, secrets and pipelines, and QA automation if the money paths are complex enough to need a dedicated test suite.

Many teams begin with a pod of 3 to 5 senior engineers (a tech lead plus engineers), and a full pod is about seven. Smaller rescues can start with a tech lead plus one or two engineers. Ryz engineers on your team start from $7,000 per month (our published range is $7,000–$15,000 per engineer per month, mostly mid-level to senior), quoted per team. Project cost is team size × months × monthly rate. Once you say go, engineers can typically start in under two weeks. Ryz engineers work on your team, reporting to your leads. Scope your team.

Related

FAQ

Our Cursor codebase is too messy. Is a rewrite the only option?

Rarely. A Cursor repo is already a standard codebase in a mainstream stack, so most of the mess is duplication, missing authorization checks, weak tests and unpinned dependencies, all of which can be fixed in place. Rewrite only modules that can't be covered by characterization tests.

Can we keep using Cursor after the cleanup?

Yes, and most teams should. The cleanup adds project rules in .cursor/rules, a BUGBOT.md, branch protection and automated plus human review, so future Agent and Cloud Agent changes follow the agreed conventions instead of inventing new ones.

How long does it take to clean up an AI-generated codebase?

It depends on the size of the repo, how many places business rules are duplicated, how much of the money path already has meaningful tests, how far production schema has drifted from migrations, and how many people keep shipping changes during the work. The first two weeks produce a codebase map and a prioritized remaining-scope plan, which is the honest basis for any estimate.

What does it cost to hire engineers to fix a Cursor codebase?

Cost is team size times months times the monthly rate per engineer. Monthly rates depend on seniority, the mix of roles and how many engineers the scope needs, and quotes are built per team once the repo and remaining-scope plan have been reviewed.

Are tests written by Cursor good enough for production?

Sometimes, but check before you trust them. Break a money path on purpose and watch for a red test. If none does, add behavior-level characterization tests before any refactor.

Questions we didn't answer? Email info@ryzlabs.com.

Thanks — your message has been sent. We’ll get back to you soon.

Something went wrong while sending your message. Please try again or email info@ryzlabs.com.

Explore Ryz Labs

Software development servicesAI development companyIndustriesStaff augmentationAI pod teamsNearshore software developmentHire engineers by roleEngineer ratesGuidesBuyer guidesCase studiesHow we vet engineers

Ryz Labs

Senior engineers on your team. AI pod teams that ship.

Tell us what you're building. You get a scoped plan, a price and the names of the people who would do the work.

  • Only the top 1% of tens of thousands interviewed make it
  • On US business hours, including New York hours
  • Trusted by Fortune 500 engineering teams

Tell us who you need

A Ryz partner replies with a scoped team plan.

Start a conversation →

Prefer to talk? Book a 15-min call →