Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
athola avatar

Code Refinement

  • 113 installs
  • 325 repo stars
  • Updated August 2, 2026
  • athola/claude-night-market

Code Refinement is an agent skill that detects block-level algorithmic inefficiencies and suggests better algorithms or data structures.

About

Code Refinement (algorithm-efficiency module) is an agent skill that hunts algorithmic inefficiencies at the function and loop level—nested iterations, redundant sorting, and similar patterns that turn linear work into quadratic cost. Solo and indie builders shipping SaaS, APIs, or CLIs use it when a feature works but feels slow, or when review time should include complexity passes without hiring a performance consultant. The skill documents concrete anti-patterns and better data structures, and points to shell-friendly grep workflows to surface suspicious nested loops in Python trees. It deliberately stays out of distributed architecture and ORM query optimization so agents stay focused on fixes a single developer can land in one PR. Pair it with your normal ship-phase testing and review; outcomes are clearer Big-O reasoning and copy-paste refactor suggestions your coding agent can implement immediately.

  • Detects nested loops on the same collection and suggests index/hash-map replacements
  • Flags repeated sort/search inside loops with sort-once guidance
  • Scoped to code-block-level patterns—not system architecture or database query plans
  • Includes grep/awk-style detection hints for Python nested-loop anti-patterns
  • Parent skill pensive:code-refinement with algorithm-efficiency module metadata

Code Refinement by the numbers

  • 113 all-time installs (skills.sh)
  • Ranked #436 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
  • Security screen: HIGH risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/athola/claude-night-market --skill code-refinement

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs113
repo stars325
Security audit2 / 3 scanners passed
Last updatedAugust 2, 2026
Repositoryathola/claude-night-market

What it does

Scan your codebase with an agent for O(n²) loops, repeated sorts, and other block-level algorithm waste before you ship or optimize hot paths.

Who is it for?

backends and scripts where you can grep the repo and want checklist-driven complexity review without a dedicated performance team.

Skip if: Database index design, caching topology, or fleet-wide profiling—this module excludes architecture and query-plan optimization by design.

When should I use this skill?

You need block-level algorithm or complexity improvements on existing code, especially nested loops and repeated sorting patterns.

What you get

You get targeted refactor patterns and detection cues so the agent can replace wasteful blocks with indexed lookups, single sorts, or clearer complexity—ready for a focused perf PR.

  • List of anti-patterns with suggested refactors
  • Optional grep commands to locate nested-loop hotspots

By the numbers

  • 4+ documented detection pattern families (nested loops, repeated sort/search, etc.)
  • Code-block scope only—not system or DB query optimization

Files

SKILL.mdMarkdownGitHub ↗

Table of Contents

Code Refinement Workflow

Analyze and improve living code quality across six dimensions.

Quick Start

/refine-code
/refine-code --level 2 --focus duplication
/refine-code --level 3 --report refinement-plan.md

When To Use

  • After rapid AI-assisted development sprints
  • Before major releases (quality gate)
  • When code "works but smells"
  • Refactoring existing modules for clarity
  • Reducing technical debt in living code

When NOT To Use

  • Removing

dead/unused code (use conserve:bloat-detector)

Analysis Dimensions

#DimensionModuleWhat It Catches
1Duplication & Redundancyduplication-analysisNear-identical blocks, similar functions, copy-paste
2Algorithmic Efficiencyalgorithm-efficiencyO(n^2) where O(n) works, unnecessary iterations
3Clean Code Violationsclean-code-checksLong methods, deep nesting, poor naming, magic values
4Architectural Fitarchitectural-fitParadigm mismatches, coupling violations, leaky abstractions
5Anti-Slop Patternsclean-code-checksPremature abstraction, enterprise cosplay, hollow patterns
6Error Handlingclean-code-checksBare excepts, swallowed errors, happy-path-only
7Additive Biasimbue:justifyWorkarounds over root fixes, test tampering, unnecessary additions

Plugin-Specific Patterns

Detection patterns for plugin and skill codebases where standard code quality heuristics miss structural issues.

Delegation Stub Bodies

A skill that declares "delegates to X" but still carries the full template body is doing double duty. The delegating skill should be a thin wrapper (under 30 lines) that routes to the target. Flag any delegating skill whose body exceeds 50 lines.

Module Explosion

Flag skills with 10+ module files where 40% or more of content overlaps. Signal: two modules covering the same API surface from different angles (e.g., both describing the same config options or the same CLI flags).

Oversized Single Modules

Flag individual module files exceeding 500 lines as candidates for splitting or trimming. Large modules defeat progressive loading by forcing full-file reads for partial information.

Dead Python References

Skills referencing Python commands (python -m module.name or python -c "from module import ...") where the referenced module does not exist in the plugin's src/ directory. These are stale references to renamed or removed code.

Progressive Loading

Load modules based on refinement focus:

  • `modules/duplication-analysis.md` (~400 tokens): Duplication detection and consolidation
  • `modules/algorithm-efficiency.md` (~400 tokens): Complexity analysis and optimization
  • `modules/clean-code-checks.md` (~450 tokens): Clean code, anti-slop, error handling
  • `modules/architectural-fit.md` (~400 tokens): Paradigm alignment and coupling

Load all for thorough refinement. For focused work, load only relevant modules.

Required TodoWrite Items

1. refine:context-established: Scope, language, framework detection 2. refine:scan-complete: Findings across all dimensions 3. refine:prioritized: Findings ranked by impact and effort 4. refine:plan-generated: Concrete refactoring plan with before/after 5. refine:evidence-captured: Evidence appendix per imbue:proof-of-work 6. refine:findings-verified: Citations confirmed by citation_verifier.py 7. refine:execution-complete: All wave-listed candidates closed-or-rationale'd (only required when invocation includes "execute findings" or stronger; see Step 6)

Workflow

Step 1: Establish Context (refine:context-established)

Detect project characteristics:

# Language detection
find . -not -path "*/.venv/*" -not -path "*/__pycache__/*" \
  -not -path "*/node_modules/*" -not -path "*/.git/*" \
  \( -name "*.py" -o -name "*.ts" -o -name "*.rs" -o -name "*.go" \) \
  | head -20

# Framework detection
ls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null

# Size assessment
find . -not -path "*/.venv/*" -not -path "*/__pycache__/*" \
  -not -path "*/node_modules/*" -not -path "*/.git/*" \
  \( -name "*.py" -o -name "*.ts" -o -name "*.rs" \) \
  | xargs wc -l 2>/dev/null | tail -1

Step 2: Dimensional Scan (refine:scan-complete)

Load relevant modules and execute analysis per tier level. For dimension 7 (Additive Bias), run Skill(imbue:justify) to compute the bias score, check Iron Law compliance, and flag unnecessary additions or workarounds.

Step 3: Prioritize (refine:prioritized)

Rank findings by:

  • Impact: How much quality improves (HIGH/MEDIUM/LOW)
  • Effort: Lines changed, files touched (SMALL/MEDIUM/LARGE)
  • Risk: Likelihood of introducing bugs (LOW/MEDIUM/HIGH)

Priority = HIGH impact + SMALL effort + LOW risk first.

Step 4: Generate Plan (refine:plan-generated)

For each finding, produce:

  • File path and line range
  • Anchor: verbatim source text at the cited line
  • Current code snippet
  • Proposed improvement
  • Rationale (which principle/dimension)
  • Estimated effort

Step 5: Evidence Capture (refine:evidence-captured)

Document with imbue:proof-of-work (if available):

  • [E1], [E2] references for each finding
  • Metrics before/after where measurable
  • Principle violations cited

Fallback: If imbue is not installed, capture evidence inline in the report using the same [E1] reference format without TodoWrite integration.

Step 6: Execute Findings (refine:execution-complete)

Steps 1-5 produce a plan. Steps 6 produces closures. Both are part of the skill. Execution does not stop at planning unless the user explicitly says "plan only".

Execution mode detection

Match the user's invocation phrasing against this table to determine execution scope:

User saidModeStop when
/code-refinement (no qualifier)Plan onlyAfter Step 5
--dry-run or "just plan"Plan onlyAfter Step 5
"execute findings" / "apply fixes"Plan, execute Wave 1After all SMALL-effort, and LOW-risk findings closed
"execute all findings" / "all phases" / "all waves"Plan and execute every waveAfter every finding (or every wave-listed candidate) is either closed by commit or has explicit per-item rationale in the synthesis
"ignore scope guard"Override branch-size limitsBranch metrics do not gate execution. Continue past RED zone.
"do not stop until complete" / "until ALL ... complete"No mid-task summariesOnly declare done when synthesis has every wave-listed candidate closed-or-rationale'd

The triggers compose: --tier 3 --execute all findings --ignore-scope-guard means run every Wave 2 and Wave 3 candidate to closure regardless of branch size.

Completion gate (when execution mode is active)

The task is not complete until ALL of the following hold:

1. Wave 2 candidates (medium-effort, listed in synthesis "Wave 2 Candidates" section): every entry has either a closure commit or an explicit per-item line in the synthesis stating why it is not viable. 2. Wave 3 candidates (large-effort, listed in synthesis "Wave 3 Candidates" section): same gate. Do not pre-emptively defer LARGE-effort items with generic "needs dedicated PR" rationale when the user said "execute all". Execute the mechanical ones (split-by-class, mixin-package, module-merge) and reserve "deferred" only for items requiring architecture-level decisions (schema changes, new dependency declarations, new venv layouts). 3. Synthesis updated: docs/refinement/<date>/00-synthesis.md records every closure with its commit SHA and every deferral with one-sentence rationale.

Anti-pattern detector for the agent itself

If the model finds itself doing any of the following during execution, this is a stop-hook leak. Go back to executing findings:

Anti-patternRecognise as
"Wave 2 closed. Moving to Wave 3." (mid-run summary)Premature turn-completion signal: keep working
"Documenting deferred items with rationale" before all mechanical items are doneSkipping execution under a paper trail
Writing a completion summary while >0 listed candidates lack closure-or-rationaleViolation of completion gate
Re-asking user "should I continue?" when invocation included "do not stop"Ignoring the explicit no-mid-task-summary contract

If the harness fires a stop signal mid-execution and the completion gate is not met, immediately resume with the next finding.

Verify Findings Are Grounded (refine:findings-verified)

Every finding must cite a real location and a verbatim anchor. Write findings to .review/findings.json and confirm each citation resolves:

python plugins/imbue/scripts/citation_verifier.py \
  --findings .review/findings.json --repo-root .

Drop or label UNVERIFIED any finding the verifier fails (exit 1); only verified findings enter the report. See Skill(imbue:review-core) Step 5 and Skill(imbue:structured-output) for the schema.

Exit Criteria

  • [ ] All six analysis dimensions have a verdict (finding or "no issue

detected") for the target scope.

  • [ ] Each finding includes a file path, line range, and verbatim

Anchor (the exact source text at that line).

  • [ ] Every reported finding carries a Location + verbatim Anchor

confirmed by citation_verifier.py (exit 0), or unverified findings were dropped or labeled UNVERIFIED.

Tiered Analysis

TierTimeScope
1: Quick (default)2-5 minComplexity hotspots, obvious duplication, naming, magic values
2: Targeted10-20 minAlgorithm analysis, full duplication scan, architectural alignment
3: Deep30-60 minAll above and cross-module coupling, paradigm fitness, thorough plan

Cross-Plugin Dependencies

DependencyRequired?Fallback
pensive:sharedYesCore review patterns
imbue:proof-of-workOptionalInline evidence in report
conserve:code-quality-principlesOptionalBuilt-in KISS/YAGNI/SOLID checks
archetypes:architecture-paradigmsOptionalPrinciple-based checks only (no paradigm detection)

Supporting Modules

  • Code quality analysis - duplication detection commands and consolidation strategies

When optional plugins are not installed, the skill degrades gracefully:

  • Without imbue: Evidence captured inline, no TodoWrite proof-of-work
  • Without conserve: Uses built-in clean code checks (subset)
  • Without archetypes: Skips paradigm-specific alignment, uses coupling/cohesion principles only

Related skills

How it compares

Use instead of vague “make it faster” chat requests when you want procedural anti-pattern detection at the loop level.

FAQ

Who is code-refinement for?

Developers and small teams using Claude Code, Cursor, or Codex who want agent-guided algorithm cleanup on existing code before or right after ship.

When should I use code-refinement?

During Ship perf work when endpoints lag; during Build when implementing list-heavy features; after review when grep shows nested loops on the same collection.

Is code-refinement safe to install?

It is read/analysis oriented (Read, Grep, Glob)—review the Security Audits panel on this Prism page and inspect the parent night-market repo before granting broad filesystem access.

Code Review & Qualitybackendtesting

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.