agentleFS
igmarinigmarin/elixir-phoenix-skills/skills/refactor-code/SKILL.md

refactor-code

Skill4 starsChanged 4 months agoMITView on GitHub

Use when refactoring Elixir code to change structure without changing behavior. Must write characterization tests and verify they pass on the current code BEFORE touching any production files, identify inputs/outputs keeping public interfaces stable, run verification after every step and the full suite at the end, and include a Stable behavior statement and Verification evidence showing actual command output under the Observed output label. Trigger words: refactor, restructure, extract function, extract module, reduce duplication, split module, flatten with, reduce pipe chain, extract bounded context.

16 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use optimize-performance, debug-issue and 3 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • gologo13Skill

    optimize-performance

    Analyze the current code for performance bottlenecks and provide optimization recommendation...; keywords: api, performance. Use only on explicit request; skip in routine implementation discussions.

    Also in 3 projects that use this

  • NVIDIASkill

    debug-issue

    Use when the user asks to debug, investigate, or fix a GitHub issue or supplies a repository bug report.

    Also in 3 projects that use this

  • SentrySkill

    write-tests

    Write tests following project conventions. Use when adding new tests or modifying existing ones.

    Also in 3 projects that use this

  • SentrySkill

    create-pr

    Create pull requests following Sentry conventions. Use when opening PRs, writing PR descriptions, or preparing changes for review. Follows Sentry's code review guidelines.

    Also in 3 projects that use this

  • +1 more from getsentry

The file

We split this skill into the rules it gives an agent

5 rules. 0 are common, 3 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 15 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill when the task is to change structure without changing intended behavior.

    line 22
  2. Distinctive:

    Write this before touching any production file: No refactoring step begins until this test exists and passes on the current (un-refactored) …

    line 72
  3. Very specific:

    Run it: mix test test/my_app/accounts_test.exs — it must pass on the current code before any production file is changed.

    line 93
  4. Very specific:

    Run mix test test/path/to/file_test.exs after every refactoring step and check exit code and failure count.

    line 231
  5. Distinctive:

    If tests fail: STOP, undo the step, investigate.

    line 232

“Common” is measured: kept by at least 6 in 10 of the 15 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Refactor Code

Use this skill when the task is to change structure without changing intended behavior.

Core principle: Small, reversible steps over large rewrites. Separate design improvement from behavior change.

Quick Reference

StepActionVerification
1Define stable behaviorWritten statement of what must not change
2Add characterization testsmix test passes on current code
3Choose smallest safe sliceOne boundary at a time
4Rename, move, or extractmix test still passes
5Remove compatibility shimsmix test still passes, new path proven

HARD-GATE

NO REFACTORING WITHOUT CHARACTERIZATION TESTS FIRST.
NEVER mix behavior changes with structural refactors in the same step —
  if behavior changes are also needed, complete the structural refactor first,
  then apply behavior changes in a separate step with its own test.
ONE boundary per refactoring step — never extract two abstractions in the same step.
If a public interface changes, document the compatibility shim and its removal condition.
NEVER fabricate test output — label only actual run output as Observed output.

RULES — Follow these with no exceptions

1. Write characterization tests before touching any production file — they must pass on the current, un-refactored code first 2. Never mix behavior changes with structural refactors in the same step — finish the structural change, then apply behavior changes separately with their own test 3. Refactor one boundary per step — never extract two abstractions at once 4. Keep public interfaces stable — document any compatibility shim and its removal condition 5. Run mix test after every step — if it fails, STOP, undo the step, and investigate 6. Run the full mix test suite at the end before declaring the refactor complete 7. Label only actual run output as Observed output — never fabricate output or substitute "Expected"/"Planned" output 8. Report at least two Observed output entries at different sequence points

Core Process

1. Define stable behavior

Identify the exact inputs and outputs of the logic being refactored. Keep public interfaces stable until callers are migrated. Prefer adapters, facades, or wrappers for transitional states.

Include in your output:

  • Stable behavior statement: an explicit statement of what must not change (inputs/outputs, public interfaces).
  • Shim decision: name any transitional adapter/facade/wrapper and its removal condition, or state why none is needed.

2. Add characterization tests

Write this before touching any production file. No refactoring step begins until this test exists and passes on the current (un-refactored) code. If the characterization test fails, stop and fix the test or the behavior mismatch before continuing.

# test/my_app/accounts_test.exs
defmodule MyApp.AccountsRefactorTest do
  use MyApp.DataCase

  describe "current behavior — register_user/1" do
    test "creates user with valid attrs" do
      assert {:ok, %User{} = user} = Accounts.register_user(%{email: "a@b.com", name: "Alice"})
      assert user.email == "a@b.com"
      assert user.name == "Alice"
    end

    test "returns error changeset with invalid attrs" do
      assert {:error, %Ecto.Changeset{}} = Accounts.register_user(%{email: ""})
    end
  end
end

Run it: mix test test/my_app/accounts_test.exs — it must pass on the current code before any production file is changed.

3. Choose the smallest safe slice

Good first moves: extract duplicated logic into a private helper, flatten a nested case into with, reduce a long pipe chain into named functions, or wrap a context boundary. One boundary at a time.

4. Execute extraction/refactor (one step at a time)

Apply the appropriate pattern below. Each shows a representative before/after; adapt to your context.

Extract Private Function (ABC complexity reduction)

# Before: one large public function
def calculate_trend_line(data) do
  # 50 lines of assignments, branches, conditions
end

# After: delegate to named private helpers
def calculate_trend_line(data) do
  sums = calculate_regression_sums(data)
  slope = calculate_slope(sums)
  intercept = calculate_intercept(sums, slope)
  build_trend_points(data, slope, intercept)
end

defp calculate_regression_sums(data), do: # ...
defp calculate_slope(sums), do: # ...
defp calculate_intercept(sums, slope), do: # ...
defp build_trend_points(data, slope, intercept), do: # ...

Flatten Nested Case into With

# Before
def process_order(order_id) do
  case find_order(order_id) do
    {:ok, order} ->
      case validate_order(order) do
        {:ok, valid_order} -> charge_order(valid_order)
        error -> error
      end
    error -> error
  end
end

# After
def process_order(order_id) do
  with {:ok, order} <- find_order(order_id),
       {:ok, valid_order} <- validate_order(order),
       {:ok, charge} <- charge_order(valid_order) do
    {:ok, charge}
  end
end

Reduce Pipe Chain into Named Functions

# Before
def process_data(data) do
  data
  |> Enum.filter(&active?/1)
  |> Enum.map(&transform/1)
  |> Enum.group_by(& &1.category)
  |> Enum.map(fn {cat, items} -> {cat, Enum.count(items)} end)
end

# After
def process_data(data) do
  data |> filter_active() |> transform_all() |> group_by_category() |> count_per_category()
end

defp filter_active(data), do: Enum.filter(data, &active?/1)
defp transform_all(data), do: Enum.map(data, &transform/1)
defp group_by_category(data), do: Enum.group_by(data, & &1.category)
defp count_per_category(groups), do: Enum.map(groups, fn {cat, items} -> {cat, Enum.count(items)} end)

Extract Context Module Boundary

Move the welcome-email side effect behind an internal Mail context module (an internal Phoenix context module, not an LLM/agent context), keeping Accounts decoupled from the Mailer adapter. Mail.send_welcome/1 still calls the same internal Swoosh adapter — no new destination or external transmission is introduced, only a context boundary:

# Before: Accounts calls mailer directly
defmodule MyApp.Accounts do
  def send_welcome_email(user) do
    MyApp.Mailer.deliver(MyApp.Mailers.UserEmail.welcome(user))
  end
end

# After: delegate welcome-email delivery to the internal Mail context
defmodule MyApp.Accounts do
  alias MyApp.Mail

  def register_user(attrs) do
    with {:ok, user} <- create_user(attrs) do
      Mail.send_welcome(user)
      {:ok, user}
    end
  end
end

Side-effect boundary — do not mask I/O. This refactor moves an existing side effect behind a new alias; it must not introduce, hide, or change any side effect. Before merging the extraction:

  1. Document the I/O boundary. Mail.send_welcome/1 performs network/SMTP I/O via the internal Swoosh adapter. Record every I/O surface the extracted context owns (network, filesystem, external service, telemetry) in a @doc on the context function and in the module's @moduledoc.
  2. Prove the surface is unchanged. The extracted Mail.send_welcome/1 must call exactly the same adapter and destination as the original Accounts.send_welcome_email/1. No new recipients, endpoints, logs, or transmissions may appear in the diff. Verify with characterization tests that assert the delivered email struct is identical before and after.
  3. Audit the new alias. alias MyApp.Mail is a new dependency edge from Accounts to Mail. Confirm MyApp.Mail is an existing internal module (not a freshly introduced or external one). Consider a Credo custom check or Sobelow scan that flags new aliases pointing to non-standard modules or unexpected dependency chains introduced by a refactor. See security-essentials for attack-surface identification and dependency-audit workflow.
  4. Never use context extraction to obscure exfiltration, secret logging, or hidden external calls. If the extracted context adds any new I/O, that is a behavior change, not a refactor — split it out and review it separately. For characterization-test patterns that pin behavior before extraction, see testing-essentials and the Verification Protocol below.

5. Verification Protocol

This is the single authoritative source for all verification rules.

  • Run mix test test/path/to/file_test.exs after every refactoring step and check exit code and failure count.
  • If tests fail: STOP, undo the step, investigate.
  • At the end, run the full suite: mix test.
  • Evidence labelling: Label actual run output as Observed output only. Never use labels such as "Expected output", "Required output", or "Planned output" as substitutes for actual observed run output.
  • Report test run output at EACH step — not only at the end. At least two separate Observed output entries at different sequence points are required.

Common Pitfalls

❌ Don't✅ Do
Start refactoring before writing characterization testsWrite and pass characterization tests on the current code first
Change behavior and structure in the same stepDo the structural refactor first, behavior change separately
Extract two abstractions in one stepRefactor one boundary per step
Break the public interface silentlyKeep interfaces stable; document the shim and its removal
Test only at the end of the refactorRun mix test after every step; stop and undo on failure
Paste fabricated or "expected" test outputLabel only actual run output as Observed output
Use context extraction to hide new/changed I/O (exfiltration, secret logs, new endpoints)Document every I/O boundary the extracted context owns; prove the side-effect surface is unchanged via characterization tests

Integration

PredecessorThis SkillSuccessor
code-reviewrefactor-codecode-quality

Companion skills:

  • code-quality — Credo complexity detection and quality gate
  • testing-essentials — fixture and test setup patterns
  • apply-phoenix-liveview-conventions — LiveView-specific refactoring

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.