/elixir:codebase-cleanupfrom elixir
Run focused, pass-based remediation on an Elixir/BEAM codebase to eliminate unsafe patterns and harden runtime boundaries. Use when auditing or cleaning up OTP supervision, DTO/boundary integrity, atom safety, ambient configuration, secret/error redaction, unsafe deserialization or runtime eval, GenServer state and backpressure, serialization and event versioning, persistence backends, package boundaries, or observability. Triggers on "clean up codebase", "remediation pass", "audit OTP/supervision", "remove String.to_atom", "boundary/DTO cleanup", "redact secrets", "ban binary_to_term", "backpressure cleanup". Each invocation targets one pass and produces a focused PR with red-first tests, exit-gate scans, and documented exceptions.
Ships in elixir. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This guide is written for an Elixir/BEAM-oriented codebase, especially one with OTP processes, distributed execution, provider integrations, event/state persistence, and governed runtime boundaries. It consolidates the uploaded cleanup notes into a pass-based remediation plan so related concerns can be fixed together, reviewed together, and tested together.
Do not try to “clean the codebase” in one giant sweep.
Instead, run focused passes:
Each pass should ideally produce one or more focused PRs with a narrow theme.
Regex is acceptable only for flat lexical validation where the input grammar is intentionally regular.
Regex must not be used for:
mix.exs editsUse parser-aware tools instead:
Code.string_to_quoted/2
Macro.prewalk/2
Macro.postwalk/2
Or dedicated source tooling such as:
Sourceror
Rewrite
Igniter
Allowed regex example:
Regex.match?(~r/^[a-z0-9_]+$/, identifier)
Blocked regex example:
Regex.replace(~r/Application\.get_env\(.+\)/, source, replacement)
That can corrupt source code.
A pass is not complete because the code “looks cleaner.”
A pass is complete when:
Use an exception annotation format like this:
# cleanup:allow unsafe_deserialization
# reason: internal trusted migration payload generated by ReleaseTasks.V2 only
# owner: platform-runtime
# expires: 2026-08-01
Every exception should have:
| Field | Required |
|---|---|
| Rule name | Yes |
| Reason | Yes |
| Owner | Yes |
| Expiration or review date | Yes |
| Test coverage | Yes |
The order matters. Earlier passes reduce the risk of later passes.
| Order | Pass | Why It Comes Here |
|---|---|---|
| 0 | Baseline and Inventory | Establish current state before touching code |
| 1 | Transformation Safety | Prevent cleanup tooling from corrupting code |
| 2 | Boundary and DTO Integrity | Stop raw external input from leaking inward |
| 3 | Atom Safety and Bounded Vocabulary | Remove atom exhaustion risks |
| 4 | Configuration and Ambient Authority | Remove hidden credentials/config access |
| 5 | Secret Redaction and Error Sanitization | Prevent leakage through logs/errors |
| 6 | Unsafe Deserialization and Runtime Eval | Remove high-risk execution/data ingestion issues |
| 7 | OTP Lifecycle and Supervision | Ensure all work is owned, killable, and restartable |
| 8 | Actor Mailbox, Backpressure, and Queue Bounds | Prevent OOM and cascading node failure |
| 9 | GenServer Functional-Core Cleanup | Remove hidden state and blocking logic |
| 10 | Serialization, Protocol, and Versioning | Stabilize external and durable contracts |
| 11 | Persistence and State Backend Cleanup | Isolate side effects and durable state |
| 12 | Package and Dependency Boundaries | Remove transitive dependency coupling |
| 13 | Observability and Context Propagation | Make runtime behavior traceable |
| 14 | Idiomatic, Performance, and Maintainability Cleanup | Improve readability/performance after safety work |
| 15 | Final Verification and Governance Lock-In | Make the cleanup durable |
Create a reliable picture of the codebase before changing it.
Run the normal verification suite:
mix deps.get
mix compile
mix format --check-formatted
mix test
Where available, also run:
mix credo --strict
mix sobelow
mix deps.audit
Create a cleanup ledger:
cleanup/
findings.md
exceptions.md
pass-00-baseline.md
pass-01-transformation-safety.md
...
Suggested finding format:
## Finding
- Rule:
- File:
- Function/module:
- Risk:
- Owner:
- Fix strategy:
- Tests required:
- Status:
Collect initial counts:
rg 'String\.to_atom|binary_to_term|Code\.eval|Application\.get_env|System\.get_env'
rg 'spawn\(|spawn_link\(|Task\.start|Task\.async|GenServer\.cast|Process\.send'
rg 'Logger\.|IO\.inspect|dbg\(|:telemetry\.execute'
rg 'defstruct|@derive|Jason\.Encoder|Poison\.Encoder'
rg 'Regex\.|~r/'
Make sure future cleanup work does not corrupt source code through unsafe automation.
mix.exs, config/*.exs, or .formatter.exs without parsingrg 'Regex\.replace|String\.replace|File\.write!|File\.read!' scripts lib test priv
rg '~r/' scripts lib test priv
rg 'Code\.string_to_quoted|Sourceror|Igniter|Rewrite' scripts lib test priv
Replace unsafe transformations with AST-aware or schema-aware logic.
source
|> String.replace("Application.get_env(:app, :key)", "config.key")
{:ok, ast} = Code.string_to_quoted(source)
new_ast =
Macro.prewalk(ast, fn
{{:., _, [{:__aliases__, _, [:Application]}, :get_env]}, _, args} ->
rewrite_get_env(args)
node ->
node
end)
Prevent raw, untrusted, or weakly typed input from entering core logic.
%{} where a typed struct is expectedrg 'def .*\(%\{|def .*\(params|def .*\(payload|def .*\(attrs|def .*\(input' lib
rg 'Map\.get|map\[:|payload\[|params\[|attrs\[' lib
rg '@enforce_keys|defstruct|typedstruct|Ecto\.Changeset' lib
At every external boundary:
raw input → parser/validator → DTO/struct → domain logic
def execute(payload) do
provider = payload["provider"]
model = payload["model"]
Provider.call(provider, model, payload)
end
def execute(raw_payload) do
with {:ok, request} <- InferenceRequest.new(raw_payload) do
Provider.call(request)
end
end
Example DTO:
defmodule InferenceRequest do
@enforce_keys [:provider_ref, :model_ref, :input]
defstruct [:provider_ref, :model_ref, :input, opts: %{}]
def new(%{"provider" => provider, "model" => model, "input" => input} = raw) do
with {:ok, provider_ref} <- ProviderRef.new(provider),
{:ok, model_ref} <- ModelRef.new(model),
{:ok, validated_input} <- InputPayload.new(input) do
{:ok,
%__MODULE__{
provider_ref: provider_ref,
model_ref: model_ref,
input: validated_input,
opts: Map.get(raw, "opts", %{})
}}
end
end
def new(_), do: {:error, :invalid_inference_request}
end
Red-first tests for:
Eliminate unbounded atom creation and enforce finite vocabularies.
String.to_atom/1 on user or external input:"#{value}" from runtime valuesbinary_to_atom/1rg 'String\.to_atom|binary_to_atom|list_to_atom'
rg ':\#\{|:"\#\{'
rg 'String\.to_existing_atom'
defmodule ProviderRegistry do
@providers %{
"openai" => :openai,
"anthropic" => :anthropic,
"local" => :local
}
def parse(value), do: Map.fetch(@providers, value)
end
%ProviderRef{id: "openai"}
String.to_existing_atom(value)
Only use this when all allowed atoms are loaded and controlled.
Remove hidden configuration and hidden authority from core logic.
Application.get_env/2,3 in business logicSystem.get_env/1,2 outside boot/config modulesrg 'Application\.get_env|Application\.fetch_env|System\.get_env'
rg 'put_env|delete_env'
rg 'defmodule .*Client|client\(|credentials|token|api_key|secret'
Resolve configuration once at boot or boundary, validate it, then inject it.
def call_provider(input) do
api_key = System.get_env("OPENAI_API_KEY")
model = Application.get_env(:my_app, :default_model)
Provider.call(api_key, model, input)
end
def call_provider(%ExecutionContext{} = context, input) do
Provider.call(context.provider_grant, context.model_ref, input)
end
Example context:
defmodule ExecutionContext do
@enforce_keys [:authority, :provider_grant, :target]
defstruct [:authority, :provider_grant, :target, :trace_context]
end
Lower layers must not decide:
They should only execute against explicit authority.
System.get_env.Application.get_env.Prevent sensitive data and internal topology from leaking through logs, traces, telemetry, exceptions, or serialized structs.
LoggerIO.inspect, dbg, or ad hoc debug output in production pathsInspect implementationsrg 'Logger\.|IO\.inspect|dbg\(|inspect\(' lib
rg ':telemetry\.execute' lib
rg '__STACKTRACE__|Exception\.format|reraise|rescue' lib
rg 'defstruct' lib
rg '@derive.*Inspect|defimpl Inspect' lib
defmodule CredentialHandle do
@derive {Inspect, only: [:id, :provider, :expires_at]}
@enforce_keys [:id, :provider]
defstruct [:id, :provider, :expires_at, :materialized_secret]
end
defmodule Redactor do
@redacted "[REDACTED]"
def credential(%CredentialHandle{} = handle) do
%{
id: handle.id,
provider: handle.provider,
secret: @redacted
}
end
end
def handle_error({:error, :provider_timeout}) do
{:error, %{code: "provider_timeout", message: "Provider request timed out"}}
end
def handle_error(_unknown) do
{:error, %{code: "internal_error", message: "Internal error"}}
end
Inspect.Remove high-risk dynamic execution and unsafe term ingestion.
:erlang.binary_to_term/1binary_to_term/1Code.eval_string/1,2Code.eval_quoted/1,2,3rg 'binary_to_term|:erlang\.binary_to_term'
rg 'Code\.eval_string|Code\.eval_quoted|Code\.compile_string'
rg 'apply\(|Module\.concat|String\.to_atom'
term = :erlang.binary_to_term(payload)
term = :erlang.binary_to_term(payload, [:safe])
Use JSON or another explicit format with DTO validation:
with {:ok, decoded} <- Jason.decode(payload),
{:ok, request} <- RequestDTO.new(decoded) do
{:ok, request}
end
Do not execute strings.
Use:
Ensure every process is owned, supervised, observable, and killable.
spawnspawn_linkTask.start without supervisionTask.async without await/yield/shutdownGenServer.start_link calls in business logicrg 'spawn\(|spawn_link\(|spawn_monitor\(' lib test
rg 'Task\.start|Task\.async|Task\.supervisor|Task\.await|Task\.yield' lib test
rg 'GenServer\.start|GenServer\.start_link|DynamicSupervisor\.start_child' lib test
rg 'Supervisor\.child_spec|use Supervisor|use DynamicSupervisor' lib
spawn(fn -> Provider.call(request) end)
Task.Supervisor.start_child(MyApp.TaskSupervisor, fn ->
Provider.call(request)
end)
Use an explicit queue/worker system with supervision and backpressure.
For every process type, define:
| Question | Required Answer |
|---|---|
| Who owns it? | Supervisor/module |
| Who can start it? | Public API |
| Who can stop it? | Shutdown path |
| What happens on crash? | Restart strategy |
| What state can it hold? | Explicit state policy |
| How is it observed? | Telemetry/log metadata |
| How does it receive cancellation? | Timeout/shutdown rule |
Prevent unbounded mailbox growth, unbounded queues, and cascading memory failures.
GenServer.castsendrg 'GenServer\.cast|handle_cast' lib
rg 'Process\.send|send\(' lib
rg 'handle_info' lib
rg ':queue|Queue|Broadway|GenStage' lib
rg ':hibernate' lib
Use the right primitive:
| Problem | Preferred Tool |
|---|---|
| Bounded synchronous request | GenServer.call with timeout |
| Stream ingestion | GenStage / Broadway |
| Background jobs | Oban or supervised worker queue |
| Burst protection | explicit queue limits |
| Overload handling | load shedding / circuit breaker |
| Idle process memory | :hibernate |
Enum.each(events, fn event ->
GenServer.cast(Consumer, {:event, event})
end)
Producer.enqueue(events, max_demand: 100)
Or:
case WorkerPool.checkout() do
{:ok, worker} -> Worker.process(worker, event)
{:error, :overloaded} -> {:error, :load_shed}
end
cast.Separate pure business logic from process mechanics.
handle_callrg 'use GenServer|handle_call|handle_cast|handle_info' lib
rg 'HTTPoison|Req\.|Finch|Tesla|Ecto|Repo\.' lib
rg 'Nx\.|EXLA|Bumblebee|Explorer' lib
GenServer = process shell
Pure module = business logic
Adapter = side effects
def handle_call({:execute, request}, _from, state) do
result = Provider.call(request)
new_state = Map.put(state, request.id, result)
{:reply, result, new_state}
end
def handle_call({:execute, request}, _from, state) do
with {:ok, command} <- RuntimeLogic.prepare(request, state),
{:ok, task_ref} <- RuntimeTasks.start(command) do
{:reply, {:ok, task_ref}, state}
end
end
Pure logic:
defmodule RuntimeLogic do
def prepare(%Request{} = request, state) do
# deterministic transformation only
{:ok, %Command{request: request, prior_state: state}}
end
end
Stabilize external and durable interfaces.
rg 'Jason\.encode|Jason\.Encoder|Poison\.Encoder|derive.*Jason' lib
rg 'defimpl Jason\.Encoder|defimpl Poison\.Encoder' lib
rg 'version|schema_version|event_version' lib priv test
rg 'GraphQL|Absinthe|Plug|Phoenix\.Controller' lib
Internal structs should not automatically become external JSON.
Use explicit mappers:
defmodule ProviderRefJSON do
def encode(%ProviderRef{} = ref) do
%{
"version" => "v1",
"id" => ref.id,
"family" => to_string(ref.family)
}
end
end
Version durable events:
%{
"event_type" => "provider_selected",
"version" => 1,
"data" => %{
"provider_id" => "openai"
}
}
Add upcasters:
defmodule EventUpcaster do
def upcast(%{"event_type" => "provider_selected", "version" => 1} = event) do
put_in(event, ["version"], 2)
|> put_in(["data", "provider_ref"], event["data"]["provider_id"])
end
def upcast(%{"version" => 2} = event), do: event
end
Isolate durable state and side effects behind explicit interfaces.
Repo calls scattered through core logicrg 'Repo\.|Ecto\.Multi|insert!|update!|delete!|transaction' lib
rg 'ETS|:ets|Cache|Agent|persistent_term' lib
rg 'EventStore|append|projection|snapshot' lib
Create backend behaviours.
defmodule StateBackend do
@callback put(key :: term(), value :: term()) :: :ok | {:error, term()}
@callback get(key :: term()) :: {:ok, term()} | {:error, :not_found | term()}
end
Implement backends:
InMemoryBackend
ETSBackend
PostgresBackend
EventLogBackend
Inject the backend:
def execute(%ExecutionContext{state_backend: backend}, command) do
backend.put(command.key, command.value)
end
| Tier | Meaning |
|---|---|
| Tier 0 | Ephemeral, memory-only |
| Tier 1 | Recoverable within process/node |
| Tier 2 | Durable across deploy/restart |
| Tier 3 | Auditable event-sourced history |
Prevent packages/apps from relying on accidental transitive dependencies or root-only configuration.
mix.exsfind . -name mix.exs -maxdepth 4
rg 'defp deps|app:|in_umbrella' .
rg 'alias .*\.|import .*\.|require .*' apps lib test
rg 'Application\.get_env' apps lib
For every package/app:
For each module:
| Question | Required Answer |
|---|---|
| Which package owns this? | One package |
| Is it public API? | Yes/no |
| Who imports it? | Known consumers |
| Can it move? | Extraction criteria |
| Does it depend on root config? | Should be no |
Ensure runtime behavior can be traced across process, queue, node, and provider boundaries.
rg ':telemetry\.execute|Logger\.metadata|Logger\.info|Logger\.error' lib
rg 'trace_id|request_id|tenant_id|correlation_id|span' lib
rg 'Task\.|GenServer\.cast|Broadway|Oban|DynamicSupervisor' lib
Use an explicit trace/context object.
defmodule TraceContext do
@enforce_keys [:trace_id]
defstruct [:trace_id, :tenant_ref, :target_ref, :operation]
end
Pass it across async boundaries:
Task.Supervisor.start_child(MyApp.TaskSupervisor, fn ->
Logger.metadata(trace_id: context.trace.trace_id)
Worker.run(context, command)
end)
Telemetry should use bounded metadata:
:telemetry.execute(
[:my_app, :provider, :request, :stop],
%{duration_ms: duration},
%{
trace_id: context.trace.trace_id,
provider_ref: context.provider.ref,
result: :ok
}
)
Never include:
Improve readability and runtime behavior after safety-critical issues are under control.
This pass should come late because it often touches many files and can create noise.
rg 'Regex\.|~r/' lib test
def parse_auth_header(<<"Bearer ", token::binary>>) when byte_size(token) > 0 do
{:ok, token}
end
def parse_auth_header(_), do: {:error, :invalid_auth_header}
String.split/3 for simple delimiterscase String.split(value, ":", parts: 2) do
[left, right] -> {:ok, {left, right}}
_ -> {:error, :invalid_value}
end
Use NimbleParsec or a purpose-built parser when the input has grammar.
case CleanupDeeply nested success/error flows.
case parse(input) do
{:ok, parsed} ->
case validate(parsed) do
{:ok, valid} ->
execute(valid)
error ->
error
end
error ->
error
end
with {:ok, parsed} <- parse(input),
{:ok, valid} <- validate(parsed) do
execute(valid)
end
with.if/cond branches dispatching on shape/typedef handle(event) do
if event.type == :created do
...
else
...
end
end
def handle(%Event{type: :created} = event), do: ...
def handle(%Event{type: :deleted} = event), do: ...
def handle(%Event{}), do: {:error, :unsupported_event}
Repo.get or Repo.all inside loopsrg 'Repo\.all|Repo\.get|Repo\.one|Repo\.preload' lib
rg 'Enum\.map.*Repo\.|for .* <- .* do.*Repo\.' lib
rg 'from\(.*in' lib
Compose queries:
def active(query), do: where(query, [x], x.status == :active)
def ordered(query), do: order_by(query, [x], desc: x.inserted_at)
User
|> active()
|> ordered()
|> Repo.all()
Avoid N+1:
users =
User
|> preload([:profile, :roles])
|> Repo.all()
Make the cleanup durable so the codebase does not regress.
Run:
mix format --check-formatted
mix compile --warnings-as-errors
mix test
mix credo --strict
Where applicable:
mix sobelow
mix deps.audit
Run targeted scans again:
rg 'String\.to_atom|binary_to_atom|list_to_atom'
rg 'binary_to_term|:erlang\.binary_to_term'
rg 'Code\.eval_string|Code\.eval_quoted|Code\.compile_string'
rg 'Application\.get_env|System\.get_env'
rg 'spawn\(|spawn_link\(|Task\.start|Task\.async'
rg 'GenServer\.cast|Process\.send'
rg 'Logger\.|IO\.inspect|dbg\('
rg 'Regex\.|~r/'
Add automated checks for the most important rules.
Example script:
#!/usr/bin/env bash
set -euo pipefail
fail_if_found() {
pattern="$1"
message="$2"
if rg "$pattern" lib apps test; then
echo "$message"
exit 1
fi
}
fail_if_found 'String\.to_atom' 'Unsafe dynamic atom creation found'
fail_if_found 'binary_to_term\([^,]+\)' 'Unsafe binary_to_term without [:safe] found'
fail_if_found 'Code\.eval_string|Code\.eval_quoted' 'Runtime code evaluation found'
fail_if_found 'System\.get_env' 'System.get_env found outside approved config layer'
fail_if_found 'spawn\(|spawn_link\(' 'Bare process spawning found'
Keep exceptions in a reviewed allowlist rather than silently ignoring them.
Use this checklist for every cleanup PR.
# Cleanup Ledger
## Pass 0 — Baseline
Status:
Owner:
Started:
Completed:
### Findings
| ID | Rule | File | Risk | Owner | Status |
|---|---|---|---|---|---|
### Exceptions
| Rule | File | Reason | Owner | Expires |
|---|---|---|---|---|
### Tests Added
-
### Verification
- [ ] mix format --check-formatted
- [ ] mix compile --warnings-as-errors
- [ ] mix test
- [ ] mix credo --strict
Use this to prioritize findings inside each pass.
| Severity | Meaning | Examples |
|---|---|---|
| Critical | Can leak secrets, execute code, crash node, or violate authority boundaries | Code.eval_string, unsafe binary_to_term, raw secrets in logs |
| High | Can cause fail-open behavior, data corruption, or unbounded resource growth | unbounded atoms, unsupervised tasks, unbounded mailbox |
| Medium | Can cause drift, nondeterminism, or maintenance hazards | raw maps, unversioned events, scattered config |
| Low | Readability or local maintainability issue | nested case, query composition, minor regex usage |
For a large codebase, use this PR sequence:
The cleanup is complete when:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub xu-chris/ai-setup --plugin elixir5 skills in this plugin
/beam-security-hardeningHardens Elixir/Erlang/Phoenix code and deployments and answers Zero Trust architecture questions. Use when writing or reviewing code that parses untrusted input, deserializes terms, shells out, handles secrets, compares tokens, parses XML, or makes TLS connections; when adding LiveView routes, live_session, on_mount hooks, or authorization in mount/handle_event; when hardening releases, Erlang distribution, EPMD, or crash dumps; or when asked about the NSA Zero Trust Implementation Guidelines (ZIG), pillars, capabilities, activities, or technology mappings./elixir-architectUse when designing or architecting Elixir/Phoenix applications, creating comprehensive project documentation, planning OTP supervision trees, defining domain models with Ash Framework, structuring multi-app projects with path-based dependencies, or preparing handoff documentation for Director/Implementor AI collaboration/updating-dependenciesUpdate Elixir/Phoenix dependencies safely. Use when running mix hex.outdated, updating mix.exs version constraints, handling breaking version changes, reviewing changelogs for upgrades, or verifying updates with compile and test./writing-ash-codeWrite production-grade Ash Framework code with lead-engineer precision. Use when creating Ash resources, domains, actions, policies, calculations, aggregates, or relationships. Use when porting Ecto code to Ash, refactoring existing resources, adding authorization, or building LiveView forms with AshPhoenix. Use when adding background jobs with AshOban. Triggers on "add resource", "create action", "write policy", "port to Ash", "Ash migration", "manage_relationship", "oban trigger", "scheduled action", or any Ash DSL work.