
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-refinementAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 113 |
|---|---|
| repo stars | ★ 325 |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | athola/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
Table of Contents
- Quick Start
- When to Use
- Analysis Dimensions
- Progressive Loading
- Required TodoWrite Items
- Workflow
- Tiered Analysis
- Cross-Plugin Dependencies
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.mdWhen 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
| # | Dimension | Module | What It Catches |
|---|---|---|---|
| 1 | Duplication & Redundancy | duplication-analysis | Near-identical blocks, similar functions, copy-paste |
| 2 | Algorithmic Efficiency | algorithm-efficiency | O(n^2) where O(n) works, unnecessary iterations |
| 3 | Clean Code Violations | clean-code-checks | Long methods, deep nesting, poor naming, magic values |
| 4 | Architectural Fit | architectural-fit | Paradigm mismatches, coupling violations, leaky abstractions |
| 5 | Anti-Slop Patterns | clean-code-checks | Premature abstraction, enterprise cosplay, hollow patterns |
| 6 | Error Handling | clean-code-checks | Bare excepts, swallowed errors, happy-path-only |
| 7 | Additive Bias | imbue:justify | Workarounds 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 -1Step 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 said | Mode | Stop when |
|---|---|---|
/code-refinement (no qualifier) | Plan only | After Step 5 |
--dry-run or "just plan" | Plan only | After Step 5 |
| "execute findings" / "apply fixes" | Plan, execute Wave 1 | After all SMALL-effort, and LOW-risk findings closed |
| "execute all findings" / "all phases" / "all waves" | Plan and execute every wave | After 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 limits | Branch metrics do not gate execution. Continue past RED zone. |
| "do not stop until complete" / "until ALL ... complete" | No mid-task summaries | Only 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-pattern | Recognise 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 done | Skipping execution under a paper trail |
| Writing a completion summary while >0 listed candidates lack closure-or-rationale | Violation 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+ verbatimAnchor
confirmed by citation_verifier.py (exit 0), or unverified findings were dropped or labeled UNVERIFIED.
Tiered Analysis
| Tier | Time | Scope |
|---|---|---|
| 1: Quick (default) | 2-5 min | Complexity hotspots, obvious duplication, naming, magic values |
| 2: Targeted | 10-20 min | Algorithm analysis, full duplication scan, architectural alignment |
| 3: Deep | 30-60 min | All above and cross-module coupling, paradigm fitness, thorough plan |
Cross-Plugin Dependencies
| Dependency | Required? | Fallback |
|---|---|---|
pensive:shared | Yes | Core review patterns |
imbue:proof-of-work | Optional | Inline evidence in report |
conserve:code-quality-principles | Optional | Built-in KISS/YAGNI/SOLID checks |
archetypes:architecture-paradigms | Optional | Principle-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
Algorithm Efficiency Module
Identify time and space complexity inefficiencies at the code block level.
Scope
This module focuses on code-block-level optimizations, not system architecture or database query optimization. It catches patterns where a better algorithm or data structure eliminates unnecessary work.
Detection Patterns
1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))
# Anti-pattern: O(n^2) lookup
for item in items:
for other in items:
if item.id == other.parent_id:
...
# Better: O(n) with index
index = {item.id: item for item in items}
for item in items:
parent = index.get(item.parent_id)Detection:
# Find nested for-loops on same variable (Python)
grep -n "for .* in " --include="*.py" -r . | \
awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,"",var); gsub(/:.*/,"",var); print file, line, var}' | \
sort | uniq -f2 -d2. Repeated Sort / Search
# Anti-pattern: sorting inside a loop
for query in queries:
sorted_data = sorted(data) # O(n log n) per query = O(m * n log n)
result = bisect.bisect(sorted_data, query)
# Better: sort once
sorted_data = sorted(data) # O(n log n) once
for query in queries:
result = bisect.bisect(sorted_data, query) # O(m * log n)Detection:
# Find sort/sorted inside loops
grep -n "sorted\|\.sort()" --include="*.py" -r . | while read line; do
file=$(echo "$line" | cut -d: -f1)
num=$(echo "$line" | cut -d: -f2)
# Check if inside a for/while loop
sed -n "$((num-5)),$((num))p" "$file" | grep -q "for \|while " && echo "SORT_IN_LOOP: $line"
done3. List Where Set/Dict Suffices
# Anti-pattern: O(n) membership test
if item in large_list: # O(n)
...
# Better: O(1) membership test
large_set = set(large_list)
if item in large_set: # O(1)
...Detection:
# Find "in list_var" patterns (heuristic)
grep -n " in \[" --include="*.py" -r .
grep -n " not in " --include="*.py" -r . | grep -v "not in {" | grep -v "not in set("4. String Concatenation in Loop
# Anti-pattern: O(n^2) string building
result = ""
for item in items:
result += str(item) + ", "
# Better: O(n) with join
result = ", ".join(str(item) for item in items)5. Unnecessary Intermediate Collections
# Anti-pattern: builds full list just to iterate
all_items = [transform(x) for x in data] # allocates full list
for item in all_items:
process(item)
# Better: generator (lazy evaluation)
for item in (transform(x) for x in data):
process(item)6. Repeated Computation (Missing Memoization)
# Anti-pattern: recomputes expensive value
def get_result(n):
# called 1000x with same n values
return expensive_compute(n)
# Better: cache
from functools import lru_cache
@lru_cache(maxsize=128)
def get_result(n):
return expensive_compute(n)Complexity Estimation Heuristics
Rather than formal Big-O analysis, use practical heuristics:
| Pattern | Likely Complexity | Flag When |
|---|---|---|
| Single loop over data | O(n) | Data > 10K and no early exit |
| Nested loop, same data | O(n^2) | Always flag |
| Sort inside loop | O(m * n log n) | Always flag |
in list inside loop | O(n * m) | List > 100 items |
| Recursive without memo | O(2^n) potential | Recursive calls > 1 |
| String concat in loop | O(n^2) | Loop > 100 iterations |
Scoring
| Pattern | Severity | Confidence |
|---|---|---|
| Nested loop, same data | HIGH | 85% |
| Sort/search in loop | HIGH | 90% |
| List where set suffices | MEDIUM | 80% |
| String concat in loop | MEDIUM | 85% |
| Missing memoization | LOW | 65% |
| Unnecessary intermediates | LOW | 70% |
Output Format
finding: algorithm-inefficiency
severity: HIGH
type: nested_loop_same_collection
location:
file: src/matching.py
lines: 45-58
current_complexity: O(n^2)
suggested_complexity: O(n)
strategy: build_index_first
effort: SMALLArchitectural Fit Module
Evaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.
Two-Mode Operation
Mode 1: Paradigm-Aware (archetypes plugin installed)
When archetypes is available, detect the project's paradigm and check alignment:
Skill(archetypes:architecture-paradigms) -> detect paradigm -> check violationsSupported paradigms from archetypes:
- Functional Core / Imperative Shell
- Hexagonal (Ports & Adapters)
- Layered Architecture
- Pipeline / Data Flow
- Modular Monolith
- Event-Driven
- Client-Server
- Microkernel
- CQRS/ES
Mode 2: Principle-Based (fallback, no archetypes)
Check universal coupling/cohesion principles without paradigm detection:
- Dependency direction (no circular deps)
- Layer violations (UI calling DB directly)
- Cohesion (related code grouped together)
- Encapsulation (no leaking internals)
Detection: Coupling Violations
1. Circular Dependencies
# Python: Find circular imports (heuristic)
grep -rn "^from \|^import " --include="*.py" . | \
awk -F: '{file=$1; gsub(/.*from /,"",$3); gsub(/ import.*/,"",$3); print file, $3}' | \
sort | while read a b; do
grep -q "from.*$(basename $a .py)" "$b.py" 2>/dev/null && \
echo "CIRCULAR: $a <-> $b"
done2. Layer Violations
Common layer boundaries to check:
- Presentation should not import from data/persistence
- Domain/business logic should not depend on framework
- Utilities should not depend on domain
# Find cross-layer imports (convention: src/{layer}/)
# Customize layer names per project
for violation in \
"handlers.*import.*models\." \
"views.*import.*database" \
"api.*import.*sql\|cursor\|query"; do
grep -rn "$violation" --include="*.py" . 2>/dev/null && echo "LAYER_VIOLATION: $violation"
done3. Feature Envy
A method that uses more features of another class than its own:
# Heuristic: methods with many external references
# Look for methods where self.X appears less than other_obj.Y
grep -A20 "def " --include="*.py" -r . | \
awk '/def /{fn=$0; self=0; other=0} /self\./{self++} /[a-z]+\./{other++} /^$/{if(other>self*2 && other>3) print "FEATURE_ENVY:", fn}'4. Inappropriate Intimacy
Classes that access each other's private members:
# Find access to _private members from outside class
grep -rn "\._[a-z]" --include="*.py" . | grep -v "self\._\|cls\._\|__init__\|test_" | head -205. Shotgun Surgery Indicators
Changes to one concept require touching many files:
# Heuristic: functions/classes with same name prefix across many files
grep -rn "^def " --include="*.py" . | sed 's/def //;s/(.*//' | \
awk -F: '{print $2}' | sed 's/_.*//' | sort | uniq -c | sort -rn | \
awk '$1>4{print "SCATTERED_CONCEPT ("$1" files):", $2}'Detection: Cohesion Issues
Low Cohesion Indicators
# Files with many unrelated public functions (>8)
grep -c "^def " --include="*.py" -r . | awk -F: '$2>8{print "LOW_COHESION:", $0}'
# Classes with unrelated method groups
# Heuristic: methods that don't reference same instance variablesModule Size Imbalance
# Find modules that are disproportionately large
find . -name "*.py" -not -path "*/.venv/*" -exec wc -l {} + | \
sort -rn | head -10
# Flag if largest is >5x the medianParadigm-Specific Checks
Functional Core / Imperative Shell
- [ ] Pure functions don't perform I/O
- [ ] Side effects isolated to shell layer
- [ ] Domain logic is testable without mocks
Hexagonal
- [ ] Ports defined as interfaces/protocols
- [ ] Adapters don't leak into domain
- [ ] Dependency flow: adapters -> ports -> domain
Layered
- [ ] Dependencies flow downward only
- [ ] No layer bypassing
- [ ] Clear layer boundaries in directory structure
Scoring
| Pattern | Severity | Confidence |
|---|---|---|
| Circular dependency | HIGH | 90% |
| Layer violation | HIGH | 85% |
| Feature envy (strong) | MEDIUM | 75% |
| Low cohesion (>10 methods) | MEDIUM | 80% |
| Inappropriate intimacy | MEDIUM | 80% |
| Scattered concept | LOW | 65% |
| Module size imbalance | LOW | 70% |
Output Format
finding: architectural-violation
severity: HIGH
type: circular_dependency
locations:
- file: src/services/user.py
imports: src/models/user.py
- file: src/models/user.py
imports: src/services/user.py
strategy: introduce_interface
paradigm_note: "Violates dependency inversion; extract protocol"
effort: MEDIUMClean Code Checks Module
Detect violations of clean code principles, AI slop patterns, and error handling gaps.
Covers three dimensions: Clean Code, Anti-Slop, and Error Handling.
Clean Code Violations
1. Long Methods (>30 lines)
# Python: Find long functions
grep -n "^def \|^ def " --include="*.py" -r . | while read line; do
file=$(echo "$line" | cut -d: -f1)
num=$(echo "$line" | cut -d: -f2)
# Count lines until next def or end
length=$(sed -n "${num},\$p" "$file" | awk '/^def |^ def /{if(NR>1)exit}END{print NR}')
[ "$length" -gt 30 ] && echo "LONG_METHOD ($length lines): $line"
doneRefactoring: Extract method, compose method pattern.
2. Deep Nesting (>3 levels)
# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)
grep -rn "^ " --include="*.py" . | head -20
grep -rn "^\t\t\t\t" --include="*.js" --include="*.ts" . | head -20Refactoring: Guard clauses, extract method, strategy pattern.
3. Magic Numbers and Strings
# Find magic numbers (excluding 0, 1, common constants)
grep -rn "[^a-zA-Z_][2-9][0-9]\{1,\}[^a-zA-Z_0-9\"']" --include="*.py" . | \
grep -v "range\|port\|version\|#\|test_\|assert" | head -20Refactoring: Extract to named constants.
4. Poor Naming
Indicators of AI-generated generic names:
# Find generic function names
grep -rn "def process\|def handle\|def manage\|def do_\|def run_" --include="*.py" . | \
grep -v "test_\|__" | head -20
# Find single-letter variables (outside loops/lambdas)
grep -rn " [a-z] = " --include="*.py" . | grep -v "for [a-z] in\|lambda [a-z]" | head -205. God Classes (>300 lines or >10 methods)
# Python: Large classes
grep -c "def " --include="*.py" -r . | awk -F: '$2>10{print "GOD_CLASS:", $0}'Anti-Slop Patterns
AI-specific code smells that traditional linters miss.
1. Premature Abstraction
Base classes/interfaces with only 1 implementation.
# Python: ABC with single inheritor
grep -rn "class.*ABC\|@abstractmethod" --include="*.py" . | cut -d: -f1 | sort -u | while read f; do
class=$(grep -oP "class \K\w+" "$f" | head -1)
[ -n "$class" ] && {
inheritors=$(grep -rn "($class)" --include="*.py" . | wc -l)
[ "$inheritors" -lt 2 ] && echo "PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)"
}
done2. Enterprise Cosplay
Over-engineered patterns for simple problems:
- Factory for a single type
- Strategy pattern with one strategy
- Observer with one subscriber
- Middleware chain for single operation
# Find *Factory, *Builder, *Strategy with few usages
for pattern in Factory Builder Strategy Observer; do
grep -rn "class.*$pattern" --include="*.py" --include="*.ts" . 2>/dev/null | while read line; do
class=$(echo "$line" | grep -oP "class \K\w+")
refs=$(grep -rn "$class" --include="*.py" --include="*.ts" . | wc -l)
[ "$refs" -lt 4 ] && echo "ENTERPRISE_COSPLAY ($refs refs): $line"
done
done3. Hollow Abstractions
Code that adds indirection without value:
# Anti-pattern: Wrapper that just delegates
class UserService:
def __init__(self, repo):
self.repo = repo
def get_user(self, id):
return self.repo.get_user(id) # Just passes through
def save_user(self, user):
return self.repo.save_user(user) # Just passes through4. Verbose Where Concise Suffices
AI tends toward verbosity. Look for:
- Explicit boolean returns:
if x: return True; else: return False - Unnecessary else after return
- Redundant variable assignments before return
Error Handling Checks
1. Bare/Broad Excepts
# Find bare except
grep -rn "except:" --include="*.py" -r .
# Find overly broad except
grep -rn "except Exception:" --include="*.py" -r . | grep -v "logging\|logger\|log\."2. Swallowed Errors
# except + pass (swallowed)
grep -A1 "except" --include="*.py" -r . | grep -B1 "pass$" | grep "except"3. Happy-Path-Only Code
# Functions >50 lines without any error handling
grep -rn "^def " --include="*.py" . | while read line; do
file=$(echo "$line" | cut -d: -f1)
num=$(echo "$line" | cut -d: -f2)
block=$(sed -n "${num},$((num+60))p" "$file")
has_error=$(echo "$block" | grep -c "raise\|except\|Error\|error\|Warning")
lines=$(echo "$block" | wc -l)
[ "$lines" -gt 50 ] && [ "$has_error" -eq 0 ] && echo "HAPPY_PATH_ONLY: $line"
doneScoring
| Pattern | Severity | Confidence |
|---|---|---|
| Bare except / swallowed error | HIGH | 95% |
| God class (>300 lines) | HIGH | 90% |
| Long method (>50 lines) | MEDIUM | 90% |
| Premature abstraction | MEDIUM | 85% |
| Magic numbers | MEDIUM | 80% |
| Deep nesting (>4) | MEDIUM | 85% |
| Generic naming | LOW | 70% |
| Verbose patterns | LOW | 75% |
Integration with conserve:code-quality-principles
If the conserve plugin is installed, reference Skill(conserve:code-quality-principles) for KISS, YAGNI, and SOLID principle definitions with language-specific examples.
Fallback (conserve not installed): This module contains sufficient built-in checks for clean code violations. The conserve skill adds richer examples and conflict resolution guidance (e.g., "KISS vs SOLID" trade-offs).
Code Quality Analysis Module
Shared patterns for code quality and deduplication analysis across review contexts.
Quick Detection Commands
Duplication Detection
# Python: Find similar function signatures
grep -rn "^def \|^ def " --include="*.py" . | \
sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d
# TypeScript/JavaScript: Similar declarations
grep -rn "function \|const .* = (" --include="*.ts" --include="*.js" . | \
sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d
# Find repeated code blocks (5+ lines)
find . -name "*.py" -not -path "*/.venv/*" | while read f; do
awk 'NR%5==1{hash=""; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' "$f"
done | sort | uniq -d -w 100 | head -10Redundancy Patterns
# Find similar error handling blocks
grep -c "try:" --include="*.py" -r . | awk -F: '$2>5{print "HIGH_TRY_COUNT:", $0}'
# Find repeated validation patterns
grep -rn "if not.*:" --include="*.py" . | \
sed 's/if not \(.*\):/\1/' | sort | uniq -c | sort -rn | head -10Quality Dimensions
| Dimension | Detection Method | Severity |
|---|---|---|
| Exact duplication (10+ lines) | Hash-based | HIGH |
| Similar functions (3+) | Signature matching | MEDIUM |
| Repeated patterns | Structural analysis | LOW-MEDIUM |
| Copy-paste indicators | Comment/naming similarity | MEDIUM |
Integration with PR Review
When invoked from /pr-review, analyze only changed files:
# Get changed files
CHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only | grep -E '\.(py|ts|js|rs|go)$')
# Run targeted analysis on changed files only
for file in $CHANGED_FILES; do
# Check for duplication within file
# Check for redundancy with existing codebase
doneConsolidation Strategies
| Pattern | Strategy | When to Apply |
|---|---|---|
| Same logic 3+ times | Extract function | Always |
| Multiple classes share methods | Extract base/mixin | 3+ shared methods |
| Same logic, different constants | Configuration-driven | 2+ occurrences |
| Same workflow, different steps | Template method | Clear workflow pattern |
Output Format
finding: code-quality
type: duplication|redundancy|complexity
severity: HIGH|MEDIUM|LOW
confidence: 70-95%
locations:
- file: path/to/file.py
lines: 45-62
- file: path/to/other.py
lines: 23-40
strategy: extract_function|extract_class|configure|template_method
effort: SMALL|MEDIUM|LARGEFull Analysis: Invoke pensive:code-refinement
For thorough code quality analysis, invoke the full pensive:code-refinement skill:
Skill(pensive:code-refinement)This provides six analysis dimensions:
| Dimension | Module | What It Catches |
|---|---|---|
| Duplication & Redundancy | duplication-analysis | Near-identical blocks, similar functions, copy-paste |
| Algorithmic Efficiency | algorithm-efficiency | O(n^2) where O(n) works, unnecessary iterations, time/space complexity |
| Clean Code Violations | clean-code-checks | Long methods, deep nesting, poor naming, magic values |
| Architectural Fit | architectural-fit | Paradigm mismatches, coupling violations, leaky abstractions |
| Anti-Slop Patterns | clean-code-checks | Premature abstraction, enterprise cosplay, hollow patterns |
| Error Handling | clean-code-checks | Bare excepts, swallowed errors, happy-path-only |
Cross-Reference
- Full skill:
Skill(pensive:code-refinement)- All six dimensions - Algorithm efficiency:
pensive:code-refinement/modules/algorithm-efficiency- Time/space complexity analysis - Clean code:
pensive:code-refinement/modules/clean-code-checks- SOLID, naming, complexity - Architectural fit:
pensive:code-refinement/modules/architectural-fit- Coupling, cohesion, paradigm alignment - Makefile-specific:
pensive:makefile-review/modules/deduplication-patterns- Pattern rules, functions - Safety-critical patterns:
pensive:safety-critical-patterns- NASA Power of 10 adapted guidelines
Duplication Analysis Module
Detect near-identical code blocks, similar functions, and copy-paste patterns.
Why Duplication Matters
AI-assisted coding produces qualitatively different duplication:
- AI suggests new implementations rather than reusing existing code
- Tab-completion generates similar blocks instead of abstracting
- 8x increase in 5+ line duplicated blocks (GitClear 2024)
Detection Methods
1. Exact Block Duplication
# Use conserve's detect_duplicates.py if available
python3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5 2>/dev/null || \
echo "FALLBACK: Manual duplication scan"
# Fallback: hash-based detection (no external deps)
find . -name "*.py" -not -path "*/.venv/*" -not -path "*/node_modules/*" | while read f; do
awk 'NR%5==1{hash=""; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' "$f"
done | sort | uniq -d -w 1002. Similar Function Signatures
# Python: Functions with near-identical signatures
grep -rn "^def \|^ def " --include="*.py" . | \
sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d
# TypeScript/JavaScript: Similar function declarations
grep -rn "function \|const .* = (" --include="*.ts" --include="*.js" . | \
sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d
# Rust: Similar fn signatures
grep -rn "^pub fn \|^fn " --include="*.rs" . | \
sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d3. Structural Similarity
Look for repeated patterns:
- Multiple if/elif chains with same structure
- Repeated try/except blocks with minor variations
- Similar class methods across different classes
- Parallel data transformation pipelines
# Find structurally similar blocks (Python)
grep -rn "if.*:\n.*elif.*:\n.*elif" --include="*.py" . 2>/dev/null
# Find repeated error handling patterns
grep -c "try:" --include="*.py" -r . | awk -F: '$2>3{print "HIGH_TRY_COUNT:", $0}'Consolidation Strategies
Strategy 1: Extract Function
When: Same logic repeated 3+ times
# Before: Repeated validation in 3 handlers
def handler_a(data):
if not data.get('name'): raise ValueError("Missing name")
if len(data['name']) > 100: raise ValueError("Name too long")
...
# After: Shared validation
def validate_name(data):
if not data.get('name'): raise ValueError("Missing name")
if len(data['name']) > 100: raise ValueError("Name too long")Strategy 2: Extract Base Class / Mixin
When: Multiple classes share 3+ methods with identical logic
Strategy 3: Configuration-Driven
When: Same logic with different constants/parameters
# Before: 5 similar report generators
# After: One generator with config
def generate_report(config: ReportConfig) -> Report: ...Strategy 4: Template Method Pattern
When: Same workflow, different steps
Scoring
| Pattern | Severity | Confidence |
|---|---|---|
| 10+ line exact duplicate | HIGH | 95% |
| 5-9 line exact duplicate | MEDIUM | 90% |
| Similar function signatures (3+) | MEDIUM | 80% |
| Structural similarity | LOW | 70% |
Output Format
finding: duplication
severity: HIGH
locations:
- file: src/handlers/user.py
lines: 45-62
- file: src/handlers/order.py
lines: 23-40
duplicate_lines: 18
strategy: extract_function
suggested_name: validate_entity_permissions
effort: SMALLCode Refinement Insight Generation
After completing the code refinement analysis, post findings as insights to GitHub Discussions for tracking.
When to Run
Run this module AFTER the refinement analysis is complete. Post findings of type Optimization, Bug Alert, or Improvement.
Process
1. Collect refinement findings from the analysis 2. Map refinement categories to insight types:
- Duplication:
[Optimization] - Algorithm issues:
[Optimization] - Clean code violations:
[Improvement] - Error handling gaps:
[Bug Alert] - Architecture misfit:
[Improvement]
3. Post via the insight engine:
cd /home/alext/claude-night-market
python3 -c "
import sys, json
sys.path.insert(0, 'plugins/abstract/scripts')
from insight_types import Finding
from post_insights_to_discussions import post_findings
findings = [
Finding(
type='$INSIGHT_TYPE',
severity='$SEVERITY',
skill='$SKILL_OR_FILE',
summary='$SUMMARY',
evidence='$EVIDENCE',
recommendation='$RECOMMENDATION',
source='code-refinement',
)
]
urls = post_findings(findings)
for url in urls:
print(f'Posted: {url}')
"4. The posting script handles all dedup automatically
Quality Filters
Only post findings that meet these criteria:
- Severity is "high" or "medium"
- The finding is specific (not generic advice)
- Evidence references concrete code locations
- Recommendation is actionable within one PR
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.