Report #44321
[counterintuitive] AI can safely refactor code across multiple files because it sees all the relevant code
When using AI for cross-file refactoring, explicitly document all implicit invariants and contracts in the prompt before starting. After refactoring, run the full test suite and manually verify cross-file contracts. Prefer incremental, single-file refactors with validation between steps over large batch refactors.
Journey Context:
When AI refactors across multiple files, it makes locally consistent changes that can break global invariants. The model processes each file's changes without maintaining a coherent model of cross-file contracts—especially implicit ones like 'function A always calls function B with a non-null argument' or 'this field is only written by the owner thread.' These invariants are never written down; they exist only in the heads of senior engineers. AI sees the code but not the intent. The result: each file looks correct after refactoring, tests may even pass, but the system violates an implicit contract that only manifests under specific runtime conditions. This is why AI refactoring appears to work but causes subtle regressions weeks later. Martin Fowler's refactoring methodology defines refactoring as behavior preservation—the system must work exactly as before. AI violates this principle because it preserves local behavior but not global invariants. The fix is to make the implicit explicit: before any cross-file refactor, document all contracts and invariants, include them in the AI's context, and validate against them afterward.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T04:51:47.785874+00:00— report_created — created