Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- === README.md ==============================================
- # Route File Refactor Prompt Pack
- A safe, step-by-step instruction set for splitting a large monolithic route file into smaller, organized domain modules — without changing how your code works.
- ---
- ## What is this?
- When a backend grows over time, one route file ends up handling everything — authentication, payments, user data, API keys, admin tools. It becomes hard to read, hard to test, and risky to change.
- This pack gives an AI agent (specifically Replit Agent) a precise set of instructions to split that file into smaller focused files, safely, one piece at a time.
- **Nothing changes about how your code behaves.** Same routes, same logic, same error messages. Just better organized.
- ---
- ## What is in this pack?
- | File | What it is |
- |---|---|
- | `README.md` | This file |
- | `refactor-prompt.json` | The instruction set you hand to the agent |
- | `REFACTOR_BASELINE.md` | Created automatically by the agent during the process — your safety record |
- | `REFACTOR_LOG.md` | Created automatically by the agent — a log of every step taken |
- > The last two files do not exist yet. The agent creates them when it starts work.
- ---
- ## What does the agent actually do?
- ### Before touching any code
- The agent asks you 8 setup questions — your file path, test command, type-check command, and a few safety checks. It will not start until you answer all of them.
- ### Phase 0 — Verification
- The agent reads your route file independently and maps out everything:
- - Every route, its HTTP method, and its line number (saved to `REFACTOR_BASELINE.md`)
- - All shared helpers and middleware
- - Any closures that might cause problems when moved
- - Whether your webhook handler is safely located
- - Whether any security middleware has hidden dependencies
- It then asks you to confirm the groupings before anything moves.
- ### Phase 1 — The actual split
- Six steps, each requiring your approval before the next begins:
- 1. Extract all shared helpers into `_middleware.ts`
- 2. Extract the simplest domain files first
- 3. Extract any feature-flag-gated blocks
- 4. Extract medium-complexity domains
- 5. Extract SSE/streaming routes last (highest risk, done when everything else is clean)
- 6. Create the final `index.ts` and remove the original file
- ### After every single file change
- The agent runs:
- - Your test suite
- - Your type-checker
- - A route count diff against the baseline
- If anything fails it restores the file immediately and stops. It does not try to fix errors on its own.
- ---
- ## How to use it
- ### Option A — Paste directly into Replit Agent chat
- 1. Open `refactor-prompt.json`
- 2. Copy the entire contents
- 3. Paste into your Replit Agent chat
- 4. The agent will ask you the setup questions and begin
- ### Option B — Save to your repo
- 1. Copy `refactor-prompt.json` into a `prompts/` folder in your repo
- 2. When ready to refactor, open the file and paste its contents into the agent chat
- ---
- ## Requirements
- - Your project must have a working test suite before you start
- - Your working tree must be clean (no uncommitted changes) — changes are reverted via git, so a clean state is what makes rollback possible
- - You need to know your test command and type-check command
- - You need to know where your webhook handler lives (if you have one)
- - Designed for Express/TypeScript. The route-detection grep pattern is Express-specific but easy to adjust for Fastify, Hono, or Koa.
- ---
- ## What files can this be used for?
- This pack was designed for route files but the same approach works for any large monolithic file. Common candidates:
- - `server/agents.ts` — multi agent stage logic
- - `server/index.ts` — server setup mixed with middleware and webhooks
- - Any file that has grown beyond 1000 lines and handles multiple unrelated concerns
- The JSON is roughly 80% reusable for other files. The Phase 0 questions and verification steps stay the same. Only the domain groupings change.
- ---
- ## What the agent will NOT do
- - Edit any handler logic
- - Change status codes or error messages
- - Add or remove dependencies
- - Rename imports beyond correcting path depths
- - Fix forward if a test fails — it always restores and stops
- ---
- ## If something goes wrong
- The agent writes every finding and every verification result to `REFACTOR_LOG.md` as it works. If a session ends unexpectedly, open that file to see exactly where things stopped and what state the repo is in.
- ---
- ## Glossary
- | Term | Plain meaning |
- |---|---|
- | Refactor | Split or reorganize code without changing what it does |
- | Monolithic file | One big file doing too many things |
- | Domain module | A smaller file responsible for one area (e.g. auth, payments) |
- | Middleware | Code that runs before your route handler (e.g. checking if user is logged in) |
- | SSE | Server-Sent Events — a way of streaming live updates to the browser |
- | Registration order | The sequence routes are added to the server — order matters in Express |
- | Hermetic block | A section of code that is self-contained and does not depend on anything outside it |
- | Closure | A function that uses variables from the scope it was defined in |
- === refactor-prompt.json ============================================================
- {
- "name": "Monolithic Route File Refactor",
- "version": "1.0",
- "target_agent": "Replit Agent",
- "description": "Safe incremental refactor of a monolithic route file into per-domain route modules. Zero behavior change.",
- "setup": {
- "instruction": "Ask the user all of these questions before opening any files. Do not proceed until all are answered.",
- "questions": [
- "What is the path to the monolithic route file you want refactored?",
- "What should the target routes directory be named?",
- "What is your test command?",
- "What is your type-check command?",
- "Do you have an HTTP integration test or smoke test script? If yes, what is the command?",
- "Where does your raw-body webhook handler live?",
- "Are there any uncommitted changes or in-progress work in the repo right now? If yes, stop — do not proceed until the working tree is clean. A clean git state is required so that any step can be reverted.",
- "Confirm you want me to stop and wait for your approval after every step before continuing."
- ]
- },
- "global_rules": [
- "Do one file at a time. Do not open and edit multiple files simultaneously.",
- "Run the full verification suite after every single file change.",
- "If verification fails: restore the file to its previous state immediately. Do not attempt to fix the error. Write the failure to REFACTOR_LOG.md and stop. Wait for the user.",
- "If you are unsure about anything, stop and ask. Do not make assumptions.",
- "After completing each step, stop and wait for user approval before starting the next one.",
- "Do not edit the package manifest.",
- "Do not change any handler logic, status codes, error messages, or middleware chains.",
- "Do not introduce a Router-per-file pattern unless the original already used one.",
- "Do not use sub-mounting unless the original already did.",
- "Import path depth corrections are permitted but the set of imported symbols must remain identical.",
- "If any move requires touching handler internals to compile, stop and report the coupling. Do not edit logic."
- ],
- "phase_0": {
- "name": "Ground-Truth Verification",
- "instruction": "Mandatory. Do before writing any code.",
- "steps": [
- {
- "id": "0a",
- "name": "Write baseline to file",
- "action": "Run grep -n 'app.(get|post|put|patch|delete|use)(' against the route file. This pattern matches Express-style registration; adjust it for other frameworks (Fastify, Hono, Koa). Write full output to REFACTOR_BASELINE.md in the repo root. This is the source of truth for the entire refactor."
- },
- {
- "id": "0b",
- "name": "Verify structural facts",
- "instruction": "Open the route file. Do not trust any line numbers the user gave. Verify everything yourself. Write each finding to REFACTOR_BASELINE.md under a clearly labelled section.",
- "checks": [
- {
- "id": "a",
- "name": "Entrypoint",
- "action": "Identify the exported entrypoint function signature. Confirm routes are attached directly to the app object."
- },
- {
- "id": "b",
- "name": "Module-level helpers",
- "action": "List everything defined outside the entrypoint function: limiters, schemas, middleware factories, utility functions, type declarations. Ask the user to confirm the list is complete before proceeding."
- },
- {
- "id": "c",
- "name": "In-function closures",
- "action": "Grep for any functions or closures defined inside the entrypoint function. For each, identify exactly what variables it captures.",
- "stop_condition": "If it captures anything scoped inside the entrypoint (not module-level imports), stop, write the finding to REFACTOR_BASELINE.md, and report to the user. Do not continue."
- },
- {
- "id": "d",
- "name": "Feature-flag-gated blocks",
- "action": "Grep for any if (process.env.) blocks wrapping route registrations. For each, verify it does not reference variables defined outside that block but inside the entrypoint.",
- "stop_condition": "If any external references exist, stop and report."
- },
- {
- "id": "e",
- "name": "Webhook handler",
- "action": "Confirm there is no raw-body webhook handler in this file. Cross-check against the file the user named in setup.",
- "stop_condition": "If you find a webhook here, stop immediately and report."
- },
- {
- "id": "f",
- "name": "Security middleware",
- "action": "Ask the user to name every security-critical middleware function in the file. For each, verify it does not close over variables scoped inside the entrypoint.",
- "stop_condition": "If any do, stop and report."
- },
- {
- "id": "g",
- "name": "Inline type declarations",
- "action": "List every type and interface declared in the file, their line numbers, and which handlers reference them."
- },
- {
- "id": "h",
- "name": "Async registration",
- "action": "Check whether any route registration setup code contains await expressions. Note which routes if found."
- }
- ]
- },
- {
- "id": "0c",
- "name": "Domain grouping",
- "action": "Present the full route inventory to the user. Ask them to assign each route to a domain module file. Do not assume any groupings. Write the confirmed mapping to REFACTOR_BASELINE.md."
- },
- {
- "id": "0d",
- "name": "Registration order",
- "action": "Ask the user to confirm the required middleware and route registration order. Write the confirmed order to REFACTOR_BASELINE.md. This order is load-bearing and must not change."
- }
- ],
- "gate": "Do not proceed to Phase 1 until the user has reviewed and approved REFACTOR_BASELINE.md."
- },
- "phase_1": {
- "name": "Refactor Steps",
- "steps": [
- {
- "id": "1",
- "name": "Create _middleware.ts",
- "actions": [
- "Create _middleware.ts in the routes directory.",
- "Move all module-level helpers, limiters, schemas, middleware factories, utility functions, and inline type declarations into it.",
- "Lift any in-function closures confirmed in Phase 0 to capture only module-level imports — move them to module scope here.",
- "Import everything back into the original route file so it compiles identically.",
- "No routes move in this step."
- ],
- "gate": "Run verification. Write results to REFACTOR_LOG.md. Stop and wait for approval."
- },
- {
- "id": "2",
- "name": "Extract leaf domain modules",
- "actions": [
- "Extract the domains the user marked as lowest-risk in Step 0c.",
- "One domain per approval cycle.",
- "For each: create the domain file, move its routes, update import path depths, import the registrar into the main route file and call it at the exact same position.",
- "Do not change any imported symbols."
- ],
- "gate": "Run verification after each domain. Write results to REFACTOR_LOG.md. Stop and wait for approval before the next domain."
- },
- {
- "id": "3",
- "name": "Extract hermetic feature-flag blocks",
- "actions": [
- "For each feature-flag-gated block confirmed hermetic in Phase 0:",
- "Create its domain file.",
- "Move the entire block contents into an exported registrar function.",
- "In the main route file, call the registrar inside an identical guard at the identical position."
- ],
- "gate": "Run verification. Write results to REFACTOR_LOG.md. Stop and wait for approval."
- },
- {
- "id": "4",
- "name": "Extract intermediate-risk domain modules",
- "actions": [
- "Extract the domains the user marked as medium complexity.",
- "Same process as Step 2, one domain per approval cycle."
- ],
- "gate": "Run verification after each domain. Write results to REFACTOR_LOG.md. Stop and wait for approval before the next domain."
- },
- {
- "id": "5",
- "name": "Extract SSE and streaming routes",
- "actions": [
- "Extract the domains the user identified as touching SSE or streaming.",
- "These go last because all surrounding noise is now gone.",
- "Same process as Step 2, one domain per approval cycle."
- ],
- "gate": "Run verification after each domain. Write results to REFACTOR_LOG.md. Stop and wait for approval before the next domain."
- },
- {
- "id": "6",
- "name": "Finalize index.ts",
- "actions": [
- "Do not rename the original route file.",
- "Create a new file at <routes-directory>/index.ts.",
- "Copy only the entrypoint function into it — it should contain only calls to each domain registrar in the confirmed registration order from REFACTOR_BASELINE.md.",
- "Update whatever file imports the entrypoint to point to the new location.",
- "Run verification.",
- "Only if verification passes: delete the original route file.",
- "Run verification again after deletion."
- ],
- "gate": "Write results to REFACTOR_LOG.md. Stop and wait for final approval."
- }
- ]
- },
- "verification_protocol": {
- "instruction": "Run all checks after every file change.",
- "checks": [
- {
- "name": "Test suite",
- "action": "Run the test command the user provided. All tests must pass.",
- "report": "Pass/fail/skip counts."
- },
- {
- "name": "Type-checker",
- "action": "Run the type-check command the user provided.",
- "report": "Must be zero errors."
- },
- {
- "name": "Route inventory diff",
- "action": "Grep the same pattern used in Step 0a across all files in the routes directory. Diff against REFACTOR_BASELINE.md.",
- "report": "Must be identical: same paths, same count, same order."
- },
- {
- "name": "Smoke test",
- "action": "If the user provided a smoke test command in setup, run it.",
- "report": "Pass or fail."
- }
- ],
- "failure_protocol": "If any check fails: restore the changed file immediately. Write the error to REFACTOR_LOG.md. Stop. Report to the user. Do not proceed."
- },
- "output_format": {
- "instruction": "Use this format after every step.",
- "fields": {
- "step": "Number and name",
- "files_changed": "List of created, modified, deleted files",
- "test_result": "Pass/fail and counts",
- "type_check_result": "Zero errors or N errors",
- "route_inventory_diff": "Identical or differences listed",
- "smoke_test": "Pass, fail, or not configured",
- "blockers_or_findings": "None or details"
- },
- "closing_line": "Awaiting your approval to continue."
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment