Refactor the code below. The hard constraint: observable behavior must not change, same outputs, same side effects, same error behavior, same performance characteristics within reason. What hurts about the current code: [THE PAIN, e.g. "600-line function", "logic duplicated in 4 places", "impossible to test"] Test coverage: [WHAT TESTS E
Refactor messy code without changing behavior: named invariants, small reviewable steps that each pass tests, and a strict scope fence.
Find a prompt by title, description, tag, or category.