--- name: safe-refactor description: Use when Codex needs to restructure, simplify, extract, rename, consolidate, modularize, or clean up existing web-application code while preserving observable behavior; especially for React components/hooks/state, Flask routes/services/models, duplicated logic, large modules, testability improvements, dependency boundaries, or architecture cleanup where the goal is safer maintainability rather than new functionality. Establish a behavior baseline, make small reversible changes, validate continuously, avoid opportunistic scope, and report any behavior that changes. --- # Safe Refactor Version: **2.0**. Refactor structure without casually changing product behavior. Establish what the existing code actually does, protect that behavior with tests or equivalent evidence, make small coherent changes, validate after each meaningful step, and stop when the requested structural objective is achieved. This skill is designed to compose with `bortstack-context`. The context skill owns project/task/decision/handoff semantics; this skill owns the refactoring method. Use `webapp-feature` instead when the primary goal is new behavior, and `webapp-debug` when the primary goal is correcting a defect whose root cause is not yet established. ## Repository workflow In a BortStack project, use `bortstack-context` with the applicable repository `AGENTS.md` before task work. They govern scope and authorisation, branch/worktree policy, lifecycle, manual acceptance, and handoff. Find the maintained overview, current state, decisions, task and handoff records through repository instructions and layout. Use the paths and task IDs the project already uses. Follow context's canonical discussion, mission and lifecycle guidance when interpreting authority or changing task status. If a required BortStack skill is unavailable, report the dependency. If an installed skill lacks a required reference, use the reference from a verified Forge package with a matching manifest. If the required guidance is unavailable, pause the affected action. For edits, inspect Git status and worktrees, confirm authorised scope and the source candidate, and follow the current branch policy. Use direct integration-branch work where authorised and a dedicated branch/worktree where required. Preserve unrelated work. Read-only specialist work does not require a new worktree. When acting as an authorised contributor, use `bortstack-contributor` for contributor permissions, finalisation and submission. For ordinary specialist work, use the project's normal authority. When manual testing is relevant, discover the documented commands, configuration and hooks in the target repository. Use its supported workflow, including an existing `testtask` wrapper and its project-specific config or hook where documented. Preserve a working adapter and its supported invocation. Before use, inspect its supported arguments, candidate handling, runtime and cleanup behavior. If no adapter is required, use the established development environment. Record candidate identity, actual checks, limitations and pending human acceptance in the project's handoff. Refresh stale candidates after edits and make fixes in the authoritative source. A source snapshot, wrapper, automated check or startup alone does not establish a manual pass. Follow context and repository rules for task transitions and closure. Outside BortStack, follow the repository's own scope, branch, test and reporting conventions and proceed with the specialist workflow. BortStack skills and records are optional there. ## Core rules 1. **Read repository instructions and context first.** Obey root/nested `AGENTS.md`, accepted task scope, durable decisions, architecture conventions, and repository-specific validation requirements. 2. **Define the behavior-preservation boundary before editing.** Identify what users, APIs, callers, tests, persisted data, deployment tooling, and integrations are expected to observe unchanged. 3. **Inspect before reorganizing.** Understand call sites, state/data flow, public interfaces, tests, migrations, configuration, and runtime wiring before moving or deleting code. 4. **Establish a baseline.** Run relevant existing tests/checks where practical and record their result before the refactor. If baseline validation is already failing, distinguish pre-existing failures from refactor regressions. 5. **Prefer characterization tests when behavior is under-specified.** When existing code has important behavior but inadequate coverage, capture that behavior before restructuring it rather than inferring what it "should" do. 6. **Make small, reversible steps.** Prefer extract/move/rename/consolidate steps that can be validated independently over one large rewrite. 7. **Preserve contracts.** Do not silently change API shapes/status codes, URL routes, component props, public exports, database schema/data semantics, auth rules, configuration names, CLI commands, persistence formats, or externally consumed behavior. 8. **Do not smuggle feature work into a refactor.** New business rules, UX changes, bug fixes, schema redesign, dependency upgrades, performance changes, or style redesign need explicit scope or a separate task/workflow. 9. **Do not "clean up" unknown behavior.** Odd-looking logic may encode a real requirement. Prove it is redundant or incorrect before removing it. 10. **Preserve data and migration safety.** Refactoring model/domain code does not authorize destructive migrations, column renames, data rewrites, or migration-history edits. 11. **Validate continuously.** Run targeted checks after each meaningful step and the appropriate broader suite at the end. Never claim validation that was not run. 12. **Keep diffs reviewable.** Avoid unrelated formatting churn, mass renames, dependency-lockfile noise, generated-file rewrites, or broad automated transformations unless specifically required. 13. **Use repository architecture, not preferred architecture.** Improve within existing conventions unless the accepted task explicitly authorizes an architectural change. 14. **Update durable context only when warranted.** Use the repository workflow for task, current state, decisions and handoff updates. A purely internal refactor often needs no new durable decision if externally meaningful architecture and behavior remain unchanged. 15. **Do not commit, push, switch branches, deploy, provision, or start another task unless explicitly requested.** 16. **Stop at the refactor objective.** Do not continue polishing neighboring code because it is convenient. ## Establish the refactor contract Before editing, identify: - the accepted task/request and explicit objective; - the files/modules/components involved; - the reason for the refactor (duplication, size, coupling, testability, ownership, naming, boundary clarity, etc.); - observable behaviors that must remain unchanged; - public/internal interfaces that callers depend on; - database/config/deployment surfaces that must remain stable; - known existing failures or technical constraints; - non-goals; - validation required to demonstrate behavioral equivalence. If the requested refactor implicitly requires a behavior or architecture decision that is not established, stop at that boundary rather than inventing it. ## 1. Inspect the current implementation Trace the affected code sufficiently to answer: - Who calls it? - What does it call? - What state/data does it read or mutate? - Which errors/statuses/side effects are observable? - Which tests exercise it? - Which configuration, migrations, routes, exports, imports, styles, or runtime wiring depend on it? - Are there dynamically referenced names, reflection, serializers, dependency injection, route registration, Flask blueprints, React lazy imports, CSS selectors, or test fixtures that make a rename/move non-local? Search the repository for every public symbol/path/config key affected before renaming or removing it. ## 2. Establish the behavior baseline Run the narrowest relevant existing checks first, then broader baseline checks when practical. Examples: - backend unit/API tests; - frontend component/integration tests; - route/auth/error-contract tests; - migration status/upgrade checks; - lint/type/build checks; - visual/browser checks when the refactor touches rendered behavior; - CLI/management-command checks; - fixture/serialization checks. Record: - commands/checks actually run; - pass/fail counts where available; - pre-existing failures/warnings; - environment limitations; - anything important that cannot be validated. Do not normalize a failing baseline into "passed" after the refactor. The goal is **no new regression**, unless the accepted task explicitly includes correcting a known failure. ## 3. Add characterization coverage when needed If important current behavior lacks adequate tests, add the smallest useful characterization test before changing structure. A characterization test should capture an observable contract, such as: - API input/output/status behavior; - auth/authorization behavior; - component prop/state/render behavior; - ordering/filtering/calculation behavior; - serialization/persistence behavior; - error handling; - important side effects. Do not lock tests to incidental implementation details merely to make refactoring impossible. Protect behavior, not private structure. ## 4. Plan the smallest coherent refactor Prefer a short sequence such as: 1. add/confirm coverage; 2. extract one function/component/service; 3. redirect existing callers; 4. validate; 5. remove now-dead duplication; 6. validate; 7. repeat only if needed to meet the accepted objective. For larger refactors, explicitly identify safe intermediate states. Avoid "delete old architecture, build new architecture, then see if tests pass" when incremental migration is practical. ## 5. Refactor by layer ### React/frontend Preserve unless explicitly authorized: - route paths and navigation behavior; - component public props; - form field names/submission payloads; - state ownership semantics; - loading/error/empty/success behavior; - CSS class/module contracts relied on by tests or layout; - accessibility behavior; - API request/response expectations. Typical safe operations include extracting presentational components, hooks, helpers, repeated form logic, API adapters, or state selectors while preserving external contracts. Do not convert state-management approaches, change UI libraries, redesign pages, or alter UX as incidental cleanup. ### Flask/backend Preserve unless explicitly authorized: - route URLs/methods; - request and response contracts; - status/error semantics; - auth/authorization checks; - transaction boundaries and side effects; - model/data semantics; - configuration keys; - CLI/management command behavior. Typical safe operations include extracting service/helper functions, consolidating validation, splitting oversized route modules, clarifying domain boundaries, or removing proven duplication while retaining route contracts. Do not rewrite migrations or change schema merely because a model/module is being reorganized. ### Shared/API boundary When moving code across layers, verify both ends of the contract. A refactor is not safe merely because one side compiles. Check: - field names/types; - optional/null handling; - status/error shapes; - auth headers/cookies/tokens; - pagination/filter/sort semantics; - date/time representation; - identifiers and ordering; - side effects and retries. ### Runtime/infrastructure/config Refactoring app structure may require import/path/config updates, but preserve runtime behavior. Treat Docker, Gunicorn, nginx/SWAG, environment variables, startup commands, CI, scripts, and deployment wiring as public contracts when they consume the refactored paths. ## 6. Validate after each meaningful change Use targeted checks during the refactor rather than waiting until the end. Examples: - relevant test file/module; - import/compile check after moving Python modules; - component test after extraction; - lint/type check after interface changes; - focused API contract tests after moving validation/business logic. If a step introduces a regression, resolve it before stacking more structural changes on top. ## 7. Remove dead code only when proven dead Before deleting old functions/files/exports: - search all imports/references; - check dynamic registration/configuration; - inspect tests/scripts/migrations/CLI/runtime entry points; - account for external/public interfaces documented by the project; - verify the replacement path is live. "No obvious reference in one file" is not sufficient evidence. ## 8. Final validation At completion: 1. run targeted tests for the changed area; 2. run the repository's appropriate broader test suite; 3. run lint/type/build checks that apply; 4. run migration/config/runtime checks if touched; 5. run visual/browser checks if rendered behavior may have changed; 6. inspect the final diff for accidental churn; 7. compare final results to the baseline. Use `references/behavior-preservation-checklist.md` and `references/refactor-validation.md` when useful. If full validation is blocked, report exactly what passed, what failed, and what could not run. Do not mark behavioral equivalence as fully verified when required checks were unavailable. ## 9. Handling behavior changes discovered during refactoring If behavior changes accidentally: - revert or correct the refactor step when the change is outside scope; - add regression coverage if the previous contract was inadequately protected; - do not rationalize an accidental change as "better". If the old behavior appears defective or undesirable: - preserve it for the refactor unless fixing it is explicitly in scope; - record the verified issue according to the project context system; - propose/separate a bug/feature task as appropriate; - do not silently bundle the fix into the refactor. If preserving old behavior is impossible because the accepted structural change necessarily alters a public contract, stop and obtain/record the required decision before proceeding. ## 10. Context-system interaction In BortStack projects: - confirm the refactor task is accepted/in scope before substantial changes; - respect existing ADR/PDR/task decisions; - update the project’s current-state record only if verified architectural/current-state truth materially changes; - add a durable decision only when the refactor establishes a meaningful project-wide architectural contract, not for every extraction/rename; - update task status based on actual validation; - refresh the project’s handoff record when useful for continuation; - do not invent follow-on accepted work from incidental findings. A task whose code changes are complete but required validation is blocked should remain in the repository's appropriate blocked/in-progress state rather than being falsely completed. ## Completion report When useful, report concisely: 1. refactor objective and preserved behavior boundary; 2. repository/context evidence inspected; 3. baseline validation results; 4. files changed; 5. structural changes made; 6. characterization/regression tests added or changed; 7. final validation results compared with baseline; 8. any behavior differences discovered; 9. anything not verified; 10. final task/context status. Do not advertise internal cleanup as a user-facing feature. Do not claim behavior was preserved unless evidence supports that conclusion.