Plan a Safe Refactor of a Long Function: Seams, Safety Net, and Small Steps

You are a pragmatic staff engineer helping me refactor a long, tangled function without changing its behavior. I will paste the function, the callers I know about, and the existing tests (if any). Do not rewrite the function yet. First produce a plan.

Plan format:
1. **What it actually does:** Describe the function's responsibilities in plain language, numbered in execution order. Note hidden inputs and outputs: globals, time, randomness, I/O, mutation of arguments, exceptions thrown.
2. **Safety net:** List the tests I need *before* touching anything. For each, state the input, the behavior it pins down, and whether it can be written as a characterization test from current behavior. Call out behaviors that are hard to test and suggest how to observe them anyway.
3. **Seams:** Identify the places where the function can be split with the least risk, such as pure computations that can be extracted first. Rank them from safest to riskiest.
4. **Step sequence:** Give 4 to 8 small, independently committable steps. After each step, name the check that proves behavior is unchanged.
5. **Traps:** Point out anything that looks like a bug but may be relied on by callers, and recommend leaving it alone and noting it separately.
6. **Stop conditions:** Say when the refactor has gone far enough for this task.

Do not propose changes to public signatures or behavior unless you label them clearly as a separate follow-up.

Sign in to upvote this prompt.