This prompt is designed for tech leads and senior engineers who have already identified a structural improvement goal and need a safe, ordered execution plan before touching any code. The ideal user has access to the relevant source files and understands the target architecture, but needs the AI to reason about cross-file dependencies, ordering constraints, and verification gates. Use this when the refactoring involves renaming symbols, extracting interfaces, reorganizing modules, changing shared contracts, or migrating patterns across a codebase where the order of changes determines whether the build stays green.
Prompt
Multi-File Refactoring Plan Generation Prompt

When to Use This Prompt
Identify the right scenarios for generating a dependency-aware, multi-file refactoring plan and understand when this prompt should not be used.
The prompt assumes you provide the refactoring goal and the relevant source files or file paths. It does not perform the refactoring itself—it produces a step-by-step plan that a developer or coding agent will execute. The output includes explicit preconditions per step (what must be true before a file is touched), verification checks (how to confirm the step succeeded), and rollback triggers (what failure signals mean the step should be reversed). This makes it suitable for high-stakes changes in production codebases, monorepos, shared libraries, and any system where a broken intermediate state is unacceptable.
Do not use this prompt for single-file refactorings where ordering is trivial, for greenfield code generation where no existing dependencies exist, or when you lack access to the source files the plan must reference. The prompt also should not be used as a substitute for actual build verification—it plans the verification steps but does not run them. For changes involving database schema migrations, infrastructure-as-code, or polyglot codebases where dependencies cross language boundaries, supplement the prompt with explicit cross-system dependency documentation. After generating the plan, always review the ordering for deadlocks, validate preconditions against your actual build system, and run the verification checks before marking any step complete.
Use Case Fit
Where the Multi-File Refactoring Plan Generation Prompt works and where it does not. Use these cards to decide if this prompt fits your workflow before wiring it into a pipeline.
Good Fit: Structured Refactoring with Known Scope
Use when: you have a clear refactoring goal (e.g., extract interface, break circular dependency, migrate a type system) and the affected module boundaries are understood. The prompt excels at producing ordered step plans with preconditions and verification checks. Guardrail: always provide the prompt with a concrete list of target files or a dependency graph—vague goals produce vague plans.
Bad Fit: Exploratory Cleanup Without a Goal
Avoid when: the task is open-ended code cleanup like 'improve the codebase' or 'reduce technical debt everywhere.' The prompt needs a specific structural change to reason about ordering and dependencies. Without a target, it generates generic advice rather than actionable per-file plans. Guardrail: decompose broad cleanup into specific, scoped refactoring tasks before invoking this prompt.
Required Inputs: Dependency Graph and Change Intent
What to watch: the prompt cannot infer your full dependency graph from a few file paths. If you omit build-order constraints, transitive dependencies, or test coverage maps, the plan will miss ordering violations. Guardrail: supply a machine-readable dependency graph (e.g., module imports, build targets, or test-to-source mappings) alongside the change description. The plan quality is bounded by the graph quality.
Operational Risk: Plan Drift During Execution
What to watch: a refactoring plan generated before execution may become stale if the codebase changes during implementation. Steps that assume a clean build may fail if another merge lands first. Guardrail: re-run the plan generation after rebasing onto the latest main branch, and include a pre-step that verifies the build is green before any refactoring step begins.
Operational Risk: Intermediate State Breakage
What to watch: multi-step refactoring plans can leave the codebase in a non-compiling or broken state between steps if ordering is wrong or a step is skipped. This breaks bisectability and blocks other developers. Guardrail: require that every step in the plan ends with a green build and passing tests. Add explicit rollback triggers for any step that fails verification.
Operational Risk: Hallucinated Dependencies
What to watch: the model may invent dependencies between files that do not exist, or miss real dependencies that cross module boundaries through reflection, config, or runtime wiring. Guardrail: validate the generated plan against a static analysis tool or build graph. Flag any dependency in the plan that cannot be confirmed by tooling, and require human review for dynamic or reflection-based dependencies.
Copy-Ready Prompt Template
A ready-to-use prompt for generating a step-by-step, multi-file refactoring plan with dependency ordering, preconditions, and verification checks.
The following prompt template is designed to be pasted directly into your AI coding agent or LLM interface. It instructs the model to act as a senior software architect and produce a structured, actionable refactoring plan. The plan will decompose a high-level refactoring goal into an ordered sequence of file-level changes, ensuring that each step's preconditions are met by prior steps and that the codebase remains in a compilable, testable state throughout the process.
markdownYou are a senior software architect planning a multi-file refactoring. Your task is to produce a detailed, step-by-step plan that can be executed safely and reviewed by a human engineering lead. **Refactoring Goal:** [REFACTORING_GOAL] **Repository Context:** - Primary Language & Build System: [LANGUAGE_AND_BUILD_SYSTEM] - Key Files/Modules Involved: [KEY_FILES_AND_MODULES] - Existing Test Infrastructure: [TEST_INFRASTRUCTURE] - Known Constraints: [CONSTRAINTS] **Output Requirements:** Generate a refactoring plan as a JSON object with the following structure. Do not include any text outside the JSON object. { "goal_summary": "A concise restatement of the refactoring goal.", "overall_risk_assessment": "Low|Medium|High", "steps": [ { "step_id": 1, "description": "A clear, actionable description of the change.", "files_to_modify": ["path/to/file1.ts", "path/to/file2.ts"], "preconditions": [ "All prior steps must be completed and verified.", "The project must build successfully.", "Existing unit tests for [specific module] must pass." ], "verification_checks": [ "Run command: [specific build or test command]", "Manually verify that [specific behavior] is unchanged." ], "rollback_instructions": "Use `git revert` on the commit for this step. If this step is part of a larger commit, manually revert the changes to the listed files." } ], "final_verification": { "command": "[e.g., npm run test:all]", "expected_outcome": "All tests pass and the build is green." } } **Critical Constraints:** - **Ordering:** A step's preconditions MUST be satisfied by the completion of all previous steps. Do not create a step that depends on a change that hasn't been made yet. - **Atomicity:** Each step should be as small as possible while keeping the project in a buildable state. Avoid combining unrelated changes in a single step. - **Verification:** Every step must include a concrete verification check (e.g., a specific command to run, a test suite to execute, or a manual check to perform). - **Rollback:** Every step must include a clear, safe rollback instruction.
To adapt this template, replace the square-bracket placeholders with your specific context. The [REFACTORING_GOAL] should be a high-level description of the change, such as "Extract the authentication logic from UserService into a dedicated AuthService." The [KEY_FILES_AND_MODULES] should list the primary files you know are involved, giving the model a starting point for its dependency analysis. The [CONSTRAINTS] field is critical for grounding the plan in reality—include details like "Must maintain backward compatibility with the v1 API" or "Cannot introduce new third-party dependencies." After receiving the output, you should validate the plan's ordering logic before executing any steps, as described in the full playbook.
Prompt Variables
Each placeholder required by the Multi-File Refactoring Plan Generation Prompt. Validate these inputs before sending the prompt to avoid hallucinated file paths, missing dependencies, or unsafe ordering.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[REFACTORING_GOAL] | Describes the structural improvement to be made | Extract shared validation logic into a common utility module | Must be a single, clear objective. Reject if it contains multiple unrelated goals or is a feature request rather than a structural change. |
[REPOSITORY_CONTEXT] | Provides file tree, dependency graph, and symbol references | JSON object with keys: fileTree, dependencyGraph, symbolIndex | Must contain at least one file path and one dependency edge. Reject if the dependency graph is empty when fileTree has more than one file. |
[AFFECTED_FILES] | List of files known to require changes | ["src/auth/login.ts", "src/auth/signup.ts", "src/shared/validators.ts"] | Each path must exist in [REPOSITORY_CONTEXT].fileTree. Reject if any path is not found or if the list is empty. |
[CONSTRAINTS] | Rules that must not be violated during refactoring | Do not change public API signatures. Maintain backward compatibility with existing tests. | Must be a non-empty string. Parse for contradictory constraints. Flag if a constraint conflicts with [REFACTORING_GOAL]. |
[TEST_SUITE_MAP] | Maps files to their associated test files | {"src/auth/login.ts": ["tests/auth/login.test.ts"]} | Each key must exist in [AFFECTED_FILES]. Each test file path must exist in [REPOSITORY_CONTEXT].fileTree. Warn if any affected file has zero mapped tests. |
[ROLLBACK_TRIGGERS] | Conditions that should trigger step reversal | Any step that causes a test failure in a dependent module must be rolled back before proceeding. | Must define at least one concrete, verifiable condition. Reject vague triggers like 'if something goes wrong'. |
[OUTPUT_SCHEMA] | Expected structure for the refactoring plan | JSON array of steps, each with: stepId, description, fileChanges, preconditions, verification, rollbackSteps | Must be a valid JSON Schema or TypeScript interface. Validate that it includes required fields: stepId, fileChanges, preconditions, verification. |
Implementation Harness Notes
How to wire the Multi-File Refactoring Plan Generation Prompt into an application or coding agent workflow.
This prompt is not a chat command; it is a planning step inside a larger refactoring pipeline. The typical harness calls this prompt after a change request is parsed and before any file is modified. The application layer must supply the repository map, the change intent, and any static analysis results as structured inputs. The prompt returns a plan, not code. That plan must be validated, ordered, and reviewed before execution begins.
Wire the prompt into a state machine with clear gates. First, assemble the input context: a dependency graph (from a build tool or static analyzer), a file inventory with symbol tables, and the refactoring goal expressed as a structured change description. Feed these into the prompt template as [DEPENDENCY_GRAPH], [FILE_INVENTORY], and [REFACTORING_GOAL]. The model returns a JSON plan with steps, preconditions, verification checks, and rollback triggers. Validate the output immediately: check that every step's preconditions reference files or symbols that exist in the input inventory, that no step depends on a later step's output, and that verification checks are testable. If validation fails, retry with the validation errors appended to [CONSTRAINTS] or escalate for human review.
For production use, log every plan generation attempt with the input hash, model version, and validation result. Store the validated plan as an immutable artifact before execution begins. When the plan executes, track each step's completion state and verify post-conditions before proceeding. If a verification check fails, halt execution and trigger the rollback sequence defined in the plan. Never let the agent continue past a failed verification without human approval. The prompt itself is stateless; the harness owns all execution state, retry logic, and safety gates.
Expected Output Contract
Validate the refactoring plan output against this contract before passing it to the execution agent. Each field must satisfy the listed validation rule; reject or repair the plan if any required field is missing or invalid.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
plan_title | string | Non-empty string with max 120 characters. Must summarize the refactoring intent. | |
steps | array of objects | Array length >= 1. Each element must conform to the step schema defined in [STEP_SCHEMA]. | |
steps[].step_id | string | Unique within the array. Format: step-N where N is a 1-indexed integer matching array position. | |
steps[].description | string | Non-empty string describing the change. Must reference at least one file path from [TARGET_FILES]. | |
steps[].preconditions | array of strings | Each string must reference a prior step_id or an external condition verifiable by the execution harness. | |
steps[].verification | string | Must include a specific, executable check (e.g., 'Run [TEST_COMMAND] and expect exit code 0'). Cannot be a generic statement like 'verify it works'. | |
steps[].rollback | string | Must describe a reversible action or a git revert command. If the step is not independently reversible, must state 'Rollback requires reverting to step [N]'. | |
ordering_constraints | array of strings | Each string must encode a dependency rule (e.g., 'step-2 depends on step-1'). Every step_id referenced must exist in the steps array. |
Common Failure Modes
Multi-file refactoring plans fail in predictable ways. These cards cover the most common failure modes, why they happen, and how to guard against them before the plan reaches your editor.
Ordering Violations
What to watch: The plan schedules a step that depends on a change from a later step, causing a broken intermediate state. This happens when the model fails to trace transitive dependencies across files. Guardrail: Validate the plan by checking that every precondition references a step that appears earlier in the sequence. Run a topological sort on the declared dependencies and flag any cycles or forward references.
Hallucinated Dependencies
What to watch: The plan claims File A depends on File B when no such dependency exists in the codebase. This bloats the plan with unnecessary ordering constraints and can cause the agent to modify files that don't need changes. Guardrail: Require the prompt to cite specific import statements, function calls, or type references for each claimed dependency. Cross-check every cited dependency against the actual codebase before accepting the plan.
Missing Transitive Dependents
What to watch: The plan identifies direct dependents of a changed file but misses indirect dependents two or more hops away. This leaves the codebase in a state where a downstream consumer breaks because an intermediate file changed its contract. Guardrail: Run a dependency graph traversal tool against the actual codebase and diff the results against the plan's file list. Flag any file in the tool's output that is absent from the plan.
Incomplete Verification Gates
What to watch: The plan includes verification steps that are too vague to be useful, such as 'verify the build passes' without specifying which build command or which files must compile. This leads to false confidence when the verification step is skipped or misinterpreted. Guardrail: Require each verification step to include a specific command, expected exit code, and a list of files that must be checked. Reject plans where any verification step lacks a concrete, executable check.
Rollback Blind Spots
What to watch: The plan provides rollback steps that assume all prior steps succeeded, but offers no guidance for partial rollback when only some steps were applied. This leaves the operator stranded if a mid-plan failure occurs. Guardrail: Require the plan to include a rollback trigger condition and a per-step undo action. Validate that each undo action restores the file to its pre-step state without depending on later steps having been applied.
Scope Creep in Refactoring Steps
What to watch: A step labeled 'rename getCwd to getCurrentWorkingDirectory' also reformats the file, changes a log level, and removes a comment. This makes the plan unreviewable and increases the blast radius of any rollback. Guardrail: Add a constraint to the prompt that each step must address exactly one semantic change. Validate the plan by checking that no step modifies more than one category of change per file.
Evaluation Rubric
Use this rubric to evaluate the quality of a multi-file refactoring plan before shipping the prompt to production. Each criterion targets a specific failure mode common in AI-generated patch plans.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Step Ordering Correctness | No step depends on a change from a later step. All preconditions are satisfied by prior steps or initial state. | A step references a symbol, file, or contract that is introduced in a subsequent step. | Topological sort validation: extract dependency graph from plan steps and verify no forward edges exist. |
Precondition Completeness | Every step lists all preconditions required for that step to succeed (file state, build status, test pass). | A step fails during simulation because an unstated precondition is not met (e.g., a file must exist but was not created yet). | Simulated dry-run: for each step, check that all referenced files, symbols, and build states exist in the state produced by prior steps. |
Verification Check Coverage | Every step includes at least one verification check (build, test, lint, or manual review) appropriate to the change type. | A step that modifies public API surface has no verification check, or a step that touches build config has no build verification. | Schema check: confirm each step object has a non-empty verification field. Spot-check that verification type matches change risk level. |
Rollback Trigger Specificity | Every step with side effects defines a concrete, measurable rollback trigger (e.g., test failure, build break, specific error code). | Rollback triggers are vague (e.g., 'if something goes wrong') or missing for steps that modify shared state. | Keyword extraction: confirm rollback trigger fields contain measurable conditions (error codes, test names, file hashes) rather than natural-language hand-waving. |
File Scope Accuracy | Every file listed in the plan is actually affected by the refactoring. No hallucinated files or missed affected files. | Plan includes files that do not exist in the repository, or omits files that static analysis shows are affected by the change. | Cross-reference plan file list against repository file tree and dependency graph. Flag files not found. Flag affected files not listed. |
Dependency Impact Awareness | Plan identifies downstream consumers of changed APIs and includes consumer update steps or explicit deferral rationale. | A public API change is planned with no mention of callers, importers, or dependents that static analysis confirms exist. | For each API-level change in the plan, query the dependency graph for consumers. Flag any change with consumers but no consumer step or deferral note. |
Intermediate State Safety | No step leaves the codebase in a state that would fail build, break tests, or corrupt data if execution stopped mid-plan. | A step removes a function definition before all call sites are updated, or changes a schema before all writers are migrated. | Simulate partial execution: for each step N, evaluate whether the codebase state after step N is valid (builds, tests pass). Flag any invalid intermediate state. |
Human Approval Gate Placement | Steps with high risk (schema changes, public API breaks, data migrations) include explicit human approval gates before execution. | A breaking API change or data migration step has no approval gate, or approval is placed after the change rather than before. | Risk classification check: tag each step by risk level. Confirm all high-risk steps have an approval gate field set to true and positioned before the change action. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and minimal validation. Focus on getting a readable plan for a single language or framework you know well. Drop the rollback triggers and verification checks if you're just exploring feasibility.
Simplify the output schema to a flat list of steps with file paths and descriptions. Skip the precondition/postcondition fields.
Watch for
- Ordering violations where step N references a symbol that step N-1 hasn't created yet
- Plans that suggest editing generated files or vendored dependencies
- Missing intermediate build verification—the plan assumes each step compiles without checking

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us