Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
docs: lead with code health as a measure-locate-fix loop and document refactoring intelligence (#595)
Raghav Chamadiyae25948eb9896
diff --git a/.github/assets/health-loop.svg b/.github/assets/health-loop.svgnew file mode 100644index 000000000..85ee7b80e--- /dev/null+++ b/.github/assets/health-loop.svg@@ -0,0 +1,79 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 624" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#94A3B8"/>+ </marker>+ </defs>++ <!-- backdrop -->+ <rect x="0" y="0" width="1200" height="624" rx="16" fill="#FFFFFF"/>+ <rect x="0.5" y="0.5" width="1199" height="623" rx="16" fill="none" stroke="#E5E7EB"/>++ <!-- top: the engine -->+ <rect x="330" y="28" width="540" height="48" rx="24" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="600" y="52" text-anchor="middle" fill="#0F172A" font-size="16" font-weight="700">25 deterministic biomarkers</text>+ <text x="600" y="69" text-anchor="middle" fill="#94A3B8" font-size="12">tree-sitter + git history · zero LLM · under 30s</text>++ <!-- fan-out connectors -->+ <path d="M600,76 L600,96 M300,96 L900,96 M300,96 L300,116 M600,96 L600,116 M900,96 L900,116" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#arrow)"/>++ <!-- ===== MEASURE ===== -->+ <text x="40" y="180" fill="#F59520" font-size="13" font-weight="700" letter-spacing="2">MEASURE</text>++ <!-- defect (headline) -->+ <rect x="140" y="120" width="320" height="118" rx="12" fill="#FEF6EC" stroke="#F59520" stroke-opacity="0.75"/>+ <text x="160" y="150" fill="#B45309" font-size="11" font-weight="700" letter-spacing="1.5">★ HEADLINE</text>+ <text x="160" y="180" fill="#0F172A" font-size="20" font-weight="700">Defect risk</text>+ <text x="160" y="206" fill="#64748B" font-size="13">Bug-calibrated, 1–10 per file.</text>+ <text x="160" y="224" fill="#64748B" font-size="13">The number everything is graded on.</text>++ <!-- maintainability -->+ <rect x="490" y="120" width="320" height="118" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="510" y="150" fill="#94A3B8" font-size="11" font-weight="700" letter-spacing="1.5">CO-EQUAL VIEW</text>+ <text x="510" y="180" fill="#0F172A" font-size="20" font-weight="700">Maintainability</text>+ <text x="510" y="206" fill="#64748B" font-size="13">Cohesion, brain methods, DRY,</text>+ <text x="510" y="224" fill="#64748B" font-size="13">primitive obsession — change cost.</text>++ <!-- performance -->+ <rect x="840" y="120" width="320" height="118" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="860" y="150" fill="#94A3B8" font-size="11" font-weight="700" letter-spacing="1.5">CO-EQUAL VIEW</text>+ <text x="860" y="180" fill="#0F172A" font-size="20" font-weight="700">Performance risk</text>+ <text x="860" y="206" fill="#64748B" font-size="13">N+1 / I-O-in-loop shapes,</text>+ <text x="860" y="224" fill="#64748B" font-size="13">resolved through the call graph.</text>++ <!-- converge -->+ <path d="M300,238 L300,262 L600,262 M900,238 L900,262 L600,262 M650,262 L600,262 M600,262 L600,290" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#arrow)"/>++ <!-- ===== LOCATE ===== -->+ <text x="40" y="332" fill="#F59520" font-size="13" font-weight="700" letter-spacing="2">LOCATE</text>+ <rect x="140" y="298" width="1020" height="64" rx="12" fill="#F0F7FF" stroke="#BFDBFE"/>+ <text x="600" y="326" text-anchor="middle" fill="#1E3A8A" font-size="15" font-weight="600">Graph + git history pinpoint where the risk concentrates</text>+ <text x="600" y="348" text-anchor="middle" fill="#64748B" font-size="13">call-graph centrality · hot-path proximity · co-change blast radius</text>++ <path d="M600,362 L600,388" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#arrow)"/>++ <!-- ===== FIX ===== -->+ <text x="40" y="468" fill="#F59520" font-size="13" font-weight="700" letter-spacing="2">FIX</text>+ <rect x="140" y="396" width="1020" height="98" rx="12" fill="#F0FDF4" stroke="#10B981" stroke-opacity="0.8"/>+ <text x="160" y="424" fill="#047857" font-size="13" font-weight="700" letter-spacing="1.5">REFACTORING INTELLIGENCE</text>+ <text x="160" y="448" fill="#64748B" font-size="13">Concrete, graph-aware plans — not template strings:</text>++ <!-- four chips -->+ <g font-size="13.5" font-weight="600">+ <rect x="160" y="460" width="220" height="26" rx="13" fill="#ECFDF5" stroke="#6EE7B7"/>+ <text x="270" y="477" text-anchor="middle" fill="#065F46">Extract Class</text>+ <rect x="392" y="460" width="220" height="26" rx="13" fill="#ECFDF5" stroke="#6EE7B7"/>+ <text x="502" y="477" text-anchor="middle" fill="#065F46">Extract Helper</text>+ <rect x="624" y="460" width="220" height="26" rx="13" fill="#ECFDF5" stroke="#6EE7B7"/>+ <text x="734" y="477" text-anchor="middle" fill="#065F46">Move Method</text>+ <rect x="856" y="460" width="220" height="26" rx="13" fill="#ECFDF5" stroke="#6EE7B7"/>+ <text x="966" y="477" text-anchor="middle" fill="#065F46">Break Cycle</text>+ </g>++ <path d="M600,494 L600,520" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#arrow)"/>++ <!-- hand-off -->+ <rect x="330" y="528" width="540" height="68" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="600" y="558" text-anchor="middle" fill="#0F172A" font-size="16" font-weight="700">Your agent executes the plan</text>+ <text x="600" y="580" text-anchor="middle" fill="#94A3B8" font-size="13">copy-to-agent prompt · opt-in LLM code-gen + diff · CLI · MCP · web</text>+</svg>diff --git a/.github/assets/intelligence-layers.svg b/.github/assets/intelligence-layers.svgnew file mode 100644index 000000000..bbfeb4549--- /dev/null+++ b/.github/assets/intelligence-layers.svg@@ -0,0 +1,88 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 520" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">+ <defs>+ <marker id="a2" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#94A3B8"/>+ </marker>+ </defs>++ <rect x="0" y="0" width="1200" height="520" rx="16" fill="#FFFFFF"/>+ <rect x="0.5" y="0.5" width="1199" height="519" rx="16" fill="none" stroke="#E5E7EB"/>++ <!-- one index -->+ <rect x="400" y="26" width="400" height="50" rx="25" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="600" y="49" text-anchor="middle" fill="#0F172A" font-size="16" font-weight="700">One index · <tspan fill="#64748B" font-weight="400">repowise init</tspan></text>+ <text x="600" y="67" text-anchor="middle" fill="#94A3B8" font-size="12">indexed once, kept in sync on every commit</text>++ <!-- fan-out to five layers -->+ <path d="M600,76 L600,92 M230,92 L980,92 M230,92 L230,108 M417.5,92 L417.5,108 M600,92 L600,108 M782.5,92 L782.5,108 M980,92 L980,108" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#a2)"/>++ <!-- five layer cards -->+ <g>+ <!-- Graph -->+ <rect x="140" y="112" width="180" height="168" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="160" y="143" fill="#2563EB" font-size="18" font-weight="700">◈</text>+ <text x="184" y="143" fill="#0F172A" font-size="17" font-weight="700">Graph</text>+ <text x="160" y="172" fill="#64748B" font-size="12.5">Dependency + call</text>+ <text x="160" y="190" fill="#64748B" font-size="12.5">graph, 15 languages.</text>+ <text x="160" y="208" fill="#64748B" font-size="12.5">Communities,</text>+ <text x="160" y="226" fill="#64748B" font-size="12.5">centrality, flows.</text>++ <!-- Git -->+ <rect x="327.5" y="112" width="180" height="168" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="347.5" y="143" fill="#2563EB" font-size="18" font-weight="700">◈</text>+ <text x="371.5" y="143" fill="#0F172A" font-size="17" font-weight="700">Git</text>+ <text x="347.5" y="172" fill="#64748B" font-size="12.5">Hotspots, ownership,</text>+ <text x="347.5" y="190" fill="#64748B" font-size="12.5">co-change coupling,</text>+ <text x="347.5" y="208" fill="#64748B" font-size="12.5">bus factor — signals</text>+ <text x="347.5" y="226" fill="#64748B" font-size="12.5">statics can't see.</text>++ <!-- Docs -->+ <rect x="515" y="112" width="180" height="168" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="535" y="143" fill="#2563EB" font-size="18" font-weight="700">◈</text>+ <text x="559" y="143" fill="#0F172A" font-size="17" font-weight="700">Docs</text>+ <text x="535" y="172" fill="#64748B" font-size="12.5">LLM wiki per file,</text>+ <text x="535" y="190" fill="#64748B" font-size="12.5">rebuilt every commit.</text>+ <text x="535" y="208" fill="#64748B" font-size="12.5">Hybrid RAG search,</text>+ <text x="535" y="226" fill="#64748B" font-size="12.5">freshness scoring.</text>++ <!-- Decisions -->+ <rect x="702.5" y="112" width="180" height="168" rx="12" fill="#F8FAFC" stroke="#E2E8F0"/>+ <text x="722.5" y="143" fill="#2563EB" font-size="18" font-weight="700">◈</text>+ <text x="746.5" y="143" fill="#0F172A" font-size="17" font-weight="700">Decisions</text>+ <text x="722.5" y="172" fill="#64748B" font-size="12.5">Architectural</text>+ <text x="722.5" y="190" fill="#64748B" font-size="12.5">decisions mined from</text>+ <text x="722.5" y="208" fill="#64748B" font-size="12.5">8 sources, evidence-</text>+ <text x="722.5" y="226" fill="#64748B" font-size="12.5">backed, linked.</text>++ <!-- Code Health (highlight) -->+ <rect x="890" y="112" width="180" height="168" rx="12" fill="#FEF6EC" stroke="#F59520" stroke-opacity="0.8"/>+ <text x="910" y="143" fill="#F59520" font-size="18" font-weight="700">★</text>+ <text x="934" y="143" fill="#0F172A" font-size="17" font-weight="700">Code Health</text>+ <text x="910" y="172" fill="#B45309" font-size="12.5">Defect-validated.</text>+ <text x="910" y="190" fill="#64748B" font-size="12.5">3 signals + concrete</text>+ <text x="910" y="208" fill="#64748B" font-size="12.5">refactoring plans.</text>+ <text x="910" y="226" fill="#64748B" font-size="12.5">Zero LLM, under 30s.</text>++ <!-- per-card subtle footer rule + signature tool -->+ <line x1="160" y1="252" x2="300" y2="252" stroke="#E2E8F0"/>+ <line x1="347.5" y1="252" x2="487.5" y2="252" stroke="#E2E8F0"/>+ <line x1="535" y1="252" x2="675" y2="252" stroke="#E2E8F0"/>+ <line x1="722.5" y1="252" x2="862.5" y2="252" stroke="#E2E8F0"/>+ <line x1="910" y1="252" x2="1050" y2="252" stroke="#F59520" stroke-opacity="0.35"/>+ <text x="160" y="271" fill="#94A3B8" font-size="11" font-family="monospace">get_context</text>+ <text x="347.5" y="271" fill="#94A3B8" font-size="11" font-family="monospace">get_risk</text>+ <text x="535" y="271" fill="#94A3B8" font-size="11" font-family="monospace">get_answer</text>+ <text x="722.5" y="271" fill="#94A3B8" font-size="11" font-family="monospace">get_why</text>+ <text x="910" y="271" fill="#B45309" font-size="11" font-family="monospace">get_health</text>+ </g>++ <!-- converge to delivery -->+ <path d="M230,280 L230,308 L600,308 M417.5,280 L417.5,308 M600,280 L600,308 M782.5,280 L782.5,308 L600,308 M980,280 L980,308 L600,308 M600,308 L600,332" fill="none" stroke="#CBD5E1" stroke-width="1.5" marker-end="url(#a2)"/>++ <!-- delivery surfaces -->+ <rect x="140" y="340" width="930" height="68" rx="12" fill="#F0F7FF" stroke="#BFDBFE"/>+ <text x="605" y="368" text-anchor="middle" fill="#1E3A8A" font-size="15" font-weight="600">Delivered everywhere your work happens</text>+ <text x="605" y="390" text-anchor="middle" fill="#64748B" font-size="13">9 task-shaped MCP tools · CLI · local dashboard · auto-generated CLAUDE.md / AGENTS.md · PR bot</text>++ <text x="600" y="452" text-anchor="middle" fill="#94A3B8" font-size="13" font-style="italic">Each layer compounds the others — the graph locates what git flags, health scores it, decisions explain it.</text>+</svg>diff --git a/README.md b/README.mdindex 29c35dd9c..e844337b2 100644--- a/README.md+++ b/README.md@@ -29,6 +29,7 @@<p align="center"><sub><a href="#the-five-layers">Layers</a> ·<a href="#-code-health--the-layer-nobody-else-nails">Code Health</a> ·+ <a href="#refactoring-intelligence">Refactoring</a> ·<a href="#benchmarks">Benchmarks</a> ·<a href="#supported-languages">Languages</a> ·<a href="#quickstart">Quickstart</a> ·@@ -40,9 +41,9 @@---<p align="center">- <strong>up to −96% context tokens</strong> · <strong>−70% agent tool calls</strong> · <strong>answer quality at parity</strong><br/>- <strong>60–90% fewer tokens</strong> on noisy command output · errors-first, fully reversible<br/>- <strong>code health that predicts real bugs</strong> · <strong>ROC AUC 0.74</strong> · <strong>2.3×</strong> the commercial market leader under a fixed review budget+ <strong>measure, locate, and fix what your AI ships</strong><br/>+ <strong>code health that predicts real bugs</strong> · <strong>ROC AUC 0.74</strong> · <strong>2.3×</strong> the commercial market leader under a fixed review budget<br/>+ <strong>graph-aware refactoring plans</strong> your agent can execute · <strong>up to −96% context tokens</strong> · <strong>−70% agent tool calls</strong> at answer-quality parity</p><p align="center"><sub>Measured, reproducible, on public codebases — <a href="#benchmarks">see the benchmarks ↓</a></sub></p>@@ -53,24 +54,27 @@</div>-Your AI coding agent reads files. It doesn't know which ones change together,-which ones are dead, or *why* they were built the way they were. It has the-source code and no memory of how the codebase got there.--repowise fixes that. It indexes your codebase into **five intelligence layers** —-dependency graph, git history, auto-generated docs, architectural decisions, and-code health — and exposes them to Claude Code, Codex, and any MCP-compatible agent-through **nine task-shaped tools**. The result: your agent answers *"why does-auth work this way?"* instead of *"here is what `auth.ts` contains"* — with-**fewer tool calls, fewer file reads, and lower cost per query, at comparable-answer quality** ([benchmarks ↓](#benchmarks)).--That is one half of the job. AI now writes a large and growing share of the code,-and the humans accountable for it need to trust what ships. So the same index-also powers a **defect-validated code-health score**, **change-risk scoring** on-every PR, and **agent provenance** that shows how much of your code an AI wrote-and whether it is healthy. One index: context your agent can use, signals your-team can trust.+AI now writes a large and growing share of the code, and the humans accountable+for it have to trust what ships. A score that says *"this file is risky"* isn't+enough — you need to know **where** the risk concentrates and **how** to fix it.++repowise closes that loop. It indexes your codebase once and scores **every file+for defect risk, maintainability, and performance** from 25 deterministic+biomarkers — calibrated against a real defect corpus, no LLM, in under 30 seconds+([the proof ↓](#-code-health--the-layer-nobody-else-nails)). The same index then+**locates** the risk through a real dependency graph and git history, and+**generates the fix**: concrete, graph-aware refactoring plans — split this god+class, move this method, break this dependency cycle, dedup this clone — that+your coding agent can execute.++And because it is all one index, your agent gets the rest for free: **five+intelligence layers** — dependency graph, git history, auto-generated docs,+architectural decisions, and code health — exposed to Claude Code, Codex, and any+MCP-compatible agent through **nine task-shaped tools**. Your agent answers *"why+does auth work this way?"* instead of *"here is what `auth.ts` contains"* — with+fewer tool calls, fewer file reads, and lower cost per query, at comparable+answer quality ([benchmarks ↓](#benchmarks)). One index: context your agent can+use, signals your team can trust, and the fix it can apply.---@@ -85,7 +89,7 @@ Each layer is queryable from the CLI, the MCP tools, and the local dashboard.| **◈ Git** | hotspots (churn × complexity) · ownership % · co-change pairs (hidden coupling) · bus factor · contributor profiles · module health · reviewer suggestions | Behavioral signals static analysis can't see || **◈ Docs** | LLM-generated wiki per module/file · incremental on every commit · freshness + confidence scoring · hybrid RAG search (FTS + vector via RRF) · selectable wiki styles (comprehensive / reference / tutorial / caveman) | Stays current — rebuilt every commit || **◈ Decisions** | architectural decisions mined from **8 sources**, evidence-backed (verified / fuzzy / unverified), linked to graph nodes, connected by `supersedes`/`refines`/`conflicts_with` edges, tracked for staleness | **★ Captured nowhere else** |-| **★ Code Health** | **25 deterministic biomarkers**, 1–10 per file · **three signals: defect risk · maintainability · performance** · coverage ingestion · trend alerts · refactoring targets · **zero LLM, <30s** | **★ Defect-validated — our edge ↓** |+| **★ Code Health** | **25 deterministic biomarkers**, 1–10 per file · **three signals: defect risk · maintainability · performance** · coverage ingestion · trend alerts · **concrete graph-aware refactoring plans** (Extract Class / Helper / Move Method / Break Cycle) · **zero LLM, <30s** | **★ Defect-validated, with the fix attached — our edge ↓** |Full deep-dive on every layer (graph, git, docs, decisions, hooks, auto-sync,dead code, CLAUDE.md generation): **[docs/INTELLIGENCE_LAYERS.md →](docs/INTELLIGENCE_LAYERS.md)**@@ -95,7 +99,14 @@ dead code, CLAUDE.md generation): **[docs/INTELLIGENCE_LAYERS.md →](docs/INTEL## ★ Code Health — the layer nobody else nailsCode health is repowise's deepest differentiator — the one layer with no real-equivalent, and **the only one we can prove predicts real bugs**.+equivalent, and **the only one we can prove predicts real bugs**. It runs as a+loop: **measure** every file across three signals, **locate** where the risk+concentrates through the graph and git history, then **fix** it with a concrete+refactoring plan your agent can execute.++<div align="center">+<img src=".github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle) your agent executes" width="100%" />+</div>repowise scores **every file 1–10** from **25 deterministic biomarkers** —McCabe complexity, deep nesting, brain methods, class cohesion (LCOM4), god@@ -148,6 +159,46 @@ significant). [Full methodology & CIs →](https://github.com/repowise-dev/repowUser guide & per-biomarker reference: **[docs/CODE_HEALTH.md](docs/CODE_HEALTH.md)**+### Refactoring intelligence++A health score tells you a file is in trouble. Every other tool stops there, or+prints the same static sentence for every god class in every repo. repowise names+the **specific** fix, computed deterministically from the graph, the class model,+and git co-change — the same data the score is built on:++- **Extract Class** — split an incohesive class along its real cohesion groups+ (LCOM4 components): *"these methods + these fields belong together; these don't."*+- **Extract Helper** — dedup a clone across its exact occurrences, with the+ shared helper placed at the community centroid of the files involved.+- **Move Method** — relocate a feature-envy method to the class it actually talks+ to (Jaccard distance over the call graph), not the one it lives in.+- **Break Cycle** — name the minimal set of import edges to invert to break a+ dependency cycle (greedy minimum feedback arc set over the real import graph).++Every plan carries its **blast radius** (the callers and co-changing files that+must move with it) and is ranked **graph-aware** — `impact × call-graph centrality+× blast radius`, so a fix on a central hub outranks the same fix on a leaf. That+is the wedge: the leading commercial tool ranks by churn alone, stays+within-function, and ignores its own coupling signal when it generates code.++The deterministic plan is the product; an LLM is **strictly opt-in** and never in+the indexing hot path. Turn it on and any plan can be expanded into generated code+plus a unified diff, fed the graph and co-change context a bare codegen tool+throws away.++```bash+repowise health --refactoring-targets # ranked plans, biggest win for least effort+```++```python+get_health(include=["refactoring"]) # the same structured plans over MCP+```++The web **Refactoring** tab renders each plan as a card — the split groups as a+tree, the move arrow, the clone occurrences with line links — with a+**copy-to-agent** button and the opt-in **Generate code** diff view. Full+reference: **[docs/REFACTORING.md](docs/REFACTORING.md)**+---## Change risk & agent provenance@@ -259,8 +310,9 @@ finder) · **C4 Architecture** (Context → Containers → Components) · **Risk(hotspots, ownership heatmap, module health, dead code, blast radius) ·**Contributors** (per-author profiles) · **Decisions** (evidence drawer,evolution timeline, decision-graph) · **Health** (three signals — defect ·-maintainability · performance — coverage, trends) · **Security** (local pattern-scan) · **Costs** · **Workspace**+maintainability · performance — coverage, trends) · **Refactoring** (ranked plan+cards, blast radius, copy-to-agent, opt-in code-gen diff) · **Security** (local+pattern scan) · **Costs** · **Workspace**(cross-repo contracts & co-changes). Full view-by-view list in[docs/USER_GUIDE.md](docs/USER_GUIDE.md).@@ -403,7 +455,7 @@ diverges from live `.git/HEAD`.| `get_risk(targets, changed_files?)` | Hotspot scores, dependents, co-change partners, ownership, test gaps, security signals. Pass `changed_files` for PR mode → a `directive` block (`will_break`, `missing_cochanges`, `missing_tests`, `governance_risk`). || `get_why(query?, targets?)` | Architectural decision records, status, evidence spans, and the supersession **lineage chain**. Falls back to git archaeology when no ADRs exist. || `get_dead_code(...)` | Unreachable code by confidence tier with cleanup-impact estimates; cross-repo consumer detection in workspace mode. |-| `get_health(targets?, include?)` | Biomarker scores per file across three signals (defect · maintainability · performance). Dashboard mode → KPIs + lowest-scoring files + module rollup; targeted mode → per-file findings. Self-check before a PR via `include`: `accuracy` (does the score find the bugs), `signals` (per-file churn / owners / prior defects), `churn_complexity`, a dimension name to filter findings, plus `coverage`, `refactoring`, `trend`. |+| `get_health(targets?, include?)` | Biomarker scores per file across three signals (defect · maintainability · performance). Dashboard mode → KPIs + lowest-scoring files + module rollup; targeted mode → per-file findings. Self-check before a PR via `include`: `accuracy` (does the score find the bugs), `signals` (per-file churn / owners / prior defects), `churn_complexity`, a dimension name to filter findings, plus `coverage`, `trend`, and `refactoring` → **structured, graph-aware refactoring plans** (split groups, move target, cut edges + blast radius), not template strings. |Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of~30 greps+reads) and the full reference: **[docs/MCP_TOOLS.md →](docs/MCP_TOOLS.md)**@@ -426,6 +478,7 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of| Untested-hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ | ❌ || Health trend + declining alerts | ✅ rolling snapshots | ❌ | ❌ | ❌ | ✅ || Refactoring recommendations | ✅ deterministic | ❌ | ❌ | ❌ | ✅ |+| Concrete cross-file refactoring plans (Extract Class / Move Method / Break Cycle) | ✅ graph-aware + blast radius | ❌ | ❌ | ❌ | ⚠️ within-function only || Git intelligence (hotspots, ownership, co-change) | ✅ | ❌ | ❌ | ❌ | ✅ || Bus factor analysis | ✅ | ❌ | ❌ | ❌ | ✅ || Dead code detection | ✅ | ❌ | ❌ | ❌ | ❌ |@@ -434,8 +487,9 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of| Local dashboard | ✅ | ❌ | ❌ | ❌ IDE only | ✅ |**repowise is the intersection:** behavioral git intelligence + a defect-validated-code-health score + auto-generated docs + agent-native MCP + architectural-decisions + multi-repo workspace intelligence — self-hostable and open source.+code-health score *with the graph-aware fix attached* + auto-generated docs ++agent-native MCP + architectural decisions + multi-repo workspace intelligence —+self-hostable and open source.Full side-by-side comparisons (CodeScene, DeepWiki, Sourcegraph, Cursor, GitClear):**[repowise.dev/compare →](https://www.repowise.dev/compare)**.diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 43b73e521..d427bdb78 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -352,7 +352,7 @@ Compute per-file code-health scores from 25 deterministic biomarkers (McCabe com|------|-------------|| `--file <path>` | Deep-dive a single file (relative path) || `--module <prefix>` | Restrict the report to files whose path starts with this prefix |-| `--refactoring-targets` | Print top refactoring candidates ranked by impact / effort |+| `--refactoring-targets` | Print structured, graph-aware refactoring plans (Extract Class / Helper / Move Method / Break Cycle), ranked `impact × centrality × blast radius`. See [REFACTORING.md](REFACTORING.md) || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) || `--coverage <path>` | Ingest a coverage report (LCOV / Cobertura / Clover). Repeat for multiple files || `--coverage-format` | Override coverage-format auto-detection: `lcov`, `cobertura`, `clover` |diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 12860e985..d134b34ff 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -9,6 +9,16 @@ recent defect history, test-quality smells, and more. **No LLM calls, no cloud rPython over tree-sitter + git data, designed to finish in under 30 seconds on a3 000-file repo.+<div align="center">+<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle) your agent executes" width="100%" />+</div>++Code health runs as a loop: **measure** every file across three signals,+**locate** where the risk concentrates through the dependency graph and git+history, then **fix** it with a concrete refactoring plan an agent can execute+(see [Refactoring targets](#refactoring-targets) and+[docs/REFACTORING.md](REFACTORING.md)).+## Quick start```bash@@ -547,18 +557,48 @@ fraction), and shows up on the `/repos/<id>/health/coverage` dashboard.repowise health --refactoring-targets```-Ranks candidates by `total_impact / effort_bucket` so the biggest wins for-the least work surface first. Each row carries a deterministic, rule-based-suggestion (`"Split this function. It carries high cyclomatic complexity..."`).+A health score tells you a file is in trouble; a refactoring target names the+**specific** fix. Repowise emits one structured `RefactoringSuggestion` per+opportunity, computed deterministically during the health pass from data it has+already produced — the call graph, the class cohesion model, the clone pairs, and+git co-change. No re-parse, no LLM, inside the same <30s budget. Four detectors+ship today:++| Type | What it names | Built from |+|------|---------------|------------|+| **Extract Class** | The cohesion groups an incohesive / god class should split into — the exact methods + fields per group. | LCOM4 union-find components; god-class shape confirmed by Lanza-Marinescu (WMC = Σ McCabe, TCC). |+| **Extract Helper** | A clone's exact occurrences and where the shared helper should live. | Rabin–Karp clone pairs (line ranges + token count + co-change); extraction site = community centroid of the files. Transitive clones are clustered into one suggestion, not pairwise nags. |+| **Move Method** | A feature-envy method and the class it actually belongs to. | Jaccard distance of the method's entity set (fields/methods it touches) to each class over the call graph; fires only when a foreign class is clearly nearer than its own. |+| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | Strongly-connected component → greedy minimum feedback arc set over the real import edges. |++Each suggestion is **structured data, not a string**: a `plan` (the split groups,+the move target, the cut edges), the `evidence` that justifies it (LCOM4=3, the+clone ranges, the cycle size), the `impact_delta` (the health deduction it+recovers), an `effort_bucket` (`S`/`M`/`L`/`XL`), and a **`blast_radius`** — the+callers and co-changing files that must move with it. Human-readable text is+rendered from the structure at the edges (CLI / MCP / web); the structure is the+source of truth.++**Ranking is graph-aware.** Suggestions sort by `impact_delta × call-graph+centrality × blast_radius`, so a plan on a central hub file outranks the same plan+on a leaf — not the churn-only sort other tools use. The default surface honors a+`min_confidence` gate (`low` / `medium` / `high`, default `medium`).For agentic workflows, the same data is one MCP call away:```python-get_health(include=["refactoring"]) # dashboard + suggestions+get_health(include=["refactoring"]) # ranked structured plansget_health(targets=["src/api/server.py"]) # one file in detailget_health(targets=["module:src.api"]) # everything in a module```+The web **Refactoring** tab renders each plan as a card (split groups as a tree,+move arrow, clone occurrences with line links) with a **copy-to-agent** prompt and+an opt-in **Generate code** action that expands a plan into generated code plus a+unified diff. Code generation is strictly opt-in (`refactoring.llm.enabled`) and+never runs in the indexing hot path. Full reference:+**[docs/REFACTORING.md](REFACTORING.md)**.+## TrendsEvery health run writes a `HealthSnapshot` row (rolling 50 entries per repo).@@ -759,6 +799,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts) · 7.0| Health trend tracking | ✅ | ✅ | ❌ | ❌ || Declining health alerts | ✅ | ✅ | ❌ | ❌ || Refactoring recommendations | ✅ deterministic | ✅ | ❌ | ❌ |+| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Move Method / Break Cycle, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file || Free for internal use | ✅ AGPL-3.0 | ❌ $15–30/author | ✅ public repos | ❌ |## See alsodiff --git a/docs/CONFIG.md b/docs/CONFIG.mdindex 367e2fd74..d6eb4a00c 100644--- a/docs/CONFIG.md+++ b/docs/CONFIG.md@@ -117,6 +117,33 @@ mcp:`get_architecture`) are added automatically in workspace mode and ignored ifnamed in single-repo mode. See [MCP_TOOLS.md](MCP_TOOLS.md#configuring-the-tool-surface).+### The `refactoring:` block++Controls the refactoring-intelligence layer — the structured Extract Class /+Extract Helper / Move Method / Break Cycle plans surfaced by `repowise health+--refactoring-targets`, `get_health(include=["refactoring"])`, and the web+Refactoring tab. The deterministic detectors run inside the normal health pass;+this block only tunes which fire and the opt-in code-generation step.++```yaml+refactoring:+ enabled: true # the deterministic plans (zero LLM, in the health pass)+ detectors:+ disabled: [] # e.g. [move_method] to silence one detector+ min_confidence: medium # low | medium | high — the surface gate+ llm:+ enabled: false # opt-in code generation; gates the generate-code endpoint+ provider: null # falls back to the repo's configured LLM provider+ model: null+```++- The deterministic layer is **zero-LLM** and runs in the `init` / `update`+ health pass; only `llm.enabled` ever calls a provider, and only on demand+ (never in the indexing hot path).+- Per-path disables reuse the `.repowise/health-rules.json` glob mechanism (the+ same one biomarkers use).+- Full reference: [REFACTORING.md](REFACTORING.md).+---## LLM providersdiff --git a/docs/INTELLIGENCE_LAYERS.md b/docs/INTELLIGENCE_LAYERS.mdindex 327283c64..b78ff7050 100644--- a/docs/INTELLIGENCE_LAYERS.md+++ b/docs/INTELLIGENCE_LAYERS.md@@ -4,6 +4,14 @@ repowise indexes your codebase **once**, builds five intelligence layers, thenkeeps them in sync on every commit. This document is the deep dive — the READMEgives the one-paragraph version of each layer and links here for the detail.+<div align="center">+<img src="../.github/assets/intelligence-layers.svg" alt="repowise's five intelligence layers — one index (repowise init) fans into Graph, Git, Docs, Decisions, and Code Health, each surfaced through its signature MCP tool and delivered through 9 task-shaped tools, the CLI, the local dashboard, auto-generated CLAUDE.md/AGENTS.md, and the PR bot" width="100%" />+</div>++The layers are not a menu — they **compound**. The graph locates what git flags,+code health scores it, decisions explain why it is shaped that way, and the docs+make all of it searchable in natural language.+1. [Graph Intelligence](#graph-intelligence)2. [Git Intelligence](#git-intelligence)3. [Documentation Intelligence](#documentation-intelligence)@@ -172,6 +180,12 @@ an L2-logistic regression — with NLOC as an explicit control — fits eachbiomarker's defect lift *beyond* file size. Only the learned constants ship; theruntime stays fully deterministic.+The same biomarker stream produces **three orthogonal signals** — **defect risk**+(the calibrated headline number), **maintainability**, and **performance risk** —+co-equal views never blended into one number. And it does not stop at scoring:+the layer **closes the loop** into concrete, graph-aware **refactoring plans**+(see below) an agent can execute.+```bashrepowise health # KPIs + lowest-scoring filesrepowise health --coverage cov.lcov # ingest coverage, light up untested-hotspot@@ -185,8 +199,14 @@ repowise status # one-line summary in the status report`coverage_gradient`).- **Trend tracking** — a rolling 50-row snapshot history powers `DecliningHealth` and `Predicted Decline` alerts.-- **Refactoring suggestions** — deterministic, rule-based, ranked by- impact / effort, on the dashboard and via `get_health(include=["refactoring"])`.+- **Refactoring plans** — deterministic, structured, **graph-aware**: Extract+ Class (LCOM4 cohesion split), Extract Helper (clone dedup), Move Method (feature+ envy), and Break Cycle (minimum feedback arc set), each carrying its concrete+ plan, recovered impact, and blast radius. Ranked by `impact × centrality ×+ blast radius`, on the dashboard **Refactoring** tab, via `repowise health+ --refactoring-targets`, and via `get_health(include=["refactoring"])`. An opt-in+ LLM pass expands any plan into generated code + a diff. See+ [`docs/REFACTORING.md`](REFACTORING.md).- **Per-file overrides** via `.repowise/health-rules.json`.Validated against real defect history — seediff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex 700d94dc2..5e32f6e92 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -436,7 +436,7 @@ code-health merge-gate judges it on.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `targets` | list[string] | No | File paths, or `module:foo` to expand a module's file set. Empty → dashboard mode. |-| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (rule-based suggestions per finding), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn × complexity quadrant points, dashboard mode), and a dimension name — `"performance"` / `"defect"` / `"maintainability"` — to filter findings to that pillar. |+| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans — see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn × complexity quadrant points, dashboard mode), and a dimension name — `"performance"` / `"defect"` / `"maintainability"` — to filter findings to that pillar. || `repo` | string | No | *(workspace only)* Target repo alias || `limit` | int | No | Max rows in the lowest-scoring file list (default 20, capped at 50) |@@ -460,6 +460,13 @@ The opt-in enrichments:- **`churn_complexity`** → `churn_complexity` points (one per recently-changedfile: 90-day commit count, max CCN, NLOC, score, churn percentile) — therefactor zone where volatility and tangle collide.+- **`refactoring`** → ranked, structured refactoring plans (not template+ strings): `extract_class` (the cohesion `groups` to split into), `extract_helper`+ (clone `occurrences` + `suggested_site`), `move_method` (`{method, from_class,+ to_class}`), and `break_cycle` (the import `cut_edges`). Each plan carries its+ `evidence`, `impact_delta`, `effort_bucket`, and `blast_radius`, ranked+ `impact × centrality × blast radius`. Full shapes in+ [`docs/REFACTORING.md`](REFACTORING.md).- **dimension filter** → narrows the returned findings to one pillar. Pair with`"biomarkers"` for the full (uncapped) finding set, e.g.`include=["biomarkers", "performance"]`.diff --git a/docs/REFACTORING.md b/docs/REFACTORING.mdnew file mode 100644index 000000000..81dff5ccd--- /dev/null+++ b/docs/REFACTORING.md@@ -0,0 +1,174 @@+# Refactoring intelligence (`repowise health --refactoring-targets`)++A health score tells you a file is in trouble. **Refactoring intelligence names+the specific fix.** Every other tool stops at the score, or prints the same+static sentence for every god class in every repo. repowise emits one structured+plan per opportunity — *split `GraphBuilder` into these three cohesive groups*,+*move `resolve_call` to the `resolvers` class where its calls actually land*,+*break the `pipeline ↔ update` import cycle by inverting this one edge* — computed+deterministically from the same graph, class model, and git data the score is+built on.++```bash+repowise health --refactoring-targets # ranked plans, biggest win for least effort+repowise health --refactoring-targets --format json+```++It runs **inside the health pass** (`init` / `update`), reusing data already+computed — no re-parse, **no LLM, no network**, inside the same <30s budget. The+LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in-code-generation)).++<div align="center">+<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — biomarkers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" />+</div>++## The four detectors++Each detector is a self-contained module registered into a registry (adding a+refactoring type is a new file + a registry entry, like the biomarker registry).+A detector degrades to **"no suggestion" on any missing signal — never a wrong+one** — and produces stable-sorted, deterministic output.++| Type | What it names | Detection (deterministic) |+|------|---------------|---------------------------|+| **Extract Class** | The cohesion groups an incohesive / god class should split into — the exact methods + fields per group. | LCOM4 union-find components (each disconnected component is a candidate class), with the god-class shape confirmed via Lanza-Marinescu (WMC = Σ McCabe, TCC). |+| **Extract Helper** | A clone's exact occurrences and where the shared helper belongs. | Rabin–Karp clone pairs (line ranges, token count, co-change). The extraction site is the community centroid of the involved files; transitive clones (A↔B, B↔C) are clustered into one suggestion, not pairwise nags. |+| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. |+| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. |++The algorithms are derived from public academic literature (Fokaefs-Tsantalis+HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking),+not from any product.++## Anatomy of a suggestion++Every suggestion is **structured data, not a string** — the structure is the+source of truth; human-readable text is rendered only at the edges (CLI / MCP /+web).++| Field | Meaning |+|-------|---------|+| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` |+| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |+| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, or the cycle + `cut_edges`. |+| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size. |+| `impact_delta` | The health score the refactoring would recover (the deduction of the biomarker it answers); `0` for the graph-native types that answer no biomarker. |+| `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. |+| `blast_radius` | What else must move: the callers, co-change partners, and importing files. |+| `confidence` | `low` \| `medium` \| `high` — drives the `min_confidence` surface gate. |+| `source_biomarker` | The finding this answers (e.g. `low_cohesion`, `god_class`, `dry_violation`). |++The per-type `plan` / `evidence` / `blast_radius` shapes are documented in full in+`packages/core/src/repowise/core/analysis/health/refactoring/models.py`.++## Ranking — graph-aware, not churn-only++Each detector sorts its own output, but the surfaces show one mixed list, so the+**global** order is what matters. A single unified rank blends three orthogonal+signals as a product of `(1 + signal)` factors (so a zero in any one dimension+shapes the order without annihilating the plan):++```+score = (1 + impact_delta)+ × (1 + log1p(target centrality)) # importer count / in-degree+ × (1 + log1p(blast radius)) # how much else moves — a mild amplifier+ × confidence_weight # high 1.25 · medium 1.0 · low 0.75+```++A plan on a **central hub file outranks the same plan on a leaf**. Because the+impact-free graph-native types (Move Method, Break Cycle) still rank via+centrality and blast radius, they interleave fairly with the impact-bearing+types rather than sinking below them. Ties break on type → file → target, so the+order is fully deterministic.++> **The wedge.** The leading commercial code-health tool ranks refactoring+> targets by **churn alone**, generates code **within-function only**, and ignores+> its own coupling signal at generation time. repowise ranks by graph centrality,+> works **across files** (class splits, method moves, cycle breaks), and feeds the+> co-change + graph context straight into the plan.++## Surfaces++```bash+repowise health --refactoring-targets # ranked table+```++```python+# MCP — the same structured plans, ranked+get_health(include=["refactoring"])+get_health(targets=["src/api/server.py"]) # one file+get_health(targets=["module:src.api"]) # one module+```++```text+# REST — what the web tab reads+GET /api/repos/{repo_id}/refactoring/targets?refactoring_type=extract_class&min_confidence=high+GET /api/repos/{repo_id}/refactoring/{suggestion_id} # one plan + blast-radius detail+```++The web **Refactoring** tab renders each plan as a card — the split groups as a+small tree, the move arrow, the clone occurrences with line links — over an+impact/effort quadrant, with per-type filter chips (URL-synced). Each card has a+**copy-to-agent** button that exports the structured plan + source spans + blast+radius as a prompt a coding agent can execute.++## Opt-in code generation++The deterministic plan is the product. An LLM is **strictly opt-in** and **never+in the indexing hot path** — it only runs when you ask for code for a specific+plan. Enable it in `.repowise/config.yaml`:++```yaml+refactoring:+ enabled: true+ detectors:+ disabled: [] # e.g. [move_method]+ min_confidence: medium # low | medium | high+ llm:+ enabled: false # opt-in; gates the generate-code endpoint+ provider: null # falls back to the repo's configured provider+ model: null+```++With `llm.enabled` set, the **Generate code** action on a plan card (or the+endpoint below) gathers the plan's real source spans off the working tree, builds+a behavior-preservation prompt carrying the structured plan **plus the+graph/co-change context** a bare codegen tool throws away, and returns the+refactored code and a unified diff. For Extract Class it runs an **LCOM4+before/after self-check** (re-walking the generated classes) to report whether the+split actually improved cohesion. Results are cached on disk by a content hash+(plan + source + model), so the same plan never pays twice.++```text+POST /api/repos/{repo_id}/refactoring/{suggestion_id}/generate-code+GET /api/repos/{repo_id}/refactoring/settings # read llm.enabled + provider/model+PUT /api/repos/{repo_id}/refactoring/settings # toggle it from the dashboard+```++Code generation needs the working tree on disk (it reads the real source spans),+so it is a local-`serve` capability: it returns `403` when disabled and `404`+when the repo has no accessible checkout. **Apply is out of scope** — the wedge is+the plan and the reviewable diff, not auto-applied edits.++## Configuration++Per-path disables reuse the existing `.repowise/health-rules.json` glob+mechanism, so a refactoring type can be silenced for generated or vendored paths+the same way a biomarker is:++```json+{+ "rules": [+ { "path": "src/generated/**", "disabled_biomarkers": ["dry_violation"] }+ ]+}+```++## See also++- [`docs/CODE_HEALTH.md`](CODE_HEALTH.md) — the biomarkers and the three health+ signals the suggestions are built on.+- [`docs/INTELLIGENCE_LAYERS.md`](INTELLIGENCE_LAYERS.md) — how code health fits+ the five-layer index.+- [`docs/MCP_TOOLS.md`](MCP_TOOLS.md) — the `get_health(include=["refactoring"])`+ response shape.