---
name: rust-deframework-migration
description: >-
  End-to-end staging-first protocol for de-frameworking an existing web application
  (Next.js, React, Vue, Svelte, Node, Python/FastAPI, Prisma, Tailwind, BaaS stacks)
  into a lean, high-efficiency Rust + Vanilla Web architecture (or pure static Caddy/Nginx
  site) with 100% 1:1 visual, CSS, UX, API, and functional parity verified via Playwright
  before controlled cutover and owner-gated decommissioning.
---

# Rust De-Framework Migration (Staging-First, 100% Parity)

Rebuild an existing framework-heavy web application into a single, ultra-efficient **Rust binary + Vanilla HTML/CSS/JS** (or pure static site where no backend is needed) **without touching production** until a staging subdomain (`staging.<domain>`) achieves **100% verified 1:1 parity** across visuals, CSS, responsive layouts, UX interactions, APIs, auth, data, and SEO.

## Core Non-Negotiable Laws

1. **Zero Production Impact Until Cutover:** Production remains 100% untouched throughout Audit, Blueprint, Build, and Verification. All new work runs on an isolated staging subdomain (`staging.<domain>`) with strict `STAGING_SAFE_MODE` (separate cloned DB, no production credentials, trapped outbound emails, disabled live webhooks/billing/crons, `robots.txt: Disallow: /`).
2. **Frameworkless Target Stack:** Eliminate runtime JS/Python web frameworks (Next.js, React, Vue, Svelte, Express, FastAPI, Prisma, Turborepo, heavy BaaS stacks).
   - **Static-only apps** (no server secrets or persistence): Pure Vanilla HTML/CSS/JS served directly by reverse proxy `file_server` (`0 MB` app RAM).
   - **Dynamic apps**: Single Rust binary (`axum` + `askama` compile-time SSR templates + Vanilla ES Modules + `sqlx` for Postgres or `rusqlite` for SQLite). Keep specialized external sidecars (e.g., Chromium/FFmpeg media renderers) *only* where Rust genuinely shouldn't replace them.
   - **Sibling clients** (mobile apps, browser extensions, third-party webhooks): Keep them intact by preserving exact API contracts rather than rewriting them.
3. **100% Visual, CSS & Functional Parity (Playwright-Verified):** "It compiles" and "`curl` returns 200" are **never** sufficient. Every page, breakpoint (desktop + mobile), theme, modal, form, and flow **must** be verified side-by-side against production using **Playwright** (or available headless browser automation) with zero console errors, zero 404/broken assets, zero CSS/layout regressions, and zero broken interactions.
4. **Build-Time CSS Fidelity — Never Eyeball Styles:** Preserve 100% of existing visual styling from Day 1. Compile existing Tailwind/PostCSS stylesheets at *build time* (zero runtime Node) or extract exact CSS design tokens, self-host WOFF2 fonts, and preserve exact SVG icon paths. See [references/css-and-playwright-parity.md](references/css-and-playwright-parity.md).
5. **Owner-Gated Cutover & Decommissioning:** Never cut over production or delete legacy containers, databases, DNS rules, or framework code automatically. Both **Cutover** and **Decommissioning** require explicit owner sign-off after full parity proof and a clean post-cutover soak period.

---

## Model Selection Guide (Google Gemini & Anthropic Claude)

Match model capability to stage complexity so you get rock-solid architecture and 100% parity without wasting high-tier quota on mechanical work:

| Stage / Task | Recommended Claude Model | Recommended Google Model | Why |
| :--- | :--- | :--- | :--- |
| **Stage 0: Deep Audit & Inventory** | **Claude Opus** (fallback: Sonnet) | **Gemini Pro (High reasoning)** | Catches subtle redirects, hidden middleware, auth quirks, raw SQL, and edge cases across large repos. |
| **Stage 1: Architecture Blueprint & Security Design** | **Claude Opus** | **Gemini Pro (High reasoning)** | High-leverage decisions (auth/cookie compatibility, CSRF/CSP, DB schema, CSS pipeline, staging isolation). Get this wrong and everything downstream hurts. |
| **Stage 2: Vertical Slice Implementation (Rust, Templates, Vanilla JS, CSS)** | **Claude Sonnet** | **Gemini Pro (Standard)** | Fast, accurate execution against a locked blueprint and clear contracts. Escalate to Opus / Pro (High) only for gnarly concurrency, OAuth/crypto, or complex state bugs. |
| **Stage 3: Playwright Parity Suite, Visual Diffing & CSS Fixing** | **Claude Sonnet** (Opus for tricky visual/layout root causes) | **Gemini Pro (Multimodal / Vision)** | Vision-capable models excel at comparing prod vs. staging Playwright screenshots side-by-side and spotting subtle CSS/spacing/font regressions. |
| **Stage 4: Cutover Runbook, DB Integrity Verification & Final Audit** | **Claude Opus** | **Gemini Pro (High reasoning)** | Zero-margin-for-error production switch, DB count/FK checks, rollback safety, and decommission verification. |
| **Mechanical Scans (File lists, grep inventories, log summaries)** | **Claude Haiku** | **Gemini Flash** | Cheap, fast, keeps main context clean. |

---

## Five-Stage Execution Workflow

Follow these stages strictly in order. Do **not** skip ahead or mix stages.

### Stage 0 — Full Codebase & Live Dependency Audit (Read-Only)
Produce `MIGRATION_AUDIT.md` without modifying any application code. Inventory:
1. **Page Routes & Navigation:** Every static/dynamic page, error page (`404`/`500`), redirect, rewrite, canonical URL, `robots.txt`, `sitemap*.xml`, OpenGraph/meta tags, and JSON-LD structured data.
2. **API Contract Matrix:** Every `(HTTP_METHOD, PATH)`, query params, request/response JSON shapes, status codes, headers, rate limits, and auth/RBAC rules.
3. **Database & Storage:** Every table, column, index, constraint, sequence, JSONB payload shape, raw SQL query, file upload/bucket path, and caching layer (Redis/ISR/CDN).
4. **Auth, Security & Integrations:** Password hashing format (e.g., `bcrypt`/`scrypt`/`argon2`), session/JWT/cookie structure (for zero-logout migration if needed), OAuth providers, CSRF, CSP, payments/webhooks, outbound email, background crons, and third-party APIs.
5. **CSS, Fonts, Icons & Static Assets:** Every stylesheet entry point, Tailwind config/plugins/custom tokens, theme classes (`dark`/CSS vars), fonts (Google Fonts vs local WOFF2), icon libraries (e.g., Lucide/Heroicons), `public/` files, and image optimization routes (`/_next/image`).
6. **Pre-Existing Defects & Sidecars:** List existing bugs found during audit and any specialized sidecars (e.g., headless browser video renderers) so the owner decides what to keep, fix, or retire.

### Stage 1 — Architecture Blueprint & Spec (`MIGRATION_BLUEPRINT.md`)
Compile `MIGRATION_AUDIT.md` into a locked `MIGRATION_BLUEPRINT.md` covering:
1. **Target Workspace Layout:** Place the Rust workspace (e.g., `rust/` or `crates/`) alongside the untouched legacy app so both coexist cleanly during staging.
2. **Stack & Crate Decisions:** Exact crates (`axum`, `tokio`, `tower-http`, `askama`, `sqlx`/`rusqlite`, `argon2`, `governor`, `moka`, `reqwest`), plus explicit pushbacks where a sidecar or sibling client should remain untouched.
3. **Build-Time CSS, Fonts, Icons & Asset Pipeline:** Concrete plan guaranteeing **Day-1 visual parity** (see [references/css-and-playwright-parity.md](references/css-and-playwright-parity.md)).
4. **Vanilla JS DOM Contract:** Route-scoped ES modules (`<script type="module">`), safe DOM construction (prefer `textContent` / `createElement` over raw `innerHTML`), and progressive enhancement.
5. **Security & Auth Parity:** Cookie flags (`HttpOnly`, `Secure`, `SameSite=Lax`, `__Host-` prefix), CSRF protection, strict CSP (verified not to break styles/fonts/scripts), SSRF guards, and auth migration strategy.
6. **Staging Isolation Topology (`STAGING_SAFE_MODE`):** Exact subdomain, proxy config, separate DB/volume/bucket, Mailpit/sandbox traps, and blocked crawlers.
7. **Vertical Slice Build Order:** Ordered single-touch verticals (each written to 100% completion—no stub/placeholder phases):
   - V0: Spine (Cargo workspace, DB pool/migrations, auth/session, CSRF/CSP, healthcheck, compiled CSS & static asset serving)
   - V1: Public SSR pages, SEO (`sitemap.xml`, `robots.txt`, meta/OG), and read APIs
   - V2: Interactive client flows (Vanilla ES Modules, forms, modals, filters, search, uploads)
   - V3: Mutations, webhooks (with idempotency), payments (test mode), email templates, and scheduled crons
   - V4: Admin / internal dashboards (e.g., Askama partials + minimal vanilla JS or vendored htmx)
8. **100% Parity Verification Matrix, Cutover Runbook & Decommissioning Plan.**

> **HARD GATE 1:** Pause and present `MIGRATION_BLUEPRINT.md` plus any open owner decisions. Do **not** start writing Rust/UI code until the owner approves the blueprint.

### Stage 2 — Isolated Staging Subdomain Build (`staging.<domain>`)
1. **Provision Isolated Staging First:** Stand up `staging.<domain>` behind your reverse proxy (Caddy/Nginx) pointing to the new Rust container, connected **only** to a cloned staging database and staging storage bucket with `STAGING_SAFE_MODE=1`.
2. **Verify CSS & Assets Before Building Pages:** Confirm on the very first route that compiled CSS loads with `200 text/css`, fonts load with `200 font/woff2`, icons render crisply, and CSP emits zero violations in Playwright.
3. **Ship Vertical Slices to 100%:** Complete each vertical end-to-end (Rust handler + Askama template + CSS classes + Vanilla ES Module + unit/integration test + Playwright check on staging) before moving to the next vertical.
4. **Never Leave Placeholder UI or Partial CSS:** If a component has hover states, mobile drawers, dark mode, loading spinners, empty states, or error banners on prod, port them completely in the same vertical.

### Stage 3 — 100% 1:1 Parity Verification Gate (Playwright + Automated + Live Staging)
Run the full verification suite against `https://<prod-domain>` vs `https://staging.<domain>` using [references/css-and-playwright-parity.md](references/css-and-playwright-parity.md):
1. **Playwright Visual, CSS & Asset Parity (Every Route × Desktop + Mobile):**
   - Capture side-by-side full-page screenshots (`1440×900` desktop and `390×844` mobile) for every public and authenticated route.
   - Assert **0** `pageerror` exceptions, **0** `console.error` messages, **0** HTTP `>= 400` responses (CSS, JS, fonts, images, API calls), **0** broken images (`naturalWidth === 0`), **0** horizontal overflow (`scrollWidth > innerWidth`), and **100%** of stylesheets loaded cleanly.
   - Compare computed CSS styles (`fontFamily`, `fontSize`, `color`, `backgroundColor`, `padding`, `borderRadius`, bounding-box layout) on key landmarks (`header`, `nav`, `h1`, primary CTA, cards, forms, `footer`) between prod and staging.
   - Inspect screenshots visually (using multimodal review + human spot-check) for spacing, alignment, z-index, icon sizing, hover/focus/active states, modals, and responsive breakpoints.
2. **Functional & Interactive E2E Parity:**
   - Playwright E2E flows for every user journey: auth (login, signup, password reset, OAuth, logout, session persistence), CRUD forms & validation errors, search/filter/sort/pagination, uploads, billing/webhooks (test mode), emails (verified in Mailpit), and admin actions.
3. **API, SEO & Security Parity:**
   - Automated diff of HTTP status codes, redirects, `<title>`, `<meta description>`, canonical links, OG tags, JSON-LD, `robots.txt`, `sitemap.xml`, response headers, and API JSON schemas.
   - Negative security suite: CSRF/Origin `403`, unauthenticated `401`, cross-user/RBAC `403`, XSS escaping, rate-limit `429`.
4. **Performance & Footprint Benchmark:**
   - Record before/after RAM usage, Docker image size, cold-start time, p50/p99 TTFB, JS bundle weight, and Lighthouse scores.
5. **Zero-Defect Fix Loop:** Log every discrepancy in `PARITY_REPORT.md`, fix it, and re-run Playwright until **every check is 100% green**.

> **HARD GATE 2:** Present `PARITY_REPORT.md` (with Playwright screenshots, zero-error proof, and benchmark delta) to the owner. Do **not** cut over production until the owner explicitly approves.

### Stage 4 — Controlled Cutover, Soak & Owner-Gated Decommissioning
Follow [references/cutover-and-decommission.md](references/cutover-and-decommission.md):
1. **Cutover:** Quiet window → quiesce background writers/crons → brief read-only freeze + atomic final DB clone/sync → automated row-count, sequence, and FK integrity verification (abort on *any* mismatch) → atomic reverse-proxy flip (`prod` → Rust service) → live post-cutover Playwright & health smoke test.
2. **Soak Period (Instant Rollback Ready):** Keep legacy app containers and legacy DB volumes **stopped but intact on disk** for the soak window (typically 3–7 days) so rollback takes `< 5 seconds` if needed. Monitor logs, error rates, latency, crons, and RAM.
3. **Decommissioning (ONLY AFTER EXPLICIT OWNER APPROVAL):**
   - Archive final backup snapshot of legacy DB + config.
   - Remove legacy containers, unused DB/BaaS sidecars, and staging subdomain containers/volumes.
   - Remove staging DNS records, staging reverse-proxy blocks, and temporary staging secrets.
   - Tag git history (e.g., `pre-decommission-legacy`), remove legacy framework directories/dependencies in a clean commit, and re-run tests + live health + resource stats.

---

## Reference Files

Load these on demand as you enter each stage:
- [references/prompts.md](references/prompts.md) — Copy-pasteable prompt pack for Stages 0–4 (with Google & Claude model guidance per prompt).
- [references/css-and-playwright-parity.md](references/css-and-playwright-parity.md) — Bulletproof CSS/font/icon/asset parity pipeline, common migration traps, and a ready-to-run Playwright 1:1 parity script template.
- [references/cutover-and-decommission.md](references/cutover-and-decommission.md) — Staging `STAGING_SAFE_MODE` checklist, zero-downtime cutover runbook, instant rollback procedure, and owner-gated decommissioning checklist.
