--- name: anneal description: Use when the user wants to systematically fix AI code slop — duplicated logic, over-engineering, silent error swallowing, convention drift, cargo-cult patterns, and other LLM-introduced architectural decay — over a specified duration --- # Anneal Systematically harden a codebase by fixing AI-introduced code slop over a user-specified duration. The clock decides when work stops, not you. ## Your Role You are the **orchestrator**. You do exactly two things: 1. **Manage the clock** — check time before every dispatch, stop when the deadline passes 2. **Dispatch subagents** — give them the slop catalog, the progress file path, and get out of the way You do NOT do any actual work. No code changes, no file edits, no exploration, no analysis, no "quick fixes." All productive work happens inside subagents. Your context is reserved exclusively for the dispatch loop. If you catch yourself doing anything other than checking time, reading the progress file, and dispatching — stop. That work belongs in a subagent. ## The Iron Law ``` YOU DO NOT DECIDE WHEN THE WORK IS DONE. THE CLOCK DECIDES. ``` Your only job is to keep dispatching useful work until the deadline passes. You have zero authority to judge completeness, sufficiency, or "good enough." The user gave you a duration. You use all of it. ## Inputs The user provides two things: 1. **Codebase** — the project to anneal (defaults to the current working directory) 2. **Duration** — how long to run (e.g., "4 hours", "overnight", "90 minutes") If the duration is vague ("overnight"), interpret it as 8 hours. If truly ambiguous, ask once. ## The Slop Catalog These are the patterns AI agents actually introduce into codebases. Every subagent receives this catalog as its detection guide. The subagent picks the highest-impact instance it can find — the catalog is a field guide, not a queue. ### 1. Duplication Instead of Reuse Reimplements logic that already exists elsewhere in the codebase. The agent lacked full-repo context and produced a new version instead of calling the existing one. Look for: near-identical functions across files, same algorithm implemented with different variable names, utility code that duplicates a library the project already depends on. **Fix:** Delete the duplicate, call the original. If the duplicate is better, replace the original and update all call sites. ### 2. Over-Engineering 200-line abstraction for a 15-line problem. Factory patterns with one product. Strategy interfaces with one strategy. Config objects for a single caller. Abstract base classes with one child. The agent pattern-matched to enterprise code in its training data instead of solving the actual problem. **Fix:** Inline the abstraction. Replace the class with a function. Remove the interface and use the concrete type. Delete the config object and pass the values directly. ### 3. Silent Error Swallowing Broad try-catch that catches everything and either logs a generic message or does nothing. Error handling that doesn't match actual failure modes — catching exceptions that can't be thrown, recovering from errors that shouldn't be recovered from. **Fix:** Remove try-catch blocks around code that can't throw. Narrow broad catches to specific exceptions. Let fatal errors propagate. Replace log-and-continue with log-and-throw where the caller needs to know. ### 4. Convention Blindness The project uses pattern A for database access, but the agent introduced pattern B. There are now four different ways to make HTTP requests. The team's established approach was ignored and a new one invented. Imports from different layers that violate the project's dependency direction. **Fix:** Rewrite to use the project's established convention. If unsure which convention is canonical, look at the most files, the oldest files, or any ADRs/docs. ### 5. Plausible-but-Wrong Logic Compiles and passes basic tests but contains subtle bugs. Off-by-one errors hidden behind reasonable-looking code. Race conditions in concurrent paths. Security gaps — improper input validation, missing auth checks, SQL built by concatenation. Excessive or redundant I/O operations. **Fix:** Correct the logic. Add a test that catches the specific bug. If the fix is uncertain, leave a TODO with the exact concern and move on — don't guess. ### 6. Hallucinated APIs Calls methods that don't exist on the type. Uses config options removed two versions ago. References internal APIs that aren't part of the public contract. Imports packages that aren't in the dependency manifest. **Fix:** Replace with the correct API. Check the actual library version the project uses, not what the agent assumed. ### 7. Cargo-Cult Patterns Retry logic where retrying is inappropriate (non-idempotent operations, permanent failures). Circuit breakers in single-caller contexts. Dependency injection frameworks for three-function programs. Caching with no eviction in a long-running process. The pattern was applied structurally without understanding its preconditions. **Fix:** Remove the pattern entirely if the preconditions aren't met. Replace with the simpler thing that actually fits. ### 8. Verbosity Inflation Formal docstrings on trivial getters. Comments restating what the next line of code does. Variable names that are sentences. Functions decomposed into sub-functions that are each called once and are harder to read than the inline version. **Fix:** Delete comments that restate code. Inline single-use sub-functions if the result is more readable. Shorten names that are sentences to names that are words. Remove docstrings that say nothing beyond the signature. ### 9. Modular Mirage Files are separated but responsibilities are scattered. A "UserService" that also handles email, a "utils" file per feature that contains unrelated functions. Modules that import from each other in a cycle. Superficially clean file tree, semantically incoherent boundaries. **Fix:** Move code to where it belongs by responsibility. Break cycles by extracting shared logic. Merge files that have no reason to be separate. Don't just rename — restructure. ### 10. Tautological Tests Tests that mirror the implementation — they verify the code does what it does, not what it should do. Mock everything so the test tests nothing. Snapshot tests of unstable output. Tests that were auto-updated to pass after a behavior change instead of catching the regression. **Fix:** Rewrite tests to assert on behavior and outcomes, not implementation details. Remove mocks that make the test vacuous. Delete snapshot tests that snapshot noise. ## Safety Protocol Every iteration follows this sequence. No exceptions. 1. **Run the test suite** before making any changes. If tests don't pass at baseline, log it and still proceed — but note which tests were already broken. 2. **Make one focused change** — one slop pattern, one area of the codebase. Small blast radius. 3. **Run the test suite** after the change. Compare results to the baseline from step 1. 4. **If new test failures appear: revert everything, log what was attempted and why it broke, move on.** Do not debug. Do not retry. Do not "fix the tests." Revert and find different work. 5. **If tests pass: commit.** One atomic commit per iteration. 6. **Never change public API signatures**, exported types, or external behavior. Annealing fixes internals. 7. **Never change behavior.** If you're not sure whether a change alters behavior, it probably does. Skip it. ## The Process ```dot digraph anneal { rankdir=TB; node [shape=box]; start [label="Record start time\nCompute deadline" shape=doublecircle]; init [label="Create progress file\nin /tmp"]; check [label="Check current time\nagainst deadline" shape=diamond]; read_log [label="Read progress file"]; dispatch [label="Dispatch subagent\nwith catalog + progress file path"]; update [label="Update progress file\nwith iteration results"]; summary [label="Write final summary\nto progress file" shape=doublecircle]; start -> init -> check; check -> read_log [label="time remains"]; check -> summary [label="deadline passed"]; read_log -> dispatch; dispatch -> update; update -> check; } ``` ### Step by step 1. **Record the start time.** Run `date +%s` to get the current Unix timestamp. Compute the deadline timestamp by adding the duration. 2. **Create the progress file.** Write it to `/tmp/anneal-.md`. Initial contents: ```markdown # Anneal Run - Start: - Deadline: - Duration: - Baseline test status: ## Iterations ``` 3. **Check the time.** Run `date +%s`. Compare against the deadline timestamp. If the deadline has passed, go to step 6. This check happens BEFORE every dispatch, never after, never "when convenient." 4. **Dispatch a subagent.** Give it: - The slop catalog (the full catalog section above — paste it into the subagent prompt) - The path to the progress file — the subagent reads it to learn what was already done - Instruction: find the highest-impact slop instance in the codebase, fix it following the safety protocol, commit, and return a structured summary Do NOT give the subagent the deadline or any time awareness. It does not need to know. It finds one thing, fixes it, and returns. 5. **Update the progress file.** Append the iteration result: ```markdown ### Iteration N —