Published version comparison

Behavior-Preserving Legacy Code Refactor with Codex

1.0.02.0.0

Source version 1.0.0

Published

Initial: Initial published snapshot.

Destination version 2.0.0

Published

Major: Replace the legacy Refactor Without Breaking Existing Logic Prompt template with a domain-specific input, evidence, authority, safety, workflow, output, and verification contract.

Public field comparison

Title Changed

1.0.0
Refactor Without Breaking Existing Logic Prompt
2.0.0
Behavior-Preserving Legacy Code Refactor with Codex

Summary Changed

1.0.0
Refactor legacy code in small, reversible steps while preserving behavior and documenting regression checks.
2.0.0
Use Codex to refactor risky legacy code in small, reversible increments while preserving observable behavior, strengthening characterization coverage, and producing evidence-backed regression, rollback, and review records.

Share-purpose line Changed

1.0.0
2.0.0
Use this to refactor legacy code without silently changing established behavior, APIs, side effects, errors, data contracts, or operational expectations.

Best use cases Changed

1.0.0
Refactor Without Breaking Existing
Without Breaking Existing Logic
Code Review Planning
Regression Testing
Debugging Plan
Release Verification
2.0.0
Behavior-preserving refactoring of risky legacy code
Incremental decomposition of tightly coupled modules
Characterization testing before structural changes
Refactoring code with weak or incomplete regression coverage
Separating side effects from business logic without changing outcomes
Reducing duplication while preserving public interfaces and data contracts
Preparing high-risk refactors for code review
Regression investigation after a structural code change
Pre-release verification of behavior-preserving refactors
Rollback planning for refactors affecting production-critical code

Variables Changed

1.0.0
Goal or task
Current context
Constraints
Files, data, or examples
Definition of done
2.0.0
Refactor objective
Codebase evidence
Behavior contract
Constraints and authority
Verification commands

How to Use Changed

1.0.0
Replace every bracketed placeholder before running. Give the model enough context to inspect assumptions, ask only blocking questions, and produce a concrete deliverable. For code prompts, include relevant files, errors, logs, and test commands.
2.0.0
Open Codex and replace every bracketed variable with project-specific information. Provide the relevant source files, interfaces, tests, logs, failure reproductions, repository conventions, and authorized verification commands. Define the behavior that must not change and state exactly which files, environments, and actions Codex may inspect or modify. Run the prompt, then review the proposed or executed changes, regression evidence, unresolved risks, and rollback plan before authorizing merges, deployments, releases, or broader changes.

Example use case Changed

1.0.0
Use this when you need a production-ready refactor result in Codex & Coding, not a generic brainstorm. The expected output should include findings, implementation steps, risks, and verification checks.
2.0.0
A team needs to split a tightly coupled legacy order-calculation module into smaller testable components without changing totals, rounding, discounts, tax handling, exception behavior, public interfaces, persistence effects, or downstream integrations.

They provide Codex with the affected repository files, current tests, representative inputs and outputs, known production behavior, repository conventions, recent failure evidence, and the exact commands it may run.

Codex first establishes the behavioral baseline and identifies gaps requiring characterization tests. It then proposes a sequence of small reversible changes, verifies each authorized increment against the protected-behavior matrix, records any differences from baseline, and produces a review and rollback record without claiming that unexecuted tests, approvals, merges, or deployments occurred.

Difficulty Unchanged

1.0.0
Expert
2.0.0
Expert

Tool Unchanged

1.0.0
Codex
2.0.0
Codex

Prompt type Unchanged

1.0.0
refactor
2.0.0
refactor

Tags Changed

1.0.0
codex
refactor
Codex & Coding
regression
legacy
2.0.0
codex
refactoring
legacy-code
behavior-preservation
regression-testing
characterization testing
code-review
rollback-planning

SEO title Changed

1.0.0
Refactor Without Breaking Existing Logic Prompt | AMO.ng
2.0.0
Behavior-Preserving Legacy Code Refactor with Codex | Amo.ng

SEO description Changed

1.0.0
Refactor legacy code in small, reversible steps while preserving behavior and documenting regression checks.
2.0.0
Use Codex to refactor legacy code safely with behavior contracts, characterization tests, regression evidence, reversible changes, and rollback checks.

Prompt-body line comparison

Removed Added Unchanged context

Act as a senior Codex & Coding specialist using Codex. Your task is: [Goal or task].
Refactor the supplied legacy code toward [Refactor objective] without intentionally changing established observable behavior.

Context:
- Current situation: [Current context]
- Constraints: [Constraints]
- Available materials: [Files, data, examples, URLs, logs, notes]
- Success criteria: [Definition of done]
Required context:
- Codebase evidence and materials available for inspection: [Codebase evidence]
- Behavior that must remain stable, including known exceptions and edge cases: [Behavior contract]
- Technical constraints, permitted actions, approval gates, protected areas, and environment boundaries: [Constraints and authority]
- Available test, build, lint, type-check, benchmark, reproduction, or verification commands: [Verification commands]

Workflow:
1. Restate the objective in operational terms and identify any missing information that would block a reliable answer.
2. Make reasonable assumptions only when they are low risk, and label them clearly.
3. Produce the main deliverable for "Refactor Without Breaking Existing Logic Prompt" with enough detail that a skilled operator can execute it immediately.
4. Include edge cases, failure modes, dependencies, and tradeoffs that a junior prompt would usually miss.
5. Add a verification checklist with concrete tests, review questions, metrics, or acceptance criteria.
6. End with the smallest safe next action.
Use Codex only within the files, repository context, tools, and execution permissions actually available in the current session.

Output format:
- Executive summary
- Detailed plan or implementation
- Risks and mitigations
- Verification checklist
- Next action
Codex may inspect supplied code, trace call paths, propose patches, edit explicitly permitted files, and run authorized commands only when those capabilities are actually available.

Do not give generic advice. Optimize for a production-quality refactor outcome.
Do not imply access to files, repository history, services, secrets, databases, CI/CD systems, production environments, monitoring systems, or external resources that were not supplied or made accessible.

Evidence and behavior rules:
1. Separate supplied facts, direct code observations, command results, assumptions, hypotheses, unknowns, unsupported claims, and conflicting evidence.
2. Cite the relevant file, symbol, function, class, route, query, interface, configuration, or test for material code observations.
3. For executed commands, record the exact command, relevant environment, exit status, and material result. Never describe a test, build, migration, lint check, benchmark, or deployment check as passing without execution evidence.
4. Treat undocumented behavior as unknown until supported by tests, call-site analysis, runtime evidence, logs, an authoritative specification, or another observable contract.
5. When requirements and observed behavior conflict, identify the conflict explicitly. Do not silently choose which behavior to preserve when that decision could affect users, data, integrations, security, money, or production behavior.
6. If the refactor objective, affected code, protected behavior, or authority boundary is too ambiguous for safe implementation, ask only the questions that block progress. Until resolved, provide an inspection and characterization plan rather than claiming implementation.

Behavior-preservation contract:
Treat behavior as more than returned values.

Where relevant, preserve or explicitly account for:
- public APIs, method signatures, routes, commands, events, and interfaces;
- input validation and normalization;
- return values and serialized output;
- ordering and deterministic behavior;
- exceptions, error classes, status codes, and externally visible error messages;
- persistence behavior, transaction boundaries, database writes, and query semantics;
- side effects, emitted events, queues, notifications, files, caches, and network calls;
- retry, timeout, idempotency, and duplicate-processing behavior;
- authentication and authorization behavior;
- concurrency assumptions and shared mutable state;
- null, empty, malformed, boundary, and extreme inputs;
- rounding, precision, locale, timezone, encoding, and date behavior where applicable;
- backward compatibility with callers, consumers, integrations, stored data, and configuration;
- resource acquisition, cleanup, locking, and failure recovery;
- contractual performance or memory characteristics when they are part of expected behavior.

Do not assume every item applies. Identify which dimensions are relevant to the supplied code and explain why.

Authority and safety boundaries:
- Modify only files and symbols explicitly within scope.
- Do not access, expose, copy, or log secrets, credentials, personal data, tokens, private files, or unrelated sensitive information.
- Do not deploy, merge, publish, approve, release, delete data, alter production systems, execute destructive commands, rewrite shared history, or bypass review controls.
- Do not change public APIs, persistence formats, schemas, authentication behavior, authorization rules, dependency versions, generated artifacts, externally observable errors, or contractual performance characteristics without explicit authorization.
- Do not mix a structural refactor with an unrelated feature change, dependency upgrade, formatting sweep, schema change, or behavioral correction.
- If an apparent bug is discovered, separate the defect from the refactor. Preserve the current behavior unless the user explicitly authorizes a behavior change.
- Preserve pre-existing failing-test evidence. Do not report a pre-existing failure as a regression introduced by the refactor or as a successful fix.
- Use small, reviewable, reversible increments.
- Stop implementation and request human review when protected behavior cannot be characterized, verification is unreliable, required access is unavailable, sensitive data may be exposed, a proposed action is destructive or difficult to reverse, or the requested refactor conflicts with the agreed behavior contract.

Work through the refactor in this order:

1. Establish scope and authority
Identify the exact objective, files, symbols, callers, integrations, environments, permitted actions, prohibited actions, and approval gates.

State what Codex can actually inspect or execute.

2. Establish the behavioral baseline
Map relevant:
- entry points;
- callers and consumers;
- dependencies;
- state mutations;
- side effects;
- persistence boundaries;
- external calls;
- events and queues;
- error paths;
- concurrency assumptions;
- configuration dependencies;
- externally observable outputs.

Record unknowns instead of filling gaps with assumptions.

3. Build the protected-behavior matrix
Translate the supplied behavior contract and directly observed behavior into explicit invariants.

For each invariant record:
- behavior to preserve;
- supporting evidence;
- affected path or consumer;
- important edge cases;
- existing verification;
- missing verification;
- confidence.

Include normal behavior and relevant failure behavior.

4. Identify characterization gaps
Determine which protected behaviors are not adequately covered.

Where authorized, propose or add characterization tests before structural edits.

Each characterization test must state:
- behavior being frozen;
- setup/input;
- action;
- expected observable result;
- why the test would detect a regression.

Do not encode a suspected defect as intended behavior without flagging it for human decision.

5. Assess refactor risk
Identify risks such as:
- tight or cyclic coupling;
- hidden globals;
- static state;
- reflection;
- dynamic dispatch;
- metaprogramming;
- framework magic;
- mutable shared state;
- database or network side effects;
- timing dependencies;
- concurrency;
- weak tests;
- generated code;
- code outside the available inspection scope;
- compatibility obligations.

Rank the material risks and connect each one to a verification or containment strategy.

6. Design the smallest reversible sequence
Prefer behavior-neutral transformations such as:
- extract function or method;
- extract class or component;
- isolate side effects;
- introduce a seam around an external dependency;
- clarify naming;
- reduce duplication;
- split responsibilities;
- replace complex conditionals incrementally;
- move code without rewriting it unnecessarily.

Keep structural cleanup separate from behavior changes.

For every proposed increment state:
- protected invariant;
- exact files or symbols;
- expected structural change;
- regression risk;
- verification step;
- rollback method;
- dependency on earlier increments.

7. Implement only authorized increments
If editing is permitted, make one bounded change at a time.

After each increment:
- inspect the diff;
- identify unintended changes;
- check public interfaces;
- check control flow;
- check exceptions and error handling;
- check persistence and state mutation;
- check dependency/configuration changes;
- check unrelated formatting churn;
- run the authorized focused verification.

Do not continue past an unexplained behavioral delta.

If editing is not permitted, provide the proposed patch or implementation instructions and label them as unexecuted.

8. Verify behavior preservation
Run only authorized verification commands.

Compare baseline and candidate results.

Where relevant, verify:
- characterization tests;
- existing regression tests;
- changed branches;
- boundary and malformed inputs;
- exceptions and failure paths;
- serialization;
- database or state effects;
- side effects;
- API/interface compatibility;
- idempotency;
- concurrency-sensitive paths;
- build, lint, type-check, or static-analysis results;
- performance checks where contractual.

If a command cannot be executed, provide the exact proposed command and mark the result as unavailable.

Never convert unavailable evidence into a passing result.

9. Reconcile every observed delta
For each difference between baseline and candidate behavior, classify it as:
- expected structural-only change;
- authorized behavior change;
- pre-existing behavior;
- regression;
- unknown;
- blocked from verification.

A behavior-preserving refactor is acceptable only when protected behavior remains supported by evidence and no material unexplained regression remains.

10. Prepare rollback, review, and release handoff
Identify:
- exact changes or commits to revert;
- any non-code state requiring restoration;
- unresolved behavior questions;
- remaining coverage gaps;
- review focus areas;
- approval gates;
- release prerequisites;
- post-release verification where applicable;
- rollback triggers;
- smallest safe next action.

Do not claim deployment or release readiness while required evidence or approval is missing.

Return exactly these sections:

1. Scope and authority
- Refactor objective
- In-scope files and symbols
- Excluded areas
- Available evidence and tools
- Permitted actions
- Prohibited actions
- Required approvals
- Blocking unknowns

2. Evidence ledger
For every material claim:
- Claim
- Classification: supplied fact / code observation / command result / assumption / hypothesis / unknown / conflicting evidence
- Evidence source
- Confidence
- Conflict or uncertainty

3. Protected-behavior matrix
For each invariant:
- Protected behavior
- Evidence
- Affected callers or paths
- Relevant edge cases
- Baseline verification
- Candidate verification
- Status

4. Regression-risk assessment
For each material risk:
- Risk
- Why it matters
- Affected surface
- Likelihood
- Impact
- Containment
- Verification

5. Increment plan
For each increment:
- Order
- Change
- Rationale
- Files or symbols
- Dependency
- Risk
- Verification
- Rollback
- Status: proposed / executed / blocked / unavailable / unverified

6. Patch record
For executed edits only:
- Changed files
- Actual change made
- Material diff summary
- Unrelated changes observed

For work not executed:
- Clearly label it Proposed patch
- Do not present it as applied

7. Verification record
For every check:
- Baseline observation
- Exact command or check
- Expected result
- Actual result if executed
- Exit status if available
- Evidence
- Disposition: passed / failed / blocked / unavailable / not run

8. Behavior-delta reconciliation
For every observed difference:
- Delta
- Baseline
- Candidate
- Classification
- Explanation
- Decision or required approval

9. Residual risk and handoff
- Unresolved behavior questions
- Coverage gaps
- Remaining risks
- Review focus
- Required approvals
- Rollback trigger
- Release considerations
- Smallest safe next action

Completion language must match evidence.

Use:
- requested for user intent;
- proposed for work not executed;
- executed only for directly observed edits or commands;
- passed only for checks with supporting execution evidence;
- unavailable when Codex lacks access or capability;
- unverified when evidence is insufficient.

Never state that the refactor is fixed, regression-free, tested, approved, merged, deployed, released, production-ready, or complete unless that exact state occurred and the evidence supporting it is included.