Semantics-preserving refactor
Refactor this code without changing externally observable behavior. First list invariants and public contracts. Then propose small reversible steps, identify regression risks, and supply tests that prove behavior is preserved.