Find behavior-preserving opportunities to make a codebase smaller, clearer, and less repetitive.
This skill reports opportunities only. It does not edit code and does not write tests.
It works on four slimming axes:
Dead code - unused functions, methods, variables, parameters, imports, types, exports,
constants, branches, files, and dependencies that nothing reaches. Includes superseded code
(an old implementation whose callers all moved to a replacement) and leftover files (backups,
one-off scripts, stale fixtures/configs/assets, docs for removed features).
Redundant code - duplicate or near-duplicate blocks, whether across the repo or repeated
inside a single file, including exact copy-paste clones and per-element function copies that
differ only in a literal where one loop or lookup table would do.
Wrapper and indirection removal - thin layers that forward without adding a real role,
including inert try/catch scaffolding that adds no handling, context, or recovery.
Comment volume - commented-out code, comments that restate the code, and banner walls that
add bytes without signal. Comments should be minimal and earn their place.
The goal is not fewer lines at any cost. The goal is lower maintenance burden with behavior,
performance, readability, and validation made explicit.
When to use
Finding behavior-preserving opportunities to simplify a repository, package, module, or PR
without implementing them
Hunting dead code: unused functions, variables, imports, types, exports, unreachable branches,
orphan files, and unused dependencies (Step 4 enumerates the full set)
Hunting superseded code and leftover files: old implementations replaced by a rewrite, legacy
paths after a completed migration, versioned leftovers (*_old, *_v1, *.bak, *copy*),
scratch/debug scripts, and files nothing loads
Flagging AI-bloat shapes for behavior-preserving collapse: inert try/catch (only rethrows, or
try around code that cannot throw) and N near-identical functions repeated per element where a
loop, map, or lookup table would do
Auditing duplicated logic, schemas, handlers, or adapters, and redundant blocks repeated across
the repo or inside a single file, including exact clones
Trimming comment volume: commented-out code, comments that restate the code, and banner walls
Finding safe centralization candidates before a cleanup/refactor PR, or reviewing a bot or human
cleanup PR that claims to reduce code size
Ranking maintainability refactors by value, risk, and validation needs, when the goal is smaller
behavior-preserving structure rather than general cleanliness or AI-slop detection
When NOT to use
Bug-focused reviews, regressions, races, edge cases, or crashes - use code-review
General cleanup, naming, AI tells, dependency creep, overengineering, comment noise as a
quality smell, or duplicate-code-as-slop without an explicit slimming goal - use anti-slop.
(Comment lane: code-slimming deletes commented-out code, restating comments, and banner walls;
anti-slop judges comment noise as a smell; anti-ai-prose rewrites AI-voiced comment text.)
(AI-bloat lane: code-slimming flags the deletable/collapsible subset - inert try/catch and
copy-per-element functions - with a concrete refactor shape; anti-slop judges AI style broadly.)
Rewriting comments or docstrings for tone and AI voice (not deleting them) - use anti-ai-prose
Security vulnerabilities, secret scanning, auth flaws, or exploitability - use security-audit
Writing, debugging, or adding validation tests for a slimming recommendation - use testing
Broad quick merge checks - use full-review
Comprehensive repo audits across all applicable dimensions - use deep-audit
Direct implementation work - use the relevant language, framework, or domain skill
Routing boundaries
User intent
Use
"Slim this codebase", "find safe deletions", "review LOC deletion"
"Find replaced/superseded code", "leftover files", "old version still in tree"
code-slimming
"Delete commented-out code", "cut these comment walls down"
code-slimming
"Remove this wrapper/indirection layer", "inline this passthrough"
code-slimming
"Useless try/catch everywhere", "collapse these repeated per-X functions into a loop"
code-slimming
"Clean this up", "does this look AI-written?", "overengineered/verbose"
anti-slop
"These comments are noisy/AI-slop, clean them up"
anti-slop
"This prose/comments read AI-written, rewrite the voice"
anti-ai-prose
"Review this", "find bugs", "sanity check", "will this break?"
code-review
"Write/add/debug tests for this refactor"
testing
"Run all checks", "full review", "audit this repo"
full-review or deep-audit
"Implement the slimming/refactor"
Relevant language/framework/domain skill
Do not activate this skill for generic review, cleanup, or audit wording unless the user explicitly
asks for slimming, deduplication, deletion, wrapper removal, or behavior-preserving size reduction.
AI Self-Check
Before returning a code-slimming audit, verify:
Read-only boundary held: no source files were edited and no tests were written
Behavior preserved: every recommendation names the behavior that must stay identical
Value explained: every recommendation states why the slimmer shape is better
Tradeoffs assessed: performance, coupling, readability, bundle size, allocation count,
and test brittleness were considered where relevant
Validation named: each Do now or Do with tests item lists concrete validation
commands or test coverage needs
No abstraction theater: no vague "make this generic" or "create a base class" advice
without the proposed shape
Duplication judged in context: likely divergence, framework conventions, and explicitness
were considered before recommending centralization
Defensive duplication preserved: repeated guards across trust, process, persistence, or
public-API boundaries were not flagged for removal solely because an upstream layer validates the
same condition
Dead code proven, not guessed: every "unused" claim cites a no-reference search and rules
out reflection, dynamic dispatch, DI, serialization, plugin/CLI/route registration, public API,
conditional compilation, and test discovery before recommending deletion
Superseded claims paired: every "replaced by X" claim names the replacement, shows callers
migrated, and confirms the old path is not a kept fallback, rollback target, or flag branch
Error-handling removal behavior-checked: every inert try/catch flag proves the catch adds
nothing (rethrows unchanged, or the wrapped code cannot throw); a catch that swallows or converts
errors changes behavior when removed and is never Do now
Comment trimming is deletion, not rewriting: only commented-out code, comments that
restate the code, and dead banner walls are flagged; tone and AI-voice rewrites are routed to
anti-ai-prose, and load-bearing comments (why, invariants, links, license, lint pragmas) are kept
Correctness and security routed: bugs go to code-review; vulnerabilities go to security-audit
Routing lane held: generic cleanup, slop, correctness, security, test-writing,
broad-review, and implementation work were routed instead of reported as code-slimming findings
Routing overlap checked: recommendations do not duplicate anti-slop, code-review, testing, full-review, or deep-audit responsibilities
Spec claims verified: any statement about skill behavior, output contracts, or repo conventions is checked against current skill files and scripts
Cross-cutting agent hygiene applied - see references/agent-hygiene.md
Performance
Start with changed files, shared modules, and repeated directory shapes before scanning the whole repo.
Group repeated examples into one finding with representative paths.
Prefer cheap structural searches before expensive test suites.
Best Practices
Treat smaller code as a hypothesis, not a win.
Treat "unused" as a claim that must be proven by search, not assumed from local reading. A symbol
with zero static references can still be live through reflection, dynamic dispatch, DI,
serialization, plugin/CLI/route registration, public API, conditional compilation, or test
discovery. Prove no-reference before recommending deletion.
Keep dead-looking code that is a stable public/exported API, a documented extension point, or
guarded behind a feature flag, build target, or platform; deleting these changes a contract.
Treat commented-out code as dead code: recommend deleting it, since version control already
preserves history. Keep comments that carry intent, invariants, links, license, or lint pragmas.
Prefer deleting wrappers over adding a new abstraction layer only after proving the wrapper has no
boundary, policy, observability, compatibility, or lifecycle role.
Prefer a small well-named helper over a framework-shaped base class.
Keep domain-specific duplication when the variants are likely to diverge.
Keep defensive duplication when checks intentionally repeat across trust boundaries, process
boundaries, public APIs, persistence layers, or privileged operations. Do not remove a repeated
guard just because an upstream layer appears to validate the same condition.
Avoid centralizing across independently versioned modules, separately owned teams, protocol or API
versions, tenant-specific behavior, or plugin/provider boundaries unless the shared contract is
explicit and stable.
Recommend tests before centralization when behavior differences are subtle or undercovered.
Workflow
Step 1: Determine scope
Pick the narrowest useful scope:
PR or diff - default when uncommitted changes or a branch diff exists
Specific path - use when the user names files or directories
Whole repo - use when the user asks for a repo-wide slimming audit
For git repos, gather cheap preflight context before deciding:
repo root and branch: git rev-parse --show-toplevel, git branch --show-current
existing shared modules, helper directories, framework conventions, and recent related commits
Note the language and framework patterns in the report header. A good centralization in Python may
be a bad abstraction in Rust, Java, or C.
Step 3: Identify validation without over-running it
Running existing read-only validation commands is allowed unless the user forbids command execution
or the commands have side effects. Separate validation into three passes:
Early baseline validation - cheap checks that describe current repo or diff health:
lint or format checks when fast and obvious
type or compile checks when fast and local
documented project validation commands
Candidate coverage evidence - after finding a slimming candidate, inspect existing tests,
callers, snapshots, fixtures, or examples that exercise the behavior to preserve.
Implementation validation - commands or tests someone must run if they implement the
recommendation.
Do not run expensive full suites before candidate discovery unless the user asked for PR validation
or the project makes the command cheap and standard. If a check is missing, slow, flaky, noisy,
unavailable, external-service-dependent, or exits zero while printing warnings, report that as a
validation gap. Do not call an opportunity safe when validation is absent.
Passing current checks does not by itself make a proposed slimming safe. Do now requires
behavior-specific coverage evidence, or a trivial mechanical change whose invariant is directly
verifiable. Generic lint, type, and build commands alone are not enough for behavioral
deduplication or centralization.
For future work, identify the validation an implementation must pass. Do not write tests in this
skill.
Step 4: Search for candidates
Run the searches for all four axes. Use structural and textual searches to find:
Dead code (unused / unreachable):
functions, methods, classes, variables, parameters, constants, types, and exports with no
references anywhere in scope
imports that are never used and dependencies in the manifest that nothing imports
files and modules that nothing imports, requires, includes, or registers (orphans)
unreachable code: statements after return/throw/break, if (false) branches, dead
case arms, conditions that cannot be true, and feature-flag branches for removed flags
superseded implementations: an old code path whose callers all moved to a replacement, legacy
branches after a completed migration, parallel old/new versions of the same unit
(*_old, *_v1, *_new, *.bak, *copy*, date-suffixed files)
leftover files: one-off or scratch/debug scripts, stale fixtures, configs, and assets nothing
loads, disabled or permanently skipped test files, docs describing removed features
commented-out code blocks left behind from past edits
Redundant / duplicate code:
near-duplicate files, classes, structs, functions, methods, hooks, handlers, or components
exact copy-paste clones repeated across files or repeated inside a single file
per-element function copies: N functions identical except one literal (an element name, field,
color, route, entity) - collapse to a loop, map, or lookup table only when the contracts are
identical and likely to stay identical
repeated type, interface, schema, DTO, record, enum, or data container shapes
parallel provider, client, repository, service, or adapter implementations with the same skeleton
dependencies or helpers duplicating standard library or framework features
generated-looking copy-paste that survived human maintenance, after checking whether a generator,
schema, template, or vendored source owns it
Wrappers and bloat:
wrappers with little behavior beyond forwarding to another object or function
inert error handling: try/catch that only rethrows, catch-log-rethrow adding no context, try
around code that cannot throw, blanket per-function try/catch added mechanically, and defensive
null checks on values a type system or upstream contract already guarantees (cite the guarantee);
a catch that swallows or converts errors is behavior-changing to remove - at best Do with tests, and route any swallowed-bug concern to code-review
oversized utils, helpers, common, shared, or misc modules
comment walls: banner art, comments that restate the next line, and stale doc blocks
Discovery recipe:
Build a candidate map from changed files, same-role siblings, repeated basenames, large generic
modules, and repeated exported symbols, routes, schemas, DTOs, handlers, parsers, validators,
mappers, and serializers.
Use cheap searches before manual reading: compare same-role trees such as providers/*,
clients/*, services/*, repositories/*, handlers/*, routes/*, and adapters/*; search
repeated declarations and one-line wrappers that only forward to another call; find large generic
modules named utils, helpers, common, shared, or misc; search versioned/backup
basenames (_old, _v1, .bak, copy, date suffixes) and catch blocks that only rethrow
or log-and-rethrow.
For dead-code candidates, search for every reference to the symbol (definition site, call sites,
re-exports, string-keyed lookups, config/route tables, DI registrations) before classifying it
unused. Lean on the repo's own dead-code and clone tooling when present - it scopes the search
and reduces both misses and false positives:
Treat tool output as a candidate list, not a verdict: confirm each hit by reading, and discount
known false positives (reflection, dynamic dispatch, DI, serialization, plugin/CLI/route
registration, public API, conditional compilation, test discovery). When no tooling is available,
say so as a coverage gap.
For each candidate, read the full candidate files, at least one nearby caller, and nearby tests
to see whether the behavior contract is already captured, before classifying.
Skip or de-prioritize generated files, vendored dependencies, lockfiles, snapshots, fixtures,
minified bundles, protobuf/OpenAPI generated clients, and build artifacts unless the user scopes them.
When duplication appears in generated output, recommend changing the generator, schema, or template,
or exclude it from slimming findings. Do not recommend hand-editing generated output.
Read surrounding code before judging. Similar shape is not enough. The question is whether one
shared behavior path would be clearer, safer, and easier to validate.
Step 5: Classify opportunities
Use these labels:
Do now - small, obvious, low risk, and already covered by meaningful validation
Do with tests - likely worthwhile, but needs focused tests before implementation
Defer - valid but too broad, risky, or low-value for current churn
Leave alone - duplication is clearer, faster, intentional, or likely to diverge
These labels are audit recommendations only. Even Do now does not authorize this skill to edit
code; it means the proposed change appears safe for a separate implementation pass.
Every classified item must cite:
representative file paths and line ranges
the repeated behavior or wrapper behavior observed
the behavior invariant that must remain identical
existing validation evidence or the missing validation gap
why similar-looking cases are included, excluded, or left alone
Most findings are not merge blockers. Say so clearly.
For Do now, cite behavior-specific validation evidence: exact test files or cases that exercise
the preserved behavior, or explain why the change is purely local, mechanical, and directly
inspectable. If you cannot cite behavior-specific evidence, classify as Do with tests or Defer.
For dead-code and commented-out-code deletions, the evidence is the no-reference proof: the search
that found zero live references and the indirection paths ruled out (reflection, dynamic dispatch,
DI, serialization, plugin/CLI/route registration, public API, conditional compilation, test
discovery). A symbol unreferenced and unreachable through any of those paths is a valid Do now. If
it is exported or reachable through an unproven path, classify as Do with tests or Defer and say
which path you could not rule out.
Step 6: Evaluate tradeoffs
For every recommendation, answer:
What behavior must remain identical?
What gets smaller: LOC, concept count, duplicated call sites, public API surface, dependency
count, file count, or test surface?
What might get worse: runtime performance, bundle size, allocation count, readability, coupling,
test brittleness, or onboarding clarity?
Why is the proposed centralization better than the current duplication?
What validation would prove the change is safe?
Are duplicated checks intentionally defensive at separate boundaries, and what fails closed if one
layer is bypassed?
If a slimmer implementation affects hot paths, rendering loops, query batching, serialization,
startup, memory layout, build output, or binary size, require performance-sensitive validation
before classifying it as Do now.
Step 7: Report
It is acceptable and often correct to return zero high-value opportunities. Do not manufacture a
slimming recommendation to fill the report. Prefer a well-justified Leave alone finding over a
low-confidence abstraction.
The written deliverable follows references/report-templates.md: one template for audits with
findings (grouped by action label, plus a Removed-Code Safety Review section when the reviewed
diff removed code) and one for the zero-findings case (explicit search coverage and why-no-action
sections). The report is a read-only set of proposals: it intentionally opts out of the checkbox
Fix protocol in the Output Contract (there is nothing for an implementer to flip here). Wrap the
body with the monospace inline header, severity-grouped summary, and concise monospace conclusion
when emitting to the transcript. The saved Markdown conclusion table remaps the shared columns
exactly as defined in the Output Contract section below (Type = rec/found, Priority carries
Risk, Action = proposed/recommend).
Keep the report concise. Show the refactor shape, not a lecture.
Common Patterns
Pattern-by-pattern recognition aids - dead code and unused symbols, superseded and replaced code,
leftover files, exact and intra-file clones, commented-out code and comment walls, per-element
function copies, inert try/catch and defensive scaffolding, repeated boundary parsing, near-twin
adapters, duplicate data shapes, wrapper layers, oversized helper modules, and performance-sensitive
slimming - live in references/patterns.md. Consult it when a candidate's category or safe-collapse
shape is unclear.
Output Contract
See references/output-contract.md for the full contract.
Skill name: CODE-SLIMMING
Deliverable bucket:audits
Mode: always-on for audit and review invocations. Every invocation that analyses existing code emits the full contract - monospace inline header, severity-grouped inline summary, linked Markdown deliverable, and concise monospace conclusion. For a quick factual question (e.g., "what is wrapper removal?") respond freely without the contract.
Deliverable path:docs/local/audits/code-slimming/<YYYY-MM-DD>-<slug>.md, resolved against
the audited repo's root (use the session cwd only when the audit target is not a repo)
Severity scale: this skill overrides the shared P0-P3 scale, which the contract permits via its scale-migration note. Findings are classified by action - Do now | Do with tests | Defer | Leave alone - plus a Risk: low | medium | high field per finding (see the Workflow). This skill proposes deletions, not severity-ranked defects. Old -> new: P0-P3 priority is not used; Risk replaces the Priority column (see Conclusion-table columns below).
Conclusion-table columns (the shared table in references/output-contract.md is code-review-flavored; map it for this skill): Type is rec for opportunities or found when reviewing removed code; the Priority column carries this skill's Risk value (low | medium | high), not a P-level; Action is proposed for opportunities and recommend for removed-code safety findings. The file-deliverable groups findings by action label (Do now, Do with tests, Defer, Leave alone), not by ## P0-style headings.
Related Skills
anti-slop - code quality audit for AI-like patterns, over-abstraction, noisy comments,
hallucinated APIs, and test theater.
anti-ai-prose - prose-slimming for AI voice in docs, comments, and docstrings. Use when the
goal is removing AI-written prose patterns rather than reducing code size.
code-review - correctness audit for bugs, regressions, races, edge cases, and broken contracts.
testing - writes and debugs tests required before implementing a slimming recommendation.
security-audit - reviews security-sensitive code where "defensive" duplication may be necessary.
full-review - quick four-pass merge-safety audit; does not include code-slimming by default.
deep-audit - comprehensive repo audit; includes code-slimming as a Wave 2 maintainability pass.
Rules
Do not edit code. This skill reports opportunities only.
Do not write tests. Name missing tests and route test implementation to testing.
Do not chase LOC alone. Smaller code that is slower, more coupled, or harder to understand
is not automatically better.
Require a concrete refactor shape. Every recommendation must describe what would be
extracted, deleted, moved, or centralized.
Explain why. Every recommendation must state the maintenance benefit and the behavior that
must remain unchanged.
Validate before calling it safe. A Do now recommendation needs behavior-specific
validation evidence, or a purely local mechanical invariant that was directly inspected.
Respect language idioms. Generic helpers, inheritance, macros, templates, reflection, and
dynamic dispatch have different costs across Python, JavaScript/TypeScript, Java, Rust, C/C++,
shell, and infrastructure code.
Keep bugs and vulnerabilities in their lanes. Route correctness findings to code-review and
security findings to security-audit.
Prove dead before deleting. Never recommend deleting a symbol, file, or dependency as unused
without a no-reference search and an explicit list of indirection paths ruled out (reflection,
dynamic dispatch, DI, serialization, plugin/CLI/route registration, public API, conditional
compilation, test discovery).
Trim comments by deletion, not rewriting. Flag only commented-out code, comments that
restate the code, and dead banner walls. Keep intent, invariants, links, license, and pragmas.
Route AI-voice prose rewrites to anti-ai-prose.
1---2name: code-slimming3description: >4 · Audit read-only code slimming: dead/superseded code, unused files, duplicates, wrappers, inert try/catch, copy-per-element functions. Triggers: 'slim codebase', 'dead code', 'unused files', 'dedupe'. Not for bugs or broad reviews.5license: MIT6compatibility: "None - works on any codebase"7metadata:8 source: iuliandita/skills9 date_added: "2026-05-02"10 effort: medium11 argument_hint: "[scope-or-diff]"12---1314# Code Slimming: Read-Only Refactor Opportunity Audit1516Find behavior-preserving opportunities to make a codebase smaller, clearer, and less repetitive.17This skill reports opportunities only. It does not edit code and does not write tests.1819It works on four slimming axes:20211. **Dead code** - unused functions, methods, variables, parameters, imports, types, exports,22 constants, branches, files, and dependencies that nothing reaches. Includes superseded code23 (an old implementation whose callers all moved to a replacement) and leftover files (backups,24 one-off scripts, stale fixtures/configs/assets, docs for removed features).252. **Redundant code** - duplicate or near-duplicate blocks, whether across the repo or repeated26 inside a single file, including exact copy-paste clones and per-element function copies that27 differ only in a literal where one loop or lookup table would do.283. **Wrapper and indirection removal** - thin layers that forward without adding a real role,29 including inert try/catch scaffolding that adds no handling, context, or recovery.304. **Comment volume** - commented-out code, comments that restate the code, and banner walls that31 add bytes without signal. Comments should be minimal and earn their place.3233The goal is not fewer lines at any cost. The goal is lower maintenance burden with behavior,34performance, readability, and validation made explicit.3536## When to use3738- Finding behavior-preserving opportunities to simplify a repository, package, module, or PR39 without implementing them40- Hunting dead code: unused functions, variables, imports, types, exports, unreachable branches,41 orphan files, and unused dependencies (Step 4 enumerates the full set)42- Hunting superseded code and leftover files: old implementations replaced by a rewrite, legacy43 paths after a completed migration, versioned leftovers (`*_old`, `*_v1`, `*.bak`, `*copy*`),44 scratch/debug scripts, and files nothing loads45- Flagging AI-bloat shapes for behavior-preserving collapse: inert try/catch (only rethrows, or46 try around code that cannot throw) and N near-identical functions repeated per element where a47 loop, map, or lookup table would do48- Auditing duplicated logic, schemas, handlers, or adapters, and redundant blocks repeated across49 the repo or inside a single file, including exact clones50- Trimming comment volume: commented-out code, comments that restate the code, and banner walls51- Finding safe centralization candidates before a cleanup/refactor PR, or reviewing a bot or human52 cleanup PR that claims to reduce code size53- Ranking maintainability refactors by value, risk, and validation needs, when the goal is smaller54 behavior-preserving structure rather than general cleanliness or AI-slop detection5556## When NOT to use5758- Bug-focused reviews, regressions, races, edge cases, or crashes - use **code-review**59- General cleanup, naming, AI tells, dependency creep, overengineering, comment noise as a60 quality smell, or duplicate-code-as-slop without an explicit slimming goal - use **anti-slop**.61 (Comment lane: code-slimming deletes commented-out code, restating comments, and banner walls;62 anti-slop judges comment noise as a smell; anti-ai-prose rewrites AI-voiced comment text.)63 (AI-bloat lane: code-slimming flags the deletable/collapsible subset - inert try/catch and64 copy-per-element functions - with a concrete refactor shape; anti-slop judges AI style broadly.)65- Rewriting comments or docstrings for tone and AI voice (not deleting them) - use **anti-ai-prose**66- Security vulnerabilities, secret scanning, auth flaws, or exploitability - use **security-audit**67- Writing, debugging, or adding validation tests for a slimming recommendation - use **testing**68- Broad quick merge checks - use **full-review**69- Comprehensive repo audits across all applicable dimensions - use **deep-audit**70- Direct implementation work - use the relevant language, framework, or domain skill7172## Routing boundaries7374| User intent | Use |75|---|---|76| "Slim this codebase", "find safe deletions", "review LOC deletion" | **code-slimming** |77| "Find dead/unused code", "unused functions/files", "remove duplicates" | **code-slimming** |78| "Find replaced/superseded code", "leftover files", "old version still in tree" | **code-slimming** |79| "Delete commented-out code", "cut these comment walls down" | **code-slimming** |80| "Remove this wrapper/indirection layer", "inline this passthrough" | **code-slimming** |81| "Useless try/catch everywhere", "collapse these repeated per-X functions into a loop" | **code-slimming** |82| "Clean this up", "does this look AI-written?", "overengineered/verbose" | **anti-slop** |83| "These comments are noisy/AI-slop, clean them up" | **anti-slop** |84| "This prose/comments read AI-written, rewrite the voice" | **anti-ai-prose** |85| "Review this", "find bugs", "sanity check", "will this break?" | **code-review** |86| "Write/add/debug tests for this refactor" | **testing** |87| "Run all checks", "full review", "audit this repo" | **full-review** or **deep-audit** |88| "Implement the slimming/refactor" | Relevant language/framework/domain skill |8990Do not activate this skill for generic review, cleanup, or audit wording unless the user explicitly91asks for slimming, deduplication, deletion, wrapper removal, or behavior-preserving size reduction.9293---9495## AI Self-Check9697Before returning a code-slimming audit, verify:9899- [ ] **Read-only boundary held**: no source files were edited and no tests were written100- [ ] **Behavior preserved**: every recommendation names the behavior that must stay identical101- [ ] **Value explained**: every recommendation states why the slimmer shape is better102- [ ] **Tradeoffs assessed**: performance, coupling, readability, bundle size, allocation count,103 and test brittleness were considered where relevant104- [ ] **Validation named**: each `Do now` or `Do with tests` item lists concrete validation105 commands or test coverage needs106- [ ] **No abstraction theater**: no vague "make this generic" or "create a base class" advice107 without the proposed shape108- [ ] **Duplication judged in context**: likely divergence, framework conventions, and explicitness109 were considered before recommending centralization110- [ ] **Defensive duplication preserved**: repeated guards across trust, process, persistence, or111 public-API boundaries were not flagged for removal solely because an upstream layer validates the112 same condition113- [ ] **Dead code proven, not guessed**: every "unused" claim cites a no-reference search and rules114 out reflection, dynamic dispatch, DI, serialization, plugin/CLI/route registration, public API,115 conditional compilation, and test discovery before recommending deletion116- [ ] **Superseded claims paired**: every "replaced by X" claim names the replacement, shows callers117 migrated, and confirms the old path is not a kept fallback, rollback target, or flag branch118- [ ] **Error-handling removal behavior-checked**: every inert try/catch flag proves the catch adds119 nothing (rethrows unchanged, or the wrapped code cannot throw); a catch that swallows or converts120 errors changes behavior when removed and is never `Do now`121- [ ] **Comment trimming is deletion, not rewriting**: only commented-out code, comments that122 restate the code, and dead banner walls are flagged; tone and AI-voice rewrites are routed to123 anti-ai-prose, and load-bearing comments (why, invariants, links, license, lint pragmas) are kept124- [ ] **Correctness and security routed**: bugs go to code-review; vulnerabilities go to security-audit125- [ ] **Routing lane held**: generic cleanup, slop, correctness, security, test-writing,126 broad-review, and implementation work were routed instead of reported as code-slimming findings127- [ ] **Routing overlap checked**: recommendations do not duplicate anti-slop, code-review, testing, full-review, or deep-audit responsibilities128- [ ] **Spec claims verified**: any statement about skill behavior, output contracts, or repo conventions is checked against current skill files and scripts129- [ ] Cross-cutting agent hygiene applied - see `references/agent-hygiene.md`130131---132133## Performance134135- Start with changed files, shared modules, and repeated directory shapes before scanning the whole repo.136- Group repeated examples into one finding with representative paths.137- Prefer cheap structural searches before expensive test suites.138139---140141## Best Practices142143- Treat smaller code as a hypothesis, not a win.144- Treat "unused" as a claim that must be proven by search, not assumed from local reading. A symbol145 with zero static references can still be live through reflection, dynamic dispatch, DI,146 serialization, plugin/CLI/route registration, public API, conditional compilation, or test147 discovery. Prove no-reference before recommending deletion.148- Keep dead-looking code that is a stable public/exported API, a documented extension point, or149 guarded behind a feature flag, build target, or platform; deleting these changes a contract.150- Treat commented-out code as dead code: recommend deleting it, since version control already151 preserves history. Keep comments that carry intent, invariants, links, license, or lint pragmas.152- Prefer deleting wrappers over adding a new abstraction layer only after proving the wrapper has no153 boundary, policy, observability, compatibility, or lifecycle role.154- Prefer a small well-named helper over a framework-shaped base class.155- Keep domain-specific duplication when the variants are likely to diverge.156- Keep defensive duplication when checks intentionally repeat across trust boundaries, process157 boundaries, public APIs, persistence layers, or privileged operations. Do not remove a repeated158 guard just because an upstream layer appears to validate the same condition.159- Avoid centralizing across independently versioned modules, separately owned teams, protocol or API160 versions, tenant-specific behavior, or plugin/provider boundaries unless the shared contract is161 explicit and stable.162- Recommend tests before centralization when behavior differences are subtle or undercovered.163164## Workflow165166### Step 1: Determine scope167168Pick the narrowest useful scope:169170- **PR or diff** - default when uncommitted changes or a branch diff exists171- **Specific path** - use when the user names files or directories172- **Whole repo** - use when the user asks for a repo-wide slimming audit173174For git repos, gather cheap preflight context before deciding:175176- repo root and branch: `git rev-parse --show-toplevel`, `git branch --show-current`177- uncommitted files: `git diff --name-only`, `git diff --cached --name-only`178- branch base when available: `git merge-base HEAD @{upstream}`; otherwise detect the default179 branch and use `git merge-base HEAD origin/<default-branch>`180- default branch when needed: `git symbolic-ref refs/remotes/origin/HEAD --short 2>/dev/null`181 or inspect `git remote show origin`182- changed files and size: `git diff --name-only <base>...HEAD`, `git diff --stat <base>...HEAD`183184Scope precedence:1851861. User-provided diff or path1872. Uncommitted changes1883. Current branch against upstream1894. Current branch against the default branch1905. Whole repo, or ask one concise question when interactive191192If the scope is unclear and no diff exists, ask one concise question. In headless contexts, default193to whole repo and state the assumption.194195### Step 2: Gather context196197Read project instructions and manifests before judging code shape:198199- instruction files: `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `.cursor/rules`, `.windsurfrules`200- manifests: `package.json`, `pyproject.toml`, `go.mod`, `Cargo.toml`, `pom.xml`,201 `build.gradle`, `CMakeLists.txt`, `Makefile`202- test and check scripts203- existing shared modules, helper directories, framework conventions, and recent related commits204205Note the language and framework patterns in the report header. A good centralization in Python may206be a bad abstraction in Rust, Java, or C.207208### Step 3: Identify validation without over-running it209210Running existing read-only validation commands is allowed unless the user forbids command execution211or the commands have side effects. Separate validation into three passes:2122131. **Early baseline validation** - cheap checks that describe current repo or diff health:214 - lint or format checks when fast and obvious215 - type or compile checks when fast and local216 - documented project validation commands2172. **Candidate coverage evidence** - after finding a slimming candidate, inspect existing tests,218 callers, snapshots, fixtures, or examples that exercise the behavior to preserve.2193. **Implementation validation** - commands or tests someone must run if they implement the220 recommendation.221222Do not run expensive full suites before candidate discovery unless the user asked for PR validation223or the project makes the command cheap and standard. If a check is missing, slow, flaky, noisy,224unavailable, external-service-dependent, or exits zero while printing warnings, report that as a225validation gap. Do not call an opportunity safe when validation is absent.226227Passing current checks does not by itself make a proposed slimming safe. `Do now` requires228behavior-specific coverage evidence, or a trivial mechanical change whose invariant is directly229verifiable. Generic lint, type, and build commands alone are not enough for behavioral230deduplication or centralization.231232For future work, identify the validation an implementation must pass. Do not write tests in this233skill.234235### Step 4: Search for candidates236237Run the searches for all four axes. Use structural and textual searches to find:238239**Dead code (unused / unreachable):**240241- functions, methods, classes, variables, parameters, constants, types, and exports with no242 references anywhere in scope243- imports that are never used and dependencies in the manifest that nothing imports244- files and modules that nothing imports, requires, includes, or registers (orphans)245- unreachable code: statements after `return`/`throw`/`break`, `if (false)` branches, dead246 `case` arms, conditions that cannot be true, and feature-flag branches for removed flags247- superseded implementations: an old code path whose callers all moved to a replacement, legacy248 branches after a completed migration, parallel old/new versions of the same unit249 (`*_old`, `*_v1`, `*_new`, `*.bak`, `*copy*`, date-suffixed files)250- leftover files: one-off or scratch/debug scripts, stale fixtures, configs, and assets nothing251 loads, disabled or permanently skipped test files, docs describing removed features252- commented-out code blocks left behind from past edits253254**Redundant / duplicate code:**255256- near-duplicate files, classes, structs, functions, methods, hooks, handlers, or components257- exact copy-paste clones repeated across files or repeated inside a single file258- per-element function copies: N functions identical except one literal (an element name, field,259 color, route, entity) - collapse to a loop, map, or lookup table only when the contracts are260 identical and likely to stay identical261- repeated type, interface, schema, DTO, record, enum, or data container shapes262- repeated request parsing, query construction, pagination, validation, mapping, serialization, or error handling263- parallel provider, client, repository, service, or adapter implementations with the same skeleton264- dependencies or helpers duplicating standard library or framework features265- generated-looking copy-paste that survived human maintenance, after checking whether a generator,266 schema, template, or vendored source owns it267268**Wrappers and bloat:**269270- wrappers with little behavior beyond forwarding to another object or function271- inert error handling: try/catch that only rethrows, catch-log-rethrow adding no context, try272 around code that cannot throw, blanket per-function try/catch added mechanically, and defensive273 null checks on values a type system or upstream contract already guarantees (cite the guarantee);274 a catch that swallows or converts errors is behavior-changing to remove - at best `Do with275 tests`, and route any swallowed-bug concern to code-review276- oversized `utils`, `helpers`, `common`, `shared`, or `misc` modules277- comment walls: banner art, comments that restate the next line, and stale doc blocks278279Discovery recipe:2802811. Build a candidate map from changed files, same-role siblings, repeated basenames, large generic282 modules, and repeated exported symbols, routes, schemas, DTOs, handlers, parsers, validators,283 mappers, and serializers.2842. Use cheap searches before manual reading: compare same-role trees such as `providers/*`,285 `clients/*`, `services/*`, `repositories/*`, `handlers/*`, `routes/*`, and `adapters/*`; search286 repeated declarations and one-line wrappers that only forward to another call; find large generic287 modules named `utils`, `helpers`, `common`, `shared`, or `misc`; search versioned/backup288 basenames (`_old`, `_v1`, `.bak`, `copy`, date suffixes) and catch blocks that only rethrow289 or log-and-rethrow.2903. For dead-code candidates, search for every reference to the symbol (definition site, call sites,291 re-exports, string-keyed lookups, config/route tables, DI registrations) before classifying it292 unused. Lean on the repo's own dead-code and clone tooling when present - it scopes the search293 and reduces both misses and false positives:294295 | Concern | Common language-agnostic or per-language tools |296 |---|---|297 | Unused symbols/exports | `knip` (TS/JS; supersedes the archived `ts-prune`); `vulture`, `ruff` F401/F841 (Python); `staticcheck`, `deadcode` (Go); `cargo` `dead_code` warnings (Rust); compiler `-Wunused` (C/C++) |298 | Unused dependencies | `knip`, `depcheck` (JS); `deptry` (Python); `cargo-machete` (Rust) |299 | Copy-paste clones | `jscpd` (multi-language), `PMD CPD` (multi-language) |300301 Treat tool output as a candidate list, not a verdict: confirm each hit by reading, and discount302 known false positives (reflection, dynamic dispatch, DI, serialization, plugin/CLI/route303 registration, public API, conditional compilation, test discovery). When no tooling is available,304 say so as a coverage gap.3054. For each candidate, read the full candidate files, at least one nearby caller, and nearby tests306 to see whether the behavior contract is already captured, before classifying.307308Skip or de-prioritize generated files, vendored dependencies, lockfiles, snapshots, fixtures,309minified bundles, protobuf/OpenAPI generated clients, and build artifacts unless the user scopes them.310When duplication appears in generated output, recommend changing the generator, schema, or template,311or exclude it from slimming findings. Do not recommend hand-editing generated output.312313Read surrounding code before judging. Similar shape is not enough. The question is whether one314shared behavior path would be clearer, safer, and easier to validate.315316### Step 5: Classify opportunities317318Use these labels:319320- **Do now** - small, obvious, low risk, and already covered by meaningful validation321- **Do with tests** - likely worthwhile, but needs focused tests before implementation322- **Defer** - valid but too broad, risky, or low-value for current churn323- **Leave alone** - duplication is clearer, faster, intentional, or likely to diverge324325These labels are audit recommendations only. Even `Do now` does not authorize this skill to edit326code; it means the proposed change appears safe for a separate implementation pass.327328Every classified item must cite:329330- representative file paths and line ranges331- the repeated behavior or wrapper behavior observed332- the behavior invariant that must remain identical333- existing validation evidence or the missing validation gap334- why similar-looking cases are included, excluded, or left alone335336Most findings are not merge blockers. Say so clearly.337338For `Do now`, cite behavior-specific validation evidence: exact test files or cases that exercise339the preserved behavior, or explain why the change is purely local, mechanical, and directly340inspectable. If you cannot cite behavior-specific evidence, classify as `Do with tests` or `Defer`.341342For dead-code and commented-out-code deletions, the evidence is the no-reference proof: the search343that found zero live references and the indirection paths ruled out (reflection, dynamic dispatch,344DI, serialization, plugin/CLI/route registration, public API, conditional compilation, test345discovery). A symbol unreferenced and unreachable through any of those paths is a valid `Do now`. If346it is exported or reachable through an unproven path, classify as `Do with tests` or `Defer` and say347which path you could not rule out.348349### Step 6: Evaluate tradeoffs350351For every recommendation, answer:352353- What behavior must remain identical?354- What gets smaller: LOC, concept count, duplicated call sites, public API surface, dependency355 count, file count, or test surface?356- What might get worse: runtime performance, bundle size, allocation count, readability, coupling,357 test brittleness, or onboarding clarity?358- Why is the proposed centralization better than the current duplication?359- What validation would prove the change is safe?360- Are duplicated checks intentionally defensive at separate boundaries, and what fails closed if one361 layer is bypassed?362363If a slimmer implementation affects hot paths, rendering loops, query batching, serialization,364startup, memory layout, build output, or binary size, require performance-sensitive validation365before classifying it as `Do now`.366367### Step 7: Report368369It is acceptable and often correct to return zero high-value opportunities. Do not manufacture a370slimming recommendation to fill the report. Prefer a well-justified `Leave alone` finding over a371low-confidence abstraction.372373The written deliverable follows `references/report-templates.md`: one template for audits with374findings (grouped by action label, plus a Removed-Code Safety Review section when the reviewed375diff removed code) and one for the zero-findings case (explicit search coverage and why-no-action376sections). The report is a read-only set of proposals: it intentionally opts out of the checkbox377Fix protocol in the Output Contract (there is nothing for an implementer to flip here). Wrap the378body with the monospace inline header, severity-grouped summary, and concise monospace conclusion379when emitting to the transcript. The saved Markdown conclusion table remaps the shared columns380exactly as defined in the Output Contract section below (`Type` = `rec`/`found`, `Priority` carries381`Risk`, `Action` = `proposed`/`recommend`).382383Keep the report concise. Show the refactor shape, not a lecture.384385## Common Patterns386387Pattern-by-pattern recognition aids - dead code and unused symbols, superseded and replaced code,388leftover files, exact and intra-file clones, commented-out code and comment walls, per-element389function copies, inert try/catch and defensive scaffolding, repeated boundary parsing, near-twin390adapters, duplicate data shapes, wrapper layers, oversized helper modules, and performance-sensitive391slimming - live in `references/patterns.md`. Consult it when a candidate's category or safe-collapse392shape is unclear.393394## Output Contract395396See `references/output-contract.md` for the full contract.397398- **Skill name:** CODE-SLIMMING399- **Deliverable bucket:** `audits`400- **Mode:** always-on for audit and review invocations. Every invocation that analyses existing code emits the full contract - monospace inline header, severity-grouped inline summary, linked Markdown deliverable, and concise monospace conclusion. For a quick factual question (e.g., "what is wrapper removal?") respond freely without the contract.401- **Deliverable path:** `docs/local/audits/code-slimming/<YYYY-MM-DD>-<slug>.md`, resolved against402 the audited repo's root (use the session cwd only when the audit target is not a repo)403- **Severity scale:** this skill overrides the shared P0-P3 scale, which the contract permits via its scale-migration note. Findings are classified by action - `Do now | Do with tests | Defer | Leave alone` - plus a `Risk: low | medium | high` field per finding (see the Workflow). This skill proposes deletions, not severity-ranked defects. Old -> new: P0-P3 priority is not used; `Risk` replaces the `Priority` column (see Conclusion-table columns below).404- **Conclusion-table columns** (the shared table in `references/output-contract.md` is code-review-flavored; map it for this skill): `Type` is `rec` for opportunities or `found` when reviewing removed code; the `Priority` column carries this skill's `Risk` value (`low | medium | high`), not a P-level; `Action` is `proposed` for opportunities and `recommend` for removed-code safety findings. The file-deliverable groups findings by action label (`Do now`, `Do with tests`, `Defer`, `Leave alone`), not by `## P0`-style headings.405406## Related Skills407408- **anti-slop** - code quality audit for AI-like patterns, over-abstraction, noisy comments,409 hallucinated APIs, and test theater.410- **anti-ai-prose** - prose-slimming for AI voice in docs, comments, and docstrings. Use when the411 goal is removing AI-written prose patterns rather than reducing code size.412- **code-review** - correctness audit for bugs, regressions, races, edge cases, and broken contracts.413- **testing** - writes and debugs tests required before implementing a slimming recommendation.414- **security-audit** - reviews security-sensitive code where "defensive" duplication may be necessary.415- **full-review** - quick four-pass merge-safety audit; does not include code-slimming by default.416- **deep-audit** - comprehensive repo audit; includes code-slimming as a Wave 2 maintainability pass.417418## Rules4194201. **Do not edit code.** This skill reports opportunities only.4212. **Do not write tests.** Name missing tests and route test implementation to testing.4223. **Do not chase LOC alone.** Smaller code that is slower, more coupled, or harder to understand423 is not automatically better.4244. **Require a concrete refactor shape.** Every recommendation must describe what would be425 extracted, deleted, moved, or centralized.4265. **Explain why.** Every recommendation must state the maintenance benefit and the behavior that427 must remain unchanged.4286. **Validate before calling it safe.** A `Do now` recommendation needs behavior-specific429 validation evidence, or a purely local mechanical invariant that was directly inspected.4307. **Respect language idioms.** Generic helpers, inheritance, macros, templates, reflection, and431 dynamic dispatch have different costs across Python, JavaScript/TypeScript, Java, Rust, C/C++,432 shell, and infrastructure code.4338. **Keep bugs and vulnerabilities in their lanes.** Route correctness findings to code-review and434 security findings to security-audit.4359. **Prove dead before deleting.** Never recommend deleting a symbol, file, or dependency as unused436 without a no-reference search and an explicit list of indirection paths ruled out (reflection,437 dynamic dispatch, DI, serialization, plugin/CLI/route registration, public API, conditional438 compilation, test discovery).43910. **Trim comments by deletion, not rewriting.** Flag only commented-out code, comments that440 restate the code, and dead banner walls. Keep intent, invariants, links, license, and pragmas.441 Route AI-voice prose rewrites to anti-ai-prose.
Run npx skillmds@latest add iuliandita/code-slimming in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
· Audit read-only code slimming: dead/superseded code, unused files, duplicates, wrappers, inert try/catch, copy-per-element functions. Triggers: 'slim codebase', 'dead code', 'unused files', 'dedupe'. Not for bugs or broad reviews. It is listed under Security on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free. This skill is licensed under MIT.
iuliandita (@iuliandita) published this skill. Their other Agent Skills are listed on their SkillMD profile.