Agent skill
defrag
Analyze code for refactoring opportunities and suggest the top 10 highest-value improvements. Use this whenever the user says `/defrag`, asks to refactor, clean up code, improve code quality, identify code smells, or wants a ranked list of code improvements. This skill is for analysis only unless the user explicitly asks to apply a specific suggestion.
Install this agent skill to your Project
npx add-skill https://github.com/hexbee/hello-skills/tree/main/skills/defrag
SKILL.md
Defrag
Purpose
Use this skill to inspect one or more files, identify the highest-value refactoring opportunities, and present a ranked top 10 list with concrete code-level suggestions.
This skill is analysis-first. Do not apply edits unless the user explicitly switches from analysis to implementation.
Default Behavior
- Determine the target scope.
- Read the relevant files or the user's current selection.
- Inspect the code for the refactoring types listed below.
- If git history is available, inspect the last 30 days to find change hotspots. Prefer
scripts/git_hotspots.pyfor consistent counts. - Score each candidate refactor with the provided weighting model.
- Return the top 10 opportunities sorted by value score.
- End by asking whether the user wants any suggestion applied.
If the user did not specify files, use the most relevant local context you can discover from the conversation or repo state. If the scope is still ambiguous and a wrong guess would be misleading, ask for the file or directory to analyze.
Hard Rules
- Do not apply changes during the analysis pass.
- Do not suggest speculative architecture work that is not justified by the current code.
- Follow YAGNI. Prefer targeted, local refactors over framework churn.
- Keep constants close to usage. Do not suggest dumping values into a global constants file.
- Be specific about file path, line range, and the concrete benefit.
- Show short before/after snippets for every recommendation.
- Sort strictly by value score from highest to lowest.
Refactoring Types To Look For
Check for these opportunity types:
shorten_file: files over 300 lines that should be split into coherent unitsshorten_function: functions over 50 lines that should be decomposedreduce_nesting: nested conditionals that should become guard clauses or early returnsextract_function: repeated or complex logic that should move into a named helperrename_for_clarity: unclear names, overloaded names, or names that hide intentsimplify_conditionals: brittle or verbose branching that can be simplifiedextract_constants: magic strings, numbers, selectors, or thresholds that should become local constantsconsolidate_duplicates: duplicate logic that should be mergedmodernize_syntax: safe use of modern syntax such as destructuring or optional chainingavoid_globality: move global items closer to where they are usedoptimize_imports: remove unused imports and tighten import organizationremove_dead_code: identify unused code paths, stale helpers, or unreachable branchesadd_tests: call out risky logic with weak or missing coveragebreak_up_hotspots: inspect the last 30 days of git history and flag files changed more than 30 times
Hotspot Analysis
When git history is available:
- Inspect the last 30 days of changes.
- Find the 5 files with the highest change counts.
- For any file changed more than 30 times, suggest decomposition or responsibility splits.
If git history is unavailable, say so briefly and continue with static code analysis.
To collect hotspot data, you can run:
python skills/defrag/scripts/git_hotspots.py --repo . --days 30 --limit 5
Scoring Model
Score each refactoring from 0 to 100 using this weighted model:
- Readability improvement:
35% - Maintainability improvement:
30% - Bug risk reduction:
25% - Performance impact:
5% - Scope size:
5%
Use judgment, but keep scores internally consistent. High scores should correspond to changes that are both important and realistically actionable.
Analysis Workflow
Follow this order:
- Confirm the target files, folder, or code selection.
- Read enough surrounding context to avoid shallow suggestions.
- Check file size, function length, nesting, duplication, naming, imports, and dead code.
- If applicable, inspect tests near the target code and note important gaps.
- If applicable, inspect recent git history for churn hotspots.
- Produce more than 10 candidate opportunities if needed, then sort and keep the best 10.
Bundled Resources
scripts/git_hotspots.py: counts per-file churn from recent git history and returns a JSON summary for hotspot analysisevals/evals.json: starter prompts for validating trigger behavior and output structureagents/openai.yaml: UI-facing metadata and default invocation prompt
Output Format
Use this exact structure for each ranked item:
{rank}. {type} (Value: {score}/100)
- File:
{filepath}:{start_line}-{end_line} - Description: {one-line description}
- Rationale: {why this helps}
Before:
{current code snippet}
After:
{refactored code snippet}
After the ranked list, end with:
Found {N} refactoring opportunities. Top 10 shown with average score: {avg}
Then ask:
Would you like me to apply any of these? Say "apply #1" or "apply all".
Snippet Guidance
- Keep before/after snippets focused on the exact issue.
- Show enough context to make the refactor understandable.
- Prefer realistic after examples that fit the current code style.
- Do not fabricate unrelated helper layers or abstractions.
Review Mindset
Optimize for the highest-value improvements, not the largest number of comments.
A strong result:
- catches structural issues before cosmetic ones
- points to the exact lines that matter
- proposes changes that reduce future editing cost
- avoids vague advice such as "clean this up" or "improve readability"
Failure Modes To Avoid
Do not:
- recommend massive rewrites without evidence
- flood the list with trivial rename suggestions when there are larger structural problems
- suggest moving everything into shared utils or managers
- present style-only changes as high-value refactors
- apply code edits unless the user explicitly asks for implementation
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
analogy-commentary
Turn source content into a familiar analogy framework, then produce concise commentary angles and a short take. Use when the user asks whether a post, article, speech, or idea is “like” a known story, theory, faction, historical pattern, or strategic lens.
deep-productivity
Master deep work productivity through the three types of work framework (Building, Maintenance, Recovery). Use when user needs to: (1) Build a sustainable deep work routine with just 1 hour/day, (2) Create vision/anti-vision for life direction, (3) Structure goals using the 10-year → 1-year → 1-month → 1-week hierarchy, (4) Apply project-based learning to bridge skill gaps, (5) Identify lever-moving tasks that actually progress goals, (6) Balance focus work with necessary recovery for creativity.
multi-agent-systems
Design and implement multi-agent LLM architectures using the orchestrator-subagent pattern. Use when: (1) Deciding whether to use multi-agent vs single-agent systems, (2) Implementing context isolation for high-volume operations, (3) Parallelizing independent research tasks, (4) Creating specialized agents with focused tool sets, (5) Building verification subagents for quality assurance, or (6) Analyzing context-centric decomposition boundaries.
agent-first-product-strategy
Reframe AI product and SaaS strategy from human-user assumptions to agent-first execution. Use when redefining product positioning, success metrics, API/docs priorities, go-to-market, or roadmap decisions for an AI-native market where agents are primary software users.
claim-ledger
将研究与写作中的主张转成“Claim-Evidence-Boundary”可核验账本。用于在产出前强制补齐证据、反证、边界与可发布性判断,防止无依据断言并提升复用性。
debog-yourself
Help users identify and escape psychological traps that are holding them back. Use when user feels stuck, unable to progress, facing a deadlock, or experiencing decision paralysis. Provide diagnostic frameworks and specific strategies to help users understand which trap pattern they're in and find a path forward.
Didn't find tool you were looking for?