Custom Slash Commands and Subagents for Multi-File Refactors in Claude Code
A single prompt can't safely refactor a multi-file codebase. Here's how repo-scoped slash commands and staged subagents in Claude Code fix that, with git safety gates included.
Custom Slash Commands and Subagents for Multi-File Refactors in Claude Code
If you've pointed Claude Code at a single file and asked it to "refactor this to use TRPC," you've probably seen the failure mode: the endpoint gets rewritten, the request handler looks clean, and then npm run build throws twelve errors because nothing downstream got touched. The frontend still calls the old fetch() route. The Zod schema doesn't match the old interface. Nobody told the test fixtures.
This isn't a model intelligence problem. It's a scope problem. A single generic prompt asks the agent to hold the entire dependency graph of a change in its head at once, across files it hasn't necessarily read, and then execute it in one pass with no checkpoint. That's a lot to ask, even of a strong model. The fix isn't a smarter prompt — it's a smaller one, repeated with structure.
Where monolithic prompting actually breaks
Three failure modes show up over and over in multi-file refactors, and they're worth naming because each has a different root cause:
Partial file edits. The agent updates the service implementation but leaves the TypeScript interface, the database schema, or the mock test fixtures untouched. It optimized for "make this file correct" instead of "make this change correct."
Hallucinated import paths. In a monorepo, an agent that hasn't been told about your package aliases will guess a relative path like ../../components/ui instead of @myorg/ui. It's not being careless — it just doesn't know your tsconfig paths unless you've put that context in front of it.
Broken test suites. The agent generates code, declares victory, and never runs tsc or the test runner. Compilation errors and failing assertions only surface when you run the build yourself, usually after the agent has already moved on.
None of these are things a longer, more detailed single prompt fixes reliably. They're things a process fixes.
Repo-scoped slash commands: codify the process once
Claude Code lets you define reusable, repository-scoped commands as Markdown files in .claude/commands/. Instead of re-explaining your refactor standards every session, you write them once and invoke them by name:
<!-- .claude/commands/refactor-endpoint.md -->
---
description: Refactors a REST endpoint to a TypeScript TRPC procedure with validation and test updates.
argument_schema:
- name: endpoint_path
description: Relative path to the route file (e.g., src/api/users.ts)
---
# Refactoring Objective: Convert REST to TRPC
You are an expert fullstack TypeScript engineer. Refactor the specified endpoint: $ARG_ENDPOINT_PATH.
## Multi-Phase Execution Protocol:
1. **Phase 1 (Analysis):** Inspect the target file and map all dependencies, types, and database queries.
2. **Phase 2 (Type & Router Definition):** Create the new TRPC router definition with strict Zod validation schemas.
3. **Phase 3 (Frontend Call Updates):** Locate all client-side fetch() references and update them to use the TRPC hook.
4. **Phase 4 (Verification):** Run npm run type-check and npm test. Fix any compilation errors before finalizing.
The useful part here isn't the YAML frontmatter — it's Phase 4. Baking "run the type-checker and the test suite before you finish" directly into the command definition means it happens every time, not just when you remember to ask for it.
Split the job into subagent stages instead of one context window
Even with a good command, cramming analysis, code generation, and verification into a single context window pushes an agent toward shortcuts, especially on a large refactor. Splitting the work into stages, each with a narrower job, holds up better in practice:
| Stage | Job | What it catches |
|---|---|---|
| 1. Architect / Planner | Scans the codebase, builds a file-dependency refactor graph | Every file the change touches, before any code is written |
| 2. Code Transformation | Executes discrete AST edits — updates interfaces, exports, imports | Prevents partial edits by working off the Stage 1 map |
| 3. Verification / Test Runner | Runs tsc --noEmit and the Vitest suite |
Broken builds and failing tests, before you ever see the diff |
Stage 1 matters more than it looks like it should. If the planner never builds the dependency graph, Stage 2 is back to guessing which files to touch — you've just added ceremony around the same monolithic-prompt problem. The dependency graph is the actual fix; the staging is what makes the graph get built and used before code changes start.
Git safety gates: never let the agent commit for you
However clean the pipeline, the last stage should hand control back to you, not to git commit. Two things are worth hard-requiring in the command definition:
- No auto-commit. The agent presents a summary table of modified files and a unified diff. You review it. This is the actual safety net — everything upstream (planning, transformation, verification) is there to make this diff worth trusting, not to replace your review of it.
- A lint pass at the end. Running
npx eslint --fixafter the transformation stage keeps formatting consistent without you having to police it manually.
The comparison, concretely
| Task type | Monolithic prompting | Slash command + subagent pipeline |
|---|---|---|
| API migration | Misses frontend caller references | Dependency scan across the repo catches them |
| Type refactoring | Silently substitutes any where it gets stuck |
Hard gate on tsc --noEmit — it can't pass silently |
| Database schema | Migration files drift out of sync with the ORM | Schema, ORM, and query layers are updated as one coordinated step |
The pattern across all three rows is the same: monolithic prompting fails silently, and the pipeline fails loudly, at a stage where you can still do something about it. That's the whole value proposition — not that the agent gets smarter, but that the process stops letting mistakes travel downstream unnoticed.
If you're running Claude Code on anything bigger than a single-service repo, the ten minutes it takes to write a .claude/commands/ file and a three-stage pipeline pays for itself the first time it catches a desynced schema before it hits your test suite.
Accelerate your AI Agents & Developer Tools Modernization Roadmap
Need custom architecture auditing, automated OpenAPI contract generation, or zero-downtime microservice migration guidance for your engineering team?
Frequently Asked Questions
Why does a single prompt fail at multi-file refactoring in Claude Code?
A generic prompt tends to update the file you pointed at and stop there. It skips the TypeScript interfaces, database schemas, and test fixtures that depend on it, guesses at import paths in monorepos instead of using package aliases, and rarely runs a build or test step to confirm the change actually compiles.
Do custom slash commands replace the need for testing after a refactor?
No. The command should end by running tsc --noEmit and the test suite as an explicit gate, and the agent should stop and fix errors before calling the job done — not assume the generated code compiles.
Subscribe to RenovateAPI
Get weekly architectural guides, API refactoring strategies, and technical SEO updates delivered directly to your inbox.
Discussion (2)
Extremely helpful breakdown of the Strangler Fig pattern! We're currently refactoring a legacy Java monolith at work and the OpenAPI gateway routing tips saved us weeks of experimentation.
The schema JSON-LD and FAQ block structure really helps with indexing. Great technical detail on entity mentions too.
Suggested Related Articles
Your AI Coding Agent Doesn't Need All 30 Skills Loaded at Once
Two-tier progressive discovery keeps coding agents like Claude Code fast by loading skill instructions only when a task actually needs them.
Building a Google Maps Business Location Picker in React (With Nearby Business Search)
A practical React + TypeScript guide to a Google Maps location picker: reverse geocoding, nearby business discovery via Places API (New), custom markers, and the errors that trip everyone up.
The AI Wrote Code That Compiles, Runs, and Is Wrong: A Debugging Workflow
A practical three-tier workflow for catching the subtle bugs, boundary omissions, and security gaps AI coding assistants keep shipping.