# Vibe Code Rescue Playbook: Turning an AI-Generated Codebase Into a Production-Ready App

An AI-generated codebase usually fails in a predictable way. Not with one dramatic bug, but with the same small shortcut repeated across fifty files. That pattern changes how you should approach a vibe code rescue: you are not hunting a needle, you are fixing a template that got copied everywhere.

This post is a practical engineering playbook for taking an AI-built MVP from "it works on the demo" to a production-ready app. It assumes a typical stack (a TypeScript or Python web app, a Postgres or similar database, a hosted backend, maybe an LLM integration), but the phases apply to most stacks.

## Phase 0: Freeze, fork and inventory

Before changing anything, get control of the environment.

- **Freeze risky deploys.** Agree that nothing ships to production during the first audit days except security fixes.
- **Confirm ownership.** Make sure the company, not an individual's personal account, owns the repo, cloud project, domain, app store accounts and database.
- **Inventory the system.** List every runtime, external API, background job, webhook and environment variable. AI tools are generous with integrations, and some of them will be forgotten experiments still holding live credentials.

The output is a one-page system map. Every later phase refers back to it.

## Phase 1: Automated triage

![AI-generated code audit pipeline: secret scanning, dependency audit, static analysis and type checking feeding a ranked findings list](https://cdn.hashnode.com/uploads/covers/6adf4f7a2498241548ff96b9/df86ce6e-f13e-4bb8-b356-71cee2a10cc2.jpg align="center")

Do not read 40,000 lines by hand first. Let tools rank the problems for you.

| Check | What it catches | Example tooling |
| --- | --- | --- |
| Secret scanning (full git history) | Keys committed and later "deleted" | gitleaks, trufflehog |
| Dependency audit | Known CVEs, abandoned packages | `npm audit`, `pip-audit`, OSV-Scanner |
| Static analysis | Injection, unsafe deserialization, missing checks | Semgrep, CodeQL, Bandit |
| Type checking in strict mode | Silent `any`, null paths | `tsc --strict`, mypy |
| Dead code and duplication | Copy-pasted handlers, unused files | knip, ts-prune, jscpd |

Two notes on running these against AI-generated code:

1. **Scan history, not just HEAD.** Vibe-coded repos often have secrets that were committed in an early prompt cycle and removed later. They are still in git history, so rotate them.
2. **Expect clusters.** If Semgrep flags one route handler for a missing ownership check, grep for the same pattern. It is almost always repeated.

## Phase 2: Fix authorization at the data layer

The single most common serious issue in an AI-generated code audit is broken object-level authorization: the API checks that a user is signed in, but not that the record belongs to them.

Patching each endpoint works, but it relies on every future endpoint remembering the rule. A sturdier fix is to enforce ownership where the data lives.

If you are on Postgres (including hosted options that expose Postgres directly to the client), row-level security is a strong default:

```sql
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

CREATE POLICY invoices_owner_only ON invoices
  USING (org_id = current_setting('app.current_org_id')::uuid);
```

Your API sets `app.current_org_id` per request from the verified session, and the database refuses cross-tenant reads even if a handler forgets the check. Pair this with a small set of tests that sign in as user A and try to fetch user B's records. Those tests should fail loudly forever.

## Phase 3: Characterization tests before refactoring

You cannot safely refactor code whose behavior nobody wrote down. Characterization tests (also called golden master tests) capture what the system does today, right or wrong, so you can change the structure without changing behavior by accident.

Focus on the money paths: signup, login, checkout or subscription, and the one workflow customers pay for. A few dozen API-level tests here are worth more than hundreds of unit tests on helper functions.

Then wire them into CI so no pull request merges without passing:

```yaml
# .github/workflows/ci.yml (excerpt)
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx tsc --noEmit
      - run: npm test
      - run: npx gitleaks detect --no-banner
```

Now the AI tools can keep helping you write code, but every change has to pass the same gate a human change would.

## Phase 4: Make failures visible

Many AI-built apps swallow errors with an empty `catch`, or log to a console nobody reads. Before refactoring anything large, add:

- **Error tracking** with release tags, so you can tie a spike to a deploy.
- **Structured logs** with a request ID passed through every service call.
- **Basic traces** around external calls (payments, email, LLM APIs). OpenTelemetry is a vendor-neutral way to start.
- **Two or three alerts** that matter: error rate, failed payments and queue backlog.

## Phase 5: Refactor with the strangler fig pattern

![Strangler fig pattern for vibe code rescue: new production-ready modules gradually replacing AI-generated legacy routes behind one gateway](https://cdn.hashnode.com/uploads/covers/6adf4f7a2498241548ff96b9/6e6b80d4-a2a7-4f38-a315-705dbc4c174c.jpg align="center")

For most rescues, a big-bang rewrite is the riskiest choice. The strangler fig pattern lets you replace the system one slice at a time:

1. Put a routing layer (API gateway, reverse proxy or framework middleware) in front of the old code.
2. Rebuild one bounded area, for example billing, as a clean module with tests.
3. Route traffic for that area to the new module, keep the old path as a fallback, and watch the metrics.
4. Delete the old code once the new path is stable. Then pick the next slice.

This keeps the product shipping while the foundation improves, which is what customers and investors care about.

## Phase 6: Put guardrails on LLM features

If the product calls an LLM, add cost and safety controls before usage grows:

- Per-user and per-org rate limits and monthly token budgets.
- Response caching for repeated prompts.
- Timeouts and retries with backoff, so one slow provider call does not tie up workers.
- Server-side prompts only. Never ship system prompts or provider keys to the client.

## Rescue vs rebuild: an engineering scorecard

Score each item from 0 (bad) to 2 (good). A total of 7 or more usually favors a staged rescue; 4 or below suggests a rebuild of at least the core.

| Signal | 0 | 2 |
| --- | --- | --- |
| Data model | Untyped JSON blobs, no constraints | Normalized schema with keys |
| Testability | Cannot isolate any module | API-level tests possible today |
| Product fit | Built for a pivoted product | Matches the roadmap |
| Stack | Unmaintained framework | Mainstream, supported versions |
| Security posture | Secrets in client, no authz | Fixable with focused changes |

## Where this fits for US teams

Rescue work is mostly unglamorous engineering discipline applied quickly. If you want a partner to run it, look for one that starts with a written audit and works under recognized security processes. Our team at Webshark works under ISO 27001 and CMMI Level 3, and our [software development company in the USA](https://www.webshark.tech/software-development-company-usa) page describes how we run these engagements. For rescues where the main product is a mobile app built with AI tools, see our [mobile app development services for US companies](https://www.webshark.tech/mobile-app-development-company-usa).

If you are weighing an offshore team for this kind of work, my overview of [offshore mobile app development companies in India for US businesses](https://www.linkedin.com/pulse/top-offshore-mobile-app-development-companies-india-us-kachhawah-u5btf/) covers what to compare.

## Takeaway

A vibe code rescue is not a rewrite. It is a sequence: inventory, automated triage, authorization at the data layer, characterization tests, visibility, then slice-by-slice refactoring. Done in that order, an AI-built MVP can become a production-ready app without stopping the product.

Which phase would your current codebase struggle with most? Tell us in the comments.

---

*Published by Webshark Engineering, the engineering blog of Webshark Web Services:* [*https://www.webshark.tech/*](https://www.webshark.tech/)
