{"id":"a6405727-c4f8-4d58-a57c-6e73f8b61e6e","entityType":"agent","slug":"clawhub-athola-nm-conserve-bloat-detector","name":"bloat-detector","canonicalUrl":"https://www.xpersona.co/agent/clawhub-athola-nm-conserve-bloat-detector","canonicalPath":"/agent/clawhub-athola-nm-conserve-bloat-detector","generatedAt":"2026-10-10T10:02:19.277Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T07:25:54.796Z","emptyReason":null},"description":"Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Skill: bloat-detector Owner: athola Summary: Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:09:25.175Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:31:57.564Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:48:46.997Z | user Release v1.9.16 v1.9.15 | 2026-07-04T21:22:21.079Z | user Release v1.9.15 v1.9.14 | 2026-06-30T17","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.6K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-conserve-bloat-detector","sourceUrl":"https://clawhub.ai/athola/nm-conserve-bloat-detector","homepage":"https://clawhub.ai/athola/skills/nm-conserve-bloat-detector","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/athola/nm-conserve-bloat-detector","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/athola/skills/nm-conserve-bloat-detector","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":40,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Skill: bloat-detector Owner: athola Summary: Detects codebase bloat via dead "},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:25:54.796Z","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-10T07:25:54.796Z","emptyReason":null},"stars":null,"forks":null,"downloads":1592,"packageName":null,"latestVersion":"1.9.19","tractionLabel":"1.6K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:25:54.795Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T07:25:54.796Z","lastCrawledAt":"2026-10-10T07:25:54.795Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T07:25:54.795Z","lastVerifiedAt":null,"highlights":[{"version":"1.9.19","createdAt":"2026-08-26T13:09:25.175Z","changelog":"Release v1.9.19","fileCount":11,"zipByteSize":24949},{"version":"1.9.17","createdAt":"2026-07-30T05:31:57.564Z","changelog":"Release v1.9.17","fileCount":11,"zipByteSize":25008},{"version":"1.9.16","createdAt":"2026-07-14T19:48:46.997Z","changelog":"Release v1.9.16","fileCount":11,"zipByteSize":25088},{"version":"1.9.15","createdAt":"2026-07-04T21:22:21.079Z","changelog":"Release v1.9.15","fileCount":11,"zipByteSize":25097},{"version":"1.9.14","createdAt":"2026-06-30T17:53:01.903Z","changelog":"Release v1.9.14","fileCount":11,"zipByteSize":25169},{"version":"1.9.13","createdAt":"2026-06-27T16:17:18.753Z","changelog":"Release v1.9.13","fileCount":11,"zipByteSize":25170},{"version":"1.9.12","createdAt":"2026-06-19T03:11:09.371Z","changelog":"Release v1.9.12","fileCount":11,"zipByteSize":25024},{"version":"1.0.3","createdAt":"2026-06-07T21:24:35.235Z","changelog":"Release v1.9.11","fileCount":11,"zipByteSize":24944}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-conserve-bloat-detector","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-conserve-bloat-detector/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/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-10T10:02:19.272Z"}},"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-conserve-bloat-detector/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-conserve-bloat-detector/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-10T07:25:54.796Z","emptyReason":null},"readme":"Skill: bloat-detector\n\nOwner: athola\n\nSummary: Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans\n\nTags: latest:1.9.19\n\nVersion history:\n\nv1.9.19 | 2026-08-26T13:09:25.175Z | user\n\nRelease v1.9.19\n\nv1.9.17 | 2026-07-30T05:31:57.564Z | user\n\nRelease v1.9.17\n\nv1.9.16 | 2026-07-14T19:48:46.997Z | user\n\nRelease v1.9.16\n\nv1.9.15 | 2026-07-04T21:22:21.079Z | user\n\nRelease v1.9.15\n\nv1.9.14 | 2026-06-30T17:53:01.903Z | user\n\nRelease v1.9.14\n\nv1.9.13 | 2026-06-27T16:17:18.753Z | user\n\nRelease v1.9.13\n\nv1.9.12 | 2026-06-19T03:11:09.371Z | user\n\nRelease v1.9.12\n\nv1.0.3 | 2026-06-07T21:24:35.235Z | user\n\nRelease v1.9.11\n\nv1.0.2 | 2026-05-09T02:16:30.588Z | user\n\nRelease v1.9.5\n\nv1.0.1 | 2026-05-06T14:16:49.494Z | user\n\nRelease v1.9.4\n\nv1.0.0 | 2026-04-11T10:01:34.404Z | auto\n\nInitial release of bloat-detector skill.\n\n- Introduces progressive analysis: detects code, documentation, dependency, and git history bloat in tiers.\n- Provides /bloat-scan commands for quick scans, targeted analysis, and deep audits.\n- Outlines confidence levels and prioritization formula for remediation actions.\n- Details auto-exclusion rules and safety features (no auto-delete, dry runs, backup branches).\n- Includes documentation for use cases, module structure, and integration with related agents/skills.\n\nArchive index:\n\nArchive v1.9.19: 11 files, 24949 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (1969b), SKILL.md (5207b), _meta.json (146b)\n\nFile v1.9.19:SKILL.md\n\n---\nname: bloat-detector\ndescription: |\n  Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans\nversion: 1.9.8\ntriggers:\n  - bloat\n  - cleanup\n  - static-analysis\n  - technical-debt\n  - optimization\n  - codebase feels large or before a release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/conserve\", \"emoji\": \"\\ud83e\\udd9e\"}}\nsource: claude-night-market\nsource_plugin: conserve\n---\n\n> **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n# Bloat Detector\n\nSystematically detect and eliminate codebase bloat through progressive analysis tiers.\n\n## Bloat Categories\n\n| Category | Examples |\n|----------|----------|\n| **Code** | Dead code, God classes, Lava flow, duplication |\n| **AI-Generated** | Tab-completion bloat, vibe coding, hallucinated deps |\n| **Documentation** | Redundancy, verbosity, stale content, slop |\n| **Dependencies** | Unused imports, dependency bloat, phantom packages |\n| **Git History** | Stale files, low-churn code, massive single commits |\n\n## Quick Start\n\n### Tier 1: Quick Scan (2-5 min, no tools)\n```bash\n/bloat-scan\n```\nDetects: Large files, stale code, old TODOs, commented blocks, basic duplication\n\n### Tier 2: Targeted Analysis (10-20 min, optional tools)\n```bash\n/bloat-scan --level 2 --focus code   # or docs, deps\n```\nAdds: Static analysis (Vulture/Knip), git churn hotspots, doc similarity\n\n### Tier 3: Deep Audit (30-60 min, full tooling)\n```bash\n/bloat-scan --level 3 --report audit.md\n```\nAdds: Cross-file redundancy, dependency graphs, readability metrics\n\n## When To Use\n\n| Do | Don't |\n|----|-------|\n| Context usage > 30% | Active feature development |\n| Quarterly maintenance | Time-sensitive bugs |\n| Pre-release cleanup | Codebase < 1000 lines |\n| Before major refactoring | Tools unavailable (Tier 2/3) |\n\n## When NOT To Use\n\n- Active feature development\n- Time-sensitive bugs\n- Codebase < 1000 lines\n\n## Confidence Levels\n\n| Level | Confidence | Action |\n|-------|------------|--------|\n| HIGH | 90-100% | Safe to remove |\n| MEDIUM | 70-89% | Review first |\n| LOW | 50-69% | Investigate |\n\n## Prioritization\n\n```\nPriority = (Token_Savings × 0.4) + (Maintenance × 0.3) + (Confidence × 0.2) + (Ease × 0.1)\n```\n\n## Module Architecture\n\n**Tier 1** (always available):\n- See `modules/quick-scan.md` - Heuristics, no tools\n- See `modules/git-history-analysis.md` - Staleness, churn, vibe coding signatures\n- See `modules/growth-analysis.md` - Growth velocity, forecasts, threshold alerts\n\n**Tier 2** (optional tools):\n- See `modules/code-bloat-patterns.md` - Anti-patterns (God class, Lava flow)\n- See `modules/ai-generated-bloat.md` - AI-specific patterns (Tab bloat, hallucinations)\n- See `modules/documentation-bloat.md` - Redundancy, readability, slop detection\n- See `modules/static-analysis-integration.md` - Vulture, Knip\n\n**Shared**:\n- See `modules/remediation-types.md` - DELETE, REFACTOR, CONSOLIDATE, ARCHIVE\n\n## Ecosystem-Level Detection\n\nPatterns that span plugin boundaries or manifest configuration,\ndiscovered through ecosystem-wide audits.\n\n### `alwaysApply` Accumulation\n\nFlag plugins with 3+ skills where `alwaysApply: true`.\nEach always-on skill injects its full text into every session,\ncreating a baseline token floor before the user types anything.\nSum the `estimated_tokens` fields to report total per-session cost.\n\n### Hook Registration Gaps\n\nCompare hooks declared in `plugin.json` or `openpackage.yml`\nagainst entries in `hooks.json`. A hook present in `hooks.json`\nbut absent from the manifest is invisible to the plugin loader\nand cannot be audited, versioned, or disabled through normal\nplugin management.\n\n### Boilerplate Footer Detection\n\nScan skill files for identical multi-line text blocks repeated\nacross 10+ files (e.g., generic troubleshooting sections like\n\"Command not found / Permission errors / Unexpected behavior\").\nThese are copy-paste artifacts that inflate token cost without\nadding skill-specific value.\n\n### ToC Bloat in Skills\n\nSkills loaded into model context gain nothing from HTML-style\nTables of Contents. Detect `## Table of Contents` followed by\nbulleted anchor-link lists. These waste tokens since\nthe model reads sequentially, not via hyperlinks.\n\n### Unregistered Module Subdirectories\n\nCompare files on disk in `skills/*/modules/` against the\n`modules:` list in each skill's SKILL.md frontmatter. Files\nthat exist on disk but are not listed in the manifest are\ninvisible to progressive loading and may be dead weight or\nmissing from the load path.\n\n## Auto-Exclusions\n\nAlways excludes: `.venv`, `__pycache__`, `.git`, `node_modules`, `dist`, `build`, `vendor`\n\nAlso respects: `.gitignore`, `.bloat-ignore`\n\n## Safety\n\n- **Never auto-delete** - all changes require approval\n- **Dry-run support** - `--dry-run` for previews\n- **Backup branches** - created before bulk changes\n\n## Related\n\n- `bloat-auditor` agent - Executes scans\n- `unbloat-remediator` agent - Safe remediation\n- `context-optimization` skill - MECW principles\n\nFile v1.9.19:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-conserve-bloat-detector\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787749765175\n}\n\nFile v1.9.19:modules/ai-generated-bloat.md\n\n---\nmodule: ai-generated-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 200\n---\n\n# AI-Generated Bloat Detection Module\n\nDetect bloat patterns specific to AI-assisted coding: vibe coding artifacts, slop patterns, and agent psychosis indicators.\n\n## Why This Module Exists\n\nAI coding has created qualitatively different bloat than traditional development:\n- **2024**: First year copy/pasted lines exceeded refactored lines (GitClear)\n- **Refactoring**: Dropped from 25% (2021) to <10% (2024), predicted 3% (2025)\n- **Duplication**: 8x increase in 5+ line code blocks\n\n## AI Bloat Patterns\n\n### 1. Tab-Completion Bloat (Repetitive Logic)\n\n**Definition**: Same pattern repeated 3+ times instead of abstracted into shared function.\n\n```bash\n# Detect similar code blocks (built-in, no external deps)\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5\n\n# JSON output for CI integration\npython3 plugins/conserve/scripts/detect_duplicates.py . --format json --threshold 15\n\n# Heuristic: functions with near-identical signatures\ngrep -rn \"^def \" --include=\"*.py\" . | cut -d: -f2 | sort | uniq -c | sort -rn | head -10\n```\n\n**Confidence**: HIGH (85%)\n**Action**: REFACTOR - extract to shared utility\n**Rationale**: AI suggests new implementations rather than reusing existing code\n\n### 2. Massive Single Commits (Vibe Coding Signature)\n\n**Definition**: Commits with >500 insertions, especially without proportional tests.\n\n```bash\n# Find vibe coding commits\ngit log --oneline --shortstat | grep -E \"[0-9]{3,} insertion\" | head -20\n\n# Commits with high insertion:deletion ratio (adding without cleanup)\ngit log --shortstat --pretty=format:\"%h %s\" | awk '/insertion|deletion/ {\n  ins=$4; del=$6;\n  if (ins > 200 && (del == \"\" || ins/del > 10)) print prev, ins, del\n} {prev=$0}'\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: INVESTIGATE - review for understanding gaps\n**Rationale**: Large additions without refactoring indicate Tab-driven development\n\n### 3. Hallucinated Dependencies\n\n**Definition**: Imports referencing non-existent packages (AI hallucination).\n\n```bash\n# Python: Check for uninstallable packages\npip freeze > /tmp/installed.txt\ngrep -rh \"^import \\|^from \" --include=\"*.py\" . | \\\n  sed 's/^import //;s/^from //;s/ import.*//' | \\\n  sort -u | while read pkg; do\n    root=$(echo $pkg | cut -d. -f1)\n    grep -q \"^$root\" /tmp/installed.txt || echo \"HALLUCINATED?: $pkg\"\n  done\n\n# JavaScript: Check for phantom packages\njq -r '.dependencies // {} | keys[]' package.json | while read pkg; do\n  npm view $pkg version 2>/dev/null || echo \"HALLUCINATED?: $pkg\"\ndone\n```\n\n**Confidence**: HIGH (95%)\n**Action**: DELETE or REPLACE\n**Rationale**: AI invents plausible-sounding packages (slopsquatting risk)\n\n### 4. Happy Path Only (Test Coverage Gap)\n\n**Definition**: Code >200 lines with no corresponding tests, or tests without error assertions.\n\n```bash\n# Files without test coverage\nfind . -name \"*.py\" ! -path \"*/test*\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c '\n  lines=$(wc -l < \"$1\")\n  if [ $lines -gt 200 ]; then\n    base=$(basename \"$1\" .py)\n    test_exists=$(find . -name \"test_${base}.py\" -o -name \"${base}_test.py\" \\\n      -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n      -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | head -1)\n    [ -z \"$test_exists\" ] && echo \"UNTESTED ($lines lines): $1\"\n  fi\n' _ {} \\;\n\n# Tests without error/exception assertions\ngrep -rL \"assert.*Error\\|assert.*Exception\\|pytest.raises\\|with self.assertRaises\" \\\n  --include=\"test_*.py\" .\n```\n\n**Confidence**: HIGH (90%)\n**Action**: AUGMENT_TESTS before adding more code\n**Rationale**: AI generates happy path; errors require human insight\n\n### 5. Premature Abstraction\n\n**Definition**: Base classes/interfaces with only 1-2 implementations.\n\n```bash\n# Python: Abstract classes 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  inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n  [ $inheritors -lt 2 ] && echo \"PREMATURE: $class in $f (${inheritors} inheritors)\"\ndone\n```\n\n**Confidence**: HIGH (85%)\n**Action**: INLINE - remove abstraction until 3rd use case\n**Rationale**: AI suggests \"scalable\" patterns for simple problems\n\n### 6. Enterprise Cosplay\n\n**Definition**: Microservices, Kubernetes, complex architecture for simple applications.\n\n```bash\n# Docker complexity for simple apps\nif [ -f docker-compose.yml ]; then\n  services=$(grep -c \"^  [a-z].*:$\" docker-compose.yml)\n  code_lines=$(find . \\( -name \"*.py\" -o -name \"*.js\" \\) \\\n    -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n    -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l 2>/dev/null | tail -1 | awk '{print $1}')\n  ratio=$((code_lines / services))\n  [ $ratio -lt 500 ] && echo \"ENTERPRISE_COSPLAY: $services services for $code_lines lines\"\nfi\n\n# Kubernetes for CRUD\n[ -d k8s ] && [ $(find . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l | tail -1 | awk '{print $1}') -lt 5000 ] && \\\n  echo \"ENTERPRISE_COSPLAY: Kubernetes for <5000 lines\"\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: SIMPLIFY - evaluate if complexity is justified\n**Rationale**: AI defaults to \"production-ready\" patterns without context\n\n### 7. Documentation Slop\n\n**Definition**: AI-generated docs with excessive hedging, formulaic structure, surface insights.\n\n```bash\n# Hedge word density (AI slop indicators)\nhedge_words=\"worth noting|arguably|to some extent|it's important|consider that|generally speaking\"\nfor f in $(find . -name \"*.md\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  total=$(wc -w < \"$f\")\n  hedges=$(grep -oiE \"$hedge_words\" \"$f\" | wc -l)\n  if [ $total -gt 100 ]; then\n    density=$((hedges * 1000 / total))\n    [ $density -gt 20 ] && echo \"DOC_SLOP ($density/1000): $f\"\n  fi\ndone\n```\n\n**Confidence**: MEDIUM (65%)\n**Action**: REWRITE with concrete specifics\n**Rationale**: AI safety training creates artificial hedging\n\n## Scoring\n\n```python\nAI_BLOAT_SCORES = {\n    'tab_completion_bloat': 25,\n    'massive_single_commit': 15,\n    'hallucinated_dependency': 35,\n    'happy_path_only': 30,\n    'premature_abstraction': 20,\n    'enterprise_cosplay': 25,\n    'documentation_slop': 10,\n}\n\ndef ai_bloat_score(detected_patterns):\n    return min(100, sum(AI_BLOAT_SCORES.get(p, 0) for p in detected_patterns))\n```\n\n## Integration with Existing Tiers\n\n**Tier 1 (Quick Scan)**: Massive single commits, hedge word density\n**Tier 2 (Targeted)**: Duplication ratio, test coverage gaps, premature abstraction\n**Tier 3 (Deep Audit)**: Hallucinated dependencies, enterprise cosplay analysis\n\n## Output Format\n\n```yaml\nfile: src/services/user_manager.py\nai_bloat_patterns:\n  - tab_completion_bloat\n  - happy_path_only\nai_bloat_score: 55/100\nindicators:\n  similar_blocks: 4\n  test_coverage: 0%\n  commit_size: 847 lines\nconfidence: HIGH\naction: REFACTOR + ADD_TESTS\nrationale: \"Vibe coding signature - large addition without tests or abstraction\"\n```\n\n## Prevention Recommendations\n\nWhen AI bloat is detected, recommend:\n\n1. **Refactoring Budget**: Add 25 lines of refactoring for every 100 lines added\n2. **Test Requirement**: No merge without proportional test coverage\n3. **Understanding Gate**: Require explanation of non-trivial changes\n4. **24-Hour Rule**: Sleep before adopting new AI-suggested patterns\n\n## Related\n\n- `code-bloat-patterns` - Traditional anti-patterns (God class, Lava flow)\n- `documentation-bloat` - Readability metrics\n- `imbue:anti-cargo-cult` - Understanding verification protocol\n- Knowledge corpus: `agent-psychosis-codebase-hygiene.md`\n\nFile v1.9.19:modules/code-bloat-patterns.md\n\n---\nmodule: code-bloat-patterns\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 150\n---\n\n# Code Bloat Patterns Module\n\nDetect anti-patterns using pattern recognition and heuristics. Works without external tools.\n\n> **Tool Preference (Claude Code 2.1.31+)**: The bash snippets in this module are reference implementations for external script execution or CI pipelines. When performing these analyses directly within Claude Code, prefer native tools: use Grep instead of `grep`, Glob instead of `find`, and Read instead of `cat`/`sed`.\n\n## Anti-Patterns\n\n### 1. God Class\n**Definition:** Single class with > 500 lines, > 10 methods, multiple responsibilities.\n\n```bash\n# Quick detection\nfind . -name \"*.py\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c 'lines=$(wc -l < \"$1\"); [ $lines -gt 500 ] && echo \"GOD_CLASS: $1 - $lines lines\"' _ {} \\;\n```\n**Confidence:** HIGH (85%) | **Action:** REFACTOR into focused modules\n\n### 2. Lava Flow\n**Definition:** Ancient untouched code - commented blocks, old TODOs.\n\n```bash\n# Find files with >20% commented code\ngrep -rn \"^#\\|^//\" --include=\"*.py\" . | cut -d: -f1 | sort | uniq -c | sort -rn | head -10\n```\n**Confidence:** HIGH (90%) | **Action:** DELETE commented code\n\n### 3. Dead Code\n**Detection:** Use static analysis (Vulture/Knip) or fallback heuristic:\n```bash\n# Heuristic: find functions with 0 calls\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  func=$(echo $line | awk '{print $2}' | cut -d'(' -f1)\n  [ $(git grep -c \"$func(\" 2>/dev/null || echo 0) -eq 1 ] && echo \"DEAD: $func\"\ndone\n```\n**Confidence:** MEDIUM (70%) heuristic, HIGH (90%) with tools | **Action:** DELETE\n\n### 4. Import Bloat\n```bash\n# Star imports (block tree-shaking)\ngrep -rn \"^from .* import \\*\" --include=\"*.py\" .\n\n# Unused imports (requires autoflake)\nautoflake --check --remove-all-unused-imports -r .\n```\n**Confidence:** HIGH (95%) | **Action:** Fix imports\n\n### 5. Duplication\n**Intra-file:** Hash-based block detection (5+ line matches)\n**Cross-file:** Function signature matching\n**Semantic:** AST comparison (80%+ similarity)\n\n**Confidence:** HIGH (85%) | **Action:** EXTRACT to shared utility\n\n## Language-Specific\n\n### Python\n- Circular imports: Files with 20+ imports\n- Deep nesting: > 4 indentation levels\n\n### JavaScript/TypeScript\n- Barrel files: `export * from` breaks tree-shaking\n- CommonJS in ESM: `module.exports`/`require()` blocks bundler optimization\n\n## AI-Amplified Patterns\n\nThese traditional patterns are amplified by AI coding tools:\n\n### 6. Tab-Completion Duplication\n**Definition:** AI suggests similar code blocks instead of reusing existing functions.\n**2024 Data:** 8x increase in 5+ line duplicated blocks (GitClear)\n\n```bash\n# Quick detection: near-identical function signatures\ngrep -rn \"^def \" --include=\"*.py\" . | awk -F'def ' '{print $2}' | \\\n  cut -d'(' -f1 | sort | uniq -c | sort -rn | awk '$1 > 1'\n```\n**Confidence:** HIGH (85%) | **Action:** EXTRACT shared utility\n\n### 7. Dead Wrapper / Facade Bloat\n**Definition:** Modules that wrap existing functionality without adding meaningful logic — thin facades, unused service interfaces, or re-export layers with no consumers.\n\n**Signals:**\n- File imports from another internal module and re-exports similar API\n- No external imports of the wrapper (0 refs from outside itself)\n- Not a proper package (missing `__init__.py` for Python)\n- Docstring examples show imports but no actual code uses them\n- Functionality already exists in the wrapped module or in `examples/`\n\n```bash\n# Find Python files that only re-export from other internal modules\nfor f in $(find . -name \"*.py\" -not -path \"*/test*\" -not -path \"*/__pycache__/*\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  # Check if file mostly imports and re-calls another module's functions\n  imports=$(grep -c \"^from \\.\\.\" \"$f\" 2>/dev/null || echo 0)\n  total=$(wc -l < \"$f\" 2>/dev/null || echo 0)\n  refs=$(git grep -l \"$(basename \"$f\" .py)\" -- \"*.py\" 2>/dev/null | grep -v \"$f\" | wc -l)\n  if [ \"$imports\" -gt 2 ] && [ \"$refs\" -eq 0 ] && [ \"$total\" -gt 50 ]; then\n    echo \"DEAD_WRAPPER: $f ($total lines, $imports internal imports, 0 external refs)\"\n  fi\ndone\n```\n\n**Also check for intra-file dead wrappers:**\n```bash\n# Find classes/functions that only delegate to another method with no transformation\ngrep -rn \"def .*self\" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  lineno=$(echo \"$line\" | cut -d: -f2)\n  # Check if function body is just \"return self.other_thing(...)\"\n  body=$(sed -n \"$((lineno+1)),$((lineno+3))p\" \"$file\" 2>/dev/null)\n  if echo \"$body\" | grep -qP '^\\s+return self\\.\\w+\\(' && [ $(echo \"$body\" | wc -l) -le 2 ]; then\n    echo \"PASSTHROUGH: $file:$lineno - trivial delegation\"\n  fi\ndone\n```\n\n**Confidence:** HIGH (85%) for whole-file wrappers, MEDIUM (70%) for intra-file passthrough\n**Action:** DELETE (whole-file) or INLINE (intra-file passthrough)\n\n### 8. Premature Abstraction\n**Definition:** Base classes/interfaces with <3 implementations (YAGNI violation).\n**AI Cause:** AI defaults to \"scalable\" patterns without context.\n\n```bash\n# Find abstract classes with few inheritors\ngrep -rln \"ABC\\|abstractmethod\" --include=\"*.py\" . | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ $(grep -rc \"($class)\" --include=\"*.py\" . 2>/dev/null) -lt 3 ] && echo \"PREMATURE: $class\"\ndone\n```\n**Confidence:** HIGH (80%) | **Action:** INLINE until 3rd use case\n\n### 9. Happy Path Bias\n**Definition:** Tests verify success paths only; no error handling tested.\n**AI Cause:** AI optimizes for \"works\" demonstrations.\n\n```bash\n# Tests without error assertions\ngrep -rL \"Error\\|Exception\\|raises\\|fail\\|invalid\" --include=\"test_*.py\" .\n```\n**Confidence:** MEDIUM (70%) | **Action:** ADD error path tests\n\nFor comprehensive AI-specific patterns, see: `@module:ai-generated-bloat`\n\n## Scoring\n\n```python\nPATTERN_SCORES = {\n    'god_class': 30, 'lava_flow': 25, 'dead_code': 35,\n    'import_bloat': 15, 'duplication': 20, 'dead_wrapper': 30\n}\nscore = min(100, sum(PATTERN_SCORES[p] for p in detected))\n```\n\n## Output Format\n\n```yaml\nfile: src/legacy/manager.py\npatterns: [god_class, lava_flow, import_bloat]\nbloat_score: 85/100\nconfidence: HIGH\ntoken_estimate: ~3,400\naction: REFACTOR\n```\n\nAll actions require user approval.\n\nFile v1.9.19:modules/documentation-bloat.md\n\n---\nmodule: documentation-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 120\n---\n\n# Documentation Bloat Module\n\nDetect documentation redundancy, verbosity, and poor readability.\n\n## Detection Categories\n\n### 1. Duplicate Documentation\n\n#### Cross-File (Jaccard Similarity)\n```bash\n# Quick similarity check between two files\nwords1=$(tr '[:space:]' '\\n' < file1.md | sort -u)\nwords2=$(tr '[:space:]' '\\n' < file2.md | sort -u)\n# > 70% overlap = potential duplication\n```\n\n| Similarity | Confidence | Action |\n|------------|------------|--------|\n| > 90% | HIGH (95%) | DELETE one, keep recent |\n| 70-90% | MEDIUM (80%) | MERGE, preserve unique |\n| 50-70% | LOW (60%) | CROSS-LINK |\n\n#### Intra-File (Section Hashing)\nHash each `##` section's normalized content. Duplicates = repeated sections.\n\n**Confidence:** HIGH (85%)\n\n### 2. Excessive Verbosity\n\n| Metric | Threshold | Action |\n|--------|-----------|--------|\n| Word count | > 500 words/section | Condense |\n| Sentence length | > 25 words avg | Simplify |\n| Passive voice | > 30% | Rewrite active |\n| Readability | Flesch < 40 | Simplify |\n\n```bash\n# Quick verbosity check\nwc -w file.md  # Total words\nrg -c '\\.' file.md  # Approximate sentences (or grep -c)\n```\n\n### 3. Stale Documentation\n\n| Signal | Confidence | Action |\n|--------|------------|--------|\n| Unchanged 12+ months | HIGH (85%) | Review/Archive |\n| References deleted code | HIGH (90%) | Update/Delete |\n| No git activity | MEDIUM (75%) | Investigate |\n\n```bash\n# Find stale docs\ngit log -1 --format=\"%ar\" -- docs/*.md | rg -E \"year|months\"\n# fallback: grep -E \"year|months\"\n```\n\n### 4. Missing/Outdated References\n\n- Broken internal links: `rg -oP '\\[.*?\\]\\((?!http).*?\\)' *.md` (or `grep -oP`)\n- References to deleted files\n- Outdated API examples\n\n**Confidence:** HIGH (90%) for broken links\n\n## Scoring\n\n```python\ndef doc_bloat_score(metrics):\n    score = 0\n    if metrics['duplicate_ratio'] > 0.3: score += 30\n    if metrics['avg_words_per_section'] > 500: score += 20\n    if metrics['readability'] < 40: score += 15\n    if metrics['stale_months'] > 12: score += 25\n    return min(100, score)\n```\n\n## Output Format\n\n```yaml\nfile: docs/old-guide.md\nbloat_type: [duplicate, verbose, stale]\nbloat_score: 72/100\nconfidence: HIGH\ntoken_estimate: ~1,200\nsimilar_to: docs/guide.md (87%)\naction: MERGE\n```\n\n## Related\n- `quick-scan` - Tier 1 stale detection\n- `git-history-analysis` - Activity signals\n\nFile v1.9.19:modules/git-history-analysis.md\n\n---\nmodule: git-history-analysis\ncategory: tier-1\ndependencies: [Bash, Grep]\nestimated_tokens: 250\n---\n\n# Git History Analysis Module\n\nDetect bloat using git history: staleness, churn metrics, and reference counting.\n\n## Core Techniques\n\n### 1. Staleness Detection\n\n**Command:**\n```bash\n# Files not modified in last 6 months\ngit log --since=\"6 months ago\" --name-only --pretty=format: | sort -u > recent.txt\ncomm -13 recent.txt <(git ls-files | sort) > stale_files.txt\n```\n\n**Staleness Scoring:**\n```python\ndef staleness_score(months_since_change):\n    if months_since_change > 24:\n        return 95  # Almost certainly abandoned\n    elif months_since_change > 12:\n        return 85  # Likely abandoned\n    elif months_since_change > 6:\n        return 65  # Possibly stale\n    else:\n        return 20  # Active\n```\n\n**Confidence Modifiers:**\n- File type: Config files -20%, code files +0%\n- Last author: If single author who left project +15%\n- Dependencies: If no imports found +25%\n\n### 2. Reference Counting\n\n**Detect unused files:**\n```bash\n# For each file, count references in codebase\ngit ls-files | while read file; do\n  filename=$(basename \"$file\")\n  refs=$(git grep -l \"$filename\" | wc -l)\n  if [ $refs -eq 1 ]; then  # Only self-reference\n    echo \"0 $file\"\n  else\n    echo \"$((refs - 1)) $file\"  # Subtract self\n  fi\ndone | grep \"^0 \"\n```\n\n**Confidence:** HIGH (90%) if zero refs and stale\n\n**False Positives:**\n- Entry points (main.py, index.js)\n- Configuration files\n- Documentation\n\n### 3. Code Churn Metrics\n\n**Churn formula:**\n```bash\n# Lines added + deleted per file\ngit log --numstat --pretty=\"%H\" -- $file | \\\n  awk '{added+=$1; deleted+=$2} END {print added+deleted}'\n```\n\n**Churn Categories:**\n- **High churn (>1000 changes/year)**: Active development\n- **Low churn (<50 changes/year)**: Stable or abandoned\n- **Zero churn + old**: Strong bloat signal\n\n**Filter out cleanup-churn (release sweeps, frontmatter-only edits):**\n\nA naive commit count over-flags files swept by repo-wide release\noperations (version bumps, frontmatter additions). Filter to commits\nthat made substantive changes to the file under analysis.\n\n```bash\n# Count only commits with >5 line net change in the file\ngit log --numstat --pretty=tformat:%H -- \"$file\" | \\\n  awk '/^[0-9]/ && ($1 + $2) > 5 { count++ } END { print count }'\n```\n\nCompare against the unfiltered count: if `substantive_count <\ntotal_count / 3`, the file is **cleanup-churn** not **design churn**.\nDowngrade the thrashing/hotspot signal in that case.\n\nWorked example: `rigorous-reasoning/SKILL.md` showed 12 commits in 30\ndays. After filtering for substantive body changes (`>5` line net),\nonly 1 commit remained. The rest were repo-wide frontmatter sweeps\n(version bumps, tag adds, description tweaks). This file is NOT a\nthrashing hotspot; the signal was a false positive from cleanup-churn.\n\n**Hotspot Detection:**\n```python\ndef is_hotspot(churn, complexity):\n    \"\"\"\n    Hotspot = High churn × High complexity\n    Indicates technical debt accumulation\n    \"\"\"\n    churn_score = normalize_churn(churn)\n    complexity_score = cyclomatic_complexity(file)\n    return churn_score * complexity_score > threshold\n```\n\n### 4. Ownership Analysis\n\n**Detect abandoned code:**\n```bash\n# Find files where primary author has no recent commits\ngit log --format=\"%an\" --since=\"6 months ago\" | sort -u > active_authors.txt\n\ngit ls-files | while read file; do\n  primary_author=$(git log --format=\"%an\" -- \"$file\" | sort | uniq -c | sort -rn | head -1 | awk '{$1=\"\"; print $0}' | sed 's/^ //')\n  if ! grep -qF \"$primary_author\" active_authors.txt; then\n    echo \"$file - Primary author inactive: $primary_author\"\n  fi\ndone\n```\n\n**Confidence:** MEDIUM (70%) - Ownership transfer is possible\n\n### 5. Branch Analysis\n\n**Detect orphaned feature branches:**\n```bash\n# Branches not merged in 6+ months\ngit for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)' | \\\n  while read date branch; do\n    age_days=$(( ($(date +%s) - $(date -d \"$date\" +%s)) / 86400 ))\n    if [ $age_days -gt 180 ]; then\n      echo \"$branch - ${age_days} days old\"\n    fi\n  done\n```\n\n**Action:** Suggest cleanup or archival\n\n## Integrated Analysis\n\n### Multi-Signal Validation\n\nCombine signals for higher confidence:\n\n```python\ndef calculate_bloat_confidence(file):\n    signals = []\n\n    # Staleness\n    months = months_since_last_change(file)\n    if months > 12:\n        signals.append(('stale', 85, months))\n\n    # No references\n    refs = count_references(file)\n    if refs == 0:\n        signals.append(('unused', 90, refs))\n\n    # Low churn\n    churn = calculate_churn(file)\n    if churn < 50:  # < 50 changes/year\n        signals.append(('low_churn', 70, churn))\n\n    # Inactive owner\n    if is_owner_inactive(file):\n        signals.append(('inactive_owner', 65, None))\n\n    # Combined confidence\n    if len(signals) >= 3:\n        return 'HIGH', signals\n    elif len(signals) == 2:\n        return 'MEDIUM', signals\n    else:\n        return 'LOW', signals\n```\n\n### Example Output\n\n```yaml\nfile: src/deprecated/old_api.py\nconfidence: HIGH\nsignals:\n  - type: stale\n    score: 85\n    detail: 18 months since last change\n  - type: unused\n    score: 90\n    detail: Zero references found\n  - type: low_churn\n    score: 70\n    detail: 12 changes in last year\ncombined_score: 82\nrecommendation: DELETE\nrationale: |\n  Multiple strong signals indicate abandonment:\n  - No changes in 18 months\n  - No code references\n  - Minimal historical activity\n  Safe to remove with archival backup.\n```\n\n## AskGit Integration (Optional)\n\nIf AskGit is available, use SQL for advanced queries:\n\n```sql\n-- Find files with high churn but low recent activity\nSELECT\n  file_path,\n  SUM(additions + deletions) as total_churn,\n  MAX(author_when) as last_change\nFROM commits\nWHERE author_when < date('now', '-6 months')\nGROUP BY file_path\nHAVING total_churn > 1000\nORDER BY total_churn DESC;\n```\n\n## Performance Optimization\n\n**Caching Strategy:**\n```bash\n# Cache git log results for reuse\ngit log --all --numstat --pretty=format:'%H|%an|%ai' > /tmp/git_cache.txt\n\n# Query cache instead of running git log repeatedly\ngrep \"path/to/file\" /tmp/git_cache.txt\n```\n\n**Incremental Updates:**\n- Store previous scan results\n- Only analyze changed files\n- Delta reporting\n\n## Safety Checks\n\nBefore flagging for deletion:\n\n1. **Test Files**: Exclude `test_*.py`, `*.spec.js`\n2. **Migrations**: Database migrations must never auto-delete\n3. **CI/CD**: Files in `.github/`, `.gitlab-ci.yml`\n4. **Documentation**: User-facing docs need manual review\n\n**Whitelist Patterns:**\n```yaml\nsafe_paths:\n  - tests/\n  - migrations/\n  - .github/\n  - docs/api/  # API docs are references, not code\n\nexcluded_from_bloat_analysis:\n  # Cache directories (always exclude from counts)\n  - .venv/\n  - venv/\n  - __pycache__/\n  - .pytest_cache/\n  - .mypy_cache/\n  - .ruff_cache/\n  - .tox/\n  - .git/\n  # Dependencies and build artifacts\n  - node_modules/\n  - vendor/\n  - dist/\n  - build/\n```\n\n## Integration with Quick Scan\n\nGit analysis validates quick scan findings:\n\n```python\ndef validate_quick_scan_finding(finding):\n    # Quick scan says file is bloated\n    # Git analysis confirms or refutes\n    git_score = analyze_git_history(finding.file)\n\n    if quick_scan.score > 80 and git_score > 80:\n        return 'HIGH_CONFIDENCE'\n    elif quick_scan.score > 60 and git_score > 60:\n        return 'MEDIUM_CONFIDENCE'\n    else:\n        return 'LOW_CONFIDENCE'  # Conflicting signals\n```\n\n## Next Steps\n\nBased on git analysis:\n- **HIGH confidence**: Create cleanup PR\n- **MEDIUM confidence**: Run static analysis (Tier 2)\n- **LOW confidence**: Manual code review\n\nFile v1.9.19:modules/growth-analysis.md\n\n---\nmodule: growth-analysis\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 1500\n---\n\n# Growth Analysis Module\n\nTrack codebase growth velocity using git history.\nForecast future size, predict threshold crossings,\nand rank directories by urgency.\n\nThis module replaces the former standalone\n`/analyze-growth` command (removed in v1.6.0).\nIt runs as part of `/bloat-scan --growth`.\n\n## When to Load\n\nLoad this module when:\n\n- Running `/bloat-scan --growth`\n- Investigating rapid file or line count increases\n- Planning capacity for skill files approaching token limits\n- Preparing quarterly growth reports\n\n## Core Metrics\n\n### 1. File Count Velocity\n\nTrack how fast new files appear in a directory tree.\n\n```bash\n# File count per week for the last 8 weeks\nfor i in $(seq 0 7); do\n  date=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --until=\"$date\" --diff-filter=A \\\n    --name-only --pretty=format: -- \"$TARGET_DIR\" | \\\n    sort -u | wc -l)\n  echo \"$date $count\"\ndone | sort\n```\n\n**Output columns:** date, cumulative file count\n\n### 2. Line Count Velocity\n\nMeasure net line growth over recent commits.\n\n```bash\n# Net lines added per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  git log --since=\"$start\" --until=\"$end\" \\\n    --numstat --pretty=format: -- \"$TARGET_DIR\" | \\\n    awk '{added+=$1; deleted+=$2}\n      END {print added - deleted}'\ndone\n```\n\n**Negative values** indicate shrinkage (good after cleanup).\n\n### 3. Commit Frequency\n\nCount commits touching a path over rolling windows.\n\n```bash\n# Commits per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --since=\"$start\" --until=\"$end\" \\\n    --oneline -- \"$TARGET_DIR\" | wc -l)\n  echo \"week-$i: $count commits\"\ndone\n```\n\n### 4. Size Snapshot\n\nCurrent state measurement for the target path.\n\n```bash\n# Total lines in tracked files (exclude cache dirs)\ngit ls-files -- \"$TARGET_DIR\" | \\\n  grep -v -E '(\\.venv|__pycache__|node_modules|\\.git)' | \\\n  xargs wc -l 2>/dev/null | tail -1\n```\n\n## 30-Day Forecast\n\nUse simple linear regression on the last 8 weekly\ndata points to project 30 days forward.\n\n### Algorithm\n\n```python\ndef forecast_30d(weekly_counts):\n    \"\"\"\n    Linear least-squares fit on weekly data.\n    Returns projected value 4.3 weeks from now.\n    \"\"\"\n    n = len(weekly_counts)\n    if n < 3:\n        return None  # Not enough data\n\n    xs = list(range(n))\n    x_mean = sum(xs) / n\n    y_mean = sum(weekly_counts) / n\n\n    numerator = sum(\n        (x - x_mean) * (y - y_mean)\n        for x, y in zip(xs, weekly_counts)\n    )\n    denominator = sum((x - x_mean) ** 2 for x in xs)\n\n    if denominator == 0:\n        return y_mean  # Flat line\n\n    slope = numerator / denominator\n    intercept = y_mean - slope * x_mean\n\n    # 30 days = ~4.3 weeks beyond last data point\n    future_x = (n - 1) + 4.3\n    return slope * future_x + intercept\n```\n\n### Interpreting Forecasts\n\n- **Slope > 0**: Growing. Report weekly rate.\n- **Slope ~ 0**: Stable. No action needed.\n- **Slope < 0**: Shrinking. Recent cleanup likely working.\n\nReport the R-squared value when possible.\nLow R-squared (< 0.5) means the trend is noisy\nand the forecast is unreliable.\n\n## Threshold Crossing Predictions\n\nGiven a target limit (e.g., 500-line skill file limit),\ncalculate when the current growth rate will cross it.\n\n### Algorithm\n\n```python\ndef weeks_until_threshold(current_size, weekly_rate, limit):\n    \"\"\"\n    Returns weeks until current_size reaches limit\n    at the given weekly_rate.\n    Returns None if rate <= 0 (will never cross).\n    \"\"\"\n    if weekly_rate <= 0:\n        return None\n    remaining = limit - current_size\n    if remaining <= 0:\n        return 0  # Already exceeded\n    return remaining / weekly_rate\n```\n\n### Default Thresholds\n\n| Target | Limit | Rationale |\n|--------|-------|-----------|\n| Skill file | 500 lines | Progressive loading boundary |\n| Module file | 300 lines | Single-responsibility cap |\n| Python source | 500 lines | God class indicator |\n| Markdown doc | 300 lines | Reader attention limit |\n\nOverride thresholds with `--threshold <lines>`.\n\n## Urgency Rankings\n\nRank directories or files by how soon they will\nneed attention.\n\n### Scoring Formula\n\n```\nurgency = growth_rate * (current_size / threshold) * recency_weight\n```\n\nWhere:\n\n- `growth_rate`: Lines per week (normalized 0-1)\n- `current_size / threshold`: How close to the limit (0-1+)\n- `recency_weight`: 1.5 if accelerating, 1.0 if steady,\n  0.5 if decelerating\n\n### Urgency Categories\n\n| Category | Score Range | Action |\n|----------|------------|--------|\n| Critical | > 0.8 | Modularize or split now |\n| High | 0.5 - 0.8 | Plan optimization this sprint |\n| Medium | 0.2 - 0.5 | Add to backlog |\n| Low | < 0.2 | No action needed |\n\n### Acceleration Detection\n\nCompare the growth rate of the last 4 weeks against\nthe preceding 4 weeks.\n\n```python\ndef detect_acceleration(weekly_rates):\n    if len(weekly_rates) < 8:\n        return \"insufficient_data\"\n    recent = sum(weekly_rates[-4:]) / 4\n    earlier = sum(weekly_rates[-8:-4]) / 4\n    if earlier == 0:\n        return \"new_growth\" if recent > 0 else \"stable\"\n    ratio = recent / earlier\n    if ratio > 1.5:\n        return \"accelerating\"\n    elif ratio < 0.5:\n        return \"decelerating\"\n    return \"steady\"\n```\n\n## Output Format\n\n### Terminal Report\n\n```\n=== Growth Analysis: plugins/conserve/skills/ ===\n\nCurrent State:\n  Files:  47\n  Lines:  8,234\n  Avg:    175 lines/file\n\n30-Day Forecast:\n  Files:  +5  (52 projected)\n  Lines:  +820 (9,054 projected)\n  Rate:   ~205 lines/week\n\nThreshold Alerts:\n  bloat-detector/SKILL.md    412/500 lines  ~4 weeks to limit\n  context-optimization.md    289/300 lines  ~1 week to limit  [!]\n\nUrgency Rankings:\n  [CRITICAL] context-optimization.md   0.92\n  [HIGH]     bloat-detector/SKILL.md   0.67\n  [MEDIUM]   token-conservation.md     0.34\n  [LOW]      performance-monitoring.md 0.11\n```\n\n### Machine-Readable Output\n\n```yaml\ngrowth_analysis:\n  target: plugins/conserve/skills/\n  snapshot:\n    files: 47\n    lines: 8234\n    date: \"2026-03-10\"\n  forecast_30d:\n    files: 52\n    lines: 9054\n    confidence: 0.78\n  weekly_rate:\n    files: 1.2\n    lines: 205\n  threshold_alerts:\n    - path: context-optimization.md\n      current: 289\n      limit: 300\n      weeks_remaining: 1\n      urgency: critical\n    - path: bloat-detector/SKILL.md\n      current: 412\n      limit: 500\n      weeks_remaining: 4\n      urgency: high\n  rankings:\n    - path: context-optimization.md\n      urgency: 0.92\n      category: critical\n      acceleration: accelerating\n    - path: bloat-detector/SKILL.md\n      urgency: 0.67\n      category: high\n      acceleration: steady\n```\n\n## Integration with Bloat Scan\n\nGrowth analysis feeds into the bloat detection pipeline:\n\n- **Fast-growing files** get flagged for proactive review\n  before they become bloated\n- **Threshold alerts** trigger modularization suggestions\n  from the `remediation-types` module\n- **Urgency rankings** prioritize the bloat scan report's\n  findings list\n\n### Coordination with Other Modules\n\n- `quick-scan`: Growth data adds time dimension to\n  size-based findings\n- `git-history-analysis`: Shares git log data;\n  growth-analysis focuses on trends while\n  git-history focuses on staleness and churn\n- `remediation-types`: Growth-triggered items map to\n  REFACTOR (split) or ARCHIVE (stabilize) actions\n\n## Limitations\n\n- Requires at least 3 weeks of git history for\n  meaningful forecasts\n- Linear projection does not capture seasonal patterns\n  or burst development cycles\n- Merge commits can skew line counts; use `--no-merges`\n  when possible\n- Renamed files appear as delete + add, inflating\n  apparent growth\n\nFile v1.9.19:modules/quick-scan.md\n\n---\nmodule: quick-scan\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 200\n---\n\n# Quick Scan Module\n\nFast heuristic-based bloat detection without external tools. Completes in < 5 minutes.\n\n## Detection Patterns\n\n### 1. Large Files (God Class Candidates)\n\n```bash\n# Find files > 500 lines (excluding cache and dependency directories)\nfind . -type f \\( -name \"*.py\" -o -name \"*.js\" -o -name \"*.ts\" \\) \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/node_modules/*\" \\\n  -not -path \"*/.git/*\" \\\n  -not -path \"*/dist/*\" \\\n  -not -path \"*/build/*\" \\\n  -not -path \"*/.tox/*\" \\\n  -not -path \"*/.mypy_cache/*\" \\\n  -not -path \"*/.ruff_cache/*\" | \\\nwhile read f; do\n  lines=$(wc -l < \"$f\")\n  if [ $lines -gt 500 ]; then\n    echo \"$lines $f\"\n  fi\ndone | sort -rn\n```\n\n**Thresholds:**\n- Python: > 500 lines (God class likely)\n- JavaScript/TypeScript: > 400 lines\n- Markdown: > 300 lines (bloated docs)\n\n**Confidence:** MEDIUM (70%) - Large size suggests but doesn't confirm bloat\n\n### 2. Stale Files (Lava Flow)\n\n```bash\n# Files unchanged in 6+ months\ngit log --since=\"6 months ago\" --name-only --pretty=format: | \\\n  sort -u > recent_files.txt\n\ngit ls-files | while read f; do\n  if ! grep -qxF \"$f\" recent_files.txt; then\n    last_modified=$(git log -1 --format=\"%ai\" -- \"$f\")\n    echo \"$last_modified $f\"\n  fi\ndone | sort\n\nrm recent_files.txt\n```\n\n**Thresholds:**\n- > 12 months: HIGH confidence (95%)\n- 6-12 months: MEDIUM confidence (75%)\n- 3-6 months: LOW confidence (50%)\n\n**False Positives:** Stable libraries, configuration files (check `.bloat-ignore`)\n\n### 3. Commented Code Blocks\n\n```bash\n# Find large commented code blocks (Python)\ngrep -rn \"^#.*def \\|^#.*class \\|^#.*import \" --include=\"*.py\" . | \\\n  awk '{print $1}' | uniq -c | sort -rn\n\n# JavaScript/TypeScript\ngrep -rn \"^//.*function \\|^//.*class \\|^//.*import \" --include=\"*.js\" --include=\"*.ts\" . | \\\n  awk '{print $1}' | uniq -c | sort -rn\n```\n\n**Confidence:** HIGH (90%) - Commented code is rarely needed\n\n### 4. Old TODOs/FIXMEs\n\n```bash\n# Find TODOs with dates > 3 months old\ngrep -rn \"TODO\\|FIXME\\|HACK\" --include=\"*.py\" --include=\"*.js\" --include=\"*.ts\" --include=\"*.md\" . | \\\n  grep -E \"[0-9]{4}-[0-9]{2}\" | \\\n  while read line; do\n    # Extract date and compare (simplified - actual implementation would parse dates)\n    echo \"$line\"\n  done\n```\n\n**Thresholds:**\n- > 12 months: Remove or convert to issue\n- 6-12 months: Review for relevance\n- 3-6 months: Monitor\n\n**Confidence:** MEDIUM (70%) - Context-dependent\n\n### 5. Duplicate Patterns\n\n```bash\n# Find potential duplicate files by name similarity (excluding cache directories)\nfind . -type f \\( -name \"*.py\" -o -name \"*.js\" -o -name \"*.ts\" \\) \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/node_modules/*\" \\\n  -not -path \"*/.git/*\" | \\\n  sed 's/.*\\///' | sort | uniq -d\n\n# Find duplicate files by content hash (excluding cache directories)\nfind . -type f -name \"*.py\" \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/.git/*\" \\\n  -exec md5sum {} \\; | \\\n  sort | uniq -w32 -D | cut -d' ' -f3-\n```\n\n**Confidence:** LOW (60%) - Needs manual review, may be intentional\n\n## Scoring Algorithm\n\n```python\ndef calculate_quick_scan_score(file_path, metrics):\n    score = 0\n\n    # Size penalty\n    if metrics['lines'] > 500:\n        score += (metrics['lines'] - 500) / 100 * 10\n\n    # Staleness penalty\n    months_unchanged = metrics['months_since_change']\n    if months_unchanged > 12:\n        score += 30  # High penalty\n    elif months_unchanged > 6:\n        score += 15  # Medium penalty\n\n    # Commented code penalty\n    commented_lines = metrics['commented_code_lines']\n    score += commented_lines * 0.5\n\n    # Old TODOs\n    old_todos = metrics['todos_older_than_6mo']\n    score += old_todos * 2\n\n    # Normalize to 0-100\n    return min(score, 100)\n```\n\n## Output Format\n\n```yaml\nfile: path/to/bloated_file.py\nbloat_score: 85\nconfidence: MEDIUM\nsignals:\n  - large_file: 847 lines (threshold: 500)\n  - stale: 18 months unchanged\n  - commented_code: 23 lines\n  - old_todos: 3 (oldest: 14 months)\ntoken_estimate: ~3,200 tokens\nrecommendations:\n  - action: DELETE\n    rationale: No recent usage, high bloat score\n    safety: Check for external references first\n  - action: ARCHIVE\n    rationale: Preserve history without active maintenance\n    location: archive/legacy/\n```\n\n## Integration with Git Analysis\n\nQuick scan coordinates with `git-history-analysis` module:\n- Quick scan identifies candidates\n- Git analysis validates with reference counting\n- Combined confidence: HIGHER than either alone\n\n## Performance\n\n- **Target**: < 5 minutes for 10,000 files\n- **Method**: Parallel grep, minimal disk I/O\n- **Optimization**: Cache git log results, reuse across scans\n\n## False Positive Handling\n\nRespect `.bloat-ignore` patterns:\n\n```gitignore\n# .bloat-ignore - Patterns to exclude from bloat detection\n\n# Cache directories (should always be excluded)\n.venv/\nvenv/\n__pycache__/\n.pytest_cache/\n.mypy_cache/\n.ruff_cache/\n.tox/\n.git/\n\n# Build and distribution\ndist/\nbuild/\n*.egg-info/\n\n# Dependencies\nnode_modules/\nvendor/\n\n# IDE and editor\n.vscode/\n.idea/\n\n# Test fixtures and templates\ntests/fixtures/*\nconfig/*.template\n\n# Auto-generated code\ngenerated/*\n*_pb2.py\n```\n\n**Default Exclusions**: The scan tools should automatically exclude common cache directories even without a `.bloat-ignore` file.\n\n## Next Steps After Quick Scan\n\nBased on findings:\n- **High-confidence**: Proceed with cleanup\n- **Medium-confidence**: Run Tier 2 for validation\n- **Low-confidence**: Manual review required\n\nFile v1.9.19:modules/remediation-types.md\n\n---\nmodule: remediation-types\ncategory: remediation\ndependencies: []\nestimated_tokens: 150\n---\n\n# Remediation Types\n\nShared definitions for bloat remediation actions used by unbloat command and unbloat-remediator agent.\n\n## DELETE (Dead Code Removal)\n\nRemove files with high confidence they're unused:\n- 0 references (git grep, static analysis)\n- Stale (> 6 months unchanged)\n- High confidence (> 90%)\n- Non-core files\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | deprecated/*, test files, archive/*, 0 refs, 95%+ confidence |\n| MEDIUM | 1-2 refs, 85-94% confidence |\n| HIGH | >2 refs, <85% confidence, core infrastructure |\n\n## REFACTOR (Split God Classes)\n\nBreak large, low-cohesion files into focused modules:\n- Large files (> 500 lines)\n- Multiple responsibilities (low cohesion)\n- High cyclomatic complexity\n- Active usage (recent changes)\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Utilities, helpers, pure functions, < 3 import sites |\n| MEDIUM | Services, handlers, 3-10 import sites |\n| HIGH | Core modules, frameworks, > 10 import sites |\n\n## CONSOLIDATE (Merge Duplicates)\n\nMerge duplicate or redundant content:\n- Documentation with > 85% similarity\n- Duplicate code patterns\n- Multiple versions of same concept\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Docs, examples, pure duplication |\n| MEDIUM | Utilities with slight variations |\n| HIGH | Business logic, different contexts |\n\n## ARCHIVE (Move to Archive)\n\nMove stale but historically valuable content:\n- Old tutorials, examples\n- Deprecated but referenced\n- Historical documentation\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Examples, tutorials, < 5 refs |\n| MEDIUM | Guides, how-tos, 5-10 refs |\n| HIGH | Core docs, > 10 refs |\n\n## INLINE (Remove Dead Wrappers)\n\nReplace thin facades and passthrough functions with direct usage of the underlying implementation:\n- Whole-file wrappers with 0 external consumers → DELETE\n- Intra-file passthrough methods that only delegate → INLINE callers to use wrapped method directly\n- Re-export layers where examples/ already demonstrates the same API\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | 0 external refs, wrapper adds no logic, underlying module is stable |\n| MEDIUM | 1-2 refs, wrapper adds minor convenience (default args, error handling) |\n| HIGH | >2 refs, wrapper provides meaningful abstraction or cross-cutting concerns |\n\n**Detection Signals:**\n- File imports internal module and re-exports similar API surface\n- No `__init__.py` (not a proper package)\n- Function bodies are single `return self.other_method(...)` calls\n- Duplicate capability exists in `examples/` or `skills/` directories\n\n## Auto-Approval Levels\n\n| Level | Criteria |\n|-------|----------|\n| `low` | Confidence >= 90%, Risk = LOW, 0 refs, deprecated/test/archive files only |\n| `medium` | Confidence >= 80%, Risk <= MEDIUM, <= 2 refs, non-core |\n| `none` | Prompts for every change (default, safest) |\n\n**Note:** All levels still show preview before execution.\n\nFile v1.9.19:modules/static-analysis-integration.md\n\n---\nmodule: static-analysis-integration\ncategory: tier-2\ndependencies: [Bash, Read]\nestimated_tokens: 150\n---\n\n# Static Analysis Integration Module\n\nBridge Tier 1 heuristics with Tier 2 programmatic analysis. Auto-detects tools and falls back gracefully.\n\n## Tool Detection\n\n```bash\n# Auto-detect available tools\nTOOLS=()\ncommand -v vulture &>/dev/null && TOOLS+=(\"vulture\")\ncommand -v deadcode &>/dev/null && TOOLS+=(\"deadcode\")\ncommand -v autoflake &>/dev/null && TOOLS+=(\"autoflake\")\ncommand -v knip &>/dev/null && TOOLS+=(\"knip\")\ncommand -v sonar-scanner &>/dev/null && TOOLS+=(\"sonarqube\")\n\n[ ${#TOOLS[@]} -gt 0 ] && echo \"Tier 2 capable\" || echo \"Tier 1 only\"\n```\n\n## Python Tools\n\n| Tool | Strength | Confidence | Command |\n|------|----------|------------|---------|\n| **vulture** | Dead code detection | 80-95% | `vulture . --min-confidence 80` |\n| **deadcode** | Fast, auto-fix | 85% | `deadcode --dry` |\n| **autoflake** | Import cleanup | 95% | `autoflake --check -r .` |\n\n### Vulture (Recommended)\n```bash\nvulture . --min-confidence 80 --exclude=.venv,__pycache__,.git,node_modules\n```\n- 90-100%: Safe to remove\n- 80-89%: Review first\n- <80%: Investigate\n\n### autoflake (Imports)\n```bash\nautoflake --check --remove-all-unused-imports --expand-star-imports -r .\n# Fix: add --in-place\n```\n**Impact:** 40-70% startup time reduction\n\n## JavaScript/TypeScript\n\n| Tool | Strength | Confidence | Command |\n|------|----------|------------|---------|\n| **knip** | Files, exports, deps | 95% | `knip --include files,exports` |\n\n```bash\nknip --include files,exports,dependencies --reporter json > knip-report.json\n```\n\n**Tree-shaking prereqs:**\n- `\"type\": \"module\"` in package.json\n- Avoid `export * from` barrel patterns\n\n## Multi-Language\n\n**SonarQube** (enterprise): Duplication, complexity, code smells\n```bash\nsonar-scanner -Dsonar.sources=. -Dsonar.exclusions=\"**/node_modules/**\"\n```\n\n## Tool Selection\n\n```python\nPRIORITY = {'python': ['vulture', 'deadcode'], 'javascript': ['knip']}\ntool = next((t for t in PRIORITY.get(lang, []) if t in available), 'heuristic')\n```\n\n## Confidence Boosting\n\nWhen heuristic and tool agree: boost confidence by 15% (max 95%)\n\n```yaml\n# Output format\nfile: src/utils/helpers.py\ntype: function\nname: calculate_legacy\nconfidence: 95%\nsources: [heuristic, vulture]\naction: DELETE\n```\n\n## Graceful Degradation\n\nNo tools? Fall back to `@module:code-bloat-patterns` heuristics.\n\n## Related\n- `code-bloat-patterns` - Heuristic fallbacks\n- `bloat-auditor` - Orchestrates tool execution\n\nFile v1.9.19:skill-card.md\n\n## Description:\n\nDetects codebase bloat via dead code, duplication, complexity, and documentation bloat scans.\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 maintainers use this skill to audit repositories for dead code, duplication, oversized files, stale documentation, dependency bloat, and growth trends before cleanup, refactoring, or release work.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Some scan snippets can overwrite fixed scratch files or include commands that remove temporary files while inspecting a repository.\n\nMitigation: Review commands before running them, especially on untrusted repositories, and replace fixed scratch paths with mktemp or private cache paths.\n\nRisk: The skill may label items as DELETE or safe to remove based on heuristic bloat signals.\n\nMitigation: Treat removal recommendations as review candidates only and require user approval before changing or deleting files.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-conserve-bloat-detector)\n- [Project homepage](https://github.com/athola/claude-night-market/tree/master/plugins/conserve)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, guidance]\n\n**Output Format:** [Markdown guidance with inline shell commands and YAML-style report examples]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Produces review-oriented findings and remediation recommendations; cleanup actions require user approval.]\n\n## Skill Version(s):\n\n1.9.19 (source: release evidence)\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: 11 files, 25008 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2120b), SKILL.md (5207b), _meta.json (146b)\n\nFile v1.9.17:SKILL.md\n\n---\nname: bloat-detector\ndescription: |\n  Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans\nversion: 1.9.8\ntriggers:\n  - bloat\n  - cleanup\n  - static-analysis\n  - technical-debt\n  - optimization\n  - codebase feels large or before a release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/conserve\", \"emoji\": \"\\ud83e\\udd9e\"}}\nsource: claude-night-market\nsource_plugin: conserve\n---\n\n> **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n# Bloat Detector\n\nSystematically detect and eliminate codebase bloat through progressive analysis tiers.\n\n## Bloat Categories\n\n| Category | Examples |\n|----------|----------|\n| **Code** | Dead code, God classes, Lava flow, duplication |\n| **AI-Generated** | Tab-completion bloat, vibe coding, hallucinated deps |\n| **Documentation** | Redundancy, verbosity, stale content, slop |\n| **Dependencies** | Unused imports, dependency bloat, phantom packages |\n| **Git History** | Stale files, low-churn code, massive single commits |\n\n## Quick Start\n\n### Tier 1: Quick Scan (2-5 min, no tools)\n```bash\n/bloat-scan\n```\nDetects: Large files, stale code, old TODOs, commented blocks, basic duplication\n\n### Tier 2: Targeted Analysis (10-20 min, optional tools)\n```bash\n/bloat-scan --level 2 --focus code   # or docs, deps\n```\nAdds: Static analysis (Vulture/Knip), git churn hotspots, doc similarity\n\n### Tier 3: Deep Audit (30-60 min, full tooling)\n```bash\n/bloat-scan --level 3 --report audit.md\n```\nAdds: Cross-file redundancy, dependency graphs, readability metrics\n\n## When To Use\n\n| Do | Don't |\n|----|-------|\n| Context usage > 30% | Active feature development |\n| Quarterly maintenance | Time-sensitive bugs |\n| Pre-release cleanup | Codebase < 1000 lines |\n| Before major refactoring | Tools unavailable (Tier 2/3) |\n\n## When NOT To Use\n\n- Active feature development\n- Time-sensitive bugs\n- Codebase < 1000 lines\n\n## Confidence Levels\n\n| Level | Confidence | Action |\n|-------|------------|--------|\n| HIGH | 90-100% | Safe to remove |\n| MEDIUM | 70-89% | Review first |\n| LOW | 50-69% | Investigate |\n\n## Prioritization\n\n```\nPriority = (Token_Savings × 0.4) + (Maintenance × 0.3) + (Confidence × 0.2) + (Ease × 0.1)\n```\n\n## Module Architecture\n\n**Tier 1** (always available):\n- See `modules/quick-scan.md` - Heuristics, no tools\n- See `modules/git-history-analysis.md` - Staleness, churn, vibe coding signatures\n- See `modules/growth-analysis.md` - Growth velocity, forecasts, threshold alerts\n\n**Tier 2** (optional tools):\n- See `modules/code-bloat-patterns.md` - Anti-patterns (God class, Lava flow)\n- See `modules/ai-generated-bloat.md` - AI-specific patterns (Tab bloat, hallucinations)\n- See `modules/documentation-bloat.md` - Redundancy, readability, slop detection\n- See `modules/static-analysis-integration.md` - Vulture, Knip\n\n**Shared**:\n- See `modules/remediation-types.md` - DELETE, REFACTOR, CONSOLIDATE, ARCHIVE\n\n## Ecosystem-Level Detection\n\nPatterns that span plugin boundaries or manifest configuration,\ndiscovered through ecosystem-wide audits.\n\n### `alwaysApply` Accumulation\n\nFlag plugins with 3+ skills where `alwaysApply: true`.\nEach always-on skill injects its full text into every session,\ncreating a baseline token floor before the user types anything.\nSum the `estimated_tokens` fields to report total per-session cost.\n\n### Hook Registration Gaps\n\nCompare hooks declared in `plugin.json` or `openpackage.yml`\nagainst entries in `hooks.json`. A hook present in `hooks.json`\nbut absent from the manifest is invisible to the plugin loader\nand cannot be audited, versioned, or disabled through normal\nplugin management.\n\n### Boilerplate Footer Detection\n\nScan skill files for identical multi-line text blocks repeated\nacross 10+ files (e.g., generic troubleshooting sections like\n\"Command not found / Permission errors / Unexpected behavior\").\nThese are copy-paste artifacts that inflate token cost without\nadding skill-specific value.\n\n### ToC Bloat in Skills\n\nSkills loaded into model context gain nothing from HTML-style\nTables of Contents. Detect `## Table of Contents` followed by\nbulleted anchor-link lists. These waste tokens since\nthe model reads sequentially, not via hyperlinks.\n\n### Unregistered Module Subdirectories\n\nCompare files on disk in `skills/*/modules/` against the\n`modules:` list in each skill's SKILL.md frontmatter. Files\nthat exist on disk but are not listed in the manifest are\ninvisible to progressive loading and may be dead weight or\nmissing from the load path.\n\n## Auto-Exclusions\n\nAlways excludes: `.venv`, `__pycache__`, `.git`, `node_modules`, `dist`, `build`, `vendor`\n\nAlso respects: `.gitignore`, `.bloat-ignore`\n\n## Safety\n\n- **Never auto-delete** - all changes require approval\n- **Dry-run support** - `--dry-run` for previews\n- **Backup branches** - created before bulk changes\n\n## Related\n\n- `bloat-auditor` agent - Executes scans\n- `unbloat-remediator` agent - Safe remediation\n- `context-optimization` skill - MECW principles\n\nFile v1.9.17:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-conserve-bloat-detector\",\n  \"version\": \"1.9.17\",\n  \"publishedAt\": 1785389517564\n}\n\nFile v1.9.17:modules/ai-generated-bloat.md\n\n---\nmodule: ai-generated-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 200\n---\n\n# AI-Generated Bloat Detection Module\n\nDetect bloat patterns specific to AI-assisted coding: vibe coding artifacts, slop patterns, and agent psychosis indicators.\n\n## Why This Module Exists\n\nAI coding has created qualitatively different bloat than traditional development:\n- **2024**: First year copy/pasted lines exceeded refactored lines (GitClear)\n- **Refactoring**: Dropped from 25% (2021) to <10% (2024), predicted 3% (2025)\n- **Duplication**: 8x increase in 5+ line code blocks\n\n## AI Bloat Patterns\n\n### 1. Tab-Completion Bloat (Repetitive Logic)\n\n**Definition**: Same pattern repeated 3+ times instead of abstracted into shared function.\n\n```bash\n# Detect similar code blocks (built-in, no external deps)\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5\n\n# JSON output for CI integration\npython3 plugins/conserve/scripts/detect_duplicates.py . --format json --threshold 15\n\n# Heuristic: functions with near-identical signatures\ngrep -rn \"^def \" --include=\"*.py\" . | cut -d: -f2 | sort | uniq -c | sort -rn | head -10\n```\n\n**Confidence**: HIGH (85%)\n**Action**: REFACTOR - extract to shared utility\n**Rationale**: AI suggests new implementations rather than reusing existing code\n\n### 2. Massive Single Commits (Vibe Coding Signature)\n\n**Definition**: Commits with >500 insertions, especially without proportional tests.\n\n```bash\n# Find vibe coding commits\ngit log --oneline --shortstat | grep -E \"[0-9]{3,} insertion\" | head -20\n\n# Commits with high insertion:deletion ratio (adding without cleanup)\ngit log --shortstat --pretty=format:\"%h %s\" | awk '/insertion|deletion/ {\n  ins=$4; del=$6;\n  if (ins > 200 && (del == \"\" || ins/del > 10)) print prev, ins, del\n} {prev=$0}'\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: INVESTIGATE - review for understanding gaps\n**Rationale**: Large additions without refactoring indicate Tab-driven development\n\n### 3. Hallucinated Dependencies\n\n**Definition**: Imports referencing non-existent packages (AI hallucination).\n\n```bash\n# Python: Check for uninstallable packages\npip freeze > /tmp/installed.txt\ngrep -rh \"^import \\|^from \" --include=\"*.py\" . | \\\n  sed 's/^import //;s/^from //;s/ import.*//' | \\\n  sort -u | while read pkg; do\n    root=$(echo $pkg | cut -d. -f1)\n    grep -q \"^$root\" /tmp/installed.txt || echo \"HALLUCINATED?: $pkg\"\n  done\n\n# JavaScript: Check for phantom packages\njq -r '.dependencies // {} | keys[]' package.json | while read pkg; do\n  npm view $pkg version 2>/dev/null || echo \"HALLUCINATED?: $pkg\"\ndone\n```\n\n**Confidence**: HIGH (95%)\n**Action**: DELETE or REPLACE\n**Rationale**: AI invents plausible-sounding packages (slopsquatting risk)\n\n### 4. Happy Path Only (Test Coverage Gap)\n\n**Definition**: Code >200 lines with no corresponding tests, or tests without error assertions.\n\n```bash\n# Files without test coverage\nfind . -name \"*.py\" ! -path \"*/test*\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c '\n  lines=$(wc -l < \"$1\")\n  if [ $lines -gt 200 ]; then\n    base=$(basename \"$1\" .py)\n    test_exists=$(find . -name \"test_${base}.py\" -o -name \"${base}_test.py\" \\\n      -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n      -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | head -1)\n    [ -z \"$test_exists\" ] && echo \"UNTESTED ($lines lines): $1\"\n  fi\n' _ {} \\;\n\n# Tests without error/exception assertions\ngrep -rL \"assert.*Error\\|assert.*Exception\\|pytest.raises\\|with self.assertRaises\" \\\n  --include=\"test_*.py\" .\n```\n\n**Confidence**: HIGH (90%)\n**Action**: AUGMENT_TESTS before adding more code\n**Rationale**: AI generates happy path; errors require human insight\n\n### 5. Premature Abstraction\n\n**Definition**: Base classes/interfaces with only 1-2 implementations.\n\n```bash\n# Python: Abstract classes 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  inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n  [ $inheritors -lt 2 ] && echo \"PREMATURE: $class in $f (${inheritors} inheritors)\"\ndone\n```\n\n**Confidence**: HIGH (85%)\n**Action**: INLINE - remove abstraction until 3rd use case\n**Rationale**: AI suggests \"scalable\" patterns for simple problems\n\n### 6. Enterprise Cosplay\n\n**Definition**: Microservices, Kubernetes, complex architecture for simple applications.\n\n```bash\n# Docker complexity for simple apps\nif [ -f docker-compose.yml ]; then\n  services=$(grep -c \"^  [a-z].*:$\" docker-compose.yml)\n  code_lines=$(find . \\( -name \"*.py\" -o -name \"*.js\" \\) \\\n    -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n    -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l 2>/dev/null | tail -1 | awk '{print $1}')\n  ratio=$((code_lines / services))\n  [ $ratio -lt 500 ] && echo \"ENTERPRISE_COSPLAY: $services services for $code_lines lines\"\nfi\n\n# Kubernetes for CRUD\n[ -d k8s ] && [ $(find . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l | tail -1 | awk '{print $1}') -lt 5000 ] && \\\n  echo \"ENTERPRISE_COSPLAY: Kubernetes for <5000 lines\"\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: SIMPLIFY - evaluate if complexity is justified\n**Rationale**: AI defaults to \"production-ready\" patterns without context\n\n### 7. Documentation Slop\n\n**Definition**: AI-generated docs with excessive hedging, formulaic structure, surface insights.\n\n```bash\n# Hedge word density (AI slop indicators)\nhedge_words=\"worth noting|arguably|to some extent|it's important|consider that|generally speaking\"\nfor f in $(find . -name \"*.md\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  total=$(wc -w < \"$f\")\n  hedges=$(grep -oiE \"$hedge_words\" \"$f\" | wc -l)\n  if [ $total -gt 100 ]; then\n    density=$((hedges * 1000 / total))\n    [ $density -gt 20 ] && echo \"DOC_SLOP ($density/1000): $f\"\n  fi\ndone\n```\n\n**Confidence**: MEDIUM (65%)\n**Action**: REWRITE with concrete specifics\n**Rationale**: AI safety training creates artificial hedging\n\n## Scoring\n\n```python\nAI_BLOAT_SCORES = {\n    'tab_completion_bloat': 25,\n    'massive_single_commit': 15,\n    'hallucinated_dependency': 35,\n    'happy_path_only': 30,\n    'premature_abstraction': 20,\n    'enterprise_cosplay': 25,\n    'documentation_slop': 10,\n}\n\ndef ai_bloat_score(detected_patterns):\n    return min(100, sum(AI_BLOAT_SCORES.get(p, 0) for p in detected_patterns))\n```\n\n## Integration with Existing Tiers\n\n**Tier 1 (Quick Scan)**: Massive single commits, hedge word density\n**Tier 2 (Targeted)**: Duplication ratio, test coverage gaps, premature abstraction\n**Tier 3 (Deep Audit)**: Hallucinated dependencies, enterprise cosplay analysis\n\n## Output Format\n\n```yaml\nfile: src/services/user_manager.py\nai_bloat_patterns:\n  - tab_completion_bloat\n  - happy_path_only\nai_bloat_score: 55/100\nindicators:\n  similar_blocks: 4\n  test_coverage: 0%\n  commit_size: 847 lines\nconfidence: HIGH\naction: REFACTOR + ADD_TESTS\nrationale: \"Vibe coding signature - large addition without tests or abstraction\"\n```\n\n## Prevention Recommendations\n\nWhen AI bloat is detected, recommend:\n\n1. **Refactoring Budget**: Add 25 lines of refactoring for every 100 lines added\n2. **Test Requirement**: No merge without proportional test coverage\n3. **Understanding Gate**: Require explanation of non-trivial changes\n4. **24-Hour Rule**: Sleep before adopting new AI-suggested patterns\n\n## Related\n\n- `code-bloat-patterns` - Traditional anti-patterns (God class, Lava flow)\n- `documentation-bloat` - Readability metrics\n- `imbue:anti-cargo-cult` - Understanding verification protocol\n- Knowledge corpus: `agent-psychosis-codebase-hygiene.md`\n\nFile v1.9.17:modules/code-bloat-patterns.md\n\n---\nmodule: code-bloat-patterns\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 150\n---\n\n# Code Bloat Patterns Module\n\nDetect anti-patterns using pattern recognition and heuristics. Works without external tools.\n\n> **Tool Preference (Claude Code 2.1.31+)**: The bash snippets in this module are reference implementations for external script execution or CI pipelines. When performing these analyses directly within Claude Code, prefer native tools: use Grep instead of `grep`, Glob instead of `find`, and Read instead of `cat`/`sed`.\n\n## Anti-Patterns\n\n### 1. God Class\n**Definition:** Single class with > 500 lines, > 10 methods, multiple responsibilities.\n\n```bash\n# Quick detection\nfind . -name \"*.py\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c 'lines=$(wc -l < \"$1\"); [ $lines -gt 500 ] && echo \"GOD_CLASS: $1 - $lines lines\"' _ {} \\;\n```\n**Confidence:** HIGH (85%) | **Action:** REFACTOR into focused modules\n\n### 2. Lava Flow\n**Definition:** Ancient untouched code - commented blocks, old TODOs.\n\n```bash\n# Find files with >20% commented code\ngrep -rn \"^#\\|^//\" --include=\"*.py\" . | cut -d: -f1 | sort | uniq -c | sort -rn | head -10\n```\n**Confidence:** HIGH (90%) | **Action:** DELETE commented code\n\n### 3. Dead Code\n**Detection:** Use static analysis (Vulture/Knip) or fallback heuristic:\n```bash\n# Heuristic: find functions with 0 calls\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  func=$(echo $line | awk '{print $2}' | cut -d'(' -f1)\n  [ $(git grep -c \"$func(\" 2>/dev/null || echo 0) -eq 1 ] && echo \"DEAD: $func\"\ndone\n```\n**Confidence:** MEDIUM (70%) heuristic, HIGH (90%) with tools | **Action:** DELETE\n\n### 4. Import Bloat\n```bash\n# Star imports (block tree-shaking)\ngrep -rn \"^from .* import \\*\" --include=\"*.py\" .\n\n# Unused imports (requires autoflake)\nautoflake --check --remove-all-unused-imports -r .\n```\n**Confidence:** HIGH (95%) | **Action:** Fix imports\n\n### 5. Duplication\n**Intra-file:** Hash-based block detection (5+ line matches)\n**Cross-file:** Function signature matching\n**Semantic:** AST comparison (80%+ similarity)\n\n**Confidence:** HIGH (85%) | **Action:** EXTRACT to shared utility\n\n## Language-Specific\n\n### Python\n- Circular imports: Files with 20+ imports\n- Deep nesting: > 4 indentation levels\n\n### JavaScript/TypeScript\n- Barrel files: `export * from` breaks tree-shaking\n- CommonJS in ESM: `module.exports`/`require()` blocks bundler optimization\n\n## AI-Amplified Patterns\n\nThese traditional patterns are amplified by AI coding tools:\n\n### 6. Tab-Completion Duplication\n**Definition:** AI suggests similar code blocks instead of reusing existing functions.\n**2024 Data:** 8x increase in 5+ line duplicated blocks (GitClear)\n\n```bash\n# Quick detection: near-identical function signatures\ngrep -rn \"^def \" --include=\"*.py\" . | awk -F'def ' '{print $2}' | \\\n  cut -d'(' -f1 | sort | uniq -c | sort -rn | awk '$1 > 1'\n```\n**Confidence:** HIGH (85%) | **Action:** EXTRACT shared utility\n\n### 7. Dead Wrapper / Facade Bloat\n**Definition:** Modules that wrap existing functionality without adding meaningful logic — thin facades, unused service interfaces, or re-export layers with no consumers.\n\n**Signals:**\n- File imports from another internal module and re-exports similar API\n- No external imports of the wrapper (0 refs from outside itself)\n- Not a proper package (missing `__init__.py` for Python)\n- Docstring examples show imports but no actual code uses them\n- Functionality already exists in the wrapped module or in `examples/`\n\n```bash\n# Find Python files that only re-export from other internal modules\nfor f in $(find . -name \"*.py\" -not -path \"*/test*\" -not -path \"*/__pycache__/*\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  # Check if file mostly imports and re-calls another module's functions\n  imports=$(grep -c \"^from \\.\\.\" \"$f\" 2>/dev/null || echo 0)\n  total=$(wc -l < \"$f\" 2>/dev/null || echo 0)\n  refs=$(git grep -l \"$(basename \"$f\" .py)\" -- \"*.py\" 2>/dev/null | grep -v \"$f\" | wc -l)\n  if [ \"$imports\" -gt 2 ] && [ \"$refs\" -eq 0 ] && [ \"$total\" -gt 50 ]; then\n    echo \"DEAD_WRAPPER: $f ($total lines, $imports internal imports, 0 external refs)\"\n  fi\ndone\n```\n\n**Also check for intra-file dead wrappers:**\n```bash\n# Find classes/functions that only delegate to another method with no transformation\ngrep -rn \"def .*self\" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  lineno=$(echo \"$line\" | cut -d: -f2)\n  # Check if function body is just \"return self.other_thing(...)\"\n  body=$(sed -n \"$((lineno+1)),$((lineno+3))p\" \"$file\" 2>/dev/null)\n  if echo \"$body\" | grep -qP '^\\s+return self\\.\\w+\\(' && [ $(echo \"$body\" | wc -l) -le 2 ]; then\n    echo \"PASSTHROUGH: $file:$lineno - trivial delegation\"\n  fi\ndone\n```\n\n**Confidence:** HIGH (85%) for whole-file wrappers, MEDIUM (70%) for intra-file passthrough\n**Action:** DELETE (whole-file) or INLINE (intra-file passthrough)\n\n### 8. Premature Abstraction\n**Definition:** Base classes/interfaces with <3 implementations (YAGNI violation).\n**AI Cause:** AI defaults to \"scalable\" patterns without context.\n\n```bash\n# Find abstract classes with few inheritors\ngrep -rln \"ABC\\|abstractmethod\" --include=\"*.py\" . | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ $(grep -rc \"($class)\" --include=\"*.py\" . 2>/dev/null) -lt 3 ] && echo \"PREMATURE: $class\"\ndone\n```\n**Confidence:** HIGH (80%) | **Action:** INLINE until 3rd use case\n\n### 9. Happy Path Bias\n**Definition:** Tests verify success paths only; no error handling tested.\n**AI Cause:** AI optimizes for \"works\" demonstrations.\n\n```bash\n# Tests without error assertions\ngrep -rL \"Error\\|Exception\\|raises\\|fail\\|invalid\" --include=\"test_*.py\" .\n```\n**Confidence:** MEDIUM (70%) | **Action:** ADD error path tests\n\nFor comprehensive AI-specific patterns, see: `@module:ai-generated-bloat`\n\n## Scoring\n\n```python\nPATTERN_SCORES = {\n    'god_class': 30, 'lava_flow': 25, 'dead_code': 35,\n    'import_bloat': 15, 'duplication': 20, 'dead_wrapper': 30\n}\nscore = min(100, sum(PATTERN_SCORES[p] for p in detected))\n```\n\n## Output Format\n\n```yaml\nfile: src/legacy/manager.py\npatterns: [god_class, lava_flow, import_bloat]\nbloat_score: 85/100\nconfidence: HIGH\ntoken_estimate: ~3,400\naction: REFACTOR\n```\n\nAll actions require user approval.\n\nFile v1.9.17:modules/documentation-bloat.md\n\n---\nmodule: documentation-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 120\n---\n\n# Documentation Bloat Module\n\nDetect documentation redundancy, verbosity, and poor readability.\n\n## Detection Categories\n\n### 1. Duplicate Documentation\n\n#### Cross-File (Jaccard Similarity)\n```bash\n# Quick similarity check between two files\nwords1=$(tr '[:space:]' '\\n' < file1.md | sort -u)\nwords2=$(tr '[:space:]' '\\n' < file2.md | sort -u)\n# > 70% overlap = potential duplication\n```\n\n| Similarity | Confidence | Action |\n|------------|------------|--------|\n| > 90% | HIGH (95%) | DELETE one, keep recent |\n| 70-90% | MEDIUM (80%) | MERGE, preserve unique |\n| 50-70% | LOW (60%) | CROSS-LINK |\n\n#### Intra-File (Section Hashing)\nHash each `##` section's normalized content. Duplicates = repeated sections.\n\n**Confidence:** HIGH (85%)\n\n### 2. Excessive Verbosity\n\n| Metric | Threshold | Action |\n|--------|-----------|--------|\n| Word count | > 500 words/section | Condense |\n| Sentence length | > 25 words avg | Simplify |\n| Passive voice | > 30% | Rewrite active |\n| Readability | Flesch < 40 | Simplify |\n\n```bash\n# Quick verbosity check\nwc -w file.md  # Total words\nrg -c '\\.' file.md  # Approximate sentences (or grep -c)\n```\n\n### 3. Stale Documentation\n\n| Signal | Confidence | Action |\n|--------|------------|--------|\n| Unchanged 12+ months | HIGH (85%) | Review/Archive |\n| References deleted code | HIGH (90%) | Update/Delete |\n| No git activity | MEDIUM (75%) | Investigate |\n\n```bash\n# Find stale docs\ngit log -1 --format=\"%ar\" -- docs/*.md | rg -E \"year|months\"\n# fallback: grep -E \"year|months\"\n```\n\n### 4. Missing/Outdated References\n\n- Broken internal links: `rg -oP '\\[.*?\\]\\((?!http).*?\\)' *.md` (or `grep -oP`)\n- References to deleted files\n- Outdated API examples\n\n**Confidence:** HIGH (90%) for broken links\n\n## Scoring\n\n```python\ndef doc_bloat_score(metrics):\n    score = 0\n    if metrics['duplicate_ratio'] > 0.3: score += 30\n    if metrics['avg_words_per_section'] > 500: score += 20\n    if metrics['readability'] < 40: score += 15\n    if metrics['stale_months'] > 12: score += 25\n    return min(100, score)\n```\n\n## Output Format\n\n```yaml\nfile: docs/old-guide.md\nbloat_type: [duplicate, verbose, stale]\nbloat_score: 72/100\nconfidence: HIGH\ntoken_estimate: ~1,200\nsimilar_to: docs/guide.md (87%)\naction: MERGE\n```\n\n## Related\n- `quick-scan` - Tier 1 stale detection\n- `git-history-analysis` - Activity signals\n\nFile v1.9.17:modules/git-history-analysis.md\n\n---\nmodule: git-history-analysis\ncategory: tier-1\ndependencies: [Bash, Grep]\nestimated_tokens: 250\n---\n\n# Git History Analysis Module\n\nDetect bloat using git history: staleness, churn metrics, and reference counting.\n\n## Core Techniques\n\n### 1. Staleness Detection\n\n**Command:**\n```bash\n# Files not modified in last 6 months\ngit log --since=\"6 months ago\" --name-only --pretty=format: | sort -u > recent.txt\ncomm -13 recent.txt <(git ls-files | sort) > stale_files.txt\n```\n\n**Staleness Scoring:**\n```python\ndef staleness_score(months_since_change):\n    if months_since_change > 24:\n        return 95  # Almost certainly abandoned\n    elif months_since_change > 12:\n        return 85  # Likely abandoned\n    elif months_since_change > 6:\n        return 65  # Possibly stale\n    else:\n        return 20  # Active\n```\n\n**Confidence Modifiers:**\n- File type: Config files -20%, code files +0%\n- Last author: If single author who left project +15%\n- Dependencies: If no imports found +25%\n\n### 2. Reference Counting\n\n**Detect unused files:**\n```bash\n# For each file, count references in codebase\ngit ls-files | while read file; do\n  filename=$(basename \"$file\")\n  refs=$(git grep -l \"$filename\" | wc -l)\n  if [ $refs -eq 1 ]; then  # Only self-reference\n    echo \"0 $file\"\n  else\n    echo \"$((refs - 1)) $file\"  # Subtract self\n  fi\ndone | grep \"^0 \"\n```\n\n**Confidence:** HIGH (90%) if zero refs and stale\n\n**False Positives:**\n- Entry points (main.py, index.js)\n- Configuration files\n- Documentation\n\n### 3. Code Churn Metrics\n\n**Churn formula:**\n```bash\n# Lines added + deleted per file\ngit log --numstat --pretty=\"%H\" -- $file | \\\n  awk '{added+=$1; deleted+=$2} END {print added+deleted}'\n```\n\n**Churn Categories:**\n- **High churn (>1000 changes/year)**: Active development\n- **Low churn (<50 changes/year)**: Stable or abandoned\n- **Zero churn + old**: Strong bloat signal\n\n**Filter out cleanup-churn (release sweeps, frontmatter-only edits):**\n\nA naive commit count over-flags files swept by repo-wide release\noperations (version bumps, frontmatter additions). Filter to commits\nthat made substantive changes to the file under analysis.\n\n```bash\n# Count only commits with >5 line net change in the file\ngit log --numstat --pretty=tformat:%H -- \"$file\" | \\\n  awk '/^[0-9]/ && ($1 + $2) > 5 { count++ } END { print count }'\n```\n\nCompare against the unfiltered count: if `substantive_count <\ntotal_count / 3`, the file is **cleanup-churn** not **design churn**.\nDowngrade the thrashing/hotspot signal in that case.\n\nWorked example: `rigorous-reasoning/SKILL.md` showed 12 commits in 30\ndays. After filtering for substantive body changes (`>5` line net),\nonly 1 commit remained. The rest were repo-wide frontmatter sweeps\n(version bumps, tag adds, description tweaks). This file is NOT a\nthrashing hotspot; the signal was a false positive from cleanup-churn.\n\n**Hotspot Detection:**\n```python\ndef is_hotspot(churn, complexity):\n    \"\"\"\n    Hotspot = High churn × High complexity\n    Indicates technical debt accumulation\n    \"\"\"\n    churn_score = normalize_churn(churn)\n    complexity_score = cyclomatic_complexity(file)\n    return churn_score * complexity_score > threshold\n```\n\n### 4. Ownership Analysis\n\n**Detect abandoned code:**\n```bash\n# Find files where primary author has no recent commits\ngit log --format=\"%an\" --since=\"6 months ago\" | sort -u > active_authors.txt\n\ngit ls-files | while read file; do\n  primary_author=$(git log --format=\"%an\" -- \"$file\" | sort | uniq -c | sort -rn | head -1 | awk '{$1=\"\"; print $0}' | sed 's/^ //')\n  if ! grep -qF \"$primary_author\" active_authors.txt; then\n    echo \"$file - Primary author inactive: $primary_author\"\n  fi\ndone\n```\n\n**Confidence:** MEDIUM (70%) - Ownership transfer is possible\n\n### 5. Branch Analysis\n\n**Detect orphaned feature branches:**\n```bash\n# Branches not merged in 6+ months\ngit for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)' | \\\n  while read date branch; do\n    age_days=$(( ($(date +%s) - $(date -d \"$date\" +%s)) / 86400 ))\n    if [ $age_days -gt 180 ]; then\n      echo \"$branch - ${age_days} days old\"\n    fi\n  done\n```\n\n**Action:** Suggest cleanup or archival\n\n## Integrated Analysis\n\n### Multi-Signal Validation\n\nCombine signals for higher confidence:\n\n```python\ndef calculate_bloat_confidence(file):\n    signals = []\n\n    # Staleness\n    months = months_since_last_change(file)\n    if months > 12:\n        signals.append(('stale', 85, months))\n\n    # No references\n    refs = count_references(file)\n    if refs == 0:\n        signals.append(('unused', 90, refs))\n\n    # Low churn\n    churn = calculate_churn(file)\n    if churn < 50:  # < 50 changes/year\n        signals.append(('low_churn', 70, churn))\n\n    # Inactive owner\n    if is_owner_inactive(file):\n        signals.append(('inactive_owner', 65, None))\n\n    # Combined confidence\n    if len(signals) >= 3:\n        return 'HIGH', signals\n    elif len(signals) == 2:\n        return 'MEDIUM', signals\n    else:\n        return 'LOW', signals\n```\n\n### Example Output\n\n```yaml\nfile: src/deprecated/old_api.py\nconfidence: HIGH\nsignals:\n  - type: stale\n    score: 85\n    detail: 18 months since last change\n  - type: unused\n    score: 90\n    detail: Zero references found\n  - type: low_churn\n    score: 70\n    detail: 12 changes in last year\ncombined_score: 82\nrecommendation: DELETE\nrationale: |\n  Multiple strong signals indicate abandonment:\n  - No changes in 18 months\n  - No code references\n  - Minimal historical activity\n  Safe to remove with archival backup.\n```\n\n## AskGit Integration (Optional)\n\nIf AskGit is available, use SQL for advanced queries:\n\n```sql\n-- Find files with high churn but low recent activity\nSELECT\n  file_path,\n  SUM(additions + deletions) as total_churn,\n  MAX(author_when) as last_change\nFROM commits\nWHERE author_when < date('now', '-6 months')\nGROUP BY file_path\nHAVING total_churn > 1000\nORDER BY total_churn DESC;\n```\n\n## Performance Optimization\n\n**Caching Strategy:**\n```bash\n# Cache git log results for reuse\ngit log --all --numstat --pretty=format:'%H|%an|%ai' > /tmp/git_cache.txt\n\n# Query cache instead of running git log repeatedly\ngrep \"path/to/file\" /tmp/git_cache.txt\n```\n\n**Incremental Updates:**\n- Store previous scan results\n- Only analyze changed files\n- Delta reporting\n\n## Safety Checks\n\nBefore flagging for deletion:\n\n1. **Test Files**: Exclude `test_*.py`, `*.spec.js`\n2. **Migrations**: Database migrations must never auto-delete\n3. **CI/CD**: Files in `.github/`, `.gitlab-ci.yml`\n4. **Documentation**: User-facing docs need manual review\n\n**Whitelist Patterns:**\n```yaml\nsafe_paths:\n  - tests/\n  - migrations/\n  - .github/\n  - docs/api/  # API docs are references, not code\n\nexcluded_from_bloat_analysis:\n  # Cache directories (always exclude from counts)\n  - .venv/\n  - venv/\n  - __pycache__/\n  - .pytest_cache/\n  - .mypy_cache/\n  - .ruff_cache/\n  - .tox/\n  - .git/\n  # Dependencies and build artifacts\n  - node_modules/\n  - vendor/\n  - dist/\n  - build/\n```\n\n## Integration with Quick Scan\n\nGit analysis validates quick scan findings:\n\n```python\ndef validate_quick_scan_finding(finding):\n    # Quick scan says file is bloated\n    # Git analysis confirms or refutes\n    git_score = analyze_git_history(finding.file)\n\n    if quick_scan.score > 80 and git_score > 80:\n        return 'HIGH_CONFIDENCE'\n    elif quick_scan.score > 60 and git_score > 60:\n        return 'MEDIUM_CONFIDENCE'\n    else:\n        return 'LOW_CONFIDENCE'  # Conflicting signals\n```\n\n## Next Steps\n\nBased on git analysis:\n- **HIGH confidence**: Create cleanup PR\n- **MEDIUM confidence**: Run static analysis (Tier 2)\n- **LOW confidence**: Manual code review\n\nFile v1.9.17:modules/growth-analysis.md\n\n---\nmodule: growth-analysis\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 1500\n---\n\n# Growth Analysis Module\n\nTrack codebase growth velocity using git history.\nForecast future size, predict threshold crossings,\nand rank directories by urgency.\n\nThis module replaces the former standalone\n`/analyze-growth` command (removed in v1.6.0).\nIt runs as part of `/bloat-scan --growth`.\n\n## When to Load\n\nLoad this module when:\n\n- Running `/bloat-scan --growth`\n- Investigating rapid file or line count increases\n- Planning capacity for skill files approaching token limits\n- Preparing quarterly growth reports\n\n## Core Metrics\n\n### 1. File Count Velocity\n\nTrack how fast new files appear in a directory tree.\n\n```bash\n# File count per week for the last 8 weeks\nfor i in $(seq 0 7); do\n  date=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --until=\"$date\" --diff-filter=A \\\n    --name-only --pretty=format: -- \"$TARGET_DIR\" | \\\n    sort -u | wc -l)\n  echo \"$date $count\"\ndone | sort\n```\n\n**Output columns:** date, cumulative file count\n\n### 2. Line Count Velocity\n\nMeasure net line growth over recent commits.\n\n```bash\n# Net lines added per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  git log --since=\"$start\" --until=\"$end\" \\\n    --numstat --pretty=format: -- \"$TARGET_DIR\" | \\\n    awk '{added+=$1; deleted+=$2}\n      END {print added - deleted}'\ndone\n```\n\n**Negative values** indicate shrinkage (good after cleanup).\n\n### 3. Commit Frequency\n\nCount commits touching a path over rolling windows.\n\n```bash\n# Commits per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --since=\"$start\" --until=\"$end\" \\\n    --oneline -- \"$TARGET_DIR\" | wc -l)\n  echo \"week-$i: $count commits\"\ndone\n```\n\n### 4. Size Snapshot\n\nCurrent state measurement for the target path.\n\n```bash\n# Total lines in tracked files (exclude cache dirs)\ngit ls-files -- \"$TARGET_DIR\" | \\\n  grep -v -E '(\\.venv|__pycache__|node_modules|\\.git)' | \\\n  xargs wc -l 2>/dev/null | tail -1\n```\n\n## 30-Day Forecast\n\nUse simple linear regression on the last 8 weekly\ndata points to project 30 days forward.\n\n### Algorithm\n\n```python\ndef forecast_30d(weekly_counts):\n    \"\"\"\n    Linear least-squares fit on weekly data.\n    Returns projected value 4.3 weeks from now.\n    \"\"\"\n    n = len(weekly_counts)\n    if n < 3:\n        return None  # Not enough data\n\n    xs = list(range(n))\n    x_mean = sum(xs) / n\n    y_mean = sum(weekly_counts) / n\n\n    numerator = sum(\n        (x - x_mean) * (y - y_mean)\n        for x, y in zip(xs, weekly_counts)\n    )\n    denominator = sum((x - x_mean) ** 2 for x in xs)\n\n    if denominator == 0:\n        return y_mean  # Flat line\n\n    slope = numerator / denominator\n    intercept = y_mean - slope * x_mean\n\n    # 30 days = ~4.3 weeks beyond last data point\n    future_x = (n - 1) + 4.3\n    return slope * future_x + intercept\n```\n\n### Interpreting Forecasts\n\n- **Slope > 0**: Growing. Report weekly rate.\n- **Slope ~ 0**: Stable. No action needed.\n- **Slope < 0**: Shrinking. Recent cleanup likely working.\n\nReport the R-squared value when possible.\nLow R-squared (< 0.5) means the trend is noisy\nand the forecast is unreliable.\n\n## Threshold Crossing Predictions\n\nGiven a target limit (e.g., 500-line skill file limit),\ncalculate when the current growth rate will cross it.\n\n### Algorithm\n\n```python\ndef weeks_until_threshold(current_size, weekly_rate, limit):\n    \"\"\"\n    Returns weeks until current_size reaches limit\n    at the given weekly_rate.\n    Returns None if rate <= 0 (will never cross).\n    \"\"\"\n    if weekly_rate <= 0:\n        return None\n    remaining = limit - current_size\n    if remaining <= 0:\n        return 0  # Already exceeded\n    return remaining / weekly_rate\n```\n\n### Default Thresholds\n\n| Target | Limit | Rationale |\n|--------|-------|-----------|\n| Skill file | 500 lines | Progressive loading boundary |\n| Module file | 300 lines | Single-responsibility cap |\n| Python source | 500 lines | God class indicator |\n| Markdown doc | 300 lines | Reader attention limit |\n\nOverride thresholds with `--threshold <lines>`.\n\n## Urgency Rankings\n\nRank directories or files by how soon they will\nneed attention.\n\n### Scoring Formula\n\n```\nurgency = growth_rate * (current_size / threshold) * recency_weight\n```\n\nWhere:\n\n- `growth_rate`: Lines per week (normalized 0-1)\n- `current_size / threshold`: How close to the limit (0-1+)\n- `recency_weight`: 1.5 if accelerating, 1.0 if steady,\n  0.5 if decelerating\n\n### Urgency Categories\n\n| Category | Score Range | Action |\n|----------|------------|--------|\n| Critical | > 0.8 | Modularize or split now |\n| High | 0.5 - 0.8 | Plan optimization this sprint |\n| Medium | 0.2 - 0.5 | Add to backlog |\n| Low | < 0.2 | No action needed |\n\n### Acceleration Detection\n\nCompare the growth rate of the last 4 weeks against\nthe preceding 4 weeks.\n\n```python\ndef detect_acceleration(weekly_rates):\n    if len(weekly_rates) < 8:\n        return \"insufficient_data\"\n    recent = sum(weekly_rates[-4:]) / 4\n    earlier = sum(weekly_rates[-8:-4]) / 4\n    if earlier == 0:\n        return \"new_growth\" if recent > 0 else \"stable\"\n    ratio = recent / earlier\n    if ratio > 1.5:\n        return \"accelerating\"\n    elif ratio < 0.5:\n        return \"decelerating\"\n    return \"steady\"\n```\n\n## Output Format\n\n### Terminal Report\n\n```\n=== Growth Analysis: plugins/conserve/skills/ ===\n\nCurrent State:\n  Files:  47\n  Lines:  8,234\n  Avg:    175 lines/file\n\n30-Day Forecast:\n  Files:  +5  (52 projected)\n  Lines:  +820 (9,054 projected)\n  Rate:   ~205 lines/week\n\nThreshold Alerts:\n  bloat-detector/SKILL.md    412/500 lines  ~4 weeks to limit\n  context-optimization.md    289/300 lines  ~1 week to limit  [!]\n\nUrgency Rankings:\n  [CRITICAL] context-optimization.md   0.92\n  [HIGH]     bloat-detector/SKILL.md   0.67\n  [MEDIUM]   token-conservation.md     0.34\n  [LOW]      performance-monitoring.md 0.11\n```\n\n### Machine-Readable Output\n\n```yaml\ngrowth_analysis:\n  target: plugins/conserve/skills/\n  snapshot:\n    files: 47\n    lines: 8234\n    date: \"2026-03-10\"\n  forecast_30d:\n    files: 52\n    lines: 9054\n    confidence: 0.78\n  weekly_rate:\n    files: 1.2\n    lines: 205\n  threshold_alerts:\n    - path: context-optimization.md\n      current: 289\n      limit: 300\n      weeks_remaining: 1\n      urgency: critical\n    - path: bloat-detector/SKILL.md\n      current: 412\n      limit: 500\n      weeks_remaining: 4\n      urgency: high\n  rankings:\n    - path: context-optimization.md\n      urgency: 0.92\n      category: critical\n      acceleration: accelerating\n    - path: bloat-detector/SKILL.md\n      urgency: 0.67\n      category: high\n      acceleration: steady\n```\n\n## Integration with Bloat Scan\n\nGrowth analysis feeds into the bloat detection pipeline:\n\n- **Fast-growing files** get flagged for proactive review\n  before they become bloated\n- **Threshold alerts** trigger modularization suggestions\n  from the `remediation-types` module\n- **Urgency rankings** prioritize the bloat scan report's\n  findings list\n\n### Coordination with Other Modules\n\n- `quick-scan`: Growth data adds time dimension to\n  size-based findings\n- `git-history-analysis`: Shares git log data;\n  growth-analysis focuses on trends while\n  git-history focuses on staleness and churn\n- `remediation-types`: Growth-triggered items map to\n  REFACTOR (split) or ARCHIVE (stabilize) actions\n\n## Limitations\n\n- Requires at least 3 weeks of git history for\n  meaningful forecasts\n- Linear projection does not capture seasonal patterns\n  or burst development cycles\n- Merge commits can skew line counts; use `--no-merges`\n  when possible\n- Renamed files appear as delete + add, inflating\n  apparent growth\n\nFile v1.9.17:modules/quick-scan.md\n\n---\nmodule: quick-scan\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 200\n---\n\n# Quick Scan Module\n\nFast heuristic-based bloat detection without external tools. Completes in < 5 minutes.\n\n## Detection Patterns\n\n### 1. Large Files (God Class Candidates)\n\n```bash\n# Find files > 500 lines (excluding cache and dependency directories)\nfind . -type f \\( -name \"*.py\" -o -name \"*.js\" -o -name \"*.ts\" \\) \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/node_modules/*\" \\\n  -not -path \"*/.git/*\" \\\n  -not -path \"*/dist/*\" \\\n  -not -path \"*/build/*\" \\\n  -not -path \"*/.tox/*\" \\\n  -not -path \"*/.mypy_cache/*\" \\\n  -not -path \"*/.ruff_cache/*\" | \\\nwhile read f; do\n  lines=$(wc -l < \"$f\")\n  if [ $lines -gt 500 ]; then\n    echo \"$lines $f\"\n  fi\ndone | sort -rn\n```\n\n**Thresholds:**\n- Python: > 500 lines (God class likely)\n- JavaScript/TypeScript: > 400 lines\n- Markdown: > 300 lines (bloated docs)\n\n**Confidence:** MEDIUM (70%) - Large size suggests but doesn't confirm bloat\n\n### 2. Stale Files (Lava Flow)\n\n```bash\n# Files unchanged in 6+ months\ngit log --since=\"6 months ago\" --name-only --pretty=format: | \\\n  sort -u > recent_files.txt\n\ngit ls-files | while read f; do\n  if ! grep -qxF \"$f\" recent_files.txt; then\n    last_modified=$(git log -1 --format=\"%ai\" -- \"$f\")\n    echo \"$last_modified $f\"\n  fi\ndone | sort\n\nrm recent_files.txt\n```\n\n**Thresholds:**\n- > 12 months: HIGH confidence (95%)\n- 6-12 months: MEDIUM confidence (75%)\n- 3-6 months: LOW confidence (50%)\n\n**False Positives:** Stable libraries, configuration files (check `.bloat-ignore`)\n\n### 3. Commented Code Blocks\n\n```bash\n# Find large commented code blocks (Python)\ngrep -rn \"^#.*def \\|^#.*class \\|^#.*import \" --include=\"*.py\" . | \\\n  awk '{print $1}' | uniq -c | sort -rn\n\n# JavaScript/TypeScript\ngrep -rn \"^//.*function \\|^//.*class \\|^//.*import \" --include=\"*.js\" --include=\"*.ts\" . | \\\n  awk '{print $1}' | uniq -c | sort -rn\n```\n\n**Confidence:** HIGH (90%) - Commented code is rarely needed\n\n### 4. Old TODOs/FIXMEs\n\n```bash\n# Find TODOs with dates > 3 months old\ngrep -rn \"TODO\\|FIXME\\|HACK\" --include=\"*.py\" --include=\"*.js\" --include=\"*.ts\" --include=\"*.md\" . | \\\n  grep -E \"[0-9]{4}-[0-9]{2}\" | \\\n  while read line; do\n    # Extract date and compare (simplified - actual implementation would parse dates)\n    echo \"$line\"\n  done\n```\n\n**Thresholds:**\n- > 12 months: Remove or convert to issue\n- 6-12 months: Review for relevance\n- 3-6 months: Monitor\n\n**Confidence:** MEDIUM (70%) - Context-dependent\n\n### 5. Duplicate Patterns\n\n```bash\n# Find potential duplicate files by name similarity (excluding cache directories)\nfind . -type f \\( -name \"*.py\" -o -name \"*.js\" -o -name \"*.ts\" \\) \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/node_modules/*\" \\\n  -not -path \"*/.git/*\" | \\\n  sed 's/.*\\///' | sort | uniq -d\n\n# Find duplicate files by content hash (excluding cache directories)\nfind . -type f -name \"*.py\" \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -not -path \"*/.git/*\" \\\n  -exec md5sum {} \\; | \\\n  sort | uniq -w32 -D | cut -d' ' -f3-\n```\n\n**Confidence:** LOW (60%) - Needs manual review, may be intentional\n\n## Scoring Algorithm\n\n```python\ndef calculate_quick_scan_score(file_path, metrics):\n    score = 0\n\n    # Size penalty\n    if metrics['lines'] > 500:\n        score += (metrics['lines'] - 500) / 100 * 10\n\n    # Staleness penalty\n    months_unchanged = metrics['months_since_change']\n    if months_unchanged > 12:\n        score += 30  # High penalty\n    elif months_unchanged > 6:\n        score += 15  # Medium penalty\n\n    # Commented code penalty\n    commented_lines = metrics['commented_code_lines']\n    score += commented_lines * 0.5\n\n    # Old TODOs\n    old_todos = metrics['todos_older_than_6mo']\n    score += old_todos * 2\n\n    # Normalize to 0-100\n    return min(score, 100)\n```\n\n## Output Format\n\n```yaml\nfile: path/to/bloated_file.py\nbloat_score: 85\nconfidence: MEDIUM\nsignals:\n  - large_file: 847 lines (threshold: 500)\n  - stale: 18 months unchanged\n  - commented_code: 23 lines\n  - old_todos: 3 (oldest: 14 months)\ntoken_estimate: ~3,200 tokens\nrecommendations:\n  - action: DELETE\n    rationale: No recent usage, high bloat score\n    safety: Check for external references first\n  - action: ARCHIVE\n    rationale: Preserve history without active maintenance\n    location: archive/legacy/\n```\n\n## Integration with Git Analysis\n\nQuick scan coordinates with `git-history-analysis` module:\n- Quick scan identifies candidates\n- Git analysis validates with reference counting\n- Combined confidence: HIGHER than either alone\n\n## Performance\n\n- **Target**: < 5 minutes for 10,000 files\n- **Method**: Parallel grep, minimal disk I/O\n- **Optimization**: Cache git log results, reuse across scans\n\n## False Positive Handling\n\nRespect `.bloat-ignore` patterns:\n\n```gitignore\n# .bloat-ignore - Patterns to exclude from bloat detection\n\n# Cache directories (should always be excluded)\n.venv/\nvenv/\n__pycache__/\n.pytest_cache/\n.mypy_cache/\n.ruff_cache/\n.tox/\n.git/\n\n# Build and distribution\ndist/\nbuild/\n*.egg-info/\n\n# Dependencies\nnode_modules/\nvendor/\n\n# IDE and editor\n.vscode/\n.idea/\n\n# Test fixtures and templates\ntests/fixtures/*\nconfig/*.template\n\n# Auto-generated code\ngenerated/*\n*_pb2.py\n```\n\n**Default Exclusions**: The scan tools should automatically exclude common cache directories even without a `.bloat-ignore` file.\n\n## Next Steps After Quick Scan\n\nBased on findings:\n- **High-confidence**: Proceed with cleanup\n- **Medium-confidence**: Run Tier 2 for validation\n- **Low-confidence**: Manual review required\n\nFile v1.9.17:modules/remediation-types.md\n\n---\nmodule: remediation-types\ncategory: remediation\ndependencies: []\nestimated_tokens: 150\n---\n\n# Remediation Types\n\nShared definitions for bloat remediation actions used by unbloat command and unbloat-remediator agent.\n\n## DELETE (Dead Code Removal)\n\nRemove files with high confidence they're unused:\n- 0 references (git grep, static analysis)\n- Stale (> 6 months unchanged)\n- High confidence (> 90%)\n- Non-core files\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | deprecated/*, test files, archive/*, 0 refs, 95%+ confidence |\n| MEDIUM | 1-2 refs, 85-94% confidence |\n| HIGH | >2 refs, <85% confidence, core infrastructure |\n\n## REFACTOR (Split God Classes)\n\nBreak large, low-cohesion files into focused modules:\n- Large files (> 500 lines)\n- Multiple responsibilities (low cohesion)\n- High cyclomatic complexity\n- Active usage (recent changes)\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Utilities, helpers, pure functions, < 3 import sites |\n| MEDIUM | Services, handlers, 3-10 import sites |\n| HIGH | Core modules, frameworks, > 10 import sites |\n\n## CONSOLIDATE (Merge Duplicates)\n\nMerge duplicate or redundant content:\n- Documentation with > 85% similarity\n- Duplicate code patterns\n- Multiple versions of same concept\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Docs, examples, pure duplication |\n| MEDIUM | Utilities with slight variations |\n| HIGH | Business logic, different contexts |\n\n## ARCHIVE (Move to Archive)\n\nMove stale but historically valuable content:\n- Old tutorials, examples\n- Deprecated but referenced\n- Historical documentation\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | Examples, tutorials, < 5 refs |\n| MEDIUM | Guides, how-tos, 5-10 refs |\n| HIGH | Core docs, > 10 refs |\n\n## INLINE (Remove Dead Wrappers)\n\nReplace thin facades and passthrough functions with direct usage of the underlying implementation:\n- Whole-file wrappers with 0 external consumers → DELETE\n- Intra-file passthrough methods that only delegate → INLINE callers to use wrapped method directly\n- Re-export layers where examples/ already demonstrates the same API\n\n**Risk Assessment:**\n| Risk | Criteria |\n|------|----------|\n| LOW | 0 external refs, wrapper adds no logic, underlying module is stable |\n| MEDIUM | 1-2 refs, wrapper adds minor convenience (default args, error handling) |\n| HIGH | >2 refs, wrapper provides meaningful abstraction or cross-cutting concerns |\n\n**Detection Signals:**\n- File imports internal module and re-exports similar API surface\n- No `__init__.py` (not a proper package)\n- Function bodies are single `return self.other_method(...)` calls\n- Duplicate capability exists in `examples/` or `skills/` directories\n\n## Auto-Approval Levels\n\n| Level | Criteria |\n|-------|----------|\n| `low` | Confidence >= 90%, Risk = LOW, 0 refs, deprecated/test/archive files only |\n| `medium` | Confidence >= 80%, Risk <= MEDIUM, <= 2 refs, non-core |\n| `none` | Prompts for every change (default, safest) |\n\n**Note:** All levels still show preview before execution.\n\nFile v1.9.17:modules/static-analysis-integration.md\n\n---\nmodule: static-analysis-integration\ncategory: tier-2\ndependencies: [Bash, Read]\nestimated_tokens: 150\n---\n\n# Static Analysis Integration Module\n\nBridge Tier 1 heuristics with Tier 2 programmatic analysis. Auto-detects tools and falls back gracefully.\n\n## Tool Detection\n\n```bash\n# Auto-detect available tools\nTOOLS=()\ncommand -v vulture &>/dev/null && TOOLS+=(\"vulture\")\ncommand -v deadcode &>/dev/null && TOOLS+=(\"deadcode\")\ncommand -v autoflake &>/dev/null && TOOLS+=(\"autoflake\")\ncommand -v knip &>/dev/null && TOOLS+=(\"knip\")\ncommand -v sonar-scanner &>/dev/null && TOOLS+=(\"sonarqube\")\n\n[ ${#TOOLS[@]} -gt 0 ] && echo \"Tier 2 capable\" || echo \"Tier 1 only\"\n```\n\n## Python Tools\n\n| Tool | Strength | Confidence | Command |\n|------|----------|------------|---------|\n| **vulture** | Dead code detection | 80-95% | `vulture . --min-confidence 80` |\n| **deadcode** | Fast, auto-fix | 85% | `deadcode --dry` |\n| **autoflake** | Import cleanup | 95% | `autoflake --check -r .` |\n\n### Vulture (Recommended)\n```bash\nvulture . --min-confidence 80 --exclude=.venv,__pycache__,.git,node_modules\n```\n- 90-100%: Safe to remove\n- 80-89%: Review first\n- <80%: Investigate\n\n### autoflake (Imports)\n```bash\nautoflake --check --remove-all-unused-imports --expand-star-imports -r .\n# Fix: add --in-place\n```\n**Impact:** 40-70% startup time reduction\n\n## JavaScript/TypeScript\n\n| Tool | Strength | Confidence | Command |\n|------|----------|------------|---------|\n| **knip** | Files, exports, deps | 95% | `knip --include files,exports` |\n\n```bash\nknip --include files,exports,dependencies --reporter json > knip-report.json\n```\n\n**Tree-shaking prereqs:**\n- `\"type\": \"module\"` in package.json\n- Avoid `export * from` barrel patterns\n\n## Multi-Language\n\n**SonarQube** (enterprise): Duplication, complexity, code smells\n```bash\nsonar-scanner -Dsonar.sources=. -Dsonar.exclusions=\"**/node_modules/**\"\n```\n\n## Tool Selection\n\n```python\nPRIORITY = {'python': ['vulture', 'deadcode'], 'javascript': ['knip']}\ntool = next((t for t in PRIORITY.get(lang, []) if t in available), 'heuristic')\n```\n\n## Confidence Boosting\n\nWhen heuristic and tool agree: boost confidence by 15% (max 95%)\n\n```yaml\n# Output format\nfile: src/utils/helpers.py\ntype: function\nname: calculate_legacy\nconfidence: 95%\nsources: [heuristic, vulture]\naction: DELETE\n```\n\n## Graceful Degradation\n\nNo tools? Fall back to `@module:code-bloat-patterns` heuristics.\n\n## Related\n- `code-bloat-patterns` - Heuristic fallbacks\n- `bloat-auditor` - Orchestrates tool execution\n\nFile v1.9.17:skill-card.md\n\n## Description: <br>\nDetects codebase bloat via dead code, duplication, complexity, and doc bloat scans. <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 engineering teams use this skill to audit repositories for dead code, duplication, stale documentation, dependency bloat, and growth patterns before cleanup, refactoring, or release work. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: Cleanup recommendations such as DELETE or ARCHIVE could remove useful code or documentation if followed without validation. <br>\nMitigation: Treat findings as advisory, review each recommendation manually, and verify references and tests before removing or archiving files. <br>\nRisk: Dependency checks that query the npm registry can disclose package names or fail in confidential or air-gapped projects. <br>\nMitigation: Skip registry lookups unless network disclosure is acceptable, or run the check only in an approved environment. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-conserve-bloat-detector) <br>\n- [OpenClaw homepage](https://github.com/athola/claude-night-market/tree/master/plugins/conserve) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, shell commands, guidance] <br>\n**Output Format:** [Markdown guidance with inline shell commands and YAML-style scan examples] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Outputs are advisory bloat findings, confidence levels, and cleanup recommendations for user review.] <br>\n\n## Skill Version(s): <br>\n1.9.17 (source: ClawHub release evidence; artifact frontmatter reports 1.9.8) <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: 11 files, 25088 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2339b), SKILL.md (5207b), _meta.json (146b)\n\nFile v1.9.16:SKILL.md\n\n---\nname: bloat-detector\ndescription: |\n  Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans\nversion: 1.9.8\ntriggers:\n  - bloat\n  - cleanup\n  - static-analysis\n  - technical-debt\n  - optimization\n  - codebase feels large or before a release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/conserve\", \"emoji\": \"\\ud83e\\udd9e\"}}\nsource: claude-night-market\nsource_plugin: conserve\n---\n\n> **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n# Bloat Detector\n\nSystematically detect and eliminate codebase bloat through progressive analysis tiers.\n\n## Bloat Categories\n\n| Category | Examples |\n|----------|----------|\n| **Code** | Dead code, God classes, Lava flow, duplication |\n| **AI-Generated** | Tab-completion bloat, vibe coding, hallucinated deps |\n| **Documentation** | Redundancy, verbosity, stale content, slop |\n| **Dependencies** | Unused imports, dependency bloat, phantom packages |\n| **Git History** | Stale files, low-churn code, massive single commits |\n\n## Quick Start\n\n### Tier 1: Quick Scan (2-5 min, no tools)\n```bash\n/bloat-scan\n```\nDetects: Large files, stale code, old TODOs, commented blocks, basic duplication\n\n### Tier 2: Targeted Analysis (10-20 min, optional tools)\n```bash\n/bloat-scan --level 2 --focus code   # or docs, deps\n```\nAdds: Static analysis (Vulture/Knip), git churn hotspots, doc similarity\n\n### Tier 3: Deep Audit (30-60 min, full tooling)\n```bash\n/bloat-scan --level 3 --report audit.md\n```\nAdds: Cross-file redundancy, dependency graphs, readability metrics\n\n## When To Use\n\n| Do | Don't |\n|----|-------|\n| Context usage > 30% | Active feature development |\n| Quarterly maintenance | Time-sensitive bugs |\n| Pre-release cleanup | Codebase < 1000 lines |\n| Before major refactoring | Tools unavailable (Tier 2/3) |\n\n## When NOT To Use\n\n- Active feature development\n- Time-sensitive bugs\n- Codebase < 1000 lines\n\n## Confidence Levels\n\n| Level | Confidence | Action |\n|-------|------------|--------|\n| HIGH | 90-100% | Safe to remove |\n| MEDIUM | 70-89% | Review first |\n| LOW | 50-69% | Investigate |\n\n## Prioritization\n\n```\nPriority = (Token_Savings × 0.4) + (Maintenance × 0.3) + (Confidence × 0.2) + (Ease × 0.1)\n```\n\n## Module Architecture\n\n**Tier 1** (always available):\n- See `modules/quick-scan.md` - Heuristics, no tools\n- See `modules/git-history-analysis.md` - Staleness, churn, vibe coding signatures\n- See `modules/growth-analysis.md` - Growth velocity, forecasts, threshold alerts\n\n**Tier 2** (optional tools):\n- See `modules/code-bloat-patterns.md` - Anti-patterns (God class, Lava flow)\n- See `modules/ai-generated-bloat.md` - AI-specific patterns (Tab bloat, hallucinations)\n- See `modules/documentation-bloat.md` - Redundancy, readability, slop detection\n- See `modules/static-analysis-integration.md` - Vulture, Knip\n\n**Shared**:\n- See `modules/remediation-types.md` - DELETE, REFACTOR, CONSOLIDATE, ARCHIVE\n\n## Ecosystem-Level Detection\n\nPatterns that span plugin boundaries or manifest configuration,\ndiscovered through ecosystem-wide audits.\n\n### `alwaysApply` Accumulation\n\nFlag plugins with 3+ skills where `alwaysApply: true`.\nEach always-on skill injects its full text into every session,\ncreating a baseline token floor before the user types anything.\nSum the `estimated_tokens` fields to report total per-session cost.\n\n### Hook Registration Gaps\n\nCompare hooks declared in `plugin.json` or `openpackage.yml`\nagainst entries in `hooks.json`. A hook present in `hooks.json`\nbut absent from the manifest is invisible to the plugin loader\nand cannot be audited, versioned, or disabled through normal\nplugin management.\n\n### Boilerplate Footer Detection\n\nScan skill files for identical multi-line text blocks repeated\nacross 10+ files (e.g., generic troubleshooting sections like\n\"Command not found / Permission errors / Unexpected behavior\").\nThese are copy-paste artifacts that inflate token cost without\nadding skill-specific value.\n\n### ToC Bloat in Skills\n\nSkills loaded into model context gain nothing from HTML-style\nTables of Contents. Detect `## Table of Contents` followed by\nbulleted anchor-link lists. These waste tokens since\nthe model reads sequentially, not via hyperlinks.\n\n### Unregistered Module Subdirectories\n\nCompare files on disk in `skills/*/modules/` against the\n`modules:` list in each skill's SKILL.md frontmatter. Files\nthat exist on disk but are not listed in the manifest are\ninvisible to progressive loading and may be dead weight or\nmissing from the load path.\n\n## Auto-Exclusions\n\nAlways excludes: `.venv`, `__pycache__`, `.git`, `node_modules`, `dist`, `build`, `vendor`\n\nAlso respects: `.gitignore`, `.bloat-ignore`\n\n## Safety\n\n- **Never auto-delete** - all changes require approval\n- **Dry-run support** - `--dry-run` for previews\n- **Backup branches** - created before bulk changes\n\n## Related\n\n- `bloat-auditor` agent - Executes scans\n- `unbloat-remediator` agent - Safe remediation\n- `context-optimization` skill - MECW principles\n\nFile v1.9.16:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-conserve-bloat-detector\",\n  \"version\": \"1.9.16\",\n  \"publishedAt\": 1784058526997\n}\n\nFile v1.9.16:modules/ai-generated-bloat.md\n\n---\nmodule: ai-generated-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 200\n---\n\n# AI-Generated Bloat Detection Module\n\nDetect bloat patterns specific to AI-assisted coding: vibe coding artifacts, slop patterns, and agent psychosis indicators.\n\n## Why This Module Exists\n\nAI coding has created qualitatively different bloat than traditional development:\n- **2024**: First year copy/pasted lines exceeded refactored lines (GitClear)\n- **Refactoring**: Dropped from 25% (2021) to <10% (2024), predicted 3% (2025)\n- **Duplication**: 8x increase in 5+ line code blocks\n\n## AI Bloat Patterns\n\n### 1. Tab-Completion Bloat (Repetitive Logic)\n\n**Definition**: Same pattern repeated 3+ times instead of abstracted into shared function.\n\n```bash\n# Detect similar code blocks (built-in, no external deps)\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5\n\n# JSON output for CI integration\npython3 plugins/conserve/scripts/detect_duplicates.py . --format json --threshold 15\n\n# Heuristic: functions with near-identical signatures\ngrep -rn \"^def \" --include=\"*.py\" . | cut -d: -f2 | sort | uniq -c | sort -rn | head -10\n```\n\n**Confidence**: HIGH (85%)\n**Action**: REFACTOR - extract to shared utility\n**Rationale**: AI suggests new implementations rather than reusing existing code\n\n### 2. Massive Single Commits (Vibe Coding Signature)\n\n**Definition**: Commits with >500 insertions, especially without proportional tests.\n\n```bash\n# Find vibe coding commits\ngit log --oneline --shortstat | grep -E \"[0-9]{3,} insertion\" | head -20\n\n# Commits with high insertion:deletion ratio (adding without cleanup)\ngit log --shortstat --pretty=format:\"%h %s\" | awk '/insertion|deletion/ {\n  ins=$4; del=$6;\n  if (ins > 200 && (del == \"\" || ins/del > 10)) print prev, ins, del\n} {prev=$0}'\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: INVESTIGATE - review for understanding gaps\n**Rationale**: Large additions without refactoring indicate Tab-driven development\n\n### 3. Hallucinated Dependencies\n\n**Definition**: Imports referencing non-existent packages (AI hallucination).\n\n```bash\n# Python: Check for uninstallable packages\npip freeze > /tmp/installed.txt\ngrep -rh \"^import \\|^from \" --include=\"*.py\" . | \\\n  sed 's/^import //;s/^from //;s/ import.*//' | \\\n  sort -u | while read pkg; do\n    root=$(echo $pkg | cut -d. -f1)\n    grep -q \"^$root\" /tmp/installed.txt || echo \"HALLUCINATED?: $pkg\"\n  done\n\n# JavaScript: Check for phantom packages\njq -r '.dependencies // {} | keys[]' package.json | while read pkg; do\n  npm view $pkg version 2>/dev/null || echo \"HALLUCINATED?: $pkg\"\ndone\n```\n\n**Confidence**: HIGH (95%)\n**Action**: DELETE or REPLACE\n**Rationale**: AI invents plausible-sounding packages (slopsquatting risk)\n\n### 4. Happy Path Only (Test Coverage Gap)\n\n**Definition**: Code >200 lines with no corresponding tests, or tests without error assertions.\n\n```bash\n# Files without test coverage\nfind . -name \"*.py\" ! -path \"*/test*\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c '\n  lines=$(wc -l < \"$1\")\n  if [ $lines -gt 200 ]; then\n    base=$(basename \"$1\" .py)\n    test_exists=$(find . -name \"test_${base}.py\" -o -name \"${base}_test.py\" \\\n      -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n      -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | head -1)\n    [ -z \"$test_exists\" ] && echo \"UNTESTED ($lines lines): $1\"\n  fi\n' _ {} \\;\n\n# Tests without error/exception assertions\ngrep -rL \"assert.*Error\\|assert.*Exception\\|pytest.raises\\|with self.assertRaises\" \\\n  --include=\"test_*.py\" .\n```\n\n**Confidence**: HIGH (90%)\n**Action**: AUGMENT_TESTS before adding more code\n**Rationale**: AI generates happy path; errors require human insight\n\n### 5. Premature Abstraction\n\n**Definition**: Base classes/interfaces with only 1-2 implementations.\n\n```bash\n# Python: Abstract classes 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  inheritors=$(grep -rn \"($class)\" --include=\"*.py\" . | wc -l)\n  [ $inheritors -lt 2 ] && echo \"PREMATURE: $class in $f (${inheritors} inheritors)\"\ndone\n```\n\n**Confidence**: HIGH (85%)\n**Action**: INLINE - remove abstraction until 3rd use case\n**Rationale**: AI suggests \"scalable\" patterns for simple problems\n\n### 6. Enterprise Cosplay\n\n**Definition**: Microservices, Kubernetes, complex architecture for simple applications.\n\n```bash\n# Docker complexity for simple apps\nif [ -f docker-compose.yml ]; then\n  services=$(grep -c \"^  [a-z].*:$\" docker-compose.yml)\n  code_lines=$(find . \\( -name \"*.py\" -o -name \"*.js\" \\) \\\n    -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n    -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l 2>/dev/null | tail -1 | awk '{print $1}')\n  ratio=$((code_lines / services))\n  [ $ratio -lt 500 ] && echo \"ENTERPRISE_COSPLAY: $services services for $code_lines lines\"\nfi\n\n# Kubernetes for CRUD\n[ -d k8s ] && [ $(find . -name \"*.py\" -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" | xargs wc -l | tail -1 | awk '{print $1}') -lt 5000 ] && \\\n  echo \"ENTERPRISE_COSPLAY: Kubernetes for <5000 lines\"\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: SIMPLIFY - evaluate if complexity is justified\n**Rationale**: AI defaults to \"production-ready\" patterns without context\n\n### 7. Documentation Slop\n\n**Definition**: AI-generated docs with excessive hedging, formulaic structure, surface insights.\n\n```bash\n# Hedge word density (AI slop indicators)\nhedge_words=\"worth noting|arguably|to some extent|it's important|consider that|generally speaking\"\nfor f in $(find . -name \"*.md\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  total=$(wc -w < \"$f\")\n  hedges=$(grep -oiE \"$hedge_words\" \"$f\" | wc -l)\n  if [ $total -gt 100 ]; then\n    density=$((hedges * 1000 / total))\n    [ $density -gt 20 ] && echo \"DOC_SLOP ($density/1000): $f\"\n  fi\ndone\n```\n\n**Confidence**: MEDIUM (65%)\n**Action**: REWRITE with concrete specifics\n**Rationale**: AI safety training creates artificial hedging\n\n## Scoring\n\n```python\nAI_BLOAT_SCORES = {\n    'tab_completion_bloat': 25,\n    'massive_single_commit': 15,\n    'hallucinated_dependency': 35,\n    'happy_path_only': 30,\n    'premature_abstraction': 20,\n    'enterprise_cosplay': 25,\n    'documentation_slop': 10,\n}\n\ndef ai_bloat_score(detected_patterns):\n    return min(100, sum(AI_BLOAT_SCORES.get(p, 0) for p in detected_patterns))\n```\n\n## Integration with Existing Tiers\n\n**Tier 1 (Quick Scan)**: Massive single commits, hedge word density\n**Tier 2 (Targeted)**: Duplication ratio, test coverage gaps, premature abstraction\n**Tier 3 (Deep Audit)**: Hallucinated dependencies, enterprise cosplay analysis\n\n## Output Format\n\n```yaml\nfile: src/services/user_manager.py\nai_bloat_patterns:\n  - tab_completion_bloat\n  - happy_path_only\nai_bloat_score: 55/100\nindicators:\n  similar_blocks: 4\n  test_coverage: 0%\n  commit_size: 847 lines\nconfidence: HIGH\naction: REFACTOR + ADD_TESTS\nrationale: \"Vibe coding signature - large addition without tests or abstraction\"\n```\n\n## Prevention Recommendations\n\nWhen AI bloat is detected, recommend:\n\n1. **Refactoring Budget**: Add 25 lines of refactoring for every 100 lines added\n2. **Test Requirement**: No merge without proportional test coverage\n3. **Understanding Gate**: Require explanation of non-trivial changes\n4. **24-Hour Rule**: Sleep before adopting new AI-suggested patterns\n\n## Related\n\n- `code-bloat-patterns` - Traditional anti-patterns (God class, Lava flow)\n- `documentation-bloat` - Readability metrics\n- `imbue:anti-cargo-cult` - Understanding verification protocol\n- Knowledge corpus: `agent-psychosis-codebase-hygiene.md`\n\nFile v1.9.16:modules/code-bloat-patterns.md\n\n---\nmodule: code-bloat-patterns\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 150\n---\n\n# Code Bloat Patterns Module\n\nDetect anti-patterns using pattern recognition and heuristics. Works without external tools.\n\n> **Tool Preference (Claude Code 2.1.31+)**: The bash snippets in this module are reference implementations for external script execution or CI pipelines. When performing these analyses directly within Claude Code, prefer native tools: use Grep instead of `grep`, Glob instead of `find`, and Read instead of `cat`/`sed`.\n\n## Anti-Patterns\n\n### 1. God Class\n**Definition:** Single class with > 500 lines, > 10 methods, multiple responsibilities.\n\n```bash\n# Quick detection\nfind . -name \"*.py\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c 'lines=$(wc -l < \"$1\"); [ $lines -gt 500 ] && echo \"GOD_CLASS: $1 - $lines lines\"' _ {} \\;\n```\n**Confidence:** HIGH (85%) | **Action:** REFACTOR into focused modules\n\n### 2. Lava Flow\n**Definition:** Ancient untouched code - commented blocks, old TODOs.\n\n```bash\n# Find files with >20% commented code\ngrep -rn \"^#\\|^//\" --include=\"*.py\" . | cut -d: -f1 | sort | uniq -c | sort -rn | head -10\n```\n**Confidence:** HIGH (90%) | **Action:** DELETE commented code\n\n### 3. Dead Code\n**Detection:** Use static analysis (Vulture/Knip) or fallback heuristic:\n```bash\n# Heuristic: find functions with 0 calls\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  func=$(echo $line | awk '{print $2}' | cut -d'(' -f1)\n  [ $(git grep -c \"$func(\" 2>/dev/null || echo 0) -eq 1 ] && echo \"DEAD: $func\"\ndone\n```\n**Confidence:** MEDIUM (70%) heuristic, HIGH (90%) with tools | **Action:** DELETE\n\n### 4. Import Bloat\n```bash\n# Star imports (block tree-shaking)\ngrep -rn \"^from .* import \\*\" --include=\"*.py\" .\n\n# Unused imports (requires autoflake)\nautoflake --check --remove-all-unused-imports -r .\n```\n**Confidence:** HIGH (95%) | **Action:** Fix imports\n\n### 5. Duplication\n**Intra-file:** Hash-based block detection (5+ line matches)\n**Cross-file:** Function signature matching\n**Semantic:** AST comparison (80%+ similarity)\n\n**Confidence:** HIGH (85%) | **Action:** EXTRACT to shared utility\n\n## Language-Specific\n\n### Python\n- Circular imports: Files with 20+ imports\n- Deep nesting: > 4 indentation levels\n\n### JavaScript/TypeScript\n- Barrel files: `export * from` breaks tree-shaking\n- CommonJS in ESM: `module.exports`/`require()` blocks bundler optimization\n\n## AI-Amplified Patterns\n\nThese traditional patterns are amplified by AI coding tools:\n\n### 6. Tab-Completion Duplication\n**Definition:** AI suggests similar code blocks instead of reusing existing functions.\n**2024 Data:** 8x increase in 5+ line duplicated blocks (GitClear)\n\n```bash\n# Quick detection: near-identical function signatures\ngrep -rn \"^def \" --include=\"*.py\" . | awk -F'def ' '{print $2}' | \\\n  cut -d'(' -f1 | sort | uniq -c | sort -rn | awk '$1 > 1'\n```\n**Confidence:** HIGH (85%) | **Action:** EXTRACT shared utility\n\n### 7. Dead Wrapper / Facade Bloat\n**Definition:** Modules that wrap existing functionality without adding meaningful logic — thin facades, unused service interfaces, or re-export layers with no consumers.\n\n**Signals:**\n- File imports from another internal module and re-exports similar API\n- No external imports of the wrapper (0 refs from outside itself)\n- Not a proper package (missing `__init__.py` for Python)\n- Docstring examples show imports but no actual code uses them\n- Functionality already exists in the wrapped module or in `examples/`\n\n```bash\n# Find Python files that only re-export from other internal modules\nfor f in $(find . -name \"*.py\" -not -path \"*/test*\" -not -path \"*/__pycache__/*\" -not -path \"*/.venv/*\" -not -path \"*/node_modules/*\" -not -path \"*/.git/*\"); do\n  # Check if file mostly imports and re-calls another module's functions\n  imports=$(grep -c \"^from \\.\\.\" \"$f\" 2>/dev/null || echo 0)\n  total=$(wc -l < \"$f\" 2>/dev/null || echo 0)\n  refs=$(git grep -l \"$(basename \"$f\" .py)\" -- \"*.py\" 2>/dev/null | grep -v \"$f\" | wc -l)\n  if [ \"$imports\" -gt 2 ] && [ \"$refs\" -eq 0 ] && [ \"$total\" -gt 50 ]; then\n    echo \"DEAD_WRAPPER: $f ($total lines, $imports internal imports, 0 external refs)\"\n  fi\ndone\n```\n\n**Also check for intra-file dead wrappers:**\n```bash\n# Find classes/functions that only delegate to another method with no transformation\ngrep -rn \"def .*self\" --include=\"*.py\" . | while read line; do\n  file=$(echo \"$line\" | cut -d: -f1)\n  lineno=$(echo \"$line\" | cut -d: -f2)\n  # Check if function body is just \"return self.other_thing(...)\"\n  body=$(sed -n \"$((lineno+1)),$((lineno+3))p\" \"$file\" 2>/dev/null)\n  if echo \"$body\" | grep -qP '^\\s+return self\\.\\w+\\(' && [ $(echo \"$body\" | wc -l) -le 2 ]; then\n    echo \"PASSTHROUGH: $file:$lineno - trivial delegation\"\n  fi\ndone\n```\n\n**Confidence:** HIGH (85%) for whole-file wrappers, MEDIUM (70%) for intra-file passthrough\n**Action:** DELETE (whole-file) or INLINE (intra-file passthrough)\n\n### 8. Premature Abstraction\n**Definition:** Base classes/interfaces with <3 implementations (YAGNI violation).\n**AI Cause:** AI defaults to \"scalable\" patterns without context.\n\n```bash\n# Find abstract classes with few inheritors\ngrep -rln \"ABC\\|abstractmethod\" --include=\"*.py\" . | while read f; do\n  class=$(grep -oP \"class \\K\\w+\" \"$f\" | head -1)\n  [ $(grep -rc \"($class)\" --include=\"*.py\" . 2>/dev/null) -lt 3 ] && echo \"PREMATURE: $class\"\ndone\n```\n**Confidence:** HIGH (80%) | **Action:** INLINE until 3rd use case\n\n### 9. Happy Path Bias\n**Definition:** Tests verify success paths only; no error handling tested.\n**AI Cause:** AI optimizes for \"works\" demonstrations.\n\n```bash\n# Tests without error assertions\ngrep -rL \"Error\\|Exception\\|raises\\|fail\\|invalid\" --include=\"test_*.py\" .\n```\n**Confidence:** MEDIUM (70%) | **Action:** ADD error path tests\n\nFor comprehensive AI-specific patterns, see: `@module:ai-generated-bloat`\n\n## Scoring\n\n```python\nPATTERN_SCORES = {\n    'god_class': 30, 'lava_flow': 25, 'dead_code': 35,\n    'import_bloat': 15, 'duplication': 20, 'dead_wrapper': 30\n}\nscore = min(100, sum(PATTERN_SCORES[p] for p in detected))\n```\n\n## Output Format\n\n```yaml\nfile: src/legacy/manager.py\npatterns: [god_class, lava_flow, import_bloat]\nbloat_score: 85/100\nconfidence: HIGH\ntoken_estimate: ~3,400\naction: REFACTOR\n```\n\nAll actions require user approval.\n\nFile v1.9.16:modules/documentation-bloat.md\n\n---\nmodule: documentation-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 120\n---\n\n# Documentation Bloat Module\n\nDetect documentation redundancy, verbosity, and poor readability.\n\n## Detection Categories\n\n### 1. Duplicate Documentation\n\n#### Cross-File (Jaccard Similarity)\n```bash\n# Quick similarity check between two files\nwords1=$(tr '[:space:]' '\\n' < file1.md | sort -u)\nwords2=$(tr '[:space:]' '\\n' < file2.md | sort -u)\n# > 70% overlap = potential duplication\n```\n\n| Similarity | Confidence | Action |\n|------------|------------|--------|\n| > 90% | HIGH (95%) | DELETE one, keep recent |\n| 70-90% | MEDIUM (80%) | MERGE, preserve unique |\n| 50-70% | LOW (60%) | CROSS-LINK |\n\n#### Intra-File (Section Hashing)\nHash each `##` section's normalized content. Duplicates = repeated sections.\n\n**Confidence:** HIGH (85%)\n\n### 2. Excessive Verbosity\n\n| Metric | Threshold | Action |\n|--------|-----------|--------|\n| Word count | > 500 words/section | Condense |\n| Sentence length | > 25 words avg | Simplify |\n| Passive voice | > 30% | Rewrite active |\n| Readability | Flesch < 40 | Simplify |\n\n```bash\n# Quick verbosity check\nwc -w file.md  # Total words\nrg -c '\\.' file.md  # Approximate sentences (or grep -c)\n```\n\n### 3. Stale Documentation\n\n| Signal | Confidence | Action |\n|--------|------------|--------|\n| Unchanged 12+ months | HIGH (85%) | Review/Archive |\n| References deleted code | HIGH (90%) | Update/Delete |\n| No git activity | MEDIUM (75%) | Investigate |\n\n```bash\n# Find stale docs\ngit log -1 --format=\"%ar\" -- docs/*.md | rg -E \"year|months\"\n# fallback: grep -E \"year|months\"\n```\n\n### 4. Missing/Outdated References\n\n- Broken internal links: `rg -oP '\\[.*?\\]\\((?!http).*?\\)' *.md` (or `grep -oP`)\n- References to deleted files\n- Outdated API examples\n\n**Confidence:** HIGH (90%) for broken links\n\n## Scoring\n\n```python\ndef doc_bloat_score(metrics):\n    score = 0\n    if metrics['duplicate_ratio'] > 0.3: score += 30\n    if metrics['avg_words_per_section'] > 500: score += 20\n    if metrics['readability'] < 40: score += 15\n    if metrics['stale_months'] > 12: score += 25\n    return min(100, score)\n```\n\n## Output Format\n\n```yaml\nfile: docs/old-guide.md\nbloat_type: [duplicate, verbose, stale]\nbloat_score: 72/100\nconfidence: HIGH\ntoken_estimate: ~1,200\nsimilar_to: docs/guide.md (87%)\naction: MERGE\n```\n\n## Related\n- `quick-scan` - Tier 1 stale detection\n- `git-history-analysis` - Activity signals\n\nFile v1.9.16:modules/git-history-analysis.md\n\n---\nmodule: git-history-analysis\ncategory: tier-1\ndependencies: [Bash, Grep]\nestimated_tokens: 250\n---\n\n# Git History Analysis Module\n\nDetect bloat using git history: staleness, churn metrics, and reference counting.\n\n## Core Techniques\n\n### 1. Staleness Detection\n\n**Command:**\n```bash\n# Files not modified in last 6 months\ngit log --since=\"6 months ago\" --name-only --pretty=format: | sort -u > recent.txt\ncomm -13 recent.txt <(git ls-files | sort) > stale_files.txt\n```\n\n**Staleness Scoring:**\n```python\ndef staleness_score(months_since_change):\n    if months_since_change > 24:\n        return 95  # Almost certainly abandoned\n    elif months_since_change > 12:\n        return 85  # Likely abandoned\n    elif months_since_change > 6:\n        return 65  # Possibly stale\n    else:\n        return 20  # Active\n```\n\n**Confidence Modifiers:**\n- File type: Config files -20%, code files +0%\n- Last author: If single author who left project +15%\n- Dependencies: If no imports found +25%\n\n### 2. Reference Counting\n\n**Detect unused files:**\n```bash\n# For each file, count references in codebase\ngit ls-files | while read file; do\n  filename=$(basename \"$file\")\n  refs=$(git grep -l \"$filename\" | wc -l)\n  if [ $refs -eq 1 ]; then  # Only self-reference\n    echo \"0 $file\"\n  else\n    echo \"$((refs - 1)) $file\"  # Subtract self\n  fi\ndone | grep \"^0 \"\n```\n\n**Confidence:** HIGH (90%) if zero refs and stale\n\n**False Positives:**\n- Entry points (main.py, index.js)\n- Configuration files\n- Documentation\n\n### 3. Code Churn Metrics\n\n**Churn formula:**\n```bash\n# Lines added + deleted per file\ngit log --numstat --pretty=\"%H\" -- $file | \\\n  awk '{added+=$1; deleted+=$2} END {print added+deleted}'\n```\n\n**Churn Categories:**\n- **High churn (>1000 changes/year)**: Active development\n- **Low churn (<50 changes/year)**: Stable or abandoned\n- **Zero churn + old**: Strong bloat signal\n\n**Filter out cleanup-churn (release sweeps, frontmatter-only edits):**\n\nA naive commit count over-flags files swept by repo-wide release\noperations (version bumps, frontmatter additions). Filter to commits\nthat made substantive changes to the file under analysis.\n\n```bash\n# Count only commits with >5 line net change in the file\ngit log --numstat --pretty=tformat:%H -- \"$file\" | \\\n  awk '/^[0-9]/ && ($1 + $2) > 5 { count++ } END { print count }'\n```\n\nCompare against the unfiltered count: if `substantive_count <\ntotal_count / 3`, the file is **cleanup-churn** not **design churn**.\nDowngrade the thrashing/hotspot signal in that case.\n\nWorked example: `rigorous-reasoning/SKILL.md` showed 12 commits in 30\ndays. After filtering for substantive body changes (`>5` line net),\nonly 1 commit remained. The rest were repo-wide frontmatter sweeps\n(version bumps, tag adds, description tweaks). This file is NOT a\nthrashing hotspot; the signal was a false positive from cleanup-churn.\n\n**Hotspot Detection:**\n```python\ndef is_hotspot(churn, complexity):\n    \"\"\"\n    Hotspot = High churn × High complexity\n    Indicates technical debt accumulation\n    \"\"\"\n    churn_score = normalize_churn(churn)\n    complexity_score = cyclomatic_complexity(file)\n    return churn_score * complexity_score > threshold\n```\n\n### 4. Ownership Analysis\n\n**Detect abandoned code:**\n```bash\n# Find files where primary author has no recent commits\ngit log --format=\"%an\" --since=\"6 months ago\" | sort -u > active_authors.txt\n\ngit ls-files | while read file; do\n  primary_author=$(git log --format=\"%an\" -- \"$file\" | sort | uniq -c | sort -rn | head -1 | awk '{$1=\"\"; print $0}' | sed 's/^ //')\n  if ! grep -qF \"$primary_author\" active_authors.txt; then\n    echo \"$file - Primary author inactive: $primary_author\"\n  fi\ndone\n```\n\n**Confidence:** MEDIUM (70%) - Ownership transfer is possible\n\n### 5. Branch Analysis\n\n**Detect orphaned feature branches:**\n```bash\n# Branches not merged in 6+ months\ngit for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(refname:short)' | \\\n  while read date branch; do\n    age_days=$(( ($(date +%s) - $(date -d \"$date\" +%s)) / 86400 ))\n    if [ $age_days -gt 180 ]; then\n      echo \"$branch - ${age_days} days old\"\n    fi\n  done\n```\n\n**Action:** Suggest cleanup or archival\n\n## Integrated Analysis\n\n### Multi-Signal Validation\n\nCombine signals for higher confidence:\n\n```python\ndef calculate_bloat_confidence(file):\n    signals = []\n\n    # Staleness\n    months = months_since_last_change(file)\n    if months > 12:\n        signals.append(('stale', 85, months))\n\n    # No references\n    refs = count_references(file)\n    if refs == 0:\n        signals.append(('unused', 90, refs))\n\n    # Low churn\n    churn = calculate_churn(file)\n    if churn < 50:  # < 50 changes/year\n        signals.append(('low_churn', 70, churn))\n\n    # Inactive owner\n    if is_owner_inactive(file):\n        signals.append(('inactive_owner', 65, None))\n\n    # Combined confidence\n    if len(signals) >= 3:\n        return 'HIGH', signals\n    elif len(signals) == 2:\n        return 'MEDIUM', signals\n    else:\n        return 'LOW', signals\n```\n\n### Example Output\n\n```yaml\nfile: src/deprecated/old_api.py\nconfidence: HIGH\nsignals:\n  - type: stale\n    score: 85\n    detail: 18 months since last change\n  - type: unused\n    score: 90\n    detail: Zero references found\n  - type: low_churn\n    score: 70\n    detail: 12 changes in last year\ncombined_score: 82\nrecommendation: DELETE\nrationale: |\n  Multiple strong signals indicate abandonment:\n  - No changes in 18 months\n  - No code references\n  - Minimal historical activity\n  Safe to remove with archival backup.\n```\n\n## AskGit Integration (Optional)\n\nIf AskGit is available, use SQL for advanced queries:\n\n```sql\n-- Find files with high churn but low recent activity\nSELECT\n  file_path,\n  SUM(additions + deletions) as total_churn,\n  MAX(author_when) as last_change\nFROM commits\nWHERE author_when < date('now', '-6 months')\nGROUP BY file_path\nHAVING total_churn > 1000\nORDER BY total_churn DESC;\n```\n\n## Performance Optimization\n\n**Caching Strategy:**\n```bash\n# Cache git log results for reuse\ngit log --all --numstat --pretty=format:'%H|%an|%ai' > /tmp/git_cache.txt\n\n# Query cache instead of running git log repeatedly\ngrep \"path/to/file\" /tmp/git_cache.txt\n```\n\n**Incremental Updates:**\n- Store previous scan results\n- Only analyze changed files\n- Delta reporting\n\n## Safety Checks\n\nBefore flagging for deletion:\n\n1. **Test Files**: Exclude `test_*.py`, `*.spec.js`\n2. **Migrations**: Database migrations must never auto-delete\n3. **CI/CD**: Files in `.github/`, `.gitlab-ci.yml`\n4. **Documentation**: User-facing docs need manual review\n\n**Whitelist Patterns:**\n```yaml\nsafe_paths:\n  - tests/\n  - migrations/\n  - .github/\n  - docs/api/  # API docs are references, not code\n\nexcluded_from_bloat_analysis:\n  # Cache directories (always exclude from counts)\n  - .venv/\n  - venv/\n  - __pycache__/\n  - .pytest_cache/\n  - .mypy_cache/\n  - .ruff_cache/\n  - .tox/\n  - .git/\n  # Dependencies and build artifacts\n  - node_modules/\n  - vendor/\n  - dist/\n  - build/\n```\n\n## Integration with Quick Scan\n\nGit analysis validates quick scan findings:\n\n```python\ndef validate_quick_scan_finding(finding):\n    # Quick scan says file is bloated\n    # Git analysis confirms or refutes\n    git_score = analyze_git_history(finding.file)\n\n    if quick_scan.score > 80 and git_score > 80:\n        return 'HIGH_CONFIDENCE'\n    elif quick_scan.score > 60 and git_score > 60:\n        return 'MEDIUM_CONFIDENCE'\n    else:\n        return 'LOW_CONFIDENCE'  # Conflicting signals\n```\n\n## Next Steps\n\nBased on git analysis:\n- **HIGH confidence**: Create cleanup PR\n- **MEDIUM confidence**: Run static analysis (Tier 2)\n- **LOW confidence**: Manual code review\n\nFile v1.9.16:modules/growth-analysis.md\n\n---\nmodule: growth-analysis\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 1500\n---\n\n# Growth Analysis Module\n\nTrack codebase growth velocity using git history.\nForecast future size, predict threshold crossings,\nand rank directories by urgency.\n\nThis module replaces the former standalone\n`/analyze-growth` command (removed in v1.6.0).\nIt runs as part of `/bloat-scan --growth`.\n\n## When to Load\n\nLoad this module when:\n\n- Running `/bloat-scan --growth`\n- Investigating rapid file or line count increases\n- Planning capacity for skill files approaching token limits\n- Preparing quarterly growth reports\n\n## Core Metrics\n\n### 1. File Count Velocity\n\nTrack how fast new files appear in a directory tree.\n\n```bash\n# File count per week for the last 8 weeks\nfor i in $(seq 0 7); do\n  date=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --until=\"$date\" --diff-filter=A \\\n    --name-only --pretty=format: -- \"$TARGET_DIR\" | \\\n    sort -u | wc -l)\n  echo \"$date $count\"\ndone | sort\n```\n\n**Output columns:** date, cumulative file count\n\n### 2. Line Count Velocity\n\nMeasure net line growth over recent commits.\n\n```bash\n# Net lines added per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  git log --since=\"$start\" --until=\"$end\" \\\n    --numstat --pretty=format: -- \"$TARGET_DIR\" | \\\n    awk '{added+=$1; deleted+=$2}\n      END {print added - deleted}'\ndone\n```\n\n**Negative values** indicate shrinkage (good after cleanup).\n\n### 3. Commit Frequency\n\nCount commits touching a path over rolling windows.\n\n```bash\n# Commits per week for last 8 weeks\nfor i in $(seq 0 7); do\n  start=$(date -d \"$(( (i+1) * 7 )) days ago\" +%Y-%m-%d)\n  end=$(date -d \"$((i * 7)) days ago\" +%Y-%m-%d)\n  count=$(git log --since=\"$start\" --until=\"$end\" \\\n    --oneline -- \"$TARGET_DIR\" | wc -l)\n  echo \"week-$i: $count commits\"\ndone\n```\n\n### 4. Size Snapshot\n\nCurrent state measurement for the target path.\n\n```bash\n# Total lines in tracked files (exclude cache dirs)\ngit ls-files -- \"$TARGET_DIR\" | \\\n  grep -v -E '(\\.venv|__pycache__|node_modules|\\.git)' | \\\n  xargs wc -l 2>/dev/null | tail -1\n```\n\n## 30-Day Forecast\n\nUse simple linear regression on the last 8 weekly\ndata points to project 30 days forward.\n\n### Algorithm\n\n```python\ndef forecast_30d(weekly_counts):\n    \"\"\"\n    Linear least-squares fit on weekly data.\n    Returns projected value 4.3 weeks from now.\n    \"\"\"\n    n = len(weekly_counts)\n    if n < 3:\n        return None  # Not enough data\n\n    xs = list(range(n))\n    x_mean = sum(xs) / n\n    y_mean = sum(weekly_counts) / n\n\n    numerator = sum(\n        (x - x_mean) * (y - y_mean)\n        for x, y in zip(xs, weekly_counts)\n    )\n    denominator = sum((x - x_mean) ** 2 for x in xs)\n\n    if denominator == 0:\n        return y_mean  # Flat line\n\n    slope = numerator / denominator\n    intercept = y_mean - slope * x_mean\n\n    # 30 days = ~4.3 weeks beyond last data point\n    future_x = (n - 1) + 4.3\n    return slope * future_x + intercept\n```\n\n### Interpreting Forecasts\n\n- **Slope > 0**: Growing. Report weekly rate.\n- **Slope ~ 0**: Stable. No action needed.\n- **Slope < 0**: Shrinking. Recent cleanup likely working.\n\nReport the R-squared value when possible.\nLow R-squared (< 0.5) means the trend is noisy\nand the forecast is unreliable.\n\n## Threshold Crossing Predictions\n\nGiven a target limit (e.g., 500-line skill file limit),\ncalculate when the current growth rate will cross it.\n\n### Algorithm\n\n```python\ndef weeks_until_threshold(current_size, weekly_rate, limit):\n    \"\"\"\n    Returns weeks until current_size reaches limit\n    at the given weekly_rate.\n    Returns None if rate <= 0 (will never cross).\n    \"\"\"\n    if weekly_rate <= 0:\n        return None\n    remaining = limit - current_size\n    if remaining <= 0:\n        return 0  # Already exceeded\n    return remaining / weekly_rate\n```\n\n### Default Thresholds\n\n| Target | Limit | Rationale |\n|--------|-------|-----------|\n| Skill file | 500 lines | Progressive loading boundary |\n| Module file | 300 lines | Single-responsibility cap |\n| Python source | 500 lines | God class indicator |\n| Markdown doc | 300 lines | Reader attention limit |\n\nOverride thresholds with `--threshold <lines>`.\n\n## Urgency Rankings\n\nRank directories or files by how soon they will\nneed attention.\n\n### Scoring Formula\n\n```\nurgency = growth_rate * (current_size / threshold) * recency_weight\n```\n\nWhere:\n\n- `growth_rate`: Lines per week (normalized 0-1)\n- `current_size / threshold`: How close to the limit (0-1+)\n- `recency_weight`: 1.5 if accelerating, 1.0 if steady,\n  0.5 if decelerating\n\n### Urgency Categories\n\n| Category | Score Range | Action |\n|----------|------------|--------|\n| Critical | > 0.8 | Modularize or split now |\n| High | 0.5 - 0.8 | Plan optimization this sprint |\n| Medium | 0.2 - 0.5 | Add to backlog |\n| Low | < 0.2 | No action needed |\n\n### Acceleration Detection\n\nCompare the growth rate of the last 4 weeks against\nthe preceding 4 weeks.\n\n```python\ndef detect_acceleration(weekly_rates):\n    if len(weekly_rates) < 8:\n        return \"insufficient_data\"\n    recent = sum(weekly_rates[-4:]) / 4\n    earlier = sum(weekly_rates[-8:-4]) / 4\n    if earlier == 0:\n        return \"new_growth\" if recent > 0 else \"stable\"\n    ratio = recent / earlier\n    if ratio > 1.5:\n        return \"accelerating\"\n    elif ratio < 0.5:\n        return \"decelerating\"\n    return \"steady\"\n```\n\n## Output Format\n\n### Terminal Report\n\n```\n=== Growth Analysis: plugins/conserve/skills/ ===\n\nCurrent State:\n  Files:  47\n  Lines:  8,234\n  Avg:    175 lines/file\n\n30-Day Forecast:\n  Files:  +5  (52 projected)\n  Lines:  +820 (9,054 projected)\n  Rate:   ~205 lines/week\n\nThreshold Alerts:\n  bloat-detector/SKILL.md    412/500 lines  ~4 weeks to limit\n  context-optimization.md    289/300 lines  ~1 week to limit  [!]\n\nUrgency Rankings:\n  [CRITICAL] context-optimization.md   0.92\n  [HIGH]     bloat-detector/SKILL.md   0.67\n  [MEDIUM]   token-conservation.md     0.34\n  [LOW]      performance-monitoring.md 0.11\n```\n\n### Machine-Readable Output\n\n```yaml\ngrowth_analysis:\n  target: plugins/conserve/skills/\n  snapshot:\n    files: 47\n    lines: 8234\n    date: \"2026-03-10\"\n  forecast_30d:\n    files: 52\n    lines: 9054\n    confidence: 0.78\n  weekly_rate:\n    files: 1.2\n    lines: 205\n  threshold_alerts:\n    - path: context-optimization.md\n      current: 289\n      limit: 300\n      weeks_remaining: 1\n      urgency: critical\n    - path: bloat-detector/SKILL.md\n      current: 412\n      limit: 500\n      weeks_remaining: 4\n      urgency: high\n  rankings:\n    - path: context-optimization.md\n      urgency: 0.92\n      category: critical\n      acceleration: accelerating\n    - path: bloat-detector/SKILL.md\n      urgency: 0.67\n      category: high\n      acceleration: steady\n```\n\n## Integration with Bloat Scan\n\nGrowth analysis feeds into the bloat detection pipeline:\n\n- **Fast-growing files** get flagged for proactive review\n  before they become bloated\n- **Threshold alerts** trigger modularization suggestions\n  from the `remediation-types` module\n- **Urgency rankings** prioritize the bloat scan report's\n  findings list\n\n### Coordination with Other Modules\n\n- `quick-scan`: Growth data adds time dimension to\n  size-based findings\n- `git-history-analysis`: Shares git log data;\n  growth-analysis focuses on trends while\n  git-history focuses on staleness and churn\n- `remediation-types`: Growth-triggered items map to\n  REFACTOR (split) or ARCHIVE (stabilize) actions\n\n## Limitations\n\n- Requires at least 3 weeks of git history for\n  meaningful forecasts\n- Linear projection does not capture seasonal patterns\n  or burst development cycles\n- Merge commits can skew line counts; use `--no-merges`\n  when possible\n- Renamed files appear as delete + add, inflating\n  apparent growth\n\nFile v1.9.16:modules/quick-scan.md\n\n---\nmodule: quick-scan\ncategory: tier-1\ndependencies: [Bash, Grep, Glob]\nestimated_tokens: 200\n---\n\n# Quick Scan Module\n\nFast heuristic-based bloat detection without external tools. Completes in < 5 minutes.\n\n## Detection Patterns\n\n### 1. Large Files (God Class Candidates)\n\n```bash\n# Find files > 500 lines (excluding cache and dependency directories)\nfind . -type f \\( -name \"*.py\" -o -name \"*.js\" -o -name \"*.ts\" \\) \\\n  -not -path \"*/.venv/*\" \\\n  -not -path \"*/venv/*\" \\\n  -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/.pytest_cache/*\" \\\n  -\n\nArchive v1.9.15: 11 files, 25097 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2342b), SKILL.md (5207b), _meta.json (146b)\n\nArchive v1.9.14: 11 files, 25169 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2774b), SKILL.md (5207b), _meta.json (146b)\n\nArchive v1.9.13: 11 files, 25170 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2552b), SKILL.md (5207b), _meta.json (146b)\n\nArchive v1.9.12: 11 files, 25024 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2269b), SKILL.md (5207b), _meta.json (146b)\n\nArchive v1.0.3: 11 files, 24944 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (7661b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2518b), skill-card.md (2055b), SKILL.md (5207b), _meta.json (145b)\n\nArchive v1.0.2: 11 files, 24065 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (6676b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2516b), skill-card.md (2982b), SKILL.md (3855b), _meta.json (145b)\n\nArchive v1.0.1: 10 files, 22624 bytes\n\nFiles: modules/ai-generated-bloat.md (7823b), modules/code-bloat-patterns.md (6402b), modules/documentation-bloat.md (2446b), modules/git-history-analysis.md (6676b), modules/growth-analysis.md (7858b), modules/quick-scan.md (5794b), modules/remediation-types.md (3087b), modules/static-analysis-integration.md (2516b), SKILL.md (3855b), _meta.json (145b)","readmeExcerpt":"Skill: bloat-detector Owner: athola Summary: Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:09:25.175Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:31:57.564Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:48:46.997Z | user Release v1.9.16 v1.9.15 | 2026-07-04T21:22:21.079Z | user Release v1.9.15 v1.9.14 | 2026-06-30T17","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"/bloat-scan"},{"language":"bash","snippet":"/bloat-scan --level 2 --focus code   # or docs, deps"},{"language":"bash","snippet":"/bloat-scan --level 3 --report audit.md"},{"language":"text","snippet":"Priority = (Token_Savings × 0.4) + (Maintenance × 0.3) + (Confidence × 0.2) + (Ease × 0.1)"},{"language":"bash","snippet":"# Detect similar code blocks (built-in, no external deps)\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5\n\n# JSON output for CI integration\npython3 plugins/conserve/scripts/detect_duplicates.py . --format json --threshold 15\n\n# Heuristic: functions with near-identical signatures\ngrep -rn \"^def \" --include=\"*.py\" . | cut -d: -f2 | sort | uniq -c | sort -rn | head -10"},{"language":"bash","snippet":"# Find vibe coding commits\ngit log --oneline --shortstat | grep -E \"[0-9]{3,} insertion\" | head -20\n\n# Commits with high insertion:deletion ratio (adding without cleanup)\ngit log --shortstat --pretty=format:\"%h %s\" | awk '/insertion|deletion/ {\n  ins=$4; del=$6;\n  if (ins > 200 && (del == \"\" || ins/del > 10)) print prev, ins, del\n} {prev=$0}'"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: bloat-detector\ndescription: |\n  Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans\nversion: 1.9.8\ntriggers:\n  - bloat\n  - cleanup\n  - static-analysis\n  - technical-debt\n  - optimization\n  - codebase feels large or before a release\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/conserve\", \"emoji\": \"\\ud83e\\udd9e\"}}\nsource: claude-night-market\nsource_plugin: conserve\n---\n\n> **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n# Bloat Detector\n\nSystematically detect and eliminate codebase bloat through progressive analysis tiers.\n\n## Bloat Categories\n\n| Category | Examples |\n|----------|----------|\n| **Code** | Dead code, God classes, Lava flow, duplication |\n| **AI-Generated** | Tab-completion bloat, vibe coding, hallucinated deps |\n| **Documentation** | Redundancy, verbosity, stale content, slop |\n| **Dependencies** | Unused imports, dependency bloat, phantom packages |\n| **Git History** | Stale files, low-churn code, massive single commits |\n\n## Quick Start\n\n### Tier 1: Quick Scan (2-5 min, no tools)\n```bash\n/bloat-scan\n```\nDetects: Large files, stale code, old TODOs, commented blocks, basic duplication\n\n### Tier 2: Targeted Analysis (10-20 min, optional tools)\n```bash\n/bloat-scan --level 2 --focus code   # or docs, deps\n```\nAdds: Static analysis (Vulture/Knip), git churn hotspots, doc similarity\n\n### Tier 3: Deep Audit (30-60 min, full tooling)\n```bash\n/bloat-scan --level 3 --report audit.md\n```\nAdds: Cross-file redundancy, dependency graphs, readability metrics\n\n## When To Use\n\n| Do | Don't |\n|----|-------|\n| Context usage > 30% | Active feature development |\n| Quarterly maintenance | Time-sensitive bugs |\n| Pre-release cleanup | Codebase < 1000 lines |\n| Before major refactoring | Tools unavailable (Tier 2/3) |\n\n## When NOT To Use\n\n- Active feature development\n- Time-sensitive bugs\n- Codebase < 1000 lines\n\n## Confidence Levels\n\n| Level | Confidence | Action |\n|-------|------------|--------|\n| HIGH | 90-100% | Safe to remove |\n| MEDIUM | 70-89% | Review first |\n| LOW | 50-69% | Investigate |\n\n## Prioritization\n\n```\nPriority = (Token_Savings × 0.4) + (Maintenance × 0.3) + (Confidence × 0.2) + (Ease × 0.1)\n```\n\n## Module Architecture\n\n**Tier 1** (always available):\n- See `modules/quick-scan.md` - Heuristics, no tools\n- See `modules/git-history-analysis.md` - Staleness, churn, vibe coding signatures\n- See `modules/growth-analysis.md` - Growth velocity, forecasts, threshold alerts\n\n**Tier 2** (optional tools):\n- See `modules/code-bloat-patterns.md` - Anti-patterns (God class, Lava flow)\n- See `modules/ai-generated-bloat.md` - AI-specific patterns (Tab bloat, hallucinations)\n- See `modules/documentation-bloat.md` - Redundancy, readability, slop detection\n- See `modules/stat"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-conserve-bloat-detector\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787749765175\n}"},{"path":"modules/ai-generated-bloat.md","content":"---\nmodule: ai-generated-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 200\n---\n\n# AI-Generated Bloat Detection Module\n\nDetect bloat patterns specific to AI-assisted coding: vibe coding artifacts, slop patterns, and agent psychosis indicators.\n\n## Why This Module Exists\n\nAI coding has created qualitatively different bloat than traditional development:\n- **2024**: First year copy/pasted lines exceeded refactored lines (GitClear)\n- **Refactoring**: Dropped from 25% (2021) to <10% (2024), predicted 3% (2025)\n- **Duplication**: 8x increase in 5+ line code blocks\n\n## AI Bloat Patterns\n\n### 1. Tab-Completion Bloat (Repetitive Logic)\n\n**Definition**: Same pattern repeated 3+ times instead of abstracted into shared function.\n\n```bash\n# Detect similar code blocks (built-in, no external deps)\npython3 plugins/conserve/scripts/detect_duplicates.py . --min-lines 5\n\n# JSON output for CI integration\npython3 plugins/conserve/scripts/detect_duplicates.py . --format json --threshold 15\n\n# Heuristic: functions with near-identical signatures\ngrep -rn \"^def \" --include=\"*.py\" . | cut -d: -f2 | sort | uniq -c | sort -rn | head -10\n```\n\n**Confidence**: HIGH (85%)\n**Action**: REFACTOR - extract to shared utility\n**Rationale**: AI suggests new implementations rather than reusing existing code\n\n### 2. Massive Single Commits (Vibe Coding Signature)\n\n**Definition**: Commits with >500 insertions, especially without proportional tests.\n\n```bash\n# Find vibe coding commits\ngit log --oneline --shortstat | grep -E \"[0-9]{3,} insertion\" | head -20\n\n# Commits with high insertion:deletion ratio (adding without cleanup)\ngit log --shortstat --pretty=format:\"%h %s\" | awk '/insertion|deletion/ {\n  ins=$4; del=$6;\n  if (ins > 200 && (del == \"\" || ins/del > 10)) print prev, ins, del\n} {prev=$0}'\n```\n\n**Confidence**: MEDIUM (70%)\n**Action**: INVESTIGATE - review for understanding gaps\n**Rationale**: Large additions without refactoring indicate Tab-driven development\n\n### 3. Hallucinated Dependencies\n\n**Definition**: Imports referencing non-existent packages (AI hallucination).\n\n```bash\n# Python: Check for uninstallable packages\npip freeze > /tmp/installed.txt\ngrep -rh \"^import \\|^from \" --include=\"*.py\" . | \\\n  sed 's/^import //;s/^from //;s/ import.*//' | \\\n  sort -u | while read pkg; do\n    root=$(echo $pkg | cut -d. -f1)\n    grep -q \"^$root\" /tmp/installed.txt || echo \"HALLUCINATED?: $pkg\"\n  done\n\n# JavaScript: Check for phantom packages\njq -r '.dependencies // {} | keys[]' package.json | while read pkg; do\n  npm view $pkg version 2>/dev/null || echo \"HALLUCINATED?: $pkg\"\ndone\n```\n\n**Confidence**: HIGH (95%)\n**Action**: DELETE or REPLACE\n**Rationale**: AI invents plausible-sounding packages (slopsquatting risk)\n\n### 4. Happy Path Only (Test Coverage Gap)\n\n**Definition**: Code >200 lines with no corresponding tests, or tests without error assertions.\n\n```bash\n# Files without test coverage\nfind . -name \"*.py\" ! -path \"*/test*\" \\\n  -not -path \"*/.venv/*\" -not -pa"},{"path":"modules/code-bloat-patterns.md","content":"---\nmodule: code-bloat-patterns\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 150\n---\n\n# Code Bloat Patterns Module\n\nDetect anti-patterns using pattern recognition and heuristics. Works without external tools.\n\n> **Tool Preference (Claude Code 2.1.31+)**: The bash snippets in this module are reference implementations for external script execution or CI pipelines. When performing these analyses directly within Claude Code, prefer native tools: use Grep instead of `grep`, Glob instead of `find`, and Read instead of `cat`/`sed`.\n\n## Anti-Patterns\n\n### 1. God Class\n**Definition:** Single class with > 500 lines, > 10 methods, multiple responsibilities.\n\n```bash\n# Quick detection\nfind . -name \"*.py\" \\\n  -not -path \"*/.venv/*\" -not -path \"*/__pycache__/*\" \\\n  -not -path \"*/node_modules/*\" -not -path \"*/.git/*\" \\\n  -exec sh -c 'lines=$(wc -l < \"$1\"); [ $lines -gt 500 ] && echo \"GOD_CLASS: $1 - $lines lines\"' _ {} \\;\n```\n**Confidence:** HIGH (85%) | **Action:** REFACTOR into focused modules\n\n### 2. Lava Flow\n**Definition:** Ancient untouched code - commented blocks, old TODOs.\n\n```bash\n# Find files with >20% commented code\ngrep -rn \"^#\\|^//\" --include=\"*.py\" . | cut -d: -f1 | sort | uniq -c | sort -rn | head -10\n```\n**Confidence:** HIGH (90%) | **Action:** DELETE commented code\n\n### 3. Dead Code\n**Detection:** Use static analysis (Vulture/Knip) or fallback heuristic:\n```bash\n# Heuristic: find functions with 0 calls\ngrep -rn \"^def \" --include=\"*.py\" . | while read line; do\n  func=$(echo $line | awk '{print $2}' | cut -d'(' -f1)\n  [ $(git grep -c \"$func(\" 2>/dev/null || echo 0) -eq 1 ] && echo \"DEAD: $func\"\ndone\n```\n**Confidence:** MEDIUM (70%) heuristic, HIGH (90%) with tools | **Action:** DELETE\n\n### 4. Import Bloat\n```bash\n# Star imports (block tree-shaking)\ngrep -rn \"^from .* import \\*\" --include=\"*.py\" .\n\n# Unused imports (requires autoflake)\nautoflake --check --remove-all-unused-imports -r .\n```\n**Confidence:** HIGH (95%) | **Action:** Fix imports\n\n### 5. Duplication\n**Intra-file:** Hash-based block detection (5+ line matches)\n**Cross-file:** Function signature matching\n**Semantic:** AST comparison (80%+ similarity)\n\n**Confidence:** HIGH (85%) | **Action:** EXTRACT to shared utility\n\n## Language-Specific\n\n### Python\n- Circular imports: Files with 20+ imports\n- Deep nesting: > 4 indentation levels\n\n### JavaScript/TypeScript\n- Barrel files: `export * from` breaks tree-shaking\n- CommonJS in ESM: `module.exports`/`require()` blocks bundler optimization\n\n## AI-Amplified Patterns\n\nThese traditional patterns are amplified by AI coding tools:\n\n### 6. Tab-Completion Duplication\n**Definition:** AI suggests similar code blocks instead of reusing existing functions.\n**2024 Data:** 8x increase in 5+ line duplicated blocks (GitClear)\n\n```bash\n# Quick detection: near-identical function signatures\ngrep -rn \"^def \" --include=\"*.py\" . | awk -F'def ' '{print $2}' | \\\n  cut -d'(' -f1 | sort | uniq -c | sort -rn | awk '$1 > 1'\n```\n**Confidence:** HIG"},{"path":"modules/documentation-bloat.md","content":"---\nmodule: documentation-bloat\ncategory: tier-2\ndependencies: [Bash, Grep, Read]\nestimated_tokens: 120\n---\n\n# Documentation Bloat Module\n\nDetect documentation redundancy, verbosity, and poor readability.\n\n## Detection Categories\n\n### 1. Duplicate Documentation\n\n#### Cross-File (Jaccard Similarity)\n```bash\n# Quick similarity check between two files\nwords1=$(tr '[:space:]' '\\n' < file1.md | sort -u)\nwords2=$(tr '[:space:]' '\\n' < file2.md | sort -u)\n# > 70% overlap = potential duplication\n```\n\n| Similarity | Confidence | Action |\n|------------|------------|--------|\n| > 90% | HIGH (95%) | DELETE one, keep recent |\n| 70-90% | MEDIUM (80%) | MERGE, preserve unique |\n| 50-70% | LOW (60%) | CROSS-LINK |\n\n#### Intra-File (Section Hashing)\nHash each `##` section's normalized content. Duplicates = repeated sections.\n\n**Confidence:** HIGH (85%)\n\n### 2. Excessive Verbosity\n\n| Metric | Threshold | Action |\n|--------|-----------|--------|\n| Word count | > 500 words/section | Condense |\n| Sentence length | > 25 words avg | Simplify |\n| Passive voice | > 30% | Rewrite active |\n| Readability | Flesch < 40 | Simplify |\n\n```bash\n# Quick verbosity check\nwc -w file.md  # Total words\nrg -c '\\.' file.md  # Approximate sentences (or grep -c)\n```\n\n### 3. Stale Documentation\n\n| Signal | Confidence | Action |\n|--------|------------|--------|\n| Unchanged 12+ months | HIGH (85%) | Review/Archive |\n| References deleted code | HIGH (90%) | Update/Delete |\n| No git activity | MEDIUM (75%) | Investigate |\n\n```bash\n# Find stale docs\ngit log -1 --format=\"%ar\" -- docs/*.md | rg -E \"year|months\"\n# fallback: grep -E \"year|months\"\n```\n\n### 4. Missing/Outdated References\n\n- Broken internal links: `rg -oP '\\[.*?\\]\\((?!http).*?\\)' *.md` (or `grep -oP`)\n- References to deleted files\n- Outdated API examples\n\n**Confidence:** HIGH (90%) for broken links\n\n## Scoring\n\n```python\ndef doc_bloat_score(metrics):\n    score = 0\n    if metrics['duplicate_ratio'] > 0.3: score += 30\n    if metrics['avg_words_per_section'] > 500: score += 20\n    if metrics['readability'] < 40: score += 15\n    if metrics['stale_months'] > 12: score += 25\n    return min(100, score)\n```\n\n## Output Format\n\n```yaml\nfile: docs/old-guide.md\nbloat_type: [duplicate, verbose, stale]\nbloat_score: 72/100\nconfidence: HIGH\ntoken_estimate: ~1,200\nsimilar_to: docs/guide.md (87%)\naction: MERGE\n```\n\n## Related\n- `quick-scan` - Tier 1 stale detection\n- `git-history-analysis` - Activity signals"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Skill: bloat-detector Owner: athola Summary: Detects codebase bloat via dead code, duplication, complexity, and doc bloat scans Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:09:25.175Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:31:57.564Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:48:46.997Z | user Release v1.9.16 v1.9.15 | 2026-07-04T21:22:21.079Z | user Release v1.9.15 v1.9.14 | 2026-06-30T17","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1216,"uniquenessScore":54,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T07:25:54.796Z","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-10T07:25:54.796Z","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-10T10:02:19.277Z","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"}]}}}