{"id":"28a85888-9bd0-4b24-a189-495961eff4b9","entityType":"agent","slug":"clawhub-athola-nm-pensive-code-refinement","name":"code-refinement","canonicalUrl":"https://www.xpersona.co/agent/clawhub-athola-nm-pensive-code-refinement","canonicalPath":"/agent/clawhub-athola-nm-pensive-code-refinement","generatedAt":"2026-10-10T13:39:57.120Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":null},"description":"Improves code quality across duplication, efficiency, and architectural fit Skill: code-refinement Owner: athola Summary: Improves code quality across duplication, efficiency, and architectural fit Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:18:38.608Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:38:54.857Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:36.934Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:03:58.782Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:02","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.5K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-pensive-code-refinement","sourceUrl":"https://clawhub.ai/athola/nm-pensive-code-refinement","homepage":"https://clawhub.ai/athola/skills/nm-pensive-code-refinement","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/athola/nm-pensive-code-refinement","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/athola/skills/nm-pensive-code-refinement","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":63,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Improves code quality across duplication, efficiency, and architectural fit Skill: code-refinement Owner: athola Summary: Improves code quality across duplicati"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":null},"stars":null,"forks":null,"downloads":1493,"packageName":null,"latestVersion":"1.9.19","tractionLabel":"1.5K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T10:33:08.134Z","lastCrawledAt":"2026-10-10T10:33:08.134Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T10:33:08.134Z","lastVerifiedAt":null,"highlights":[{"version":"1.9.19","createdAt":"2026-08-26T13:18:38.608Z","changelog":"Release v1.9.19","fileCount":9,"zipByteSize":18529},{"version":"1.9.17","createdAt":"2026-07-30T05:38:54.857Z","changelog":"Release v1.9.17","fileCount":9,"zipByteSize":18511},{"version":"1.9.16","createdAt":"2026-07-14T19:55:36.934Z","changelog":"Release v1.9.16","fileCount":9,"zipByteSize":18335},{"version":"1.9.14","createdAt":"2026-06-30T18:03:58.782Z","changelog":"Release v1.9.14","fileCount":9,"zipByteSize":18572},{"version":"1.9.13","createdAt":"2026-06-27T16:22:02.471Z","changelog":"Release v1.9.13","fileCount":9,"zipByteSize":18474},{"version":"1.9.12","createdAt":"2026-06-19T03:17:08.456Z","changelog":"Release v1.9.12","fileCount":9,"zipByteSize":18532},{"version":"1.0.3","createdAt":"2026-06-18T14:11:58.983Z","changelog":"Release v1.9.12","fileCount":9,"zipByteSize":18588},{"version":"1.0.2","createdAt":"2026-05-09T02:19:14.392Z","changelog":"Release v1.9.5","fileCount":8,"zipByteSize":15313}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-pensive-code-refinement","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T13:39:57.117Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-code-refinement/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":null},"readme":"Skill: code-refinement\n\nOwner: athola\n\nSummary: Improves code quality across duplication, efficiency, and architectural fit\n\nTags: latest:1.9.19\n\nVersion history:\n\nv1.9.19 | 2026-08-26T13:18:38.608Z | user\n\nRelease v1.9.19\n\nv1.9.17 | 2026-07-30T05:38:54.857Z | user\n\nRelease v1.9.17\n\nv1.9.16 | 2026-07-14T19:55:36.934Z | user\n\nRelease v1.9.16\n\nv1.9.14 | 2026-06-30T18:03:58.782Z | user\n\nRelease v1.9.14\n\nv1.9.13 | 2026-06-27T16:22:02.471Z | user\n\nRelease v1.9.13\n\nv1.9.12 | 2026-06-19T03:17:08.456Z | user\n\nRelease v1.9.12\n\nv1.0.3 | 2026-06-18T14:11:58.983Z | user\n\nRelease v1.9.12\n\nv1.0.2 | 2026-05-09T02:19:14.392Z | user\n\nRelease v1.9.5\n\nv1.0.1 | 2026-05-06T14:20:26.914Z | user\n\nRelease v1.9.4\n\nv1.0.0 | 2026-04-15T14:01:50.597Z | auto\n\n- Initial release of the code-refinement skill, focused on improving code quality across six dimensions: duplication, efficiency, clean code, architectural fit, anti-slop, and error handling.\n- Provides a tiered analysis workflow (Quick, Targeted, Deep) to match different code review needs.\n- Supports progressive loading of analysis modules for focused or comprehensive reviews.\n- Integrates with related plugins for enhanced proof-of-work, code quality, and architectural analysis, with graceful fallback when unavailable.\n- Includes step-by-step workflow and required TodoWrite items for effective code refinement and documentation.\n\nArchive index:\n\nArchive v1.9.19: 9 files, 18529 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2319b), SKILL.md (11005b), _meta.json (146b)\n\nFile v1.9.19:SKILL.md\n\n---\nname: code-refinement\ndescription: Improves code quality across duplication, efficiency, and architectural fit\nversion: 1.9.8\ntriggers:\n  - refactoring\n  - clean-code\n  - algorithms\n  - duplication\n  - anti-slop\n  - craft\n  - code passes tests but quality is poor or before a major release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.pensive:safety-critical-patterns\", \"night-market.imbue:proof-of-work\", \"night-market.imbue:justify\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Analysis Dimensions](#analysis-dimensions)\n- [Progressive Loading](#progressive-loading)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Workflow](#workflow)\n- [Tiered Analysis](#tiered-analysis)\n- [Cross-Plugin Dependencies](#cross-plugin-dependencies)\n\n# Code Refinement Workflow\n\nAnalyze and improve living code quality across six dimensions.\n\n## Quick Start\n\n```bash\n/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md\n```\n\n## When To Use\n\n- After rapid AI-assisted development sprints\n- Before major releases (quality gate)\n- When code \"works but smells\"\n- Refactoring existing modules for clarity\n- Reducing technical debt in living code\n\n## When NOT To Use\n\n- Removing\n  dead/unused code (use conserve:bloat-detector)\n\n## Analysis Dimensions\n\n| # | Dimension | Module | What It Catches |\n|---|-----------|--------|----------------|\n| 1 | Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| 2 | Algorithmic Efficiency | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations |\n| 3 | Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| 4 | Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| 5 | Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| 6 | Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n| 7 | Additive Bias | `imbue:justify` | Workarounds over root fixes, test tampering, unnecessary additions |\n\n## Plugin-Specific Patterns\n\nDetection patterns for plugin and skill codebases where\nstandard code quality heuristics miss structural issues.\n\n### Delegation Stub Bodies\n\nA skill that declares \"delegates to X\" but still carries the\nfull template body is doing double duty. The delegating skill\nshould be a thin wrapper (under 30 lines) that routes to the\ntarget. Flag any delegating skill whose body exceeds 50 lines.\n\n### Module Explosion\n\nFlag skills with 10+ module files where 40% or more of content\noverlaps. Signal: two modules covering the same API surface\nfrom different angles (e.g., both describing the same config\noptions or the same CLI flags).\n\n### Oversized Single Modules\n\nFlag individual module files exceeding 500 lines as candidates\nfor splitting or trimming. Large modules defeat progressive\nloading by forcing full-file reads for partial information.\n\n### Dead Python References\n\nSkills referencing Python commands (`python -m module.name` or\n`python -c \"from module import ...\"`) where the referenced\nmodule does not exist in the plugin's `src/` directory. These\nare stale references to renamed or removed code.\n\n## Progressive Loading\n\nLoad modules based on refinement focus:\n\n- **`modules/duplication-analysis.md`** (~400 tokens): Duplication detection and consolidation\n- **`modules/algorithm-efficiency.md`** (~400 tokens): Complexity analysis and optimization\n- **`modules/clean-code-checks.md`** (~450 tokens): Clean code, anti-slop, error handling\n- **`modules/architectural-fit.md`** (~400 tokens): Paradigm alignment and coupling\n\nLoad all for comprehensive refinement. For focused work, load only relevant modules.\n\n## Required TodoWrite Items\n\n1. `refine:context-established` — Scope, language, framework detection\n2. `refine:scan-complete` — Findings across all dimensions\n3. `refine:prioritized` — Findings ranked by impact and effort\n4. `refine:plan-generated` — Concrete refactoring plan with before/after\n5. `refine:evidence-captured` — Evidence appendix per `imbue:proof-of-work`\n6. `refine:execution-complete` — All wave-listed candidates closed-or-rationale'd (only required when invocation includes \"execute findings\" or stronger; see Step 6)\n\n## Workflow\n\n### Step 1: Establish Context (`refine:context-established`)\n\nDetect project characteristics:\n```bash\n# Language detection\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" -o -name \"*.go\" \\) \\\n  | head -20\n\n# Framework detection\nls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null\n\n# Size assessment\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" \\) \\\n  | xargs wc -l 2>/dev/null | tail -1\n```\n\n### Step 2: Dimensional Scan (`refine:scan-complete`)\n\nLoad relevant modules and execute analysis per tier level.\nFor dimension 7 (Additive Bias), run `Skill(imbue:justify)`\nto compute the bias score, check Iron Law compliance,\nand flag unnecessary additions or workarounds.\n\n### Step 3: Prioritize (`refine:prioritized`)\n\nRank findings by:\n- **Impact**: How much quality improves (HIGH/MEDIUM/LOW)\n- **Effort**: Lines changed, files touched (SMALL/MEDIUM/LARGE)\n- **Risk**: Likelihood of introducing bugs (LOW/MEDIUM/HIGH)\n\nPriority = HIGH impact + SMALL effort + LOW risk first.\n\n### Step 4: Generate Plan (`refine:plan-generated`)\n\nFor each finding, produce:\n- File path and line range\n- Current code snippet\n- Proposed improvement\n- Rationale (which principle/dimension)\n- Estimated effort\n\n### Step 5: Evidence Capture (`refine:evidence-captured`)\n\nDocument with `imbue:proof-of-work` (if available):\n- `[E1]`, `[E2]` references for each finding\n- Metrics before/after where measurable\n- Principle violations cited\n\n**Fallback**: If `imbue` is not installed, capture evidence inline in the report using the same `[E1]` reference format without TodoWrite integration.\n\n### Step 6: Execute Findings (`refine:execution-complete`)\n\nSteps 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\".\n\n#### Execution mode detection\n\nMatch the user's invocation phrasing against this table to determine execution scope:\n\n| User said | Mode | Stop when |\n|---|---|---|\n| `/code-refinement` (no qualifier) | **Plan only** | After Step 5 |\n| `--dry-run` or \"just plan\" | **Plan only** | After Step 5 |\n| \"execute findings\" / \"apply fixes\" | **Plan, execute Wave 1** | After all SMALL-effort, and LOW-risk findings closed |\n| \"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 |\n| \"ignore scope guard\" | **Override branch-size limits** | Branch metrics do not gate execution. Continue past RED zone. |\n| \"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 |\n\nThe 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.\n\n#### Completion gate (when execution mode is active)\n\nThe task is **not complete** until ALL of the following hold:\n\n1. **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.\n2. **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).\n3. **Synthesis updated**: `docs/refinement/<date>/00-synthesis.md` records every closure with its commit SHA and every deferral with one-sentence rationale.\n\n#### Anti-pattern detector for the agent itself\n\nIf the model finds itself doing any of the following during execution, this is a stop-hook leak — go back to executing findings:\n\n| Anti-pattern | Recognise as |\n|---|---|\n| \"Wave 2 closed. Moving to Wave 3.\" (mid-run summary) | Premature turn-completion signal — keep working |\n| \"Documenting deferred items with rationale\" before all mechanical items are done | Skipping execution under a paper trail |\n| Writing a completion summary while >0 listed candidates lack closure-or-rationale | Violation of completion gate |\n| Re-asking user \"should I continue?\" when invocation included \"do not stop\" | Ignoring the explicit no-mid-task-summary contract |\n\nIf the harness fires a stop signal mid-execution and the completion gate is not met, immediately resume with the next finding.\n\n## Tiered Analysis\n\n| Tier | Time | Scope |\n|------|------|-------|\n| **1: Quick** (default) | 2-5 min | Complexity hotspots, obvious duplication, naming, magic values |\n| **2: Targeted** | 10-20 min | Algorithm analysis, full duplication scan, architectural alignment |\n| **3: Deep** | 30-60 min | All above and cross-module coupling, paradigm fitness, comprehensive plan |\n\n## Cross-Plugin Dependencies\n\n| Dependency | Required? | Fallback |\n|------------|-----------|----------|\n| `pensive:shared` | Yes | Core review patterns |\n| `imbue:proof-of-work` | Optional | Inline evidence in report |\n| `conserve:code-quality-principles` | Optional | Built-in KISS/YAGNI/SOLID checks |\n| `archetypes:architecture-paradigms` | Optional | Principle-based checks only (no paradigm detection) |\n\n## Supporting Modules\n\n- [Code quality analysis](modules/code-quality-analysis.md) - duplication detection commands and consolidation strategies\n\nWhen optional plugins are not installed, the skill degrades gracefully:\n- Without `imbue`: Evidence captured inline, no TodoWrite proof-of-work\n- Without `conserve`: Uses built-in clean code checks (subset)\n- Without `archetypes`: Skips paradigm-specific alignment, uses coupling/cohesion principles only\n\nFile v1.9.19:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-code-refinement\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750318608\n}\n\nFile v1.9.19:modules/algorithm-efficiency.md\n\n---\nmodule: algorithm-efficiency\ndescription: Detect algorithmic inefficiencies and suggest improvements\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [algorithms, complexity, performance, optimization]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Algorithm Efficiency Module\n\nIdentify time and space complexity inefficiencies at the code block level.\n\n## Scope\n\nThis 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.\n\n## Detection Patterns\n\n### 1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))\n\n```python\n# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)\n```\n\n**Detection:**\n```bash\n# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d\n```\n\n### 2. Repeated Sort / Search\n\n```python\n# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)\n```\n\n**Detection:**\n```bash\n# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone\n```\n\n### 3. List Where Set/Dict Suffices\n\n```python\n# Anti-pattern: O(n) membership test\nif item in large_list:  # O(n)\n    ...\n\n# Better: O(1) membership test\nlarge_set = set(large_list)\nif item in large_set:  # O(1)\n    ...\n```\n\n**Detection:**\n```bash\n# Find \"in list_var\" patterns (heuristic)\ngrep -n \" in \\[\" --include=\"*.py\" -r .\ngrep -n \" not in \" --include=\"*.py\" -r . | grep -v \"not in {\" | grep -v \"not in set(\"\n```\n\n### 4. String Concatenation in Loop\n\n```python\n# Anti-pattern: O(n^2) string building\nresult = \"\"\nfor item in items:\n    result += str(item) + \", \"\n\n# Better: O(n) with join\nresult = \", \".join(str(item) for item in items)\n```\n\n### 5. Unnecessary Intermediate Collections\n\n```python\n# Anti-pattern: builds full list just to iterate\nall_items = [transform(x) for x in data]  # allocates full list\nfor item in all_items:\n    process(item)\n\n# Better: generator (lazy evaluation)\nfor item in (transform(x) for x in data):\n    process(item)\n```\n\n### 6. Repeated Computation (Missing Memoization)\n\n```python\n# Anti-pattern: recomputes expensive value\ndef get_result(n):\n    # called 1000x with same n values\n    return expensive_compute(n)\n\n# Better: cache\nfrom functools import lru_cache\n\n@lru_cache(maxsize=128)\ndef get_result(n):\n    return expensive_compute(n)\n```\n\n## Complexity Estimation Heuristics\n\nRather than formal Big-O analysis, use practical heuristics:\n\n| Pattern | Likely Complexity | Flag When |\n|---------|------------------|-----------|\n| Single loop over data | O(n) | Data > 10K and no early exit |\n| Nested loop, same data | O(n^2) | Always flag |\n| Sort inside loop | O(m * n log n) | Always flag |\n| `in list` inside loop | O(n * m) | List > 100 items |\n| Recursive without memo | O(2^n) potential | Recursive calls > 1 |\n| String concat in loop | O(n^2) | Loop > 100 iterations |\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Nested loop, same data | HIGH | 85% |\n| Sort/search in loop | HIGH | 90% |\n| List where set suffices | MEDIUM | 80% |\n| String concat in loop | MEDIUM | 85% |\n| Missing memoization | LOW | 65% |\n| Unnecessary intermediates | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: algorithm-inefficiency\nseverity: HIGH\ntype: nested_loop_same_collection\nlocation:\n  file: src/matching.py\n  lines: 45-58\ncurrent_complexity: O(n^2)\nsuggested_complexity: O(n)\nstrategy: build_index_first\neffort: SMALL\n```\n\nFile v1.9.19:modules/architectural-fit.md\n\n---\nmodule: architectural-fit\ndescription: Assess code alignment with architectural paradigm and coupling principles\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [architecture, coupling, cohesion, paradigm, alignment]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Architectural Fit Module\n\nEvaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.\n\n## Two-Mode Operation\n\n### Mode 1: Paradigm-Aware (archetypes plugin installed)\n\nWhen `archetypes` is available, detect the project's paradigm and check alignment:\n\n```\nSkill(archetypes:architecture-paradigms) -> detect paradigm -> check violations\n```\n\nSupported paradigms from archetypes:\n- Functional Core / Imperative Shell\n- Hexagonal (Ports & Adapters)\n- Layered Architecture\n- Pipeline / Data Flow\n- Modular Monolith\n- Event-Driven\n- Client-Server\n- Microkernel\n- CQRS/ES\n\n### Mode 2: Principle-Based (fallback, no archetypes)\n\nCheck universal coupling/cohesion principles without paradigm detection:\n\n- Dependency direction (no circular deps)\n- Layer violations (UI calling DB directly)\n- Cohesion (related code grouped together)\n- Encapsulation (no leaking internals)\n\n## Detection: Coupling Violations\n\n### 1. Circular Dependencies\n\n```bash\n# Python: Find circular imports (heuristic)\ngrep -rn \"^from \\|^import \" --include=\"*.py\" . | \\\n  awk -F: '{file=$1; gsub(/.*from /,\"\",$3); gsub(/ import.*/,\"\",$3); print file, $3}' | \\\n  sort | while read a b; do\n    grep -q \"from.*$(basename $a .py)\" \"$b.py\" 2>/dev/null && \\\n      echo \"CIRCULAR: $a <-> $b\"\n  done\n```\n\n### 2. Layer Violations\n\nCommon layer boundaries to check:\n- Presentation should not import from data/persistence\n- Domain/business logic should not depend on framework\n- Utilities should not depend on domain\n\n```bash\n# Find cross-layer imports (convention: src/{layer}/)\n# Customize layer names per project\nfor violation in \\\n  \"handlers.*import.*models\\.\" \\\n  \"views.*import.*database\" \\\n  \"api.*import.*sql\\|cursor\\|query\"; do\n  grep -rn \"$violation\" --include=\"*.py\" . 2>/dev/null && echo \"LAYER_VIOLATION: $violation\"\ndone\n```\n\n### 3. Feature Envy\n\nA method that uses more features of another class than its own:\n\n```bash\n# Heuristic: methods with many external references\n# Look for methods where self.X appears less than other_obj.Y\ngrep -A20 \"def \" --include=\"*.py\" -r . | \\\n  awk '/def /{fn=$0; self=0; other=0} /self\\./{self++} /[a-z]+\\./{other++} /^$/{if(other>self*2 && other>3) print \"FEATURE_ENVY:\", fn}'\n```\n\n### 4. Inappropriate Intimacy\n\nClasses that access each other's private members:\n\n```bash\n# Find access to _private members from outside class\ngrep -rn \"\\._[a-z]\" --include=\"*.py\" . | grep -v \"self\\._\\|cls\\._\\|__init__\\|test_\" | head -20\n```\n\n### 5. Shotgun Surgery Indicators\n\nChanges to one concept require touching many files:\n\n```bash\n# Heuristic: functions/classes with same name prefix across many files\ngrep -rn \"^def \" --include=\"*.py\" . | sed 's/def //;s/(.*//' | \\\n  awk -F: '{print $2}' | sed 's/_.*//' | sort | uniq -c | sort -rn | \\\n  awk '$1>4{print \"SCATTERED_CONCEPT (\"$1\" files):\", $2}'\n```\n\n## Detection: Cohesion Issues\n\n### Low Cohesion Indicators\n\n```bash\n# Files with many unrelated public functions (>8)\ngrep -c \"^def \" --include=\"*.py\" -r . | awk -F: '$2>8{print \"LOW_COHESION:\", $0}'\n\n# Classes with unrelated method groups\n# Heuristic: methods that don't reference same instance variables\n```\n\n### Module Size Imbalance\n\n```bash\n# Find modules that are disproportionately large\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -exec wc -l {} + | \\\n  sort -rn | head -10\n# Flag if largest is >5x the median\n```\n\n## Paradigm-Specific Checks\n\n### Functional Core / Imperative Shell\n- [ ] Pure functions don't perform I/O\n- [ ] Side effects isolated to shell layer\n- [ ] Domain logic is testable without mocks\n\n### Hexagonal\n- [ ] Ports defined as interfaces/protocols\n- [ ] Adapters don't leak into domain\n- [ ] Dependency flow: adapters -> ports -> domain\n\n### Layered\n- [ ] Dependencies flow downward only\n- [ ] No layer bypassing\n- [ ] Clear layer boundaries in directory structure\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Circular dependency | HIGH | 90% |\n| Layer violation | HIGH | 85% |\n| Feature envy (strong) | MEDIUM | 75% |\n| Low cohesion (>10 methods) | MEDIUM | 80% |\n| Inappropriate intimacy | MEDIUM | 80% |\n| Scattered concept | LOW | 65% |\n| Module size imbalance | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: architectural-violation\nseverity: HIGH\ntype: circular_dependency\nlocations:\n  - file: src/services/user.py\n    imports: src/models/user.py\n  - file: src/models/user.py\n    imports: src/services/user.py\nstrategy: introduce_interface\nparadigm_note: \"Violates dependency inversion; extract protocol\"\neffort: MEDIUM\n```\n\nFile v1.9.19:modules/clean-code-checks.md\n\n---\nmodule: clean-code-checks\ndescription: Clean code violations, anti-slop patterns, and error handling checks\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [clean-code, anti-slop, naming, error-handling, complexity]\ndependencies: [Read, Grep, Glob, Bash]\nestimated_tokens: 450\n---\n\n# Clean Code Checks Module\n\nDetect violations of clean code principles, AI slop patterns, and error handling gaps.\n\nCovers three dimensions: Clean Code, Anti-Slop, and Error Handling.\n\n## Clean Code Violations\n\n### 1. Long Methods (>30 lines)\n\n```bash\n# Python: Find long functions\ngrep -n \"^def \\|^    def \" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Count lines until next def or end\n  length=$(sed -n \"${num},\\$p\" \"$file\" | awk '/^def |^    def /{if(NR>1)exit}END{print NR}')\n  [ \"$length\" -gt 30 ] && echo \"LONG_METHOD ($length lines): $line\"\ndone\n```\n\n**Refactoring**: Extract method, compose method pattern.\n\n### 2. Deep Nesting (>3 levels)\n\n```bash\n# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)\ngrep -rn \"^                \" --include=\"*.py\" . | head -20\ngrep -rn \"^\\t\\t\\t\\t\" --include=\"*.js\" --include=\"*.ts\" . | head -20\n```\n\n**Refactoring**: Guard clauses, extract method, strategy pattern.\n\n### 3. Magic Numbers and Strings\n\n```bash\n# Find magic numbers (excluding 0, 1, common constants)\ngrep -rn \"[^a-zA-Z_][2-9][0-9]\\{1,\\}[^a-zA-Z_0-9\\\"']\" --include=\"*.py\" . | \\\n  grep -v \"range\\|port\\|version\\|#\\|test_\\|assert\" | head -20\n```\n\n**Refactoring**: Extract to named constants.\n\n### 4. Poor Naming\n\nIndicators of AI-generated generic names:\n```bash\n# Find generic function names\ngrep -rn \"def process\\|def handle\\|def manage\\|def do_\\|def run_\" --include=\"*.py\" . | \\\n  grep -v \"test_\\|__\" | head -20\n\n# Find single-letter variables (outside loops/lambdas)\ngrep -rn \" [a-z] = \" --include=\"*.py\" . | grep -v \"for [a-z] in\\|lambda [a-z]\" | head -20\n```\n\n### 5. God Classes (>300 lines or >10 methods)\n\n```bash\n# Python: Large classes\ngrep -c \"def \" --include=\"*.py\" -r . | awk -F: '$2>10{print \"GOD_CLASS:\", $0}'\n```\n\n## Anti-Slop Patterns\n\nAI-specific code smells that traditional linters miss.\n\n### 1. Premature Abstraction\n\nBase classes/interfaces with only 1 implementation.\n\n```bash\n# Python: ABC with single inheritor\ngrep -rn \"class.*ABC\\|@abstractmethod\" --include=\"*.py\" . | cut -d: -f1 | sort -u | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ -n \"$class\" ] && {\n    inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n    [ \"$inheritors\" -lt 2 ] && echo \"PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)\"\n  }\ndone\n```\n\n### 2. Enterprise Cosplay\n\nOver-engineered patterns for simple problems:\n- Factory for a single type\n- Strategy pattern with one strategy\n- Observer with one subscriber\n- Middleware chain for single operation\n\n```bash\n# Find *Factory, *Builder, *Strategy with few usages\nfor pattern in Factory Builder Strategy Observer; do\n  grep -rn \"class.*$pattern\" --include=\"*.py\" --include=\"*.ts\" . 2>/dev/null | while read line; do\n    class=$(echo \"$line\" | grep -oP \"class \\K\\w+\")\n    refs=$(grep -rn \"$class\" --include=\"*.py\" --include=\"*.ts\" . | wc -l)\n    [ \"$refs\" -lt 4 ] && echo \"ENTERPRISE_COSPLAY ($refs refs): $line\"\n  done\ndone\n```\n\n### 3. Hollow Abstractions\n\nCode that adds indirection without value:\n```python\n# Anti-pattern: Wrapper that just delegates\nclass UserService:\n    def __init__(self, repo):\n        self.repo = repo\n    def get_user(self, id):\n        return self.repo.get_user(id)  # Just passes through\n    def save_user(self, user):\n        return self.repo.save_user(user)  # Just passes through\n```\n\n### 4. Verbose Where Concise Suffices\n\nAI tends toward verbosity. Look for:\n- Explicit boolean returns: `if x: return True; else: return False`\n- Unnecessary else after return\n- Redundant variable assignments before return\n\n## Error Handling Checks\n\n### 1. Bare/Broad Excepts\n\n```bash\n# Find bare except\ngrep -rn \"except:\" --include=\"*.py\" -r .\n# Find overly broad except\ngrep -rn \"except Exception:\" --include=\"*.py\" -r . | grep -v \"logging\\|logger\\|log\\.\"\n```\n\n### 2. Swallowed Errors\n\n```bash\n# except + pass (swallowed)\ngrep -A1 \"except\" --include=\"*.py\" -r . | grep -B1 \"pass$\" | grep \"except\"\n```\n\n### 3. Happy-Path-Only Code\n\n```bash\n# Functions >50 lines without any error handling\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  block=$(sed -n \"${num},$((num+60))p\" \"$file\")\n  has_error=$(echo \"$block\" | grep -c \"raise\\|except\\|Error\\|error\\|Warning\")\n  lines=$(echo \"$block\" | wc -l)\n  [ \"$lines\" -gt 50 ] && [ \"$has_error\" -eq 0 ] && echo \"HAPPY_PATH_ONLY: $line\"\ndone\n```\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Bare except / swallowed error | HIGH | 95% |\n| God class (>300 lines) | HIGH | 90% |\n| Long method (>50 lines) | MEDIUM | 90% |\n| Premature abstraction | MEDIUM | 85% |\n| Magic numbers | MEDIUM | 80% |\n| Deep nesting (>4) | MEDIUM | 85% |\n| Generic naming | LOW | 70% |\n| Verbose patterns | LOW | 75% |\n\n## Integration with conserve:code-quality-principles\n\nIf the `conserve` plugin is installed, reference `Skill(conserve:code-quality-principles)` for KISS, YAGNI, and SOLID principle definitions with language-specific examples.\n\n**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).\n\nFile v1.9.19:modules/code-quality-analysis.md\n\n---\nname: code-quality-analysis\ndescription: Shared code quality analysis patterns for review skills\nparent_skill: pensive:shared\ncategory: review-infrastructure\ntags: [code-quality, deduplication, redundancy, analysis, DRY]\nreusable_by: [pensive:code-refinement, pensive:unified-review, sanctum:pr-review, pensive:bug-review]\nestimated_tokens: 450\n---\n\n# Code Quality Analysis Module\n\nShared patterns for code quality and deduplication analysis across review contexts.\n\n## Quick Detection Commands\n\n### Duplication Detection\n\n```bash\n# Python: Find similar function signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Find repeated code blocks (5+ lines)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100 | head -10\n```\n\n### Redundancy Patterns\n\n```bash\n# Find similar error handling blocks\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>5{print \"HIGH_TRY_COUNT:\", $0}'\n\n# Find repeated validation patterns\ngrep -rn \"if not.*:\" --include=\"*.py\" . | \\\n  sed 's/if not \\(.*\\):/\\1/' | sort | uniq -c | sort -rn | head -10\n```\n\n## Quality Dimensions\n\n| Dimension | Detection Method | Severity |\n|-----------|-----------------|----------|\n| Exact duplication (10+ lines) | Hash-based | HIGH |\n| Similar functions (3+) | Signature matching | MEDIUM |\n| Repeated patterns | Structural analysis | LOW-MEDIUM |\n| Copy-paste indicators | Comment/naming similarity | MEDIUM |\n\n## Integration with PR Review\n\nWhen invoked from `/pr-review`, analyze only changed files:\n\n```bash\n# Get changed files\nCHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only | grep -E '\\.(py|ts|js|rs|go)$')\n\n# Run targeted analysis on changed files only\nfor file in $CHANGED_FILES; do\n  # Check for duplication within file\n  # Check for redundancy with existing codebase\ndone\n```\n\n## Consolidation Strategies\n\n| Pattern | Strategy | When to Apply |\n|---------|----------|---------------|\n| Same logic 3+ times | Extract function | Always |\n| Multiple classes share methods | Extract base/mixin | 3+ shared methods |\n| Same logic, different constants | Configuration-driven | 2+ occurrences |\n| Same workflow, different steps | Template method | Clear workflow pattern |\n\n## Output Format\n\n```yaml\nfinding: code-quality\ntype: duplication|redundancy|complexity\nseverity: HIGH|MEDIUM|LOW\nconfidence: 70-95%\nlocations:\n  - file: path/to/file.py\n    lines: 45-62\n  - file: path/to/other.py\n    lines: 23-40\nstrategy: extract_function|extract_class|configure|template_method\neffort: SMALL|MEDIUM|LARGE\n```\n\n## Full Analysis: Invoke pensive:code-refinement\n\nFor comprehensive code quality analysis, invoke the full `pensive:code-refinement` skill:\n\n```\nSkill(pensive:code-refinement)\n```\n\nThis provides six analysis dimensions:\n\n| Dimension | Module | What It Catches |\n|-----------|--------|-----------------|\n| Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| **Algorithmic Efficiency** | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations, time/space complexity |\n| Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n\n## Cross-Reference\n\n- **Full skill**: `Skill(pensive:code-refinement)` - All six dimensions\n- **Algorithm efficiency**: `pensive:code-refinement/modules/algorithm-efficiency` - Time/space complexity analysis\n- **Clean code**: `pensive:code-refinement/modules/clean-code-checks` - SOLID, naming, complexity\n- **Architectural fit**: `pensive:code-refinement/modules/architectural-fit` - Coupling, cohesion, paradigm alignment\n- **Makefile-specific**: `pensive:makefile-review/modules/deduplication-patterns` - Pattern rules, functions\n- **Safety-critical patterns**: `pensive:safety-critical-patterns` - NASA Power of 10 adapted guidelines\n\nFile v1.9.19:modules/duplication-analysis.md\n\n---\nmodule: duplication-analysis\ndescription: Detect and consolidate code duplication and redundancy\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [duplication, redundancy, DRY, consolidation]\ndependencies: [Bash, Grep, Glob, Read]\nestimated_tokens: 400\n---\n\n# Duplication Analysis Module\n\nDetect near-identical code blocks, similar functions, and copy-paste patterns.\n\n## Why Duplication Matters\n\nAI-assisted coding produces qualitatively different duplication:\n- AI suggests new implementations rather than reusing existing code\n- Tab-completion generates similar blocks instead of abstracting\n- 8x increase in 5+ line duplicated blocks (GitClear 2024)\n\n## Detection Methods\n\n### 1. Exact Block Duplication\n\n```bash\n# Use conserve's detect_duplicates.py if available\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5 2>/dev/null || \\\n  echo \"FALLBACK: Manual duplication scan\"\n\n# Fallback: hash-based detection (no external deps)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100\n```\n\n### 2. Similar Function Signatures\n\n```bash\n# Python: Functions with near-identical signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar function declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Rust: Similar fn signatures\ngrep -rn \"^pub fn \\|^fn \" --include=\"*.rs\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n```\n\n### 3. Structural Similarity\n\nLook for repeated patterns:\n- Multiple if/elif chains with same structure\n- Repeated try/except blocks with minor variations\n- Similar class methods across different classes\n- Parallel data transformation pipelines\n\n```bash\n# Find structurally similar blocks (Python)\ngrep -rn \"if.*:\\n.*elif.*:\\n.*elif\" --include=\"*.py\" . 2>/dev/null\n\n# Find repeated error handling patterns\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>3{print \"HIGH_TRY_COUNT:\", $0}'\n```\n\n## Consolidation Strategies\n\n### Strategy 1: Extract Function\n**When**: Same logic repeated 3+ times\n```python\n# Before: Repeated validation in 3 handlers\ndef handler_a(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n    ...\n\n# After: Shared validation\ndef validate_name(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n```\n\n### Strategy 2: Extract Base Class / Mixin\n**When**: Multiple classes share 3+ methods with identical logic\n\n### Strategy 3: Configuration-Driven\n**When**: Same logic with different constants/parameters\n```python\n# Before: 5 similar report generators\n# After: One generator with config\ndef generate_report(config: ReportConfig) -> Report: ...\n```\n\n### Strategy 4: Template Method Pattern\n**When**: Same workflow, different steps\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| 10+ line exact duplicate | HIGH | 95% |\n| 5-9 line exact duplicate | MEDIUM | 90% |\n| Similar function signatures (3+) | MEDIUM | 80% |\n| Structural similarity | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: duplication\nseverity: HIGH\nlocations:\n  - file: src/handlers/user.py\n    lines: 45-62\n  - file: src/handlers/order.py\n    lines: 23-40\nduplicate_lines: 18\nstrategy: extract_function\nsuggested_name: validate_entity_permissions\neffort: SMALL\n```\n\nFile v1.9.19:modules/insight-generation.md\n\n---\nname: insight-generation\ndescription: Post codebase-wide insights from refinement analysis\n---\n\n## Code Refinement Insight Generation\n\nAfter completing the code refinement analysis, post\nfindings as insights to GitHub Discussions for tracking.\n\n### When to Run\n\nRun this module AFTER the refinement analysis is complete.\nPost findings of type Optimization, Bug Alert, or\nImprovement.\n\n### Process\n\n1. Collect refinement findings from the analysis\n2. Map refinement categories to insight types:\n   - Duplication: `[Optimization]`\n   - Algorithm issues: `[Optimization]`\n   - Clean code violations: `[Improvement]`\n   - Error handling gaps: `[Bug Alert]`\n   - Architecture misfit: `[Improvement]`\n\n3. Post via the insight engine:\n\n```bash\ncd /home/alext/claude-night-market\npython3 -c \"\nimport sys, json\nsys.path.insert(0, 'plugins/abstract/scripts')\nfrom insight_types import Finding\nfrom post_insights_to_discussions import post_findings\n\nfindings = [\n    Finding(\n        type='$INSIGHT_TYPE',\n        severity='$SEVERITY',\n        skill='$SKILL_OR_FILE',\n        summary='$SUMMARY',\n        evidence='$EVIDENCE',\n        recommendation='$RECOMMENDATION',\n        source='code-refinement',\n    )\n]\nurls = post_findings(findings)\nfor url in urls:\n    print(f'Posted: {url}')\n\"\n```\n\n4. The posting script handles all dedup automatically\n\n### Quality Filters\n\nOnly post findings that meet these criteria:\n\n- Severity is \"high\" or \"medium\"\n- The finding is specific (not generic advice)\n- Evidence references concrete code locations\n- Recommendation is actionable within one PR\n\nFile v1.9.19:skill-card.md\n\n## Description:\n\nImproves code quality across duplication, efficiency, and architectural fit.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[athola](https://clawhub.ai/user/athola)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to analyze living codebases for duplication, algorithmic inefficiency, clean-code issues, architectural mismatch, anti-slop patterns, and error-handling gaps before refactoring or release.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill may perform broad repository analysis and, when explicitly invoked, modify files.\n\nMitigation: Run plan-only analysis first, review proposed edits before applying them, and keep changes scoped to a version-controlled working tree.\n\nRisk: The insight-generation module can post findings to GitHub Discussions, which may expose private or sensitive repository information.\n\nMitigation: Do not use insight generation on private or sensitive repositories unless approval, redaction, and destination checks are in place.\n\nRisk: The artifact includes scope-guard and stop-signal override behavior that can increase the amount of work performed in one run.\n\nMitigation: Avoid override modes unless explicitly approved, and retain human review gates for large or high-risk refactoring waves.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-code-refinement)\n- [OpenClaw metadata homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, guidance]\n\n**Output Format:** [Markdown analysis with inline code and shell command examples]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May produce prioritized findings, refactoring plans, evidence notes, and, when explicitly invoked, code changes or external insight posts.]\n\n## Skill Version(s):\n\n1.9.19 (source: server release metadata; artifact frontmatter lists 1.9.8)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.9.17: 9 files, 18511 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2422b), SKILL.md (11005b), _meta.json (146b)\n\nFile v1.9.17:SKILL.md\n\n---\nname: code-refinement\ndescription: Improves code quality across duplication, efficiency, and architectural fit\nversion: 1.9.8\ntriggers:\n  - refactoring\n  - clean-code\n  - algorithms\n  - duplication\n  - anti-slop\n  - craft\n  - code passes tests but quality is poor or before a major release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.pensive:safety-critical-patterns\", \"night-market.imbue:proof-of-work\", \"night-market.imbue:justify\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Analysis Dimensions](#analysis-dimensions)\n- [Progressive Loading](#progressive-loading)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Workflow](#workflow)\n- [Tiered Analysis](#tiered-analysis)\n- [Cross-Plugin Dependencies](#cross-plugin-dependencies)\n\n# Code Refinement Workflow\n\nAnalyze and improve living code quality across six dimensions.\n\n## Quick Start\n\n```bash\n/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md\n```\n\n## When To Use\n\n- After rapid AI-assisted development sprints\n- Before major releases (quality gate)\n- When code \"works but smells\"\n- Refactoring existing modules for clarity\n- Reducing technical debt in living code\n\n## When NOT To Use\n\n- Removing\n  dead/unused code (use conserve:bloat-detector)\n\n## Analysis Dimensions\n\n| # | Dimension | Module | What It Catches |\n|---|-----------|--------|----------------|\n| 1 | Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| 2 | Algorithmic Efficiency | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations |\n| 3 | Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| 4 | Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| 5 | Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| 6 | Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n| 7 | Additive Bias | `imbue:justify` | Workarounds over root fixes, test tampering, unnecessary additions |\n\n## Plugin-Specific Patterns\n\nDetection patterns for plugin and skill codebases where\nstandard code quality heuristics miss structural issues.\n\n### Delegation Stub Bodies\n\nA skill that declares \"delegates to X\" but still carries the\nfull template body is doing double duty. The delegating skill\nshould be a thin wrapper (under 30 lines) that routes to the\ntarget. Flag any delegating skill whose body exceeds 50 lines.\n\n### Module Explosion\n\nFlag skills with 10+ module files where 40% or more of content\noverlaps. Signal: two modules covering the same API surface\nfrom different angles (e.g., both describing the same config\noptions or the same CLI flags).\n\n### Oversized Single Modules\n\nFlag individual module files exceeding 500 lines as candidates\nfor splitting or trimming. Large modules defeat progressive\nloading by forcing full-file reads for partial information.\n\n### Dead Python References\n\nSkills referencing Python commands (`python -m module.name` or\n`python -c \"from module import ...\"`) where the referenced\nmodule does not exist in the plugin's `src/` directory. These\nare stale references to renamed or removed code.\n\n## Progressive Loading\n\nLoad modules based on refinement focus:\n\n- **`modules/duplication-analysis.md`** (~400 tokens): Duplication detection and consolidation\n- **`modules/algorithm-efficiency.md`** (~400 tokens): Complexity analysis and optimization\n- **`modules/clean-code-checks.md`** (~450 tokens): Clean code, anti-slop, error handling\n- **`modules/architectural-fit.md`** (~400 tokens): Paradigm alignment and coupling\n\nLoad all for comprehensive refinement. For focused work, load only relevant modules.\n\n## Required TodoWrite Items\n\n1. `refine:context-established` — Scope, language, framework detection\n2. `refine:scan-complete` — Findings across all dimensions\n3. `refine:prioritized` — Findings ranked by impact and effort\n4. `refine:plan-generated` — Concrete refactoring plan with before/after\n5. `refine:evidence-captured` — Evidence appendix per `imbue:proof-of-work`\n6. `refine:execution-complete` — All wave-listed candidates closed-or-rationale'd (only required when invocation includes \"execute findings\" or stronger; see Step 6)\n\n## Workflow\n\n### Step 1: Establish Context (`refine:context-established`)\n\nDetect project characteristics:\n```bash\n# Language detection\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" -o -name \"*.go\" \\) \\\n  | head -20\n\n# Framework detection\nls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null\n\n# Size assessment\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" \\) \\\n  | xargs wc -l 2>/dev/null | tail -1\n```\n\n### Step 2: Dimensional Scan (`refine:scan-complete`)\n\nLoad relevant modules and execute analysis per tier level.\nFor dimension 7 (Additive Bias), run `Skill(imbue:justify)`\nto compute the bias score, check Iron Law compliance,\nand flag unnecessary additions or workarounds.\n\n### Step 3: Prioritize (`refine:prioritized`)\n\nRank findings by:\n- **Impact**: How much quality improves (HIGH/MEDIUM/LOW)\n- **Effort**: Lines changed, files touched (SMALL/MEDIUM/LARGE)\n- **Risk**: Likelihood of introducing bugs (LOW/MEDIUM/HIGH)\n\nPriority = HIGH impact + SMALL effort + LOW risk first.\n\n### Step 4: Generate Plan (`refine:plan-generated`)\n\nFor each finding, produce:\n- File path and line range\n- Current code snippet\n- Proposed improvement\n- Rationale (which principle/dimension)\n- Estimated effort\n\n### Step 5: Evidence Capture (`refine:evidence-captured`)\n\nDocument with `imbue:proof-of-work` (if available):\n- `[E1]`, `[E2]` references for each finding\n- Metrics before/after where measurable\n- Principle violations cited\n\n**Fallback**: If `imbue` is not installed, capture evidence inline in the report using the same `[E1]` reference format without TodoWrite integration.\n\n### Step 6: Execute Findings (`refine:execution-complete`)\n\nSteps 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\".\n\n#### Execution mode detection\n\nMatch the user's invocation phrasing against this table to determine execution scope:\n\n| User said | Mode | Stop when |\n|---|---|---|\n| `/code-refinement` (no qualifier) | **Plan only** | After Step 5 |\n| `--dry-run` or \"just plan\" | **Plan only** | After Step 5 |\n| \"execute findings\" / \"apply fixes\" | **Plan, execute Wave 1** | After all SMALL-effort, and LOW-risk findings closed |\n| \"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 |\n| \"ignore scope guard\" | **Override branch-size limits** | Branch metrics do not gate execution. Continue past RED zone. |\n| \"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 |\n\nThe 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.\n\n#### Completion gate (when execution mode is active)\n\nThe task is **not complete** until ALL of the following hold:\n\n1. **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.\n2. **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).\n3. **Synthesis updated**: `docs/refinement/<date>/00-synthesis.md` records every closure with its commit SHA and every deferral with one-sentence rationale.\n\n#### Anti-pattern detector for the agent itself\n\nIf the model finds itself doing any of the following during execution, this is a stop-hook leak — go back to executing findings:\n\n| Anti-pattern | Recognise as |\n|---|---|\n| \"Wave 2 closed. Moving to Wave 3.\" (mid-run summary) | Premature turn-completion signal — keep working |\n| \"Documenting deferred items with rationale\" before all mechanical items are done | Skipping execution under a paper trail |\n| Writing a completion summary while >0 listed candidates lack closure-or-rationale | Violation of completion gate |\n| Re-asking user \"should I continue?\" when invocation included \"do not stop\" | Ignoring the explicit no-mid-task-summary contract |\n\nIf the harness fires a stop signal mid-execution and the completion gate is not met, immediately resume with the next finding.\n\n## Tiered Analysis\n\n| Tier | Time | Scope |\n|------|------|-------|\n| **1: Quick** (default) | 2-5 min | Complexity hotspots, obvious duplication, naming, magic values |\n| **2: Targeted** | 10-20 min | Algorithm analysis, full duplication scan, architectural alignment |\n| **3: Deep** | 30-60 min | All above and cross-module coupling, paradigm fitness, comprehensive plan |\n\n## Cross-Plugin Dependencies\n\n| Dependency | Required? | Fallback |\n|------------|-----------|----------|\n| `pensive:shared` | Yes | Core review patterns |\n| `imbue:proof-of-work` | Optional | Inline evidence in report |\n| `conserve:code-quality-principles` | Optional | Built-in KISS/YAGNI/SOLID checks |\n| `archetypes:architecture-paradigms` | Optional | Principle-based checks only (no paradigm detection) |\n\n## Supporting Modules\n\n- [Code quality analysis](modules/code-quality-analysis.md) - duplication detection commands and consolidation strategies\n\nWhen optional plugins are not installed, the skill degrades gracefully:\n- Without `imbue`: Evidence captured inline, no TodoWrite proof-of-work\n- Without `conserve`: Uses built-in clean code checks (subset)\n- Without `archetypes`: Skips paradigm-specific alignment, uses coupling/cohesion principles only\n\nFile v1.9.17:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-code-refinement\",\n  \"version\": \"1.9.17\",\n  \"publishedAt\": 1785389934857\n}\n\nFile v1.9.17:modules/algorithm-efficiency.md\n\n---\nmodule: algorithm-efficiency\ndescription: Detect algorithmic inefficiencies and suggest improvements\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [algorithms, complexity, performance, optimization]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Algorithm Efficiency Module\n\nIdentify time and space complexity inefficiencies at the code block level.\n\n## Scope\n\nThis 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.\n\n## Detection Patterns\n\n### 1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))\n\n```python\n# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)\n```\n\n**Detection:**\n```bash\n# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d\n```\n\n### 2. Repeated Sort / Search\n\n```python\n# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)\n```\n\n**Detection:**\n```bash\n# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone\n```\n\n### 3. List Where Set/Dict Suffices\n\n```python\n# Anti-pattern: O(n) membership test\nif item in large_list:  # O(n)\n    ...\n\n# Better: O(1) membership test\nlarge_set = set(large_list)\nif item in large_set:  # O(1)\n    ...\n```\n\n**Detection:**\n```bash\n# Find \"in list_var\" patterns (heuristic)\ngrep -n \" in \\[\" --include=\"*.py\" -r .\ngrep -n \" not in \" --include=\"*.py\" -r . | grep -v \"not in {\" | grep -v \"not in set(\"\n```\n\n### 4. String Concatenation in Loop\n\n```python\n# Anti-pattern: O(n^2) string building\nresult = \"\"\nfor item in items:\n    result += str(item) + \", \"\n\n# Better: O(n) with join\nresult = \", \".join(str(item) for item in items)\n```\n\n### 5. Unnecessary Intermediate Collections\n\n```python\n# Anti-pattern: builds full list just to iterate\nall_items = [transform(x) for x in data]  # allocates full list\nfor item in all_items:\n    process(item)\n\n# Better: generator (lazy evaluation)\nfor item in (transform(x) for x in data):\n    process(item)\n```\n\n### 6. Repeated Computation (Missing Memoization)\n\n```python\n# Anti-pattern: recomputes expensive value\ndef get_result(n):\n    # called 1000x with same n values\n    return expensive_compute(n)\n\n# Better: cache\nfrom functools import lru_cache\n\n@lru_cache(maxsize=128)\ndef get_result(n):\n    return expensive_compute(n)\n```\n\n## Complexity Estimation Heuristics\n\nRather than formal Big-O analysis, use practical heuristics:\n\n| Pattern | Likely Complexity | Flag When |\n|---------|------------------|-----------|\n| Single loop over data | O(n) | Data > 10K and no early exit |\n| Nested loop, same data | O(n^2) | Always flag |\n| Sort inside loop | O(m * n log n) | Always flag |\n| `in list` inside loop | O(n * m) | List > 100 items |\n| Recursive without memo | O(2^n) potential | Recursive calls > 1 |\n| String concat in loop | O(n^2) | Loop > 100 iterations |\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Nested loop, same data | HIGH | 85% |\n| Sort/search in loop | HIGH | 90% |\n| List where set suffices | MEDIUM | 80% |\n| String concat in loop | MEDIUM | 85% |\n| Missing memoization | LOW | 65% |\n| Unnecessary intermediates | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: algorithm-inefficiency\nseverity: HIGH\ntype: nested_loop_same_collection\nlocation:\n  file: src/matching.py\n  lines: 45-58\ncurrent_complexity: O(n^2)\nsuggested_complexity: O(n)\nstrategy: build_index_first\neffort: SMALL\n```\n\nFile v1.9.17:modules/architectural-fit.md\n\n---\nmodule: architectural-fit\ndescription: Assess code alignment with architectural paradigm and coupling principles\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [architecture, coupling, cohesion, paradigm, alignment]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Architectural Fit Module\n\nEvaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.\n\n## Two-Mode Operation\n\n### Mode 1: Paradigm-Aware (archetypes plugin installed)\n\nWhen `archetypes` is available, detect the project's paradigm and check alignment:\n\n```\nSkill(archetypes:architecture-paradigms) -> detect paradigm -> check violations\n```\n\nSupported paradigms from archetypes:\n- Functional Core / Imperative Shell\n- Hexagonal (Ports & Adapters)\n- Layered Architecture\n- Pipeline / Data Flow\n- Modular Monolith\n- Event-Driven\n- Client-Server\n- Microkernel\n- CQRS/ES\n\n### Mode 2: Principle-Based (fallback, no archetypes)\n\nCheck universal coupling/cohesion principles without paradigm detection:\n\n- Dependency direction (no circular deps)\n- Layer violations (UI calling DB directly)\n- Cohesion (related code grouped together)\n- Encapsulation (no leaking internals)\n\n## Detection: Coupling Violations\n\n### 1. Circular Dependencies\n\n```bash\n# Python: Find circular imports (heuristic)\ngrep -rn \"^from \\|^import \" --include=\"*.py\" . | \\\n  awk -F: '{file=$1; gsub(/.*from /,\"\",$3); gsub(/ import.*/,\"\",$3); print file, $3}' | \\\n  sort | while read a b; do\n    grep -q \"from.*$(basename $a .py)\" \"$b.py\" 2>/dev/null && \\\n      echo \"CIRCULAR: $a <-> $b\"\n  done\n```\n\n### 2. Layer Violations\n\nCommon layer boundaries to check:\n- Presentation should not import from data/persistence\n- Domain/business logic should not depend on framework\n- Utilities should not depend on domain\n\n```bash\n# Find cross-layer imports (convention: src/{layer}/)\n# Customize layer names per project\nfor violation in \\\n  \"handlers.*import.*models\\.\" \\\n  \"views.*import.*database\" \\\n  \"api.*import.*sql\\|cursor\\|query\"; do\n  grep -rn \"$violation\" --include=\"*.py\" . 2>/dev/null && echo \"LAYER_VIOLATION: $violation\"\ndone\n```\n\n### 3. Feature Envy\n\nA method that uses more features of another class than its own:\n\n```bash\n# Heuristic: methods with many external references\n# Look for methods where self.X appears less than other_obj.Y\ngrep -A20 \"def \" --include=\"*.py\" -r . | \\\n  awk '/def /{fn=$0; self=0; other=0} /self\\./{self++} /[a-z]+\\./{other++} /^$/{if(other>self*2 && other>3) print \"FEATURE_ENVY:\", fn}'\n```\n\n### 4. Inappropriate Intimacy\n\nClasses that access each other's private members:\n\n```bash\n# Find access to _private members from outside class\ngrep -rn \"\\._[a-z]\" --include=\"*.py\" . | grep -v \"self\\._\\|cls\\._\\|__init__\\|test_\" | head -20\n```\n\n### 5. Shotgun Surgery Indicators\n\nChanges to one concept require touching many files:\n\n```bash\n# Heuristic: functions/classes with same name prefix across many files\ngrep -rn \"^def \" --include=\"*.py\" . | sed 's/def //;s/(.*//' | \\\n  awk -F: '{print $2}' | sed 's/_.*//' | sort | uniq -c | sort -rn | \\\n  awk '$1>4{print \"SCATTERED_CONCEPT (\"$1\" files):\", $2}'\n```\n\n## Detection: Cohesion Issues\n\n### Low Cohesion Indicators\n\n```bash\n# Files with many unrelated public functions (>8)\ngrep -c \"^def \" --include=\"*.py\" -r . | awk -F: '$2>8{print \"LOW_COHESION:\", $0}'\n\n# Classes with unrelated method groups\n# Heuristic: methods that don't reference same instance variables\n```\n\n### Module Size Imbalance\n\n```bash\n# Find modules that are disproportionately large\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -exec wc -l {} + | \\\n  sort -rn | head -10\n# Flag if largest is >5x the median\n```\n\n## Paradigm-Specific Checks\n\n### Functional Core / Imperative Shell\n- [ ] Pure functions don't perform I/O\n- [ ] Side effects isolated to shell layer\n- [ ] Domain logic is testable without mocks\n\n### Hexagonal\n- [ ] Ports defined as interfaces/protocols\n- [ ] Adapters don't leak into domain\n- [ ] Dependency flow: adapters -> ports -> domain\n\n### Layered\n- [ ] Dependencies flow downward only\n- [ ] No layer bypassing\n- [ ] Clear layer boundaries in directory structure\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Circular dependency | HIGH | 90% |\n| Layer violation | HIGH | 85% |\n| Feature envy (strong) | MEDIUM | 75% |\n| Low cohesion (>10 methods) | MEDIUM | 80% |\n| Inappropriate intimacy | MEDIUM | 80% |\n| Scattered concept | LOW | 65% |\n| Module size imbalance | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: architectural-violation\nseverity: HIGH\ntype: circular_dependency\nlocations:\n  - file: src/services/user.py\n    imports: src/models/user.py\n  - file: src/models/user.py\n    imports: src/services/user.py\nstrategy: introduce_interface\nparadigm_note: \"Violates dependency inversion; extract protocol\"\neffort: MEDIUM\n```\n\nFile v1.9.17:modules/clean-code-checks.md\n\n---\nmodule: clean-code-checks\ndescription: Clean code violations, anti-slop patterns, and error handling checks\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [clean-code, anti-slop, naming, error-handling, complexity]\ndependencies: [Read, Grep, Glob, Bash]\nestimated_tokens: 450\n---\n\n# Clean Code Checks Module\n\nDetect violations of clean code principles, AI slop patterns, and error handling gaps.\n\nCovers three dimensions: Clean Code, Anti-Slop, and Error Handling.\n\n## Clean Code Violations\n\n### 1. Long Methods (>30 lines)\n\n```bash\n# Python: Find long functions\ngrep -n \"^def \\|^    def \" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Count lines until next def or end\n  length=$(sed -n \"${num},\\$p\" \"$file\" | awk '/^def |^    def /{if(NR>1)exit}END{print NR}')\n  [ \"$length\" -gt 30 ] && echo \"LONG_METHOD ($length lines): $line\"\ndone\n```\n\n**Refactoring**: Extract method, compose method pattern.\n\n### 2. Deep Nesting (>3 levels)\n\n```bash\n# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)\ngrep -rn \"^                \" --include=\"*.py\" . | head -20\ngrep -rn \"^\\t\\t\\t\\t\" --include=\"*.js\" --include=\"*.ts\" . | head -20\n```\n\n**Refactoring**: Guard clauses, extract method, strategy pattern.\n\n### 3. Magic Numbers and Strings\n\n```bash\n# Find magic numbers (excluding 0, 1, common constants)\ngrep -rn \"[^a-zA-Z_][2-9][0-9]\\{1,\\}[^a-zA-Z_0-9\\\"']\" --include=\"*.py\" . | \\\n  grep -v \"range\\|port\\|version\\|#\\|test_\\|assert\" | head -20\n```\n\n**Refactoring**: Extract to named constants.\n\n### 4. Poor Naming\n\nIndicators of AI-generated generic names:\n```bash\n# Find generic function names\ngrep -rn \"def process\\|def handle\\|def manage\\|def do_\\|def run_\" --include=\"*.py\" . | \\\n  grep -v \"test_\\|__\" | head -20\n\n# Find single-letter variables (outside loops/lambdas)\ngrep -rn \" [a-z] = \" --include=\"*.py\" . | grep -v \"for [a-z] in\\|lambda [a-z]\" | head -20\n```\n\n### 5. God Classes (>300 lines or >10 methods)\n\n```bash\n# Python: Large classes\ngrep -c \"def \" --include=\"*.py\" -r . | awk -F: '$2>10{print \"GOD_CLASS:\", $0}'\n```\n\n## Anti-Slop Patterns\n\nAI-specific code smells that traditional linters miss.\n\n### 1. Premature Abstraction\n\nBase classes/interfaces with only 1 implementation.\n\n```bash\n# Python: ABC with single inheritor\ngrep -rn \"class.*ABC\\|@abstractmethod\" --include=\"*.py\" . | cut -d: -f1 | sort -u | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ -n \"$class\" ] && {\n    inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n    [ \"$inheritors\" -lt 2 ] && echo \"PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)\"\n  }\ndone\n```\n\n### 2. Enterprise Cosplay\n\nOver-engineered patterns for simple problems:\n- Factory for a single type\n- Strategy pattern with one strategy\n- Observer with one subscriber\n- Middleware chain for single operation\n\n```bash\n# Find *Factory, *Builder, *Strategy with few usages\nfor pattern in Factory Builder Strategy Observer; do\n  grep -rn \"class.*$pattern\" --include=\"*.py\" --include=\"*.ts\" . 2>/dev/null | while read line; do\n    class=$(echo \"$line\" | grep -oP \"class \\K\\w+\")\n    refs=$(grep -rn \"$class\" --include=\"*.py\" --include=\"*.ts\" . | wc -l)\n    [ \"$refs\" -lt 4 ] && echo \"ENTERPRISE_COSPLAY ($refs refs): $line\"\n  done\ndone\n```\n\n### 3. Hollow Abstractions\n\nCode that adds indirection without value:\n```python\n# Anti-pattern: Wrapper that just delegates\nclass UserService:\n    def __init__(self, repo):\n        self.repo = repo\n    def get_user(self, id):\n        return self.repo.get_user(id)  # Just passes through\n    def save_user(self, user):\n        return self.repo.save_user(user)  # Just passes through\n```\n\n### 4. Verbose Where Concise Suffices\n\nAI tends toward verbosity. Look for:\n- Explicit boolean returns: `if x: return True; else: return False`\n- Unnecessary else after return\n- Redundant variable assignments before return\n\n## Error Handling Checks\n\n### 1. Bare/Broad Excepts\n\n```bash\n# Find bare except\ngrep -rn \"except:\" --include=\"*.py\" -r .\n# Find overly broad except\ngrep -rn \"except Exception:\" --include=\"*.py\" -r . | grep -v \"logging\\|logger\\|log\\.\"\n```\n\n### 2. Swallowed Errors\n\n```bash\n# except + pass (swallowed)\ngrep -A1 \"except\" --include=\"*.py\" -r . | grep -B1 \"pass$\" | grep \"except\"\n```\n\n### 3. Happy-Path-Only Code\n\n```bash\n# Functions >50 lines without any error handling\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  block=$(sed -n \"${num},$((num+60))p\" \"$file\")\n  has_error=$(echo \"$block\" | grep -c \"raise\\|except\\|Error\\|error\\|Warning\")\n  lines=$(echo \"$block\" | wc -l)\n  [ \"$lines\" -gt 50 ] && [ \"$has_error\" -eq 0 ] && echo \"HAPPY_PATH_ONLY: $line\"\ndone\n```\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Bare except / swallowed error | HIGH | 95% |\n| God class (>300 lines) | HIGH | 90% |\n| Long method (>50 lines) | MEDIUM | 90% |\n| Premature abstraction | MEDIUM | 85% |\n| Magic numbers | MEDIUM | 80% |\n| Deep nesting (>4) | MEDIUM | 85% |\n| Generic naming | LOW | 70% |\n| Verbose patterns | LOW | 75% |\n\n## Integration with conserve:code-quality-principles\n\nIf the `conserve` plugin is installed, reference `Skill(conserve:code-quality-principles)` for KISS, YAGNI, and SOLID principle definitions with language-specific examples.\n\n**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).\n\nFile v1.9.17:modules/code-quality-analysis.md\n\n---\nname: code-quality-analysis\ndescription: Shared code quality analysis patterns for review skills\nparent_skill: pensive:shared\ncategory: review-infrastructure\ntags: [code-quality, deduplication, redundancy, analysis, DRY]\nreusable_by: [pensive:code-refinement, pensive:unified-review, sanctum:pr-review, pensive:bug-review]\nestimated_tokens: 450\n---\n\n# Code Quality Analysis Module\n\nShared patterns for code quality and deduplication analysis across review contexts.\n\n## Quick Detection Commands\n\n### Duplication Detection\n\n```bash\n# Python: Find similar function signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Find repeated code blocks (5+ lines)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100 | head -10\n```\n\n### Redundancy Patterns\n\n```bash\n# Find similar error handling blocks\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>5{print \"HIGH_TRY_COUNT:\", $0}'\n\n# Find repeated validation patterns\ngrep -rn \"if not.*:\" --include=\"*.py\" . | \\\n  sed 's/if not \\(.*\\):/\\1/' | sort | uniq -c | sort -rn | head -10\n```\n\n## Quality Dimensions\n\n| Dimension | Detection Method | Severity |\n|-----------|-----------------|----------|\n| Exact duplication (10+ lines) | Hash-based | HIGH |\n| Similar functions (3+) | Signature matching | MEDIUM |\n| Repeated patterns | Structural analysis | LOW-MEDIUM |\n| Copy-paste indicators | Comment/naming similarity | MEDIUM |\n\n## Integration with PR Review\n\nWhen invoked from `/pr-review`, analyze only changed files:\n\n```bash\n# Get changed files\nCHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only | grep -E '\\.(py|ts|js|rs|go)$')\n\n# Run targeted analysis on changed files only\nfor file in $CHANGED_FILES; do\n  # Check for duplication within file\n  # Check for redundancy with existing codebase\ndone\n```\n\n## Consolidation Strategies\n\n| Pattern | Strategy | When to Apply |\n|---------|----------|---------------|\n| Same logic 3+ times | Extract function | Always |\n| Multiple classes share methods | Extract base/mixin | 3+ shared methods |\n| Same logic, different constants | Configuration-driven | 2+ occurrences |\n| Same workflow, different steps | Template method | Clear workflow pattern |\n\n## Output Format\n\n```yaml\nfinding: code-quality\ntype: duplication|redundancy|complexity\nseverity: HIGH|MEDIUM|LOW\nconfidence: 70-95%\nlocations:\n  - file: path/to/file.py\n    lines: 45-62\n  - file: path/to/other.py\n    lines: 23-40\nstrategy: extract_function|extract_class|configure|template_method\neffort: SMALL|MEDIUM|LARGE\n```\n\n## Full Analysis: Invoke pensive:code-refinement\n\nFor comprehensive code quality analysis, invoke the full `pensive:code-refinement` skill:\n\n```\nSkill(pensive:code-refinement)\n```\n\nThis provides six analysis dimensions:\n\n| Dimension | Module | What It Catches |\n|-----------|--------|-----------------|\n| Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| **Algorithmic Efficiency** | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations, time/space complexity |\n| Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n\n## Cross-Reference\n\n- **Full skill**: `Skill(pensive:code-refinement)` - All six dimensions\n- **Algorithm efficiency**: `pensive:code-refinement/modules/algorithm-efficiency` - Time/space complexity analysis\n- **Clean code**: `pensive:code-refinement/modules/clean-code-checks` - SOLID, naming, complexity\n- **Architectural fit**: `pensive:code-refinement/modules/architectural-fit` - Coupling, cohesion, paradigm alignment\n- **Makefile-specific**: `pensive:makefile-review/modules/deduplication-patterns` - Pattern rules, functions\n- **Safety-critical patterns**: `pensive:safety-critical-patterns` - NASA Power of 10 adapted guidelines\n\nFile v1.9.17:modules/duplication-analysis.md\n\n---\nmodule: duplication-analysis\ndescription: Detect and consolidate code duplication and redundancy\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [duplication, redundancy, DRY, consolidation]\ndependencies: [Bash, Grep, Glob, Read]\nestimated_tokens: 400\n---\n\n# Duplication Analysis Module\n\nDetect near-identical code blocks, similar functions, and copy-paste patterns.\n\n## Why Duplication Matters\n\nAI-assisted coding produces qualitatively different duplication:\n- AI suggests new implementations rather than reusing existing code\n- Tab-completion generates similar blocks instead of abstracting\n- 8x increase in 5+ line duplicated blocks (GitClear 2024)\n\n## Detection Methods\n\n### 1. Exact Block Duplication\n\n```bash\n# Use conserve's detect_duplicates.py if available\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5 2>/dev/null || \\\n  echo \"FALLBACK: Manual duplication scan\"\n\n# Fallback: hash-based detection (no external deps)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100\n```\n\n### 2. Similar Function Signatures\n\n```bash\n# Python: Functions with near-identical signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar function declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Rust: Similar fn signatures\ngrep -rn \"^pub fn \\|^fn \" --include=\"*.rs\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n```\n\n### 3. Structural Similarity\n\nLook for repeated patterns:\n- Multiple if/elif chains with same structure\n- Repeated try/except blocks with minor variations\n- Similar class methods across different classes\n- Parallel data transformation pipelines\n\n```bash\n# Find structurally similar blocks (Python)\ngrep -rn \"if.*:\\n.*elif.*:\\n.*elif\" --include=\"*.py\" . 2>/dev/null\n\n# Find repeated error handling patterns\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>3{print \"HIGH_TRY_COUNT:\", $0}'\n```\n\n## Consolidation Strategies\n\n### Strategy 1: Extract Function\n**When**: Same logic repeated 3+ times\n```python\n# Before: Repeated validation in 3 handlers\ndef handler_a(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n    ...\n\n# After: Shared validation\ndef validate_name(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n```\n\n### Strategy 2: Extract Base Class / Mixin\n**When**: Multiple classes share 3+ methods with identical logic\n\n### Strategy 3: Configuration-Driven\n**When**: Same logic with different constants/parameters\n```python\n# Before: 5 similar report generators\n# After: One generator with config\ndef generate_report(config: ReportConfig) -> Report: ...\n```\n\n### Strategy 4: Template Method Pattern\n**When**: Same workflow, different steps\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| 10+ line exact duplicate | HIGH | 95% |\n| 5-9 line exact duplicate | MEDIUM | 90% |\n| Similar function signatures (3+) | MEDIUM | 80% |\n| Structural similarity | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: duplication\nseverity: HIGH\nlocations:\n  - file: src/handlers/user.py\n    lines: 45-62\n  - file: src/handlers/order.py\n    lines: 23-40\nduplicate_lines: 18\nstrategy: extract_function\nsuggested_name: validate_entity_permissions\neffort: SMALL\n```\n\nFile v1.9.17:modules/insight-generation.md\n\n---\nname: insight-generation\ndescription: Post codebase-wide insights from refinement analysis\n---\n\n## Code Refinement Insight Generation\n\nAfter completing the code refinement analysis, post\nfindings as insights to GitHub Discussions for tracking.\n\n### When to Run\n\nRun this module AFTER the refinement analysis is complete.\nPost findings of type Optimization, Bug Alert, or\nImprovement.\n\n### Process\n\n1. Collect refinement findings from the analysis\n2. Map refinement categories to insight types:\n   - Duplication: `[Optimization]`\n   - Algorithm issues: `[Optimization]`\n   - Clean code violations: `[Improvement]`\n   - Error handling gaps: `[Bug Alert]`\n   - Architecture misfit: `[Improvement]`\n\n3. Post via the insight engine:\n\n```bash\ncd /home/alext/claude-night-market\npython3 -c \"\nimport sys, json\nsys.path.insert(0, 'plugins/abstract/scripts')\nfrom insight_types import Finding\nfrom post_insights_to_discussions import post_findings\n\nfindings = [\n    Finding(\n        type='$INSIGHT_TYPE',\n        severity='$SEVERITY',\n        skill='$SKILL_OR_FILE',\n        summary='$SUMMARY',\n        evidence='$EVIDENCE',\n        recommendation='$RECOMMENDATION',\n        source='code-refinement',\n    )\n]\nurls = post_findings(findings)\nfor url in urls:\n    print(f'Posted: {url}')\n\"\n```\n\n4. The posting script handles all dedup automatically\n\n### Quality Filters\n\nOnly post findings that meet these criteria:\n\n- Severity is \"high\" or \"medium\"\n- The finding is specific (not generic advice)\n- Evidence references concrete code locations\n- Recommendation is actionable within one PR\n\nFile v1.9.17:skill-card.md\n\n## Description: <br>\nImproves code quality across duplication, efficiency, and architectural fit. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use Code Refinement to analyze living code for duplication, algorithmic inefficiency, clean-code issues, architectural fit, anti-slop patterns, and error handling gaps. The skill helps produce prioritized refactoring plans and can apply changes when execution is explicitly requested. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill can move from analysis into repository-wide refactoring. <br>\nMitigation: Use plan-only mode by default and require explicit approval before edits, commits, or execution waves. <br>\nRisk: The skill includes an external insight-generation workflow for posting selected findings. <br>\nMitigation: Disable or review the insight-generation module before allowing findings to be posted externally, and require review of each finding for specificity and sensitivity. <br>\nRisk: Scope-override phrasing can bypass branch-size stopping limits. <br>\nMitigation: Do not use scope-override language unless a maintainer has approved expanded refactoring scope. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-code-refinement) <br>\n- [Clawdis homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n- [Publisher profile](https://clawhub.ai/user/athola) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [Text, Markdown, Code, Shell commands, Guidance] <br>\n**Output Format:** [Markdown reports with findings, YAML-style finding blocks, inline shell commands, and optional code changes.] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Plan-only by default unless execution is explicitly requested; external insight posting should be reviewed before use.] <br>\n\n## Skill Version(s): <br>\n1.9.17 (source: server release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.16: 9 files, 18335 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (1946b), SKILL.md (11005b), _meta.json (146b)\n\nFile v1.9.16:SKILL.md\n\n---\nname: code-refinement\ndescription: Improves code quality across duplication, efficiency, and architectural fit\nversion: 1.9.8\ntriggers:\n  - refactoring\n  - clean-code\n  - algorithms\n  - duplication\n  - anti-slop\n  - craft\n  - code passes tests but quality is poor or before a major release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.pensive:safety-critical-patterns\", \"night-market.imbue:proof-of-work\", \"night-market.imbue:justify\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Analysis Dimensions](#analysis-dimensions)\n- [Progressive Loading](#progressive-loading)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Workflow](#workflow)\n- [Tiered Analysis](#tiered-analysis)\n- [Cross-Plugin Dependencies](#cross-plugin-dependencies)\n\n# Code Refinement Workflow\n\nAnalyze and improve living code quality across six dimensions.\n\n## Quick Start\n\n```bash\n/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md\n```\n\n## When To Use\n\n- After rapid AI-assisted development sprints\n- Before major releases (quality gate)\n- When code \"works but smells\"\n- Refactoring existing modules for clarity\n- Reducing technical debt in living code\n\n## When NOT To Use\n\n- Removing\n  dead/unused code (use conserve:bloat-detector)\n\n## Analysis Dimensions\n\n| # | Dimension | Module | What It Catches |\n|---|-----------|--------|----------------|\n| 1 | Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| 2 | Algorithmic Efficiency | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations |\n| 3 | Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| 4 | Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| 5 | Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| 6 | Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n| 7 | Additive Bias | `imbue:justify` | Workarounds over root fixes, test tampering, unnecessary additions |\n\n## Plugin-Specific Patterns\n\nDetection patterns for plugin and skill codebases where\nstandard code quality heuristics miss structural issues.\n\n### Delegation Stub Bodies\n\nA skill that declares \"delegates to X\" but still carries the\nfull template body is doing double duty. The delegating skill\nshould be a thin wrapper (under 30 lines) that routes to the\ntarget. Flag any delegating skill whose body exceeds 50 lines.\n\n### Module Explosion\n\nFlag skills with 10+ module files where 40% or more of content\noverlaps. Signal: two modules covering the same API surface\nfrom different angles (e.g., both describing the same config\noptions or the same CLI flags).\n\n### Oversized Single Modules\n\nFlag individual module files exceeding 500 lines as candidates\nfor splitting or trimming. Large modules defeat progressive\nloading by forcing full-file reads for partial information.\n\n### Dead Python References\n\nSkills referencing Python commands (`python -m module.name` or\n`python -c \"from module import ...\"`) where the referenced\nmodule does not exist in the plugin's `src/` directory. These\nare stale references to renamed or removed code.\n\n## Progressive Loading\n\nLoad modules based on refinement focus:\n\n- **`modules/duplication-analysis.md`** (~400 tokens): Duplication detection and consolidation\n- **`modules/algorithm-efficiency.md`** (~400 tokens): Complexity analysis and optimization\n- **`modules/clean-code-checks.md`** (~450 tokens): Clean code, anti-slop, error handling\n- **`modules/architectural-fit.md`** (~400 tokens): Paradigm alignment and coupling\n\nLoad all for comprehensive refinement. For focused work, load only relevant modules.\n\n## Required TodoWrite Items\n\n1. `refine:context-established` — Scope, language, framework detection\n2. `refine:scan-complete` — Findings across all dimensions\n3. `refine:prioritized` — Findings ranked by impact and effort\n4. `refine:plan-generated` — Concrete refactoring plan with before/after\n5. `refine:evidence-captured` — Evidence appendix per `imbue:proof-of-work`\n6. `refine:execution-complete` — All wave-listed candidates closed-or-rationale'd (only required when invocation includes \"execute findings\" or stronger; see Step 6)\n\n## Workflow\n\n### Step 1: Establish Context (`refine:context-established`)\n\nDetect project characteristics:\n```bash\n# Language detection\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" -o -name \"*.go\" \\) \\\n  | head -20\n\n# Framework detection\nls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null\n\n# Size assessment\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" \\) \\\n  | xargs wc -l 2>/dev/null | tail -1\n```\n\n### Step 2: Dimensional Scan (`refine:scan-complete`)\n\nLoad relevant modules and execute analysis per tier level.\nFor dimension 7 (Additive Bias), run `Skill(imbue:justify)`\nto compute the bias score, check Iron Law compliance,\nand flag unnecessary additions or workarounds.\n\n### Step 3: Prioritize (`refine:prioritized`)\n\nRank findings by:\n- **Impact**: How much quality improves (HIGH/MEDIUM/LOW)\n- **Effort**: Lines changed, files touched (SMALL/MEDIUM/LARGE)\n- **Risk**: Likelihood of introducing bugs (LOW/MEDIUM/HIGH)\n\nPriority = HIGH impact + SMALL effort + LOW risk first.\n\n### Step 4: Generate Plan (`refine:plan-generated`)\n\nFor each finding, produce:\n- File path and line range\n- Current code snippet\n- Proposed improvement\n- Rationale (which principle/dimension)\n- Estimated effort\n\n### Step 5: Evidence Capture (`refine:evidence-captured`)\n\nDocument with `imbue:proof-of-work` (if available):\n- `[E1]`, `[E2]` references for each finding\n- Metrics before/after where measurable\n- Principle violations cited\n\n**Fallback**: If `imbue` is not installed, capture evidence inline in the report using the same `[E1]` reference format without TodoWrite integration.\n\n### Step 6: Execute Findings (`refine:execution-complete`)\n\nSteps 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\".\n\n#### Execution mode detection\n\nMatch the user's invocation phrasing against this table to determine execution scope:\n\n| User said | Mode | Stop when |\n|---|---|---|\n| `/code-refinement` (no qualifier) | **Plan only** | After Step 5 |\n| `--dry-run` or \"just plan\" | **Plan only** | After Step 5 |\n| \"execute findings\" / \"apply fixes\" | **Plan, execute Wave 1** | After all SMALL-effort, and LOW-risk findings closed |\n| \"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 |\n| \"ignore scope guard\" | **Override branch-size limits** | Branch metrics do not gate execution. Continue past RED zone. |\n| \"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 |\n\nThe 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.\n\n#### Completion gate (when execution mode is active)\n\nThe task is **not complete** until ALL of the following hold:\n\n1. **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.\n2. **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).\n3. **Synthesis updated**: `docs/refinement/<date>/00-synthesis.md` records every closure with its commit SHA and every deferral with one-sentence rationale.\n\n#### Anti-pattern detector for the agent itself\n\nIf the model finds itself doing any of the following during execution, this is a stop-hook leak — go back to executing findings:\n\n| Anti-pattern | Recognise as |\n|---|---|\n| \"Wave 2 closed. Moving to Wave 3.\" (mid-run summary) | Premature turn-completion signal — keep working |\n| \"Documenting deferred items with rationale\" before all mechanical items are done | Skipping execution under a paper trail |\n| Writing a completion summary while >0 listed candidates lack closure-or-rationale | Violation of completion gate |\n| Re-asking user \"should I continue?\" when invocation included \"do not stop\" | Ignoring the explicit no-mid-task-summary contract |\n\nIf the harness fires a stop signal mid-execution and the completion gate is not met, immediately resume with the next finding.\n\n## Tiered Analysis\n\n| Tier | Time | Scope |\n|------|------|-------|\n| **1: Quick** (default) | 2-5 min | Complexity hotspots, obvious duplication, naming, magic values |\n| **2: Targeted** | 10-20 min | Algorithm analysis, full duplication scan, architectural alignment |\n| **3: Deep** | 30-60 min | All above and cross-module coupling, paradigm fitness, comprehensive plan |\n\n## Cross-Plugin Dependencies\n\n| Dependency | Required? | Fallback |\n|------------|-----------|----------|\n| `pensive:shared` | Yes | Core review patterns |\n| `imbue:proof-of-work` | Optional | Inline evidence in report |\n| `conserve:code-quality-principles` | Optional | Built-in KISS/YAGNI/SOLID checks |\n| `archetypes:architecture-paradigms` | Optional | Principle-based checks only (no paradigm detection) |\n\n## Supporting Modules\n\n- [Code quality analysis](modules/code-quality-analysis.md) - duplication detection commands and consolidation strategies\n\nWhen optional plugins are not installed, the skill degrades gracefully:\n- Without `imbue`: Evidence captured inline, no TodoWrite proof-of-work\n- Without `conserve`: Uses built-in clean code checks (subset)\n- Without `archetypes`: Skips paradigm-specific alignment, uses coupling/cohesion principles only\n\nFile v1.9.16:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-code-refinement\",\n  \"version\": \"1.9.16\",\n  \"publishedAt\": 1784058936934\n}\n\nFile v1.9.16:modules/algorithm-efficiency.md\n\n---\nmodule: algorithm-efficiency\ndescription: Detect algorithmic inefficiencies and suggest improvements\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [algorithms, complexity, performance, optimization]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Algorithm Efficiency Module\n\nIdentify time and space complexity inefficiencies at the code block level.\n\n## Scope\n\nThis 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.\n\n## Detection Patterns\n\n### 1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))\n\n```python\n# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)\n```\n\n**Detection:**\n```bash\n# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d\n```\n\n### 2. Repeated Sort / Search\n\n```python\n# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)\n```\n\n**Detection:**\n```bash\n# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone\n```\n\n### 3. List Where Set/Dict Suffices\n\n```python\n# Anti-pattern: O(n) membership test\nif item in large_list:  # O(n)\n    ...\n\n# Better: O(1) membership test\nlarge_set = set(large_list)\nif item in large_set:  # O(1)\n    ...\n```\n\n**Detection:**\n```bash\n# Find \"in list_var\" patterns (heuristic)\ngrep -n \" in \\[\" --include=\"*.py\" -r .\ngrep -n \" not in \" --include=\"*.py\" -r . | grep -v \"not in {\" | grep -v \"not in set(\"\n```\n\n### 4. String Concatenation in Loop\n\n```python\n# Anti-pattern: O(n^2) string building\nresult = \"\"\nfor item in items:\n    result += str(item) + \", \"\n\n# Better: O(n) with join\nresult = \", \".join(str(item) for item in items)\n```\n\n### 5. Unnecessary Intermediate Collections\n\n```python\n# Anti-pattern: builds full list just to iterate\nall_items = [transform(x) for x in data]  # allocates full list\nfor item in all_items:\n    process(item)\n\n# Better: generator (lazy evaluation)\nfor item in (transform(x) for x in data):\n    process(item)\n```\n\n### 6. Repeated Computation (Missing Memoization)\n\n```python\n# Anti-pattern: recomputes expensive value\ndef get_result(n):\n    # called 1000x with same n values\n    return expensive_compute(n)\n\n# Better: cache\nfrom functools import lru_cache\n\n@lru_cache(maxsize=128)\ndef get_result(n):\n    return expensive_compute(n)\n```\n\n## Complexity Estimation Heuristics\n\nRather than formal Big-O analysis, use practical heuristics:\n\n| Pattern | Likely Complexity | Flag When |\n|---------|------------------|-----------|\n| Single loop over data | O(n) | Data > 10K and no early exit |\n| Nested loop, same data | O(n^2) | Always flag |\n| Sort inside loop | O(m * n log n) | Always flag |\n| `in list` inside loop | O(n * m) | List > 100 items |\n| Recursive without memo | O(2^n) potential | Recursive calls > 1 |\n| String concat in loop | O(n^2) | Loop > 100 iterations |\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Nested loop, same data | HIGH | 85% |\n| Sort/search in loop | HIGH | 90% |\n| List where set suffices | MEDIUM | 80% |\n| String concat in loop | MEDIUM | 85% |\n| Missing memoization | LOW | 65% |\n| Unnecessary intermediates | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: algorithm-inefficiency\nseverity: HIGH\ntype: nested_loop_same_collection\nlocation:\n  file: src/matching.py\n  lines: 45-58\ncurrent_complexity: O(n^2)\nsuggested_complexity: O(n)\nstrategy: build_index_first\neffort: SMALL\n```\n\nFile v1.9.16:modules/architectural-fit.md\n\n---\nmodule: architectural-fit\ndescription: Assess code alignment with architectural paradigm and coupling principles\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [architecture, coupling, cohesion, paradigm, alignment]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Architectural Fit Module\n\nEvaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.\n\n## Two-Mode Operation\n\n### Mode 1: Paradigm-Aware (archetypes plugin installed)\n\nWhen `archetypes` is available, detect the project's paradigm and check alignment:\n\n```\nSkill(archetypes:architecture-paradigms) -> detect paradigm -> check violations\n```\n\nSupported paradigms from archetypes:\n- Functional Core / Imperative Shell\n- Hexagonal (Ports & Adapters)\n- Layered Architecture\n- Pipeline / Data Flow\n- Modular Monolith\n- Event-Driven\n- Client-Server\n- Microkernel\n- CQRS/ES\n\n### Mode 2: Principle-Based (fallback, no archetypes)\n\nCheck universal coupling/cohesion principles without paradigm detection:\n\n- Dependency direction (no circular deps)\n- Layer violations (UI calling DB directly)\n- Cohesion (related code grouped together)\n- Encapsulation (no leaking internals)\n\n## Detection: Coupling Violations\n\n### 1. Circular Dependencies\n\n```bash\n# Python: Find circular imports (heuristic)\ngrep -rn \"^from \\|^import \" --include=\"*.py\" . | \\\n  awk -F: '{file=$1; gsub(/.*from /,\"\",$3); gsub(/ import.*/,\"\",$3); print file, $3}' | \\\n  sort | while read a b; do\n    grep -q \"from.*$(basename $a .py)\" \"$b.py\" 2>/dev/null && \\\n      echo \"CIRCULAR: $a <-> $b\"\n  done\n```\n\n### 2. Layer Violations\n\nCommon layer boundaries to check:\n- Presentation should not import from data/persistence\n- Domain/business logic should not depend on framework\n- Utilities should not depend on domain\n\n```bash\n# Find cross-layer imports (convention: src/{layer}/)\n# Customize layer names per project\nfor violation in \\\n  \"handlers.*import.*models\\.\" \\\n  \"views.*import.*database\" \\\n  \"api.*import.*sql\\|cursor\\|query\"; do\n  grep -rn \"$violation\" --include=\"*.py\" . 2>/dev/null && echo \"LAYER_VIOLATION: $violation\"\ndone\n```\n\n### 3. Feature Envy\n\nA method that uses more features of another class than its own:\n\n```bash\n# Heuristic: methods with many external references\n# Look for methods where self.X appears less than other_obj.Y\ngrep -A20 \"def \" --include=\"*.py\" -r . | \\\n  awk '/def /{fn=$0; self=0; other=0} /self\\./{self++} /[a-z]+\\./{other++} /^$/{if(other>self*2 && other>3) print \"FEATURE_ENVY:\", fn}'\n```\n\n### 4. Inappropriate Intimacy\n\nClasses that access each other's private members:\n\n```bash\n# Find access to _private members from outside class\ngrep -rn \"\\._[a-z]\" --include=\"*.py\" . | grep -v \"self\\._\\|cls\\._\\|__init__\\|test_\" | head -20\n```\n\n### 5. Shotgun Surgery Indicators\n\nChanges to one concept require touching many files:\n\n```bash\n# Heuristic: functions/classes with same name prefix across many files\ngrep -rn \"^def \" --include=\"*.py\" . | sed 's/def //;s/(.*//' | \\\n  awk -F: '{print $2}' | sed 's/_.*//' | sort | uniq -c | sort -rn | \\\n  awk '$1>4{print \"SCATTERED_CONCEPT (\"$1\" files):\", $2}'\n```\n\n## Detection: Cohesion Issues\n\n### Low Cohesion Indicators\n\n```bash\n# Files with many unrelated public functions (>8)\ngrep -c \"^def \" --include=\"*.py\" -r . | awk -F: '$2>8{print \"LOW_COHESION:\", $0}'\n\n# Classes with unrelated method groups\n# Heuristic: methods that don't reference same instance variables\n```\n\n### Module Size Imbalance\n\n```bash\n# Find modules that are disproportionately large\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -exec wc -l {} + | \\\n  sort -rn | head -10\n# Flag if largest is >5x the median\n```\n\n## Paradigm-Specific Checks\n\n### Functional Core / Imperative Shell\n- [ ] Pure functions don't perform I/O\n- [ ] Side effects isolated to shell layer\n- [ ] Domain logic is testable without mocks\n\n### Hexagonal\n- [ ] Ports defined as interfaces/protocols\n- [ ] Adapters don't leak into domain\n- [ ] Dependency flow: adapters -> ports -> domain\n\n### Layered\n- [ ] Dependencies flow downward only\n- [ ] No layer bypassing\n- [ ] Clear layer boundaries in directory structure\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Circular dependency | HIGH | 90% |\n| Layer violation | HIGH | 85% |\n| Feature envy (strong) | MEDIUM | 75% |\n| Low cohesion (>10 methods) | MEDIUM | 80% |\n| Inappropriate intimacy | MEDIUM | 80% |\n| Scattered concept | LOW | 65% |\n| Module size imbalance | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: architectural-violation\nseverity: HIGH\ntype: circular_dependency\nlocations:\n  - file: src/services/user.py\n    imports: src/models/user.py\n  - file: src/models/user.py\n    imports: src/services/user.py\nstrategy: introduce_interface\nparadigm_note: \"Violates dependency inversion; extract protocol\"\neffort: MEDIUM\n```\n\nFile v1.9.16:modules/clean-code-checks.md\n\n---\nmodule: clean-code-checks\ndescription: Clean code violations, anti-slop patterns, and error handling checks\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [clean-code, anti-slop, naming, error-handling, complexity]\ndependencies: [Read, Grep, Glob, Bash]\nestimated_tokens: 450\n---\n\n# Clean Code Checks Module\n\nDetect violations of clean code principles, AI slop patterns, and error handling gaps.\n\nCovers three dimensions: Clean Code, Anti-Slop, and Error Handling.\n\n## Clean Code Violations\n\n### 1. Long Methods (>30 lines)\n\n```bash\n# Python: Find long functions\ngrep -n \"^def \\|^    def \" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Count lines until next def or end\n  length=$(sed -n \"${num},\\$p\" \"$file\" | awk '/^def |^    def /{if(NR>1)exit}END{print NR}')\n  [ \"$length\" -gt 30 ] && echo \"LONG_METHOD ($length lines): $line\"\ndone\n```\n\n**Refactoring**: Extract method, compose method pattern.\n\n### 2. Deep Nesting (>3 levels)\n\n```bash\n# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)\ngrep -rn \"^                \" --include=\"*.py\" . | head -20\ngrep -rn \"^\\t\\t\\t\\t\" --include=\"*.js\" --include=\"*.ts\" . | head -20\n```\n\n**Refactoring**: Guard clauses, extract method, strategy pattern.\n\n### 3. Magic Numbers and Strings\n\n```bash\n# Find magic numbers (excluding 0, 1, common constants)\ngrep -rn \"[^a-zA-Z_][2-9][0-9]\\{1,\\}[^a-zA-Z_0-9\\\"']\" --include=\"*.py\" . | \\\n  grep -v \"range\\|port\\|version\\|#\\|test_\\|assert\" | head -20\n```\n\n**Refactoring**: Extract to named constants.\n\n### 4. Poor Naming\n\nIndicators of AI-generated generic names:\n```bash\n# Find generic function names\ngrep -rn \"def process\\|def handle\\|def manage\\|def do_\\|def run_\" --include=\"*.py\" . | \\\n  grep -v \"test_\\|__\" | head -20\n\n# Find single-letter variables (outside loops/lambdas)\ngrep -rn \" [a-z] = \" --include=\"*.py\" . | grep -v \"for [a-z] in\\|lambda [a-z]\" | head -20\n```\n\n### 5. God Classes (>300 lines or >10 methods)\n\n```bash\n# Python: Large classes\ngrep -c \"def \" --include=\"*.py\" -r . | awk -F: '$2>10{print \"GOD_CLASS:\", $0}'\n```\n\n## Anti-Slop Patterns\n\nAI-specific code smells that traditional linters miss.\n\n### 1. Premature Abstraction\n\nBase classes/interfaces with only 1 implementation.\n\n```bash\n# Python: ABC with single inheritor\ngrep -rn \"class.*ABC\\|@abstractmethod\" --include=\"*.py\" . | cut -d: -f1 | sort -u | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ -n \"$class\" ] && {\n    inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n    [ \"$inheritors\" -lt 2 ] && echo \"PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)\"\n  }\ndone\n```\n\n### 2. Enterprise Cosplay\n\nOver-engineered patterns for simple problems:\n- Factory for a single type\n- Strategy pattern with one strategy\n- Observer with one subscriber\n- Middleware chain for single operation\n\n```bash\n# Find *Factory, *Builder, *Strategy with few usages\nfor pattern in Factory Builder Strategy Observer; do\n  grep -rn \"class.*$pattern\" --include=\"*.py\" --include=\"*.ts\" . 2>/dev/null | while read line; do\n    class=$(echo \"$line\" | grep -oP \"class \\K\\w+\")\n    refs=$(grep -rn \"$class\" --include=\"*.py\" --include=\"*.ts\" . | wc -l)\n    [ \"$refs\" -lt 4 ] && echo \"ENTERPRISE_COSPLAY ($refs refs): $line\"\n  done\ndone\n```\n\n### 3. Hollow Abstractions\n\nCode that adds indirection without value:\n```python\n# Anti-pattern: Wrapper that just delegates\nclass UserService:\n    def __init__(self, repo):\n        self.repo = repo\n    def get_user(self, id):\n        return self.repo.get_user(id)  # Just passes through\n    def save_user(self, user):\n        return self.repo.save_user(user)  # Just passes through\n```\n\n### 4. Verbose Where Concise Suffices\n\nAI tends toward verbosity. Look for:\n- Explicit boolean returns: `if x: return True; else: return False`\n- Unnecessary else after return\n- Redundant variable assignments before return\n\n## Error Handling Checks\n\n### 1. Bare/Broad Excepts\n\n```bash\n# Find bare except\ngrep -rn \"except:\" --include=\"*.py\" -r .\n# Find overly broad except\ngrep -rn \"except Exception:\" --include=\"*.py\" -r . | grep -v \"logging\\|logger\\|log\\.\"\n```\n\n### 2. Swallowed Errors\n\n```bash\n# except + pass (swallowed)\ngrep -A1 \"except\" --include=\"*.py\" -r . | grep -B1 \"pass$\" | grep \"except\"\n```\n\n### 3. Happy-Path-Only Code\n\n```bash\n# Functions >50 lines without any error handling\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  block=$(sed -n \"${num},$((num+60))p\" \"$file\")\n  has_error=$(echo \"$block\" | grep -c \"raise\\|except\\|Error\\|error\\|Warning\")\n  lines=$(echo \"$block\" | wc -l)\n  [ \"$lines\" -gt 50 ] && [ \"$has_error\" -eq 0 ] && echo \"HAPPY_PATH_ONLY: $line\"\ndone\n```\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Bare except / swallowed error | HIGH | 95% |\n| God class (>300 lines) | HIGH | 90% |\n| Long method (>50 lines) | MEDIUM | 90% |\n| Premature abstraction | MEDIUM | 85% |\n| Magic numbers | MEDIUM | 80% |\n| Deep nesting (>4) | MEDIUM | 85% |\n| Generic naming | LOW | 70% |\n| Verbose patterns | LOW | 75% |\n\n## Integration with conserve:code-quality-principles\n\nIf the `conserve` plugin is installed, reference `Skill(conserve:code-quality-principles)` for KISS, YAGNI, and SOLID principle definitions with language-specific examples.\n\n**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).\n\nFile v1.9.16:modules/code-quality-analysis.md\n\n---\nname: code-quality-analysis\ndescription: Shared code quality analysis patterns for review skills\nparent_skill: pensive:shared\ncategory: review-infrastructure\ntags: [code-quality, deduplication, redundancy, analysis, DRY]\nreusable_by: [pensive:code-refinement, pensive:unified-review, sanctum:pr-review, pensive:bug-review]\nestimated_tokens: 450\n---\n\n# Code Quality Analysis Module\n\nShared patterns for code quality and deduplication analysis across review contexts.\n\n## Quick Detection Commands\n\n### Duplication Detection\n\n```bash\n# Python: Find similar function signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Find repeated code blocks (5+ lines)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100 | head -10\n```\n\n### Redundancy Patterns\n\n```bash\n# Find similar error handling blocks\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>5{print \"HIGH_TRY_COUNT:\", $0}'\n\n# Find repeated validation patterns\ngrep -rn \"if not.*:\" --include=\"*.py\" . | \\\n  sed 's/if not \\(.*\\):/\\1/' | sort | uniq -c | sort -rn | head -10\n```\n\n## Quality Dimensions\n\n| Dimension | Detection Method | Severity |\n|-----------|-----------------|----------|\n| Exact duplication (10+ lines) | Hash-based | HIGH |\n| Similar functions (3+) | Signature matching | MEDIUM |\n| Repeated patterns | Structural analysis | LOW-MEDIUM |\n| Copy-paste indicators | Comment/naming similarity | MEDIUM |\n\n## Integration with PR Review\n\nWhen invoked from `/pr-review`, analyze only changed files:\n\n```bash\n# Get changed files\nCHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only | grep -E '\\.(py|ts|js|rs|go)$')\n\n# Run targeted analysis on changed files only\nfor file in $CHANGED_FILES; do\n  # Check for duplication within file\n  # Check for redundancy with existing codebase\ndone\n```\n\n## Consolidation Strategies\n\n| Pattern | Strategy | When to Apply |\n|---------|----------|---------------|\n| Same logic 3+ times | Extract function | Always |\n| Multiple classes share methods | Extract base/mixin | 3+ shared methods |\n| Same logic, different constants | Configuration-driven | 2+ occurrences |\n| Same workflow, different steps | Template method | Clear workflow pattern |\n\n## Output Format\n\n```yaml\nfinding: code-quality\ntype: duplication|redundancy|complexity\nseverity: HIGH|MEDIUM|LOW\nconfidence: 70-95%\nlocations:\n  - file: path/to/file.py\n    lines: 45-62\n  - file: path/to/other.py\n    lines: 23-40\nstrategy: extract_function|extract_class|configure|template_method\neffort: SMALL|MEDIUM|LARGE\n```\n\n## Full Analysis: Invoke pensive:code-refinement\n\nFor comprehensive code quality analysis, invoke the full `pensive:code-refinement` skill:\n\n```\nSkill(pensive:code-refinement)\n```\n\nThis provides six analysis dimensions:\n\n| Dimension | Module | What It Catches |\n|-----------|--------|-----------------|\n| Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| **Algorithmic Efficiency** | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations, time/space complexity |\n| Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n\n## Cross-Reference\n\n- **Full skill**: `Skill(pensive:code-refinement)` - All six dimensions\n- **Algorithm efficiency**: `pensive:code-refinement/modules/algorithm-efficiency` - Time/space complexity analysis\n- **Clean code**: `pensive:code-refinement/modules/clean-code-checks` - SOLID, naming, complexity\n- **Architectural fit**: `pensive:code-refinement/modules/architectural-fit` - Coupling, cohesion, paradigm alignment\n- **Makefile-specific**: `pensive:makefile-review/modules/deduplication-patterns` - Pattern rules, functions\n- **Safety-critical patterns**: `pensive:safety-critical-patterns` - NASA Power of 10 adapted guidelines\n\nFile v1.9.16:modules/duplication-analysis.md\n\n---\nmodule: duplication-analysis\ndescription: Detect and consolidate code duplication and redundancy\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [duplication, redundancy, DRY, consolidation]\ndependencies: [Bash, Grep, Glob, Read]\nestimated_tokens: 400\n---\n\n# Duplication Analysis Module\n\nDetect near-identical code blocks, similar functions, and copy-paste patterns.\n\n## Why Duplication Matters\n\nAI-assisted coding produces qualitatively different duplication:\n- AI suggests new implementations rather than reusing existing code\n- Tab-completion generates similar blocks instead of abstracting\n- 8x increase in 5+ line duplicated blocks (GitClear 2024)\n\n## Detection Methods\n\n### 1. Exact Block Duplication\n\n```bash\n# Use conserve's detect_duplicates.py if available\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5 2>/dev/null || \\\n  echo \"FALLBACK: Manual duplication scan\"\n\n# Fallback: hash-based detection (no external deps)\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" | while read f; do\n  awk 'NR%5==1{hash=\"\"; start=NR} {hash=hash $0} NR%5==0{print hash, FILENAME, start}' \"$f\"\ndone | sort | uniq -d -w 100\n```\n\n### 2. Similar Function Signatures\n\n```bash\n# Python: Functions with near-identical signatures\ngrep -rn \"^def \\|^    def \" --include=\"*.py\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# TypeScript/JavaScript: Similar function declarations\ngrep -rn \"function \\|const .* = (\" --include=\"*.ts\" --include=\"*.js\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n\n# Rust: Similar fn signatures\ngrep -rn \"^pub fn \\|^fn \" --include=\"*.rs\" . | \\\n  sed 's/(.*//' | sort -t: -k2 | uniq -f1 -d\n```\n\n### 3. Structural Similarity\n\nLook for repeated patterns:\n- Multiple if/elif chains with same structure\n- Repeated try/except blocks with minor variations\n- Similar class methods across different classes\n- Parallel data transformation pipelines\n\n```bash\n# Find structurally similar blocks (Python)\ngrep -rn \"if.*:\\n.*elif.*:\\n.*elif\" --include=\"*.py\" . 2>/dev/null\n\n# Find repeated error handling patterns\ngrep -c \"try:\" --include=\"*.py\" -r . | awk -F: '$2>3{print \"HIGH_TRY_COUNT:\", $0}'\n```\n\n## Consolidation Strategies\n\n### Strategy 1: Extract Function\n**When**: Same logic repeated 3+ times\n```python\n# Before: Repeated validation in 3 handlers\ndef handler_a(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n    ...\n\n# After: Shared validation\ndef validate_name(data):\n    if not data.get('name'): raise ValueError(\"Missing name\")\n    if len(data['name']) > 100: raise ValueError(\"Name too long\")\n```\n\n### Strategy 2: Extract Base Class / Mixin\n**When**: Multiple classes share 3+ methods with identical logic\n\n### Strategy 3: Configuration-Driven\n**When**: Same logic with different constants/parameters\n```python\n# Before: 5 similar report generators\n# After: One generator with config\ndef generate_report(config: ReportConfig) -> Report: ...\n```\n\n### Strategy 4: Template Method Pattern\n**When**: Same workflow, different steps\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| 10+ line exact duplicate | HIGH | 95% |\n| 5-9 line exact duplicate | MEDIUM | 90% |\n| Similar function signatures (3+) | MEDIUM | 80% |\n| Structural similarity | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: duplication\nseverity: HIGH\nlocations:\n  - file: src/handlers/user.py\n    lines: 45-62\n  - file: src/handlers/order.py\n    lines: 23-40\nduplicate_lines: 18\nstrategy: extract_function\nsuggested_name: validate_entity_permissions\neffort: SMALL\n```\n\nFile v1.9.16:modules/insight-generation.md\n\n---\nname: insight-generation\ndescription: Post codebase-wide insights from refinement analysis\n---\n\n## Code Refinement Insight Generation\n\nAfter completing the code refinement analysis, post\nfindings as insights to GitHub Discussions for tracking.\n\n### When to Run\n\nRun this module AFTER the refinement analysis is complete.\nPost findings of type Optimization, Bug Alert, or\nImprovement.\n\n### Process\n\n1. Collect refinement findings from the analysis\n2. Map refinement categories to insight types:\n   - Duplication: `[Optimization]`\n   - Algorithm issues: `[Optimization]`\n   - Clean code violations: `[Improvement]`\n   - Error handling gaps: `[Bug Alert]`\n   - Architecture misfit: `[Improvement]`\n\n3. Post via the insight engine:\n\n```bash\ncd /home/alext/claude-night-market\npython3 -c \"\nimport sys, json\nsys.path.insert(0, 'plugins/abstract/scripts')\nfrom insight_types import Finding\nfrom post_insights_to_discussions import post_findings\n\nfindings = [\n    Finding(\n        type='$INSIGHT_TYPE',\n        severity='$SEVERITY',\n        skill='$SKILL_OR_FILE',\n        summary='$SUMMARY',\n        evidence='$EVIDENCE',\n        recommendation='$RECOMMENDATION',\n        source='code-refinement',\n    )\n]\nurls = post_findings(findings)\nfor url in urls:\n    print(f'Posted: {url}')\n\"\n```\n\n4. The posting script handles all dedup automatically\n\n### Quality Filters\n\nOnly post findings that meet these criteria:\n\n- Severity is \"high\" or \"medium\"\n- The finding is specific (not generic advice)\n- Evidence references concrete code locations\n- Recommendation is actionable within one PR\n\nFile v1.9.16:skill-card.md\n\n## Description: <br>\nImproves code quality across duplication, efficiency, and architectural fit. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to analyze working code for duplication, algorithmic inefficiency, clean-code issues, architectural fit, error handling gaps, and refactoring opportunities before releases or technical-debt reduction work. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The security summary flags an under-disclosed module that can publish repository findings to GitHub Discussions. <br>\nMitigation: Review before installing, use only where repository-wide analysis and possible refactoring are acceptable, and enable insight posting only after checking findings for sensitive paths, snippets, or internal issues. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-code-refinement) <br>\n- [Metadata homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, code, shell commands, guidance] <br>\n**Output Format:** [Markdown analysis with file references, code snippets, proposed refactoring plans, and optional shell commands.] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May propose or apply refactors when explicitly invoked to execute findings.] <br>\n\n## Skill Version(s): <br>\n1.9.16 (source: ClawHub release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.14: 9 files, 18572 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2584b), SKILL.md (11005b), _meta.json (146b)\n\nFile v1.9.14:SKILL.md\n\n---\nname: code-refinement\ndescription: Improves code quality across duplication, efficiency, and architectural fit\nversion: 1.9.8\ntriggers:\n  - refactoring\n  - clean-code\n  - algorithms\n  - duplication\n  - anti-slop\n  - craft\n  - code passes tests but quality is poor or before a major release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.pensive:safety-critical-patterns\", \"night-market.imbue:proof-of-work\", \"night-market.imbue:justify\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Analysis Dimensions](#analysis-dimensions)\n- [Progressive Loading](#progressive-loading)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Workflow](#workflow)\n- [Tiered Analysis](#tiered-analysis)\n- [Cross-Plugin Dependencies](#cross-plugin-dependencies)\n\n# Code Refinement Workflow\n\nAnalyze and improve living code quality across six dimensions.\n\n## Quick Start\n\n```bash\n/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md\n```\n\n## When To Use\n\n- After rapid AI-assisted development sprints\n- Before major releases (quality gate)\n- When code \"works but smells\"\n- Refactoring existing modules for clarity\n- Reducing technical debt in living code\n\n## When NOT To Use\n\n- Removing\n  dead/unused code (use conserve:bloat-detector)\n\n## Analysis Dimensions\n\n| # | Dimension | Module | What It Catches |\n|---|-----------|--------|----------------|\n| 1 | Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| 2 | Algorithmic Efficiency | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations |\n| 3 | Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| 4 | Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| 5 | Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| 6 | Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n| 7 | Additive Bias | `imbue:justify` | Workarounds over root fixes, test tampering, unnecessary additions |\n\n## Plugin-Specific Patterns\n\nDetection patterns for plugin and skill codebases where\nstandard code quality heuristics miss structural issues.\n\n### Delegation Stub Bodies\n\nA skill that declares \"delegates to X\" but still carries the\nfull template body is doing double duty. The delegating skill\nshould be a thin wrapper (under 30 lines) that routes to the\ntarget. Flag any delegating skill whose body exceeds 50 lines.\n\n### Module Explosion\n\nFlag skills with 10+ module files where 40% or more of content\noverlaps. Signal: two modules covering the same API surface\nfrom different angles (e.g., both describing the same config\noptions or the same CLI flags).\n\n### Oversized Single Modules\n\nFlag individual module files exceeding 500 lines as candidates\nfor splitting or trimming. Large modules defeat progressive\nloading by forcing full-file reads for partial information.\n\n### Dead Python References\n\nSkills referencing Python commands (`python -m module.name` or\n`python -c \"from module import ...\"`) where the referenced\nmodule does not exist in the plugin's `src/` directory. These\nare stale references to renamed or removed code.\n\n## Progressive Loading\n\nLoad modules based on refinement focus:\n\n- **`modules/duplication-analysis.md`** (~400 tokens): Duplication detection and consolidation\n- **`modules/algorithm-efficiency.md`** (~400 tokens): Complexity analysis and optimization\n- **`modules/clean-code-checks.md`** (~450 tokens): Clean code, anti-slop, error handling\n- **`modules/architectural-fit.md`** (~400 tokens): Paradigm alignment and coupling\n\nLoad all for comprehensive refinement. For focused work, load only relevant modules.\n\n## Required TodoWrite Items\n\n1. `refine:context-established` — Scope, language, framework detection\n2. `refine:scan-complete` — Findings across all dimensions\n3. `refine:prioritized` — Findings ranked by impact and effort\n4. `refine:plan-generated` — Concrete refactoring plan with before/after\n5. `refine:evidence-captured` — Evidence appendix per `imbue:proof-of-work`\n6. `refine:execution-complete` — All wave-listed candidates closed-or-rationale'd (only required when invocation includes \"execute findings\" or stronger; see Step 6)\n\n## Workflow\n\n### Step 1: Establish Context (`refine:context-established`)\n\nDetect project characteristics:\n```bash\n# Language detection\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" -o -name \"*.go\" \\) \\\n  | head -20\n\n# Framework detection\nls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null\n\n# Size assessment\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" \\) \\\n  | xargs wc -l 2>/dev/null | tail -1\n```\n\n### Step 2: Dimensional Scan (`refine:scan-complete`)\n\nLoad relevant modules and execute analysis per tier level.\nFor dimension 7 (Additive Bias), run `Skill(imbue:justify)`\nto compute the bias score, check Iron Law compliance,\nand flag unnecessary additions or workarounds.\n\n### Step 3: Prioritize (`refine:prioritized`)\n\nRank findings by:\n- **Impact**: How much quality improves (HIGH/MEDIUM/LOW)\n- **Effort**: Lines changed, files touched (SMALL/MEDIUM/LARGE)\n- **Risk**: Likelihood of introducing bugs (LOW/MEDIUM/HIGH)\n\nPriority = HIGH impact + SMALL effort + LOW risk first.\n\n### Step 4: Generate Plan (`refine:plan-generated`)\n\nFor each finding, produce:\n- File path and line range\n- Current code snippet\n- Proposed improvement\n- Rationale (which principle/dimension)\n- Estimated effort\n\n### Step 5: Evidence Capture (`refine:evidence-captured`)\n\nDocument with `imbue:proof-of-work` (if available):\n- `[E1]`, `[E2]` references for each finding\n- Metrics before/after where measurable\n- Principle violations cited\n\n**Fallback**: If `imbue` is not installed, capture evidence inline in the report using the same `[E1]` reference format without TodoWrite integration.\n\n### Step 6: Execute Findings (`refine:execution-complete`)\n\nSteps 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\".\n\n#### Execution mode detection\n\nMatch the user's invocation phrasing against this table to determine execution scope:\n\n| User said | Mode | Stop when |\n|---|---|---|\n| `/code-refinement` (no qualifier) | **Plan only** | After Step 5 |\n| `--dry-run` or \"just plan\" | **Plan only** | After Step 5 |\n| \"execute findings\" / \"apply fixes\" | **Plan, execute Wave 1** | After all SMALL-effort, and LOW-risk findings closed |\n| \"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 |\n| \"ignore scope guard\" | **Override branch-size limits** | Branch metrics do not gate execution. Continue past RED zone. |\n| \"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 |\n\nThe 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.\n\n#### Completion gate (when execution mode is active)\n\nThe task is **not complete** until ALL of the following hold:\n\n1. **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.\n2. **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).\n3. **Synthesis updated**: `docs/refinement/<date>/00-synthesis.md` records every closure with its commit SHA and every deferral with one-sentence rationale.\n\n#### Anti-pattern detector for the agent itself\n\nIf the model finds itself doing any of the following during execution, this is a stop-hook leak — go back to executing findings:\n\n| Anti-pattern | Recognise as |\n|---|---|\n| \"Wave 2 closed. Moving to Wave 3.\" (mid-run summary) | Premature turn-completion signal — keep working |\n| \"Documenting deferred items with rationale\" before all mechanical items are done | Skipping execution under a paper trail |\n| Writing a completion summary while >0 listed candidates lack closure-or-rationale | Violation of completion gate |\n| Re-asking user \"should I continue?\" when invocation included \"do not stop\" | Ignoring the explicit no-mid-task-summary contract |\n\nIf the harness fires a stop signal mid-execution and the completion gate is not met, immediately resume with the next finding.\n\n## Tiered Analysis\n\n| Tier | Time | Scope |\n|------|------|-------|\n| **1: Quick** (default) | 2-5 min | Complexity hotspots, obvious duplication, naming, magic values |\n| **2: Targeted** | 10-20 min | Algorithm analysis, full duplication scan, architectural alignment |\n| **3: Deep** | 30-60 min | All above and cross-module coupling, paradigm fitness, comprehensive plan |\n\n## Cross-Plugin Dependencies\n\n| Dependency | Required? | Fallback |\n|------------|-----------|----------|\n| `pensive:shared` | Yes | Core review patterns |\n| `imbue:proof-of-work` | Optional | Inline evidence in report |\n| `conserve:code-quality-principles` | Optional | Built-in KISS/YAGNI/SOLID checks |\n| `archetypes:architecture-paradigms` | Optional | Principle-based checks only (no paradigm detection) |\n\n## Supporting Modules\n\n- [Code quality analysis](modules/code-quality-analysis.md) - duplication detection commands and consolidation strategies\n\nWhen optional plugins are not installed, the skill degrades gracefully:\n- Without `imbue`: Evidence captured inline, no TodoWrite proof-of-work\n- Without `conserve`: Uses built-in clean code checks (subset)\n- Without `archetypes`: Skips paradigm-specific alignment, uses coupling/cohesion principles only\n\nFile v1.9.14:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-code-refinement\",\n  \"version\": \"1.9.14\",\n  \"publishedAt\": 1782842638782\n}\n\nFile v1.9.14:modules/algorithm-efficiency.md\n\n---\nmodule: algorithm-efficiency\ndescription: Detect algorithmic inefficiencies and suggest improvements\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [algorithms, complexity, performance, optimization]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Algorithm Efficiency Module\n\nIdentify time and space complexity inefficiencies at the code block level.\n\n## Scope\n\nThis 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.\n\n## Detection Patterns\n\n### 1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))\n\n```python\n# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)\n```\n\n**Detection:**\n```bash\n# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d\n```\n\n### 2. Repeated Sort / Search\n\n```python\n# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)\n```\n\n**Detection:**\n```bash\n# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone\n```\n\n### 3. List Where Set/Dict Suffices\n\n```python\n# Anti-pattern: O(n) membership test\nif item in large_list:  # O(n)\n    ...\n\n# Better: O(1) membership test\nlarge_set = set(large_list)\nif item in large_set:  # O(1)\n    ...\n```\n\n**Detection:**\n```bash\n# Find \"in list_var\" patterns (heuristic)\ngrep -n \" in \\[\" --include=\"*.py\" -r .\ngrep -n \" not in \" --include=\"*.py\" -r . | grep -v \"not in {\" | grep -v \"not in set(\"\n```\n\n### 4. String Concatenation in Loop\n\n```python\n# Anti-pattern: O(n^2) string building\nresult = \"\"\nfor item in items:\n    result += str(item) + \", \"\n\n# Better: O(n) with join\nresult = \", \".join(str(item) for item in items)\n```\n\n### 5. Unnecessary Intermediate Collections\n\n```python\n# Anti-pattern: builds full list just to iterate\nall_items = [transform(x) for x in data]  # allocates full list\nfor item in all_items:\n    process(item)\n\n# Better: generator (lazy evaluation)\nfor item in (transform(x) for x in data):\n    process(item)\n```\n\n### 6. Repeated Computation (Missing Memoization)\n\n```python\n# Anti-pattern: recomputes expensive value\ndef get_result(n):\n    # called 1000x with same n values\n    return expensive_compute(n)\n\n# Better: cache\nfrom functools import lru_cache\n\n@lru_cache(maxsize=128)\ndef get_result(n):\n    return expensive_compute(n)\n```\n\n## Complexity Estimation Heuristics\n\nRather than formal Big-O analysis, use practical heuristics:\n\n| Pattern | Likely Complexity | Flag When |\n|---------|------------------|-----------|\n| Single loop over data | O(n) | Data > 10K and no early exit |\n| Nested loop, same data | O(n^2) | Always flag |\n| Sort inside loop | O(m * n log n) | Always flag |\n| `in list` inside loop | O(n * m) | List > 100 items |\n| Recursive without memo | O(2^n) potential | Recursive calls > 1 |\n| String concat in loop | O(n^2) | Loop > 100 iterations |\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Nested loop, same data | HIGH | 85% |\n| Sort/search in loop | HIGH | 90% |\n| List where set suffices | MEDIUM | 80% |\n| String concat in loop | MEDIUM | 85% |\n| Missing memoization | LOW | 65% |\n| Unnecessary intermediates | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: algorithm-inefficiency\nseverity: HIGH\ntype: nested_loop_same_collection\nlocation:\n  file: src/matching.py\n  lines: 45-58\ncurrent_complexity: O(n^2)\nsuggested_complexity: O(n)\nstrategy: build_index_first\neffort: SMALL\n```\n\nFile v1.9.14:modules/architectural-fit.md\n\n---\nmodule: architectural-fit\ndescription: Assess code alignment with architectural paradigm and coupling principles\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [architecture, coupling, cohesion, paradigm, alignment]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Architectural Fit Module\n\nEvaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.\n\n## Two-Mode Operation\n\n### Mode 1: Paradigm-Aware (archetypes plugin installed)\n\nWhen `archetypes` is available, detect the project's paradigm and check alignment:\n\n```\nSkill(archetypes:architecture-paradigms) -> detect paradigm -> check violations\n```\n\nSupported paradigms from archetypes:\n- Functional Core / Imperative Shell\n- Hexagonal (Ports & Adapters)\n- Layered Architecture\n- Pipeline / Data Flow\n- Modular Monolith\n- Event-Driven\n- Client-Server\n- Microkernel\n- CQRS/ES\n\n### Mode 2: Principle-Based (fallback, no archetypes)\n\nCheck universal coupling/cohesion principles without paradigm detection:\n\n- Dependency direction (no circular deps)\n- Layer violations (UI calling DB directly)\n- Cohesion (related code grouped together)\n- Encapsulation (no leaking internals)\n\n## Detection: Coupling Violations\n\n### 1. Circular Dependencies\n\n```bash\n# Python: Find circular imports (heuristic)\ngrep -rn \"^from \\|^import \" --include=\"*.py\" . | \\\n  awk -F: '{file=$1; gsub(/.*from /,\"\",$3); gsub(/ import.*/,\"\",$3); print file, $3}' | \\\n  sort | while read a b; do\n    grep -q \"from.*$(basename $a .py)\" \"$b.py\" 2>/dev/null && \\\n      echo \"CIRCULAR: $a <-> $b\"\n  done\n```\n\n### 2. Layer Violations\n\nCommon layer boundaries to check:\n- Presentation should not import from data/persistence\n- Domain/business logic should not depend on framework\n- Utilities should not depend on domain\n\n```bash\n# Find cross-layer imports (convention: src/{layer}/)\n# Customize layer names per project\nfor violation in \\\n  \"handlers.*import.*models\\.\" \\\n  \"views.*import.*database\" \\\n  \"api.*import.*sql\\|cursor\\|query\"; do\n  grep -rn \"$violation\" --include=\"*.py\" . 2>/dev/null && echo \"LAYER_VIOLATION: $violation\"\ndone\n```\n\n### 3. Feature Envy\n\nA method that uses more features of another class than its own:\n\n```bash\n# Heuristic: methods with many external references\n# Look for methods where self.X appears less than other_obj.Y\ngrep -A20 \"def \" --include=\"*.py\" -r . | \\\n  awk '/def /{fn=$0; self=0; other=0} /self\\./{self++} /[a-z]+\\./{other++} /^$/{if(other>self*2 && other>3) print \"FEATURE_ENVY:\", fn}'\n```\n\n### 4. Inappropriate Intimacy\n\nClasses that access each other's private members:\n\n```bash\n# Find access to _private members from outside class\ngrep -rn \"\\._[a-z]\" --include=\"*.py\" . | grep -v \"self\\._\\|cls\\._\\|__init__\\|test_\" | head -20\n```\n\n### 5. Shotgun Surgery Indicators\n\nChanges to one concept require touching many files:\n\n```bash\n# Heuristic: functions/classes with same name prefix across many files\ngrep -rn \"^def \" --include=\"*.py\" . | sed 's/def //;s/(.*//' | \\\n  awk -F: '{print $2}' | sed 's/_.*//' | sort | uniq -c | sort -rn | \\\n  awk '$1>4{print \"SCATTERED_CONCEPT (\"$1\" files):\", $2}'\n```\n\n## Detection: Cohesion Issues\n\n### Low Cohesion Indicators\n\n```bash\n# Files with many unrelated public functions (>8)\ngrep -c \"^def \" --include=\"*.py\" -r . | awk -F: '$2>8{print \"LOW_COHESION:\", $0}'\n\n# Classes with unrelated method groups\n# Heuristic: methods that don't reference same instance variables\n```\n\n### Module Size Imbalance\n\n```bash\n# Find modules that are disproportionately large\nfind . -name \"*.py\" -not -path \"*/.venv/*\" -exec wc -l {} + | \\\n  sort -rn | head -10\n# Flag if largest is >5x the median\n```\n\n## Paradigm-Specific Checks\n\n### Functional Core / Imperative Shell\n- [ ] Pure functions don't perform I/O\n- [ ] Side effects isolated to shell layer\n- [ ] Domain logic is testable without mocks\n\n### Hexagonal\n- [ ] Ports defined as interfaces/protocols\n- [ ] Adapters don't leak into domain\n- [ ] Dependency flow: adapters -> ports -> domain\n\n### Layered\n- [ ] Dependencies flow downward only\n- [ ] No layer bypassing\n- [ ] Clear layer boundaries in directory structure\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Circular dependency | HIGH | 90% |\n| Layer violation | HIGH | 85% |\n| Feature envy (strong) | MEDIUM | 75% |\n| Low cohesion (>10 methods) | MEDIUM | 80% |\n| Inappropriate intimacy | MEDIUM | 80% |\n| Scattered concept | LOW | 65% |\n| Module size imbalance | LOW | 70% |\n\n## Output Format\n\n```yaml\nfinding: architectural-violation\nseverity: HIGH\ntype: circular_dependency\nlocations:\n  - file: src/services/user.py\n    imports: src/models/user.py\n  - file: src/models/user.py\n    imports: src/services/user.py\nstrategy: introduce_interface\nparadigm_note: \"Violates dependency inversion; extract protocol\"\neffort: MEDIUM\n```\n\nFile v1.9.14:modules/clean-code-checks.md\n\n---\nmodule: clean-code-checks\ndescription: Clean code violations, anti-slop patterns, and error handling checks\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [clean-code, anti-slop, naming, error-handling, complexity]\ndependencies: [Read, Grep, Glob, Bash]\nestimated_tokens: 450\n---\n\n# Clean Code Checks Module\n\nDetect violations of clean code principles, AI slop patterns, and error handling gaps.\n\nCovers three dimensions: Clean Code, Anti-Slop, and Error Handling.\n\n## Clean Code Violations\n\n### 1. Long Methods (>30 lines)\n\n```bash\n# Python: Find long functions\ngrep -n \"^def \\|^    def \" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Count lines until next def or end\n  length=$(sed -n \"${num},\\$p\" \"$file\" | awk '/^def |^    def /{if(NR>1)exit}END{print NR}')\n  [ \"$length\" -gt 30 ] && echo \"LONG_METHOD ($length lines): $line\"\ndone\n```\n\n**Refactoring**: Extract method, compose method pattern.\n\n### 2. Deep Nesting (>3 levels)\n\n```bash\n# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)\ngrep -rn \"^                \" --include=\"*.py\" . | head -20\ngrep -rn \"^\\t\\t\\t\\t\" --include=\"*.js\" --include=\"*.ts\" . | head -20\n```\n\n**Refactoring**: Guard clauses, extract method, strategy pattern.\n\n### 3. Magic Numbers and Strings\n\n```bash\n# Find magic numbers (excluding 0, 1, common constants)\ngrep -rn \"[^a-zA-Z_][2-9][0-9]\\{1,\\}[^a-zA-Z_0-9\\\"']\" --include=\"*.py\" . | \\\n  grep -v \"range\\|port\\|version\\|#\\|test_\\|assert\" | head -20\n```\n\n**Refactoring**: Extract to named constants.\n\n### 4. Poor Naming\n\nIndicators of AI-generated generic names:\n```bash\n# Find generic function names\ngrep -rn \"def process\\|def handle\\|def manage\\|def do_\\|def run_\" --include=\"*.py\" . | \\\n  grep -v \"test_\\|__\" | head -20\n\n# Find single-letter variables (outside loops/lambdas)\ngrep -rn \" [a-z] = \" --include=\"*.py\" . | grep -v \"for [a-z] in\\|lambda [a-z]\" | head -20\n```\n\n### 5. God Classes (>300 lines or >10 methods)\n\n```bash\n# Python: Large classes\ngrep -c \"def \" --include=\"*.py\" -r . | awk -F: '$2>10{print \"GOD_CLASS:\", $0}'\n```\n\n## Anti-Slop Patterns\n\nAI-specific code smells that traditional linters miss.\n\n### 1. Premature Abstraction\n\nBase classes/interfaces with only 1 implementation.\n\n```bash\n# Python: ABC with single inheritor\ngrep -rn \"class.*ABC\\|@abstractmethod\" --include=\"*.py\" . | cut -d: -f1 | sort -u | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ -n \"$class\" ] && {\n    inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n    [ \"$inheritors\" -lt 2 ] && echo \"PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)\"\n  }\ndone\n```\n\n### 2. Enterprise Cosplay\n\nOver-engineered patterns for simple problems:\n- Factory for a single type\n- Strategy pattern with one strategy\n- Observer with one subscriber\n- Middleware chain for single operation\n\n```bash\n# Find *Factory, *Builder, *Strategy with few usages\nfor pattern in Factory Builder Strategy Observer; do\n  grep -rn \"class.*$pattern\" --include=\"*.py\" --include=\"*.ts\" . 2>/dev/null | while read line; do\n    class=$(echo \"$line\" | grep -oP \"class \\K\\w+\")\n    refs=$(grep -rn \"$class\" --include=\"*.py\" --include=\"*.ts\" . | wc -l)\n    [ \"$refs\" -lt 4 ] && echo \"ENTERPRISE_COSPLAY ($refs refs): $line\"\n  done\ndone\n```\n\n### 3. Hollow Abstractions\n\nCode that adds indirection without value:\n```python\n# Anti-pattern: Wrapper that just delegates\nclass UserService:\n    def __init__(self, repo):\n        self.repo = repo\n    def get_user(self, id):\n        return self.repo.get_user(id)  # Just passes through\n    def save_user(self, user):\n        return self.repo.save_user(user)  # Just passes through\n```\n\n### 4. Verbose Where Concise Suffices\n\nAI tends toward verbosity. Look for:\n- Explicit boolean returns: `if x: return True; else: return False`\n- Unnecessary else after return\n- Redundant variable assignments before return\n\n## Error Handling Checks\n\n### 1. Bare/Broad Excepts\n\n```bash\n# Find bare except\ngrep -rn \"except:\" --include=\"*.py\" -r .\n# Find overly broad except\ngrep -rn \"except Exception:\" --include=\"*.py\" -r . | grep -v \"logging\\|logger\\|log\\.\"\n```\n\n### 2. Swallowed Errors\n\n```bash\n# except + pass (swallowed)\ngrep -A1 \"except\" --include=\"*.py\" -r . | grep -B1 \"pass$\" | grep \"except\"\n```\n\n### 3. Happy-Path-Only Code\n\n```bash\n# Functions >50 lines without any error handling\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  block=$(sed -n \"${num},$((num+60))p\" \"$file\")\n  has_error=$(echo \"$block\" | grep -c \"raise\\|except\\|Error\\|error\\|Warning\")\n  lines=$(echo \"$block\" | wc -l)\n  [ \"$lines\" -gt 50 ] && [ \"$has_error\" -eq 0 ] && echo \"HAPPY_PATH_ONLY: $line\"\ndone\n```\n\n## Scoring\n\n| Pattern | Severity | Confidence |\n|---------|----------|------------|\n| Bare except / swallowed error | HIGH | 95% |\n| God class (>300 lines) | HIGH | 90% |\n| Long method (>50 lines) | MEDIUM | 90% |\n| Premature abstraction | MEDIUM | 85% |\n| Magic numbers | MEDIUM | 80% |\n| Deep nesting (>4) | MEDIUM | 85% |\n| Generic naming | LOW | 70% |\n| Verbose patterns | LOW | 75% |\n\n## Integration with conserve:code-quality-principles\n\nIf the `conserve` plugin is installed, reference `Skill(conserve:code-quality-principles)` for KISS, YAGNI, and SOLID principle definitions with language-specific examples.\n\n**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).\n\nFile v1.9.14:modules/code-quality-analysis.md\n\n---\nname: code-quality-analysis\ndescription: Shared code quality analysis patterns for review skills\nparent_skill: pensive:shared\ncategory: review-infrastructure\ntags: [code-quality, deduplication, redundancy, analysis, DRY]\nreusable_by: [pensive:code-refinement, pensive:unified-review, sanctum:pr-review, pensive:bug-review]\nestimated_tokens: 450\n---\n\n# Code Quality Analysis Module\n\nShared patterns for code quality and deduplication analysis across review contexts.\n\n## Quick Detection Commands\n\n### Duplication Detection\n\n```bash\n# Python: Find similar function signatures\ngrep -rn \"^def \\|^    def \" --include=\n\nArchive v1.9.13: 9 files, 18474 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2281b), SKILL.md (11005b), _meta.json (146b)\n\nArchive v1.9.12: 9 files, 18532 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2401b), SKILL.md (11005b), _meta.json (146b)\n\nArchive v1.0.3: 9 files, 18588 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), modules/insight-generation.md (1579b), skill-card.md (2625b), SKILL.md (11005b), _meta.json (145b)\n\nArchive v1.0.2: 8 files, 15313 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), skill-card.md (2102b), SKILL.md (6320b), _meta.json (145b)\n\nArchive v1.0.1: 7 files, 14179 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), SKILL.md (6320b), _meta.json (145b)\n\nArchive v1.0.0: 7 files, 14179 bytes\n\nFiles: modules/algorithm-efficiency.md (4347b), modules/architectural-fit.md (4851b), modules/clean-code-checks.md (5624b), modules/code-quality-analysis.md (4414b), modules/duplication-analysis.md (3650b), SKILL.md (6320b), _meta.json (145b)","readmeExcerpt":"Skill: code-refinement Owner: athola Summary: Improves code quality across duplication, efficiency, and architectural fit Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:18:38.608Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:38:54.857Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:36.934Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:03:58.782Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:02","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md"},{"language":"bash","snippet":"# Language detection\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" -o -name \"*.go\" \\) \\\n  | head -20\n\n# Framework detection\nls package.json pyproject.toml Cargo.toml go.mod 2>/dev/null\n\n# Size assessment\nfind . -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.rs\" \\) \\\n  | xargs wc -l 2>/dev/null | tail -1"},{"language":"python","snippet":"# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)"},{"language":"bash","snippet":"# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d"},{"language":"python","snippet":"# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)"},{"language":"bash","snippet":"# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: code-refinement\ndescription: Improves code quality across duplication, efficiency, and architectural fit\nversion: 1.9.8\ntriggers:\n  - refactoring\n  - clean-code\n  - algorithms\n  - duplication\n  - anti-slop\n  - craft\n  - code passes tests but quality is poor or before a major release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.pensive:safety-critical-patterns\", \"night-market.imbue:proof-of-work\", \"night-market.imbue:justify\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Analysis Dimensions](#analysis-dimensions)\n- [Progressive Loading](#progressive-loading)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Workflow](#workflow)\n- [Tiered Analysis](#tiered-analysis)\n- [Cross-Plugin Dependencies](#cross-plugin-dependencies)\n\n# Code Refinement Workflow\n\nAnalyze and improve living code quality across six dimensions.\n\n## Quick Start\n\n```bash\n/refine-code\n/refine-code --level 2 --focus duplication\n/refine-code --level 3 --report refinement-plan.md\n```\n\n## When To Use\n\n- After rapid AI-assisted development sprints\n- Before major releases (quality gate)\n- When code \"works but smells\"\n- Refactoring existing modules for clarity\n- Reducing technical debt in living code\n\n## When NOT To Use\n\n- Removing\n  dead/unused code (use conserve:bloat-detector)\n\n## Analysis Dimensions\n\n| # | Dimension | Module | What It Catches |\n|---|-----------|--------|----------------|\n| 1 | Duplication & Redundancy | `duplication-analysis` | Near-identical blocks, similar functions, copy-paste |\n| 2 | Algorithmic Efficiency | `algorithm-efficiency` | O(n^2) where O(n) works, unnecessary iterations |\n| 3 | Clean Code Violations | `clean-code-checks` | Long methods, deep nesting, poor naming, magic values |\n| 4 | Architectural Fit | `architectural-fit` | Paradigm mismatches, coupling violations, leaky abstractions |\n| 5 | Anti-Slop Patterns | `clean-code-checks` | Premature abstraction, enterprise cosplay, hollow patterns |\n| 6 | Error Handling | `clean-code-checks` | Bare excepts, swallowed errors, happy-path-only |\n| 7 | Additive Bias | `imbue:justify` | Workarounds over root fixes, test tampering, unnecessary additions |\n\n## Plugin-Specific Patterns\n\nDetection patterns for plugin and skill codebases where\nstandard code quality heuristics miss structural issues.\n\n### Delegation Stub Bodies\n\nA skill that declares \"delegates to X\" but still carries the\nfull template body is doing double duty. The delegating skill\nshould be a thin wrapper (under 30 lines) that routes to the\ntarg"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-code-refinement\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750318608\n}"},{"path":"modules/algorithm-efficiency.md","content":"---\nmodule: algorithm-efficiency\ndescription: Detect algorithmic inefficiencies and suggest improvements\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [algorithms, complexity, performance, optimization]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Algorithm Efficiency Module\n\nIdentify time and space complexity inefficiencies at the code block level.\n\n## Scope\n\nThis 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.\n\n## Detection Patterns\n\n### 1. Nested Loop on Same Collection (O(n^2) -> O(n) or O(n log n))\n\n```python\n# Anti-pattern: O(n^2) lookup\nfor item in items:\n    for other in items:\n        if item.id == other.parent_id:\n            ...\n\n# Better: O(n) with index\nindex = {item.id: item for item in items}\nfor item in items:\n    parent = index.get(item.parent_id)\n```\n\n**Detection:**\n```bash\n# Find nested for-loops on same variable (Python)\ngrep -n \"for .* in \" --include=\"*.py\" -r . | \\\n  awk -F: '{file=$1; line=$2; var=$0; gsub(/.*in /,\"\",var); gsub(/:.*/,\"\",var); print file, line, var}' | \\\n  sort | uniq -f2 -d\n```\n\n### 2. Repeated Sort / Search\n\n```python\n# Anti-pattern: sorting inside a loop\nfor query in queries:\n    sorted_data = sorted(data)  # O(n log n) per query = O(m * n log n)\n    result = bisect.bisect(sorted_data, query)\n\n# Better: sort once\nsorted_data = sorted(data)  # O(n log n) once\nfor query in queries:\n    result = bisect.bisect(sorted_data, query)  # O(m * log n)\n```\n\n**Detection:**\n```bash\n# Find sort/sorted inside loops\ngrep -n \"sorted\\|\\.sort()\" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Check if inside a for/while loop\n  sed -n \"$((num-5)),$((num))p\" \"$file\" | grep -q \"for \\|while \" && echo \"SORT_IN_LOOP: $line\"\ndone\n```\n\n### 3. List Where Set/Dict Suffices\n\n```python\n# Anti-pattern: O(n) membership test\nif item in large_list:  # O(n)\n    ...\n\n# Better: O(1) membership test\nlarge_set = set(large_list)\nif item in large_set:  # O(1)\n    ...\n```\n\n**Detection:**\n```bash\n# Find \"in list_var\" patterns (heuristic)\ngrep -n \" in \\[\" --include=\"*.py\" -r .\ngrep -n \" not in \" --include=\"*.py\" -r . | grep -v \"not in {\" | grep -v \"not in set(\"\n```\n\n### 4. String Concatenation in Loop\n\n```python\n# Anti-pattern: O(n^2) string building\nresult = \"\"\nfor item in items:\n    result += str(item) + \", \"\n\n# Better: O(n) with join\nresult = \", \".join(str(item) for item in items)\n```\n\n### 5. Unnecessary Intermediate Collections\n\n```python\n# Anti-pattern: builds full list just to iterate\nall_items = [transform(x) for x in data]  # allocates full list\nfor item in all_items:\n    process(item)\n\n# Better: generator (lazy evaluation)\nfor item in (transform(x) for x in data):\n    process(item)\n```\n\n### 6. Repeated Computation (Missing Memoization)\n\n```python\n# Anti-pattern: recomputes expens"},{"path":"modules/architectural-fit.md","content":"---\nmodule: architectural-fit\ndescription: Assess code alignment with architectural paradigm and coupling principles\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [architecture, coupling, cohesion, paradigm, alignment]\ndependencies: [Read, Grep, Glob]\nestimated_tokens: 400\n---\n\n# Architectural Fit Module\n\nEvaluate whether code structure aligns with the project's architectural paradigm and coupling/cohesion principles.\n\n## Two-Mode Operation\n\n### Mode 1: Paradigm-Aware (archetypes plugin installed)\n\nWhen `archetypes` is available, detect the project's paradigm and check alignment:\n\n```\nSkill(archetypes:architecture-paradigms) -> detect paradigm -> check violations\n```\n\nSupported paradigms from archetypes:\n- Functional Core / Imperative Shell\n- Hexagonal (Ports & Adapters)\n- Layered Architecture\n- Pipeline / Data Flow\n- Modular Monolith\n- Event-Driven\n- Client-Server\n- Microkernel\n- CQRS/ES\n\n### Mode 2: Principle-Based (fallback, no archetypes)\n\nCheck universal coupling/cohesion principles without paradigm detection:\n\n- Dependency direction (no circular deps)\n- Layer violations (UI calling DB directly)\n- Cohesion (related code grouped together)\n- Encapsulation (no leaking internals)\n\n## Detection: Coupling Violations\n\n### 1. Circular Dependencies\n\n```bash\n# Python: Find circular imports (heuristic)\ngrep -rn \"^from \\|^import \" --include=\"*.py\" . | \\\n  awk -F: '{file=$1; gsub(/.*from /,\"\",$3); gsub(/ import.*/,\"\",$3); print file, $3}' | \\\n  sort | while read a b; do\n    grep -q \"from.*$(basename $a .py)\" \"$b.py\" 2>/dev/null && \\\n      echo \"CIRCULAR: $a <-> $b\"\n  done\n```\n\n### 2. Layer Violations\n\nCommon layer boundaries to check:\n- Presentation should not import from data/persistence\n- Domain/business logic should not depend on framework\n- Utilities should not depend on domain\n\n```bash\n# Find cross-layer imports (convention: src/{layer}/)\n# Customize layer names per project\nfor violation in \\\n  \"handlers.*import.*models\\.\" \\\n  \"views.*import.*database\" \\\n  \"api.*import.*sql\\|cursor\\|query\"; do\n  grep -rn \"$violation\" --include=\"*.py\" . 2>/dev/null && echo \"LAYER_VIOLATION: $violation\"\ndone\n```\n\n### 3. Feature Envy\n\nA method that uses more features of another class than its own:\n\n```bash\n# Heuristic: methods with many external references\n# Look for methods where self.X appears less than other_obj.Y\ngrep -A20 \"def \" --include=\"*.py\" -r . | \\\n  awk '/def /{fn=$0; self=0; other=0} /self\\./{self++} /[a-z]+\\./{other++} /^$/{if(other>self*2 && other>3) print \"FEATURE_ENVY:\", fn}'\n```\n\n### 4. Inappropriate Intimacy\n\nClasses that access each other's private members:\n\n```bash\n# Find access to _private members from outside class\ngrep -rn \"\\._[a-z]\" --include=\"*.py\" . | grep -v \"self\\._\\|cls\\._\\|__init__\\|test_\" | head -20\n```\n\n### 5. Shotgun Surgery Indicators\n\nChanges to one concept require touching many files:\n\n```bash\n# Heuristic: functions/classes with same name prefix across many files\ngrep -rn \"^def \" --include=\"*.py\" . | sed 's/def "},{"path":"modules/clean-code-checks.md","content":"---\nmodule: clean-code-checks\ndescription: Clean code violations, anti-slop patterns, and error handling checks\nparent_skill: pensive:code-refinement\ncategory: code-quality\ntags: [clean-code, anti-slop, naming, error-handling, complexity]\ndependencies: [Read, Grep, Glob, Bash]\nestimated_tokens: 450\n---\n\n# Clean Code Checks Module\n\nDetect violations of clean code principles, AI slop patterns, and error handling gaps.\n\nCovers three dimensions: Clean Code, Anti-Slop, and Error Handling.\n\n## Clean Code Violations\n\n### 1. Long Methods (>30 lines)\n\n```bash\n# Python: Find long functions\ngrep -n \"^def \\|^    def \" --include=\"*.py\" -r . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  num=$(echo \"$line\" | cut -d: -f2)\n  # Count lines until next def or end\n  length=$(sed -n \"${num},\\$p\" \"$file\" | awk '/^def |^    def /{if(NR>1)exit}END{print NR}')\n  [ \"$length\" -gt 30 ] && echo \"LONG_METHOD ($length lines): $line\"\ndone\n```\n\n**Refactoring**: Extract method, compose method pattern.\n\n### 2. Deep Nesting (>3 levels)\n\n```bash\n# Find deeply nested code (4+ indent levels = 16+ spaces or 4+ tabs)\ngrep -rn \"^                \" --include=\"*.py\" . | head -20\ngrep -rn \"^\\t\\t\\t\\t\" --include=\"*.js\" --include=\"*.ts\" . | head -20\n```\n\n**Refactoring**: Guard clauses, extract method, strategy pattern.\n\n### 3. Magic Numbers and Strings\n\n```bash\n# Find magic numbers (excluding 0, 1, common constants)\ngrep -rn \"[^a-zA-Z_][2-9][0-9]\\{1,\\}[^a-zA-Z_0-9\\\"']\" --include=\"*.py\" . | \\\n  grep -v \"range\\|port\\|version\\|#\\|test_\\|assert\" | head -20\n```\n\n**Refactoring**: Extract to named constants.\n\n### 4. Poor Naming\n\nIndicators of AI-generated generic names:\n```bash\n# Find generic function names\ngrep -rn \"def process\\|def handle\\|def manage\\|def do_\\|def run_\" --include=\"*.py\" . | \\\n  grep -v \"test_\\|__\" | head -20\n\n# Find single-letter variables (outside loops/lambdas)\ngrep -rn \" [a-z] = \" --include=\"*.py\" . | grep -v \"for [a-z] in\\|lambda [a-z]\" | head -20\n```\n\n### 5. God Classes (>300 lines or >10 methods)\n\n```bash\n# Python: Large classes\ngrep -c \"def \" --include=\"*.py\" -r . | awk -F: '$2>10{print \"GOD_CLASS:\", $0}'\n```\n\n## Anti-Slop Patterns\n\nAI-specific code smells that traditional linters miss.\n\n### 1. Premature Abstraction\n\nBase classes/interfaces with only 1 implementation.\n\n```bash\n# Python: ABC with single inheritor\ngrep -rn \"class.*ABC\\|@abstractmethod\" --include=\"*.py\" . | cut -d: -f1 | sort -u | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ -n \"$class\" ] && {\n    inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n    [ \"$inheritors\" -lt 2 ] && echo \"PREMATURE_ABSTRACTION: $class in $f ($inheritors inheritors)\"\n  }\ndone\n```\n\n### 2. Enterprise Cosplay\n\nOver-engineered patterns for simple problems:\n- Factory for a single type\n- Strategy pattern with one strategy\n- Observer with one subscriber\n- Middleware chain for single operation\n\n```bash\n# Find *Factory, *Builder, *Strategy with few usages\nfor pattern in Factory Builder Strategy "}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Improves code quality across duplication, efficiency, and architectural fit Skill: code-refinement Owner: athola Summary: Improves code quality across duplication, efficiency, and architectural fit Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:18:38.608Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:38:54.857Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:36.934Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:03:58.782Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:02","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1188,"uniquenessScore":55,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T10:33:08.134Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T13:39:57.120Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}