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
- neko3cs/skillstheir own version, first seen Nov 1, 2026
- Ionate-Technologies/indium-agentkittheir own version, first seen Oct 20, 2026
- Indium-AI-Labs/indium-agentkittheir own version, first seen Oct 11, 2026
- BrOrlandi/my-claude-skillstheir own version, first seen Sep 22, 2026
- genfeedai/genfeed.aitheir own version, first seen Sep 12, 2026
- hidekitux/skillstheir own version, first seen Sep 8, 2026
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.
gologo13Skilloptimize-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
NVIDIASkilldebug-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
SentrySkillwrite-tests
Write tests following project conventions. Use when adding new tests or modifying existing ones.
Also in 3 projects that use this
SentrySkillcreate-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
Other versions16 projects use a version of this.
Word for word · 0
None found.
Edited · 1
- igmarin/rails-agent-skills★ 2643% same
Wrote their own version · 15
- BrOrlandi/my-claude-skills★ 22same name
- Indium-AI-Labs/indium-agentkit★ 18same name
- Ionate-Technologies/indium-agentkit★ 17same name
- zbruhnke/claude-code-starter★ 16same name
- emaraschio/cursor-commands★ 9same name
- chrisetheridge/skills★ 4same name
- genfeedai/genfeed.ai★ 4same name
- adolfoaranaes12/BMAD-ENHANCED★ 2same name
- r2rka1/skills★ 2same name
- drafael/coding-harness★ 1same name
5 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository34 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apply-phoenix-controller-conventionsSkill
- ash-frameworkSkill
- benchee-profilingSkill
- broadway-data-pipelinesSkill
- cachex-cachingSkill
- code-qualitySkill
- code-reviewSkill
- deployment-gotchasSkill
- ecto-changeset-patternsSkill
- ecto-essentialsSkill
- ecto-migrationSkill
- ecto-nested-associationsSkill
- elixir-essentialsSkill
- gettext-i18nSkill
- liveview-streamsSkill
- mix-tasks-generatorsSkill
- oban-essentialsSkill
- otp-essentialsSkill
- phoenix-authenticationSkill
- phoenix-authorization-patternsSkill
- phoenix-channels-essentialsSkill
- phoenix-json-apiSkill
- phoenix-liveview-essentialsSkill
- phoenix-pubsub-patternsSkill
- phoenix-uploadsSkill
- property-based-testingSkill
- req-http-clientSkill
- respond-to-reviewSkill
- security-essentialsSkill
- swoosh-emailsSkill
- telemetry-essentialsSkill
- testing-essentialsSkill
- typespec-dialyzerSkill
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
- Distinctive: line 22
Use this skill when the task is to change structure without changing intended behavior.
- Distinctive: line 72
Write this before touching any production file: No refactoring step begins until this test exists and passes on the current (un-refactored) …
- Very specific: line 93
Run it: mix test test/my_app/accounts_test.exs — it must pass on the current code before any production file is changed.
- Very specific: line 231
Run mix test test/path/to/file_test.exs after every refactoring step and check exit code and failure count.
- Distinctive: line 232
If tests fail: STOP, undo the step, investigate.
“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.
Files
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
| Step | Action | Verification |
| 1 | Define stable behavior | Written statement of what must not change |
| 2 | Add characterization tests | mix test passes on current code |
| 3 | Choose smallest safe slice | One boundary at a time |
| 4 | Rename, move, or extract | mix test still passes |
| 5 | Remove compatibility shims | mix 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
endRun 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
endReduce 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
endSide-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:
- Document the I/O boundary.
Mail.send_welcome/1performs 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@docon the context function and in the module's@moduledoc.- Prove the surface is unchanged. The extracted
Mail.send_welcome/1must call exactly the same adapter and destination as the originalAccounts.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.- Audit the new alias.
alias MyApp.Mailis a new dependency edge fromAccountstoMyApp.Mailis 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. Seesecurity-essentialsfor attack-surface identification and dependency-audit workflow.- 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-essentialsand 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.exsafter 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 tests | Write and pass characterization tests on the current code first |
| Change behavior and structure in the same step | Do the structural refactor first, behavior change separately |
| Extract two abstractions in one step | Refactor one boundary per step |
| Break the public interface silently | Keep interfaces stable; document the shim and its removal |
| Test only at the end of the refactor | Run mix test after every step; stop and undo on failure |
| Paste fabricated or "expected" test output | Label 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
| Predecessor | This Skill | Successor |
| code-review | refactor-code | code-quality |
Companion skills:
code-quality— Credo complexity detection and quality gatetesting-essentials— fixture and test setup patternsapply-phoenix-liveview-conventions— LiveView-specific refactoring
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
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.

