9thlevelsoftware/legion/code-polish

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Structured multi-pass code cleanup engine for removing noise, simplifying structure, improving naming, and normalizing conventions

Install

npx vskill@latest install 9thlevelsoftware/legion/code-polish

SKILL.md

Code Polish

Structured four-pass code cleanup engine. Takes files that already work and makes them clearer, shorter, and more consistent without changing behavior. Each pass has a single focus and a concrete rubric with auto-apply rules (safe, mechanical) and flag-only rules (require human judgment).

Two integration modes:

  • Standalone: invoked via /legion:polish — user selects scope, engine runs all 4 passes, outputs POLISH.md
  • Review-integrated: invoked by review-loop after fix cycles complete — scope is the files just reviewed, output appends to REVIEW.md

The engine always dispatches to the testing-code-polisher agent personality. Load agents/testing-code-polisher.md before invoking any pass.


Section 1: Scope Resolution

Determines which files to polish. Runs before any pass begins.

Input:
phase_id — current phase (optional, from STATE.md)
file_path — explicit file or glob (optional, from CLI arg)
directory — explicit directory (optional, from --scope=directory:<path>)
scope_mode — "changed" | "directory" | "auto" (default: "auto")
Step 1: Determine base file set
If file_path provided:
base_files = resolve glob or literal path → file list
Else if phase_id provided:
Read .planning/phases/phase-{N}-plan.md
base_files = union of all files_modified across all plans in the phase
Else if scope_mode == "directory" AND directory provided:
base_files = all source files under directory (recursive)
Else:
Read .planning/STATE.md → find current phase → extract files_modified
If no current phase or no files found:
FAIL: "Cannot auto-detect scope. Provide --file, --phase, or --scope=directory:<path>"
Step 2: Expand to dependents (one level)
If scope_mode == "changed":
Skip this step entirely — polish only the base files
Else:
For each file in base_files:
Parse its exports (named exports, default export, module.exports)
Search project source files for import/require statements referencing this file
Add importing files to expanded_set (one level only — do not recurse further)
base_files = base_files ∪ expanded_set
Step 3: Apply scope overrides
If scope_mode == "changed":
Already handled in Step 2 (skip expansion)
If scope_mode == "directory":
Filter base_files to only files under the specified directory
Step 4: Filter excluded paths
Remove files matching any of:
**/node_modules/**
**/dist/**
**/build/**
**/out/**
**/.git/**
**/.planning/**
**/*.lock
**/*.min.js
**/*.min.css
**/*.map
Binary files (images, fonts, compiled assets)
Files matching patterns in .gitignore
Step 5: Cap file count
If len(base_files) > 50:
Log WARNING: "Scope contains {N} files — capping at 50. Use --scope=changed or --file to narrow."
Truncate to first 50 files (sorted by modification time, most recent first)
Step 6: Report
Log: "Polish scope: {len(base_files)} files"
Log: " Base: {count_base} | Dependents: {count_expanded} | Excluded: {count_filtered}"
Return base_files as ordered list

Section 2: Convention Detection

Detects project patterns before making any changes. Conventions discovered here govern all four passes. Higher-precedence sources override lower ones.

Input: base_files (from Section 1)
Step 1: Read explicit standards
If CLAUDE.md exists at project root:
Extract any sections about: naming, formatting, imports, comments, error handling
Store as explicit_conventions (highest precedence)
Step 2: Read detected conventions
If .planning/CODEBASE.md exists:
Extract "Conventions" or "Patterns" sections
Store as detected_conventions (medium precedence)
Step 3: Sample codebase for implicit conventions
Select up to 10 files from base_files (prefer largest files by line count)
For each sampled file, detect:
naming_style:
variables → camelCase | snake_case | PascalCase | SCREAMING_SNAKE
functions → camelCase | snake_case | PascalCase
files → kebab-case | camelCase | snake_case | PascalCase
constants → SCREAMING_SNAKE | camelCase | PascalCase
import_style:
ordering → stdlib-first | third-party-first | grouped-by-type | unordered
syntax → named-only | default-preferred | mixed
paths → absolute | relative | aliases
error_handling:
pattern → try-catch | Result-type | error-first-callback | .catch() | mix
granularity → per-call | per-function | boundary-only
comment_style:
doc_format → JSDoc | TSDoc | docstring | Javadoc | XML-doc | none
inline → above-line | end-of-line | mixed | none
function_style:
declaration → function-keyword | arrow | mixed
max_length → median function length in lines
string_style:
quotes → single | double | backtick-preferred
trailing_commas: always | never | multiline-only
semicolons: always | never | asi
file_structure:
ordering → imports-types-constants-functions-exports |
imports-constants-functions-exports |
unstructured
Store as implicit_conventions (lowest precedence)
Step 4: Merge conventions
Final convention set = explicit_conventions ⊕ detected_conventions ⊕ implicit_conventions
Where ⊕ means: for each convention key, use the highest-precedence source that defines it
If a convention is contradictory between sources, explicit wins. Log the conflict:
"Convention conflict: {key} — explicit={value_a}, detected={value_b}. Using explicit."
Step 5: Report
Log: "Detected conventions:"
For each convention key with a resolved value:
Log: " {key}: {value} (source: {explicit|detected|implicit})"
Return merged convention set

Section 3: Pass 1 — Comment Cleanup

Remove comments that add no information. Preserve comments that explain non-obvious intent. This is a deletion pass — it adds nothing.

3.1 REMOVE Rules (severity: CLEAN)

Apply these removals automatically. Every removal is logged.

RuleDescriptionExample
restates-codeComment restates what the next line does// increment counter above counter++
ai-narrationAI-generated narration or step-by-step commentary// Now we need to fetch the user data from the API
commented-out-codeCode in comments with no explanation of why it is kept// const oldHandler = () => { ... }
stale-todoTODO/FIXME/HACK with no issue reference and no date, older than the current sprint// TODO: fix this later
noise-dividerDecorative dividers or section banners that separate obvious blocks// ===================== or // --- helpers ---
signature-restatementComment restates function name, parameters, or return type already visible in the signature/** Gets user by ID */ above function getUserById(id: string): User

Detailed examples:

REMOVE — restates-code:
BEFORE:
// Set the user's name
user.name = newName;
AFTER:
user.name = newName;
REMOVE — ai-narration:
BEFORE:
// First, we need to validate the input parameters to ensure they meet
// the expected format before proceeding with the database query
validateInput(params);
AFTER:
validateInput(params);
REMOVE — commented-out-code:
BEFORE:
// function oldApproach(data) {
// return data.map(x => x * 2);
// }
function newApproach(data) {
AFTER:
function newApproach(data) {
REMOVE — stale-todo:
BEFORE:
// TODO fix this later
const result = fetchData();
AFTER:
const result = fetchData();
REMOVE — noise-divider:
BEFORE:
// ========================
// Helper Functions
// ========================
function helper() {
AFTER:
function helper() {
REMOVE — signature-restatement:
BEFORE:
/**
* Calculates the total price.
* @param items - The items array
* @returns The total price
*/
function calculateTotalPrice(items: Item[]): number {
AFTER:
function calculateTotalPrice(items: Item[]): number {
3.2 PRESERVE Rules (severity: KEEP)

Never remove comments matching these patterns. If uncertain, preserve.

RuleDescriptionExample
intentExplains WHY, not what — reasoning, tradeoff, workaround// Using setTimeout because requestAnimationFrame skips background tabs
business-logicEncodes domain rules not obvious from code// Tax-exempt if order originated from EU VAT-registered entity
legal-headerLicense, copyright, attribution// SPDX-License-Identifier: MIT
todo-with-refTODO/FIXME with issue tracker reference// TODO(PROJ-123): migrate to v2 API after deprecation deadline
gotcha-warningWarns about non-obvious side effects or constraints// WARNING: this mutates the input array — caller must clone if needed
type-annotationType hints in dynamically typed languages# type: Dict[str, List[int]] in Python 2-style code
regex-explanationExplains complex regex patterns// Matches ISO-8601 dates with optional timezone offset
3.3 Logging Format
For each removed comment, log:
PASS1 | {file_path}:{line_number} | CLEAN | "{removed_text (first 80 chars)}" | {reason_code}
Example:
PASS1 | src/auth/login.ts:42 | CLEAN | "// Set the username to the new value" | restates-code
PASS1 | src/api/handler.ts:17 | CLEAN | "// Now we need to validate the request body befor..." | ai-narration

Section 4: Pass 2 — Code Simplification

Reduce code volume and complexity without changing behavior. This pass targets structural waste — code that does more work than necessary to express its intent.

4.1 SIMPLIFY Rules (auto-apply)

Apply these transformations automatically. Each must be provably behavior-preserving.

RuleDescription
guard-clauseReplace nested if/else with early returns
lookup-tableReplace if/else chains or switch on value with object/map lookup
dead-codeRemove unreachable code after return/throw/break/continue
unused-varsRemove declared but never-referenced variables
unused-importsRemove imported but never-referenced symbols
inline-trivialInline variables used exactly once on the next line
collapse-wrapperRemove functions that only call another function with same args
stdlib-equivalentReplace hand-rolled logic with standard library calls

Detailed examples:

SIMPLIFY — guard-clause:
BEFORE:
function process(user) {
if (user) {
if (user.isActive) {
return doWork(user);
} else {
return null;
}
} else {
return null;
}
}
AFTER:
function process(user) {
if (!user || !user.isActive) return null;
return doWork(user);
}
SIMPLIFY — lookup-table:
BEFORE:
function getStatusLabel(status) {
if (status === 'active') return 'Active';
if (status === 'pending') return 'Pending';
if (status === 'closed') return 'Closed';
return 'Unknown';
}
AFTER:
const STATUS_LABELS = { active: 'Active', pending: 'Pending', closed: 'Closed' };
function getStatusLabel(status) {
return STATUS_LABELS[status] ?? 'Unknown';
}
SIMPLIFY — dead-code:
BEFORE:
function validate(input) {
if (!input) throw new Error('missing input');
return input.trim();
console.log('validated'); // unreachable
}
AFTER:
function validate(input) {
if (!input) throw new Error('missing input');
return input.trim();
}
SIMPLIFY — collapse-wrapper:
BEFORE:
function formatName(first, last) {
return buildFullName(first, last);
}
AFTER:
// Remove formatName entirely; replace call sites with buildFullName

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
62
Repository forks
7
7-day trend score
21

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/9thlevelsoftware/legion/code-polish/badge)](https://verified-skill.com/skills/9thlevelsoftware/legion/code-polish)

Something wrong with this skill or its page? Tell us.