Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

docs: strengthen the code-health validation story and fix stale references (#617)

Raghav Chamadiya37f5c1d549dd
diff --git a/README.md b/README.md
index e844337b2..d4d9d83e4 100644
--- a/README.md
+++ b/README.md
@@ -2,12 +2,12 @@
<div align="center">
-<a href="https://www.repowise.dev"><img src=".github/assets/banner.png" alt="repowise — the codebase intelligence layer for your AI coding agent" width="100%" /></a>
+<a href="https://www.repowise.dev"><img src=".github/assets/banner.png" alt="repowise: the codebase intelligence layer for your AI coding agent" width="100%" /></a>
<p align="center"><strong>Five intelligence layers · Nine MCP tools · 15 languages · Multi-repo workspaces · One <code>pip install</code></strong></p>
<p align="center">
- <a href="https://www.repowise.dev"><img src="https://img.shields.io/badge/LIVE_DEMO-repowise.dev-F59520?style=for-the-badge&labelColor=0A0A0A" alt="Live demo — repowise.dev" /></a>
+ <a href="https://www.repowise.dev"><img src="https://img.shields.io/badge/LIVE_DEMO-repowise.dev-F59520?style=for-the-badge&labelColor=0A0A0A" alt="Live demo: repowise.dev" /></a>
<a href="https://github.com/repowise-dev/repowise"><img src="https://img.shields.io/badge/Star_this_repo-1E293B?style=for-the-badge&logo=github&logoColor=white&labelColor=0A0A0A" alt="Star repowise on GitHub" /></a>
</p>
@@ -28,7 +28,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="#-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> ·
@@ -42,13 +42,13 @@
<p align="center">
<strong>measure, locate, and fix what your AI ships</strong><br/>
- <strong>code health that predicts real bugs</strong> &nbsp;·&nbsp; <strong>ROC AUC 0.74</strong> &nbsp;·&nbsp; <strong>2.3×</strong> the commercial market leader under a fixed review budget<br/>
+ <strong>code health that predicts real bugs</strong> &nbsp;·&nbsp; <strong>ROC AUC 0.74 across 21 repos</strong> &nbsp;·&nbsp; <strong>2.3×</strong> the commercial market leader under a fixed review budget<br/>
<strong>graph-aware refactoring plans</strong> your agent can execute &nbsp;·&nbsp; <strong>up to −96% context tokens</strong> &nbsp;·&nbsp; <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>
+<p align="center"><sub>Measured, reproducible, on public codebases. <a href="#benchmarks">See the benchmarks ↓</a></sub></p>
-<img src=".github/assets/demo.gif" alt="repowise demo — Claude Code querying the codebase through repowise's MCP tools, then a tour of the local dashboard" width="100%" />
+<img src=".github/assets/demo.gif" alt="repowise demo: Claude Code querying the codebase through repowise's MCP tools, then a tour of the local dashboard" width="100%" />
---
@@ -56,22 +56,22 @@
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.
+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
+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
+**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
+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
+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.
@@ -87,44 +87,46 @@ Each layer is queryable from the CLI, the MCP tools, and the local dashboard.
|---|---|---|
| **◈ Graph** | tree-sitter dependency graph across 15 languages · two-tier file + symbol nodes · 3-tier call resolution · Leiden communities · PageRank / centrality / execution flows · framework-aware route→handler edges | A real graph most tools never build |
| **◈ 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 |
+| **◈ 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 · **concrete graph-aware refactoring plans** (Extract Class / Helper / Move Method / Break Cycle) · **zero LLM, <30s** | **★ Defect-validated, with the fix attached — 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 / Split File) · **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)**
---
-## ★ Code Health — the layer nobody else nails
+## ★ Code Health: the layer nobody else nails
-Code health is repowise's deepest differentiator — the one layer with no real
+Code health is repowise's deepest differentiator: the one layer with no real
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%" />
+<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, Split File) your agent executes" width="100%" />
</div>
-repowise scores **every file 1–10** from **25 deterministic biomarkers** —
+repowise scores **every file 1–10** from **25 deterministic biomarkers**:
McCabe complexity, deep nesting, brain methods, class cohesion (LCOM4), god
classes, native Rabin–Karp clone detection, untested hotspots, function-level
churn, code-age volatility, ownership dispersion, change entropy, co-change
scatter, prior-defect history, test-quality smells, and more.
-**Three signals, one index.** The headline 1–10 is **defect risk** — the
+**Three signals, one index.** The headline 1–10 is **defect risk**: the
defect-calibrated, bug-predictive score in the table below. From the same
biomarker stream, repowise surfaces two co-equal companion views:
**maintainability** (cohesion, brain methods, primitive obsession, DRY and
god-class smells that raise change-cost without predicting bugs) and
**performance** (static I/O-in-loop / N+1 risk, including cross-function cases
-caught through the call graph). The two companions are separate lenses — never
-blended into the defect headline, so the bug-predictive number stays clean.
+caught through the call graph that file-local linters miss: standard linters
+found 0 of those cross-function cases on a 12k-file benchmark where repowise
+surfaced 557). The two companions are separate lenses, never blended into the
+defect headline, so the bug-predictive number stays clean.
> **Zero LLM calls. Zero cloud requirement. Zero new runtime dependencies.**
-> Pure Python over tree-sitter + git data — finishes in **under 30 seconds** on
+> Pure Python over tree-sitter + git data, finishing in **under 30 seconds** on
> a 3,000-file repo. The biomarker weights are **calibrated against a real defect
> corpus, not hand-tuned**; only the learned constants ship and the runtime
> stays fully deterministic.
@@ -138,11 +140,11 @@ repowise health --trend # snapshots + declining / predicted-declin
And it proves itself on *your* repo, not just a benchmark: after every index,
repowise checks its own flags against your git history and reports the hit rate
-in the terminal and on the dashboard — *"16/20 lowest-health files had a bug fix
+in the terminal and on the dashboard: *"16/20 lowest-health files had a bug fix
in the last 6 months, 3.3x the 24% baseline"*. See
[Does the score find the bugs?](docs/CODE_HEALTH.md#does-the-score-find-the-bugs).
-**Does the score actually find bugs? Yes — and it out-ranks the leading
+**Does the score actually find bugs? Yes, and it out-ranks the leading
commercial code-health tool.** On the **same 2,770 files across 9 languages**,
scored at the same leakage-free commit against the same defect labels:
@@ -154,7 +156,7 @@ scored at the same leakage-free commit against the same defect labels:
| Discrimination (ROC AUC) | **0.731** | 0.705 |
Ranking by repowise health surfaces **2.3× the defects under a fixed review
-budget** (Popt Δ +0.144, recall Δ +0.098, density Δ p = 0.003 — all paired,
+budget** (Popt Δ +0.144, recall Δ +0.098, density Δ p = 0.003, all paired and
significant). [Full methodology & CIs →](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/COMPARISON_REPORT.md)
User guide & per-biomarker reference: **[docs/CODE_HEALTH.md](docs/CODE_HEALTH.md)**
@@ -164,27 +166,30 @@ User guide & per-biomarker reference: **[docs/CODE_HEALTH.md](docs/CODE_HEALTH.m
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:
+and git co-change, the same data the score is built on:
-- **Extract Class** — split an incohesive class along its real cohesion groups
+- **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
+- **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
+- **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
+- **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).
+- **Split File**: decompose an oversized module into cohesive files (community
+ detection over its intra-file symbol graph), naming the symbols that move to
+ each new file and the import edits in every dependent.
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
+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.
+The deterministic plan is the product; the optional LLM code-gen step never runs
+during indexing and fires only on an explicit request. Any plan can then 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
@@ -194,8 +199,8 @@ repowise health --refactoring-targets # ranked plans, biggest win for lea
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
+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)**
@@ -223,11 +228,11 @@ Both are zero-LLM and reproducible. Deep dives on the hosted site:
## Benchmarks
-Reproducible, on public codebases — **[repowise-bench →](https://github.com/repowise-dev/repowise-bench)**
+Reproducible, on public codebases. **[repowise-bench →](https://github.com/repowise-dev/repowise-bench)**
-### 1 · Agent efficiency — repowise does the exploration once, offline
+### 1 · Agent efficiency: repowise does the exploration once, offline
-Most of a coding agent's spend goes to *exploration* — greping for symbols,
+Most of a coding agent's spend goes to *exploration*: greping for symbols,
reading candidate files, re-reading them as context grows. repowise does that
work once so the agent skips it on every query. Paired SWE-QA runs on real
repositories (same model, same harness, with vs without repowise's MCP tools):
@@ -240,25 +245,25 @@ repositories (same model, same harness, with vs without repowise's MCP tools):
The win is *context*: repowise hands the agent a curated answer instead of a
pile of files to read. Loading a commit's context via `get_context` costs
-**2,391 tokens vs 64,039** raw — **~27× fewer (−96%)**. Across the two
+**2,391 tokens vs 64,039** raw, **~27× fewer (−96%)**. Across the two
benchmarks, agents read **−69% to −89% fewer files** and make **−49% to −70%
fewer tool calls** at answer quality on par with raw exploration; on a long,
multi-step investigation that compounds to **−41% of the context re-read across
-the whole session**. Saved tokens are tokens you don't pay for — dollar cost
+the whole session**. Saved tokens are tokens you don't pay for, so dollar cost
drops too, though agent-side prompt caching now mutes the cost delta. Reports: [flask48](https://github.com/repowise-dev/repowise-bench/blob/master/BENCHMARK_REPORT_FLASK48.md) · [flask v3](https://github.com/repowise-dev/repowise-bench/blob/master/BENCHMARK_REPORT_FLASK_V3.md) · [sklearn48](https://github.com/repowise-dev/repowise-bench/blob/master/BENCHMARK_REPORT_SKLEARN48.md)
-### 2 · Distill — index-aware output distillation
+### 2 · Distill: index-aware output distillation
Most of what an agent reads from a shell command is noise: 300 lines of
passing tests around 4 failures, full commit bodies for "what changed
recently". `repowise distill <cmd>` compresses command output **before the
-agent reads it** — errors-first, exit code preserved, and every omission
+agent reads it**, errors-first, exit code preserved, and every omission
reversible via an inline `[repowise#<ref>]` marker (`repowise expand <ref>`).
Paired runs on a public OSS repo, per command:
| Command | Raw → distilled tokens | Saved |
|---|---|---:|
-| `pytest -q` (11 failures) | 3,374 → 1,317 | **61%** — all 11 failure lines preserved |
+| `pytest -q` (11 failures) | 3,374 → 1,317 | **61%**, all 11 failure lines preserved |
| `git log -50` | 3,064 → 331 | **89%** |
| `git diff` (30 commits) | 62,833 → 8,635 | **86%** |
@@ -269,21 +274,21 @@ commands automatically (shown for approval); `repowise saved` tracks tokens
and dollars saved. Full guide: **[docs/DISTILL.md →](docs/DISTILL.md)**
<div align="center">
-<img src=".github/assets/savings.png" alt="repowise Costs dashboard — tokens and dollars saved across distill and MCP tools" width="100%" />
-<p align="center"><sub>The <strong>Costs</strong> dashboard tallies both savings surfaces — <code>repowise distill</code> (command output) and the MCP tools (each curated answer replacing the raw file reads it stood in for) — priced at your coding agent's own model. Example shown from a week of heavy local use.</sub></p>
+<img src=".github/assets/savings.png" alt="repowise Costs dashboard: tokens and dollars saved across distill and MCP tools" width="100%" />
+<p align="center"><sub>The <strong>Costs</strong> dashboard tallies both savings surfaces: <code>repowise distill</code> (command output) and the MCP tools (each curated answer replacing the raw file reads it stood in for), priced at your coding agent's own model. Example shown from a week of heavy local use.</sub></p>
</div>
### 3 · Code health predicts real defects
Health scores are collected at a historical commit (T0); bug-fixing commits are
-counted over the following 6 months; the two are correlated — strictly no
+counted over the following 6 months; the two are correlated, with strictly no
leakage. Across **21 open-source repositories spanning all 9 Full-tier
languages**:
- **Cross-project mean ROC AUC 0.74** [95% CI 0.68–0.79] at identifying the files
- that go on to receive bug-fixes — up to **0.90** on individual repos.
-- **Survives controlling for file size** (partial Spearman ρ = −0.16) — it is not
- just "flag the big files."
+ that go on to receive bug-fixes, up to **0.90** on individual repos.
+- **Survives controlling for file size** (partial Spearman ρ = −0.16), so it is
+ not just "flag the big files."
- **Significantly out-discriminates** recent churn (+0.10 AUC) and prior-defect
history (+0.12 AUC), DeLong p < 1e-9.
- Holds up on an **external published dataset it has never seen** (PROMISE/jEdit
@@ -292,25 +297,25 @@ languages**:
Full report: **[health-defect/BENCHMARK_REPORT.md →](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/BENCHMARK_REPORT.md)**
<div align="center">
-<sub>⭐ <strong>Star the repo</strong> if repowise just saved your agent a few greps — it helps the next engineer find it, and tells us to keep building.</sub>
+<sub>⭐ <strong>Star the repo</strong> if repowise just saved your agent a few greps, it helps the next engineer find it and tells us to keep building.</sub>
</div>
---
## Local dashboard
-`repowise serve` starts a full web UI alongside the MCP server — no separate
+`repowise serve` starts a full web UI alongside the MCP server, no separate
setup.
-<img src=".github/assets/webui.gif" alt="repowise local dashboard — Overview, Knowledge Graph, Code Health map, Commits, Chat, and By the Numbers" width="100%" />
+<img src=".github/assets/webui.gif" alt="repowise local dashboard: Overview, Knowledge Graph, Code Health map, Commits, Chat, and By the Numbers" width="100%" />
Highlights: **Chat** (natural-language Q&A) · **Docs** (wiki with Mermaid +
graph sidebar) · **Graph** (interactive, 2,000+ nodes, community coloring, path
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) · **Refactoring** (ranked plan
+evolution timeline, decision-graph) · **Health** (three signals: defect,
+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
@@ -352,7 +357,7 @@ pattern scan) · **Costs** · **Workspace**
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform · Markdown · Shell | Included in the file tree; special handlers extract endpoints / targets where applicable |
| **Git-blame only** | Objective-C · Elixir · Erlang · Dart · Zig · Julia · Clojure · Haskell · OCaml · F# · … | Tracked in git history (blame, hotspots, co-change); no AST parsing yet |
-Adding a language needs **one `.scm` query file and one config entry** — no
+Adding a language needs **one `.scm` query file and one config entry**, with no
changes to the parser core. Full per-language matrix, code-health checklist, and
the contributor recipe: **[docs/LANGUAGE_SUPPORT.md →](docs/LANGUAGE_SUPPORT.md)**
@@ -394,7 +399,7 @@ repowise serve # workspace dashboard, Live System Map + per-repo pages
The workspace **Live System Map** renders your services and their typed
relationships (HTTP / gRPC / events / package deps / co-change) as a
-code-derived, always-current diagram — health-colored, filterable, with
+code-derived, always-current diagram, health-colored, filterable, with
drill-down to the underlying contracts. See
[Workspaces](docs/WORKSPACES.md#live-system-map).
@@ -407,7 +412,7 @@ non-interactive runs require `--codex`. Skip Codex setup with `--no-codex`; forc
skip `AGENTS.md` with `--agents` / `--no-agents`.
**Claude Code plugin.** Prefer a one-command setup? Install the plugin from the
-marketplace — it registers the MCP server and hook and adds `/repowise:*` slash
+marketplace: it registers the MCP server and hook and adds `/repowise:*` slash
commands (`init`, `health`, `risk`, `dead-code`, `decision`, …):
```text
@@ -426,7 +431,7 @@ To add the MCP server to another editor manually:
```
> **Init time:** the graph, git, dead-code, and code-health layers build in
-> minutes with **zero LLM calls** — run `repowise init --index-only` for a
+> minutes with **zero LLM calls**; run `repowise init --index-only` for a
> queryable index almost immediately. The one-time cost is the documentation
> layer (LLM-generated wiki pages, can run in the background). After that, every
> commit-triggered update takes **under 30 seconds** and only regenerates the
@@ -438,7 +443,7 @@ To add the MCP server to another editor manually:
## Nine MCP tools
-Most tools are designed around data entities — one module, one file, one symbol —
+Most tools are designed around data entities (one module, one file, one symbol),
forcing agents into long chains of sequential calls. repowise tools are designed
around **tasks**: pass multiple targets in one call, get complete context back.
Every response carries an `_meta` envelope with `index_age_days`,
@@ -450,7 +455,7 @@ diverges from live `.git/HEAD`.
| `get_overview()` | Architecture summary, module map, entry points, git health, community summary. First call on any unfamiliar codebase. |
| `get_answer(question)` | Hybrid retrieval (FTS + vector via RRF) + PageRank bias + 1-hop graph expansion → a cited answer with calibrated `retrieval_quality`. Returns structured `best_guesses` on low confidence. Collapses search → read → reason into one round-trip. |
| `get_context(targets, include?)` | Triage card for files / modules / symbols: title, summary, signatures, `hotspot` bit, `governing_decisions`, and `symbol_id`s. `include` opens callers/callees, ownership, metrics, decisions, full_doc. Batch many targets. |
-| `get_symbol("file.py::Name")` | Raw source bytes for one indexed symbol with exact line bounds — cheaper and safer than `Read` + offset math. |
+| `get_symbol("file.py::Name")` | Raw source bytes for one indexed symbol with exact line bounds, cheaper and safer than `Read` + offset math. |
| `search_codebase(query, kind?)` | Semantic search over the wiki, filterable by `kind` (implementation / test / config / doc), tagging each result's `search_method`. |
| `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. |
@@ -467,7 +472,7 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of
| | repowise | Google Code Wiki | DeepWiki | Swimm | CodeScene |
|---|---|---|---|---|---|
| Self-hostable, open source | ✅ AGPL-3.0 | ❌ cloud only | ❌ cloud only | ❌ Enterprise only | ✅ Docker |
-| Private repo — no cloud | ✅ | ❌ in development | ❌ OSS forks only | ✅ Enterprise tier | ✅ |
+| Private repo, no cloud | ✅ | ❌ in development | ❌ OSS forks only | ✅ Enterprise tier | ✅ |
| Auto-generated documentation | ✅ | ✅ Gemini | ✅ | ✅ PR2Doc | ❌ |
| MCP server for AI agents | ✅ 9 tools | ❌ | ✅ 3 tools | ✅ | ✅ |
| Proactive agent hooks | ✅ Claude + Codex hooks | ❌ | ❌ | ❌ | ❌ |
@@ -488,7 +493,7 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of
**repowise is the intersection:** behavioral git intelligence + a defect-validated
code-health score *with the graph-aware fix attached* + auto-generated docs +
-agent-native MCP + architectural decisions + multi-repo workspace intelligence —
+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)**.
@@ -497,14 +502,14 @@ Full side-by-side comparisons (CodeScene, DeepWiki, Sourcegraph, Cursor, GitClea
## For teams & enterprises
-[**repowise.dev**](https://www.repowise.dev) is the same engine, fully managed —
+[**repowise.dev**](https://www.repowise.dev) is the same engine, fully managed,
at feature parity with self-hosted: every CLI command, every MCP tool, the full
dashboard. We dogfood it on our own codebase: [live snapshot →](https://www.repowise.dev/s/5a6b93fa9a69) · [explore public repos →](https://www.repowise.dev/explore).
**On top of self-hosting:**
-- **Zero ops** — managed deploys & webhooks, auto re-index on every commit.
-- **Hosted MCP endpoint** — point any MCP client at one URL, no local server.
-- **Repowise PR Bot** — free GitHub App, one deterministic comment per PR
+- **Zero ops**: managed deploys & webhooks, auto re-index on every commit.
+- **Hosted MCP endpoint**: point any MCP client at one URL, no local server.
+- **Repowise PR Bot**: free GitHub App, one deterministic comment per PR
(hotspot touches, hidden coupling, declining health, dead code), zero LLM calls.
[Install →](https://github.com/apps/repowise-bot) · [Learn more →](https://www.repowise.dev/bot)
- **CVE-aware security layer**, **cross-repo intelligence at scale**, and
@@ -517,7 +522,7 @@ pricing: **[docs/COMMERCIAL.md](docs/COMMERCIAL.md)** · [Get in touch →](http
## Privacy
-- **Self-hosted:** your code never leaves your infrastructure — no code, file paths, or repo names are ever sent. The CLI does report **anonymous, opt-out** usage telemetry (command names + coarse environment only) to help us prioritize; turn it off with `repowise telemetry disable`, `DO_NOT_TRACK=1`, or by running fully offline. [What's collected →](docs/TELEMETRY.md)
+- **Self-hosted:** your code never leaves your infrastructure, so no code, file paths, or repo names are ever sent. The CLI does report **anonymous, opt-out** usage telemetry (command names + coarse environment only) to help us prioritize; turn it off with `repowise telemetry disable`, `DO_NOT_TRACK=1`, or by running fully offline. [What's collected →](docs/TELEMETRY.md)
- **BYOK:** bring your own Anthropic / OpenAI key. We never see your LLM calls. Zero data retention via Anthropic's API policy.
- **What's stored:** the NetworkX graph, LanceDB embeddings (non-reversible vectors), generated wiki pages, git metadata. Raw source is processed transiently and never persisted.
- **Fully offline:** Ollama + a local embedding model = zero external API calls.
@@ -534,7 +539,7 @@ repowise query "<q>" # ask anything from the terminal
repowise health # code-health KPIs + lowest-scoring files
repowise risk main..HEAD # score a branch / PR range for defect risk
repowise dead-code # unreachable-code report
-repowise distill pytest # compact errors-first output (reversible) — saves 60–90% tokens
+repowise distill pytest # compact errors-first output (reversible), saves 60–90% tokens
repowise saved # tokens & dollars saved by distillation
repowise doctor # check setup, API keys, store drift
```
@@ -565,9 +570,9 @@ Full guide, including how to add languages and LLM providers:
AGPL-3.0. Free for individuals, teams, and companies using repowise internally.
-For commercial licensing — the enterprise security & compliance layer, SSO/SCIM,
+For commercial licensing (the enterprise security & compliance layer, SSO/SCIM,
RBAC, workflow integrations, priority support and SLA, or embedding repowise in a
-product without AGPL obligations — see **[docs/COMMERCIAL.md](docs/COMMERCIAL.md)**
+product without AGPL obligations), see **[docs/COMMERCIAL.md](docs/COMMERCIAL.md)**
or contact [[email protected]](mailto:[email protected]).
---
diff --git a/docs/CHANGE_RISK.md b/docs/CHANGE_RISK.md
index 5da9c2d61..4cf56b565 100644
--- a/docs/CHANGE_RISK.md
+++ b/docs/CHANGE_RISK.md
@@ -1,6 +1,6 @@
# Change risk (`repowise risk`)
-`repowise risk` scores a **change** — a commit or a `base..head` range — for
+`repowise risk` scores a **change** (a commit or a `base..head` range) for
defect risk from the shape of its diff, not the health of any file. It is a
just-in-time / pre-merge signal: complementary to `repowise health` (which
scores files), and useful as a PR gate because it fires on risky *small* changes
@@ -15,7 +15,7 @@ repowise risk --format json # machine-readable
```
It runs in-process: pure `git` + learned constants. **No LLM, no network, and no
-blame at runtime** — SZZ labelling lives entirely in the offline calibration.
+blame at runtime**: SZZ labelling lives entirely in the offline calibration.
## What it measures
@@ -28,11 +28,11 @@ empirical study of just-in-time quality assurance"):
| `nf` | files touched |
| `nd`, `ns` | distinct directories / top-level subsystems touched |
| `entropy` | Shannon entropy of the per-file churn distribution (diffusion) |
-| `exp` | author's prior commit count (experience); unknown → scored neutrally |
+| `exp` | author's prior commit count (experience); unknown is scored neutrally |
These are properties of the *diff*, so the score is a change-level signal rather
than a file-size proxy. The risk is a plain L2-logistic over standardized,
-log-compressed features — `logit = intercept + Σ coefᵢ·zᵢ` — so every feature's
+log-compressed features (`logit = intercept + Σ coefᵢ·zᵢ`), so every feature's
push on the risk is exact and reported as an attributable driver (the same
linear / per-finding-attributable contract the file health score holds).
@@ -40,21 +40,21 @@ linear / per-finding-attributable contract the file health score holds).
The headline signal is **repo-relative**. The raw 0–10 logistic probability is
anchored to the offline calibration corpus, so on a repo whose typical commit is
-large the diff-size term dominates and the absolute band skews high — two-thirds
+large the diff-size term dominates and the absolute band skews high: two-thirds
of commits can read "high" while ranking perfectly normally for *that* repo. The
*ranking* is sound; the absolute band is not portable.
So the surfaces lead with where the change sits in its **own repo's**
distribution:
-- **Review priority** — `Below typical` / `Typical` / `Elevated` (terciles of
+- **Review priority**: `Below typical` / `Typical` / `Elevated` (terciles of
the repo's own commit-risk distribution). This is the signal to triage on.
-- **Percentile** — "riskier than N% of this repo's commits".
-- **Raw model score** (0–10) — kept for transparency but shown as a secondary,
+- **Percentile**: "riskier than N% of this repo's commits".
+- **Raw model score** (0–10): kept for transparency but shown as a secondary,
clearly corpus-anchored number, not the thing to act on.
Each **driver** is reported relative to *the model's baseline commit* (the
-calibration-corpus mean), not this repo — so a `+19 / −1` change can legitimately
+calibration-corpus mean), not this repo, so a `+19 / −1` change can legitimately
read "more lines added than baseline" while still ranking `Below typical` for a
repo of large commits. The signed contribution and colour (red raised the raw
score, green lowered it) carry the direction; the label only states the
@@ -70,7 +70,7 @@ Constants are learned offline against the defect corpus (AG-SZZ bug-inducing
commits as labels, time-ordered evaluation with a right-censoring gap, and a
leave-one-repo-out comparison to the churn-only baseline). On a 7-repo,
5-language slice the pooled leave-one-repo-out AUC is **0.772 vs 0.766 for
-churn-only** (Δ +0.0068, 95% CI [-0.0003, +0.0131]) — competitive with churn
+churn-only** (Δ +0.0068, 95% CI [-0.0003, +0.0131]): competitive with churn
across the corpus and stronger on some repos (clap +0.053 on a time-ordered
split). Diff size dominates the fit, with change entropy risky and author
experience protective, both literature-consistent. Only the learned constants
@@ -85,10 +85,10 @@ In a workspace, a change rarely stops at the repo boundary. When `get_risk` is
called in PR mode (`changed_files`), its `directive` block gains two cross-repo
fields derived from the [system graph](WORKSPACES.md#system-graph):
-- `will_break_consumers` — services in *other* repos that structurally depend on
+- `will_break_consumers`: services in *other* repos that structurally depend on
the changed repo (a contract or package import). These are the consumers most
likely to break.
-- `missing_cross_repo_cochanges` — services in other repos that historically
+- `missing_cross_repo_cochanges`: services in other repos that historically
co-change with the changed repo but aren't in the diff. Correlation, not a
call, so they read as "may drift," not "will break."
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 4d6faf0d6..121287f69 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -1,16 +1,15 @@
# Code Health
-Repowise computes a 1–10 health score for every file in your repo from twenty-five
-deterministic biomarkers — McCabe complexity, deep nesting, brain methods,
+Repowise computes a 1-10 health score for every file in your repo from twenty-five
+deterministic biomarkers: McCabe complexity, deep nesting, brain methods,
class cohesion (LCOM4), god classes, clone detection, untested hotspots,
-function-level churn, code-age volatility,
-ownership dispersion, relative churn, change entropy, co-change scatter,
-recent defect history, test-quality smells, and more. **No LLM calls, no cloud requirement.** Pure
-Python over tree-sitter + git data, designed to finish in under 30 seconds on a
-3 000-file repo.
+function-level churn, code-age volatility, ownership dispersion, relative churn,
+change entropy, co-change scatter, recent defect history, test-quality smells,
+and more. **No LLM calls, no cloud requirement.** Pure Python over tree-sitter
+and git data, designed to finish in under 30 seconds on a 3,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, Extract Method, Move Method, Break Cycle, Split File) your agent executes" width="100%" />
+<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, Split File) your agent executes" width="100%" />
</div>
Code health runs as a loop: **measure** every file across three signals,
@@ -19,10 +18,19 @@ history, then **fix** it with a concrete refactoring plan an agent can execute
(see [Refactoring targets](#refactoring-targets) and
[docs/REFACTORING.md](REFACTORING.md)).
+Linters check patterns. The health score predicts risk. A linter flags a line
+that matches a known-bad shape; the score estimates which files are likely to
+harbor the next bug, ranks them, and is calibrated against real defect history
+(see [Does the score find the bugs?](#does-the-score-find-the-bugs)). It uses
+signals a linter has no access to: churn, ownership, co-change, blast radius,
+hotspots. The [performance signal](#performance-static-performance-risk) is the
+one part that overlaps a linter, and even it follows the call graph across files,
+which a file-local linter cannot.
+
## Quick start
```bash
-repowise init # full index — populates health tables
+repowise init # full index, populates health tables
repowise health # KPIs + 20 worst-scoring files + top findings
repowise update # re-score only changed files on each subsequent run
```
@@ -48,49 +56,49 @@ most:
| Error handling | −0.5 | error_handling |
Twenty-five biomarkers across the categories above. `function_hotspot` and
-`code_age_volatility` are blame-based and sit in the organizational bucket —
-both are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line
-blame index is built.
+`code_age_volatility` are blame-based and sit in the organizational bucket: both
+are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line blame
+index is built.
Per-biomarker weight multipliers (see `scoring._BIOMARKER_WEIGHT_MULTIPLIER`)
let the strongest empirical predictors deduct more than the uniform severity
-table alone allows. **These weights are calibrated offline against a defect
-corpus, not hand-tuned**: each file is scored at the pre-window commit (T0, no
-leakage) and an L2-logistic regression — with NLOC as an explicit control — fits
-each biomarker's defect lift *beyond file size*. The runtime stays
-deterministic; only the learned constants ship. The strongest calibrated
-predictors are `co_change_scatter` (1.8), `change_entropy` (1.51),
-`ownership_risk` (1.38), and `nested_complexity` (1.34); the remaining
-structural complexity/size biomarkers land around 1.1–1.33. Biomarkers that fire widely but
-proved weak under leakage-free scoring (`developer_congestion`, `dry_violation`,
+table alone allows. These weights are calibrated offline against a defect
+corpus, not hand-tuned: each file is scored at the pre-window commit (T0, no
+leakage) and an L2-logistic regression (with NLOC as an explicit control) fits
+each biomarker's defect lift beyond file size. The runtime stays deterministic;
+only the learned constants ship. The strongest calibrated predictors are
+`co_change_scatter` (1.8), `change_entropy` (1.51), `ownership_risk` (1.38), and
+`nested_complexity` (1.34); the remaining structural complexity and size
+biomarkers land around 1.1 to 1.33. Biomarkers that fire widely but proved weak
+under leakage-free scoring (`developer_congestion`, `dry_violation`,
`low_cohesion`, `brain_method`, `primitive_obsession`, `bumpy_road`) are floored
-to 0.5 — kept as maintainability/parity signals, not disabled — and
+to 0.5, kept as maintainability and parity signals rather than disabled, and
`knowledge_loss` stays de-rated at 0.4. Coverage-dependent and rarely-firing
biomarkers (`untested_hotspot` 1.3, `code_age_volatility` 1.1, `churn_risk` 1.2)
-keep prior weights the corpus could not fairly measure. The calibration is
-reproduced by `local-stash/calibrate_health_weights.py` and documented in
-`repowise-bench/health-defect/BENCHMARK_REPORT.md`.
+keep prior weights the corpus could not fairly measure. The full calibration,
+with confidence intervals, is published in the [benchmark report](https://github.com/repowise-dev/repowise-bench/blob/master/health-defect/BENCHMARK_REPORT.md).
The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:
-- **Hotspot Health** — NLOC-weighted average over the files classified as
+- **Hotspot Health**: NLOC-weighted average over the files classified as
hotspots by the git layer (high churn percentile plus minimum-activity
floors), not a fixed top-N slice.
-- **Average Health** — NLOC-weighted average over all files.
-- **Worst Performer** — single lowest-scoring file.
+- **Average Health**: NLOC-weighted average over all files.
+- **Worst Performer**: single lowest-scoring file.
## Three health signals: defect risk, maintainability, and performance
-Repowise surfaces **three orthogonal health signals** computed from the same
+Repowise surfaces three orthogonal health signals computed from the same
biomarker stream by one shared scoring kernel: **defect risk** (the calibrated,
overall number), **maintainability**, and **performance**. They are co-equal
-*views*, never blended into one number (see "The overall score" below for why).
-
-The score above is the **defect-risk** signal: it is calibrated against a defect
-corpus, the bands are calibrated to it (Alert files carry ~17x the defect rate
-of Healthy files), and it is the overall number surfaced everywhere. But not
-every code smell predicts bugs. A handful of biomarkers fire widely and matter a
-lot for how hard code is to read and change, yet proved weak as defect
+views, never blended into one number (the section on the overall score below
+explains why).
+
+The score above is the defect-risk signal: it is calibrated against a defect
+corpus, the bands are calibrated to it (Alert files carry roughly 17x the defect
+rate of Healthy files), and it is the overall number surfaced everywhere. But
+not every code smell predicts bugs. A handful of biomarkers fire widely and
+matter a lot for how hard code is to read and change, yet proved weak as defect
predictors under leakage-free scoring, so the defect calibration floors them to
0.5 (`low_cohesion`, `brain_method`, `primitive_obsession`, `dry_violation`,
`error_handling`). Floored inside a defect-framed score they do two unhelpful
@@ -98,25 +106,25 @@ things at once: they still nudge the number a little (noise against the
calibrated signal) and they get no credit for the real problem they describe
(maintainability).
-Repowise therefore computes a second, parallel signal, **maintainability**, from
-the same biomarker stream:
+Repowise therefore computes a second, parallel signal, maintainability, from the
+same biomarker stream:
-- The floored smells above deduct at **full weight (1.0)** in maintainability
+- The floored smells above deduct at full weight (1.0) in maintainability
instead of the 0.5 the defect calibration imposes. The defect calibration does
not apply to a non-defect signal, so the maintainability weights are expert-set
and tuned only against the maintainability pillar's own per-category caps.
-- The structural smells that are genuine defect predictors **and** core
+- The structural smells that are genuine defect predictors and core
maintainability concerns (`god_class`, `large_method`, `nested_complexity`)
- count toward **both** dimensions.
-- Pure defect/organizational predictors (`change_entropy`, `ownership_risk`,
- `co_change_scatter`, ...) stay out of maintainability entirely.
+ count toward both dimensions.
+- Pure defect and organizational predictors (`change_entropy`, `ownership_risk`,
+ `co_change_scatter`, and the like) stay out of maintainability entirely.
The two signals are computed by the single shared scoring kernel
(`scoring.score_file`) against independent weight/category/cap tables, and they
-**never feed back into each other**. The overall, surfaced score remains exactly
-the defect score (byte-for-byte; a golden test locks this) until a later,
-deliberate decision to blend. Maintainability is surfaced alongside it as a
-co-equal headline:
+never feed back into each other. The overall, surfaced score remains exactly the
+defect score (byte-for-byte; a golden test locks this) until a later, deliberate
+decision to blend. Maintainability is surfaced alongside it as a co-equal
+headline:
- **REST/overview**: `summary.maintainability_average` plus a per-file
`maintainability_score` on every metric row.
@@ -130,18 +138,33 @@ co-equal headline:
## Performance: static performance risk
-The third signal, **performance**, flags *shapes that waste work* (code whose
+The third signal, performance, flags shapes that waste work (code whose
structure does redundant I/O), rather than measured runtime. It is deliberately
-**high-precision, low-recall**: a few real findings the rest of the toolchain
-can trust beat a wall of maybes. The detectors (all under one bounded `performance`
-category cap of 1.0, so the pillar stays advisory) are:
+high-precision and low-recall: a few real findings the rest of the toolchain can
+trust beat a wall of maybes.
+
+Standard linters do not find this class of problem. clippy, ruff's `PERF` rules,
+ESLint, and golangci-lint read one function at a time, so a loop in one file
+whose database call lives in another is invisible to them. On a 12,000-file
+benchmark the standard linters found **0** of the cross-function I/O-in-loop
+cases; repowise surfaced 557 findings across the run, about 90 of them spanning
+function boundaries, and 98% fell in categories ruff has no rule for. The
+findings are ordered by impact rather than raw count (NDCG 0.755 against 0.292
+for severity-only). One caveat: the Rust dialect was new when the benchmark ran,
+and clippy could not be run end-to-end on the corpus because of a Windows build
+wall, so the Rust comparison there is catalogue-level, not a measured
+head-to-head. The data is in the
+[perf-detection benchmark](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).
+
+The detectors (all under one bounded `performance` category cap of 1.0, so the
+pillar stays advisory) are:
- **`io_in_loop`**: a database call, network request, filesystem read, or
- subprocess spawn that runs **once per loop iteration**: the classic N+1. This
- is the moat. Two things make it more than a file-local lint:
+ subprocess spawn that runs once per loop iteration: the classic N+1. This is
+ the moat. Two things make it more than a file-local lint:
- **Dependency classification.** The loop-nested call is resolved through a
shared I/O-boundary classifier (`io_kind ∈ {db, network, filesystem,
- subprocess, lock}`) and only fires on a *classified* execution sink (an
+ subprocess, lock}`) and only fires on a classified execution sink (an
actual round-trip like `.execute` / awaited HTTP / `subprocess.run`), not a
query-builder chain or a same-named pure helper.
- **Call-graph reachability.** The loop and the I/O call need not be in the
@@ -160,38 +183,38 @@ category cap of 1.0, so the pillar stays advisory) are:
`mu.Lock` / `synchronized` / `lock(x){}`): a contention site. Activates the
`lock` I/O-boundary kind.
- **`serial_await_in_loop`**: an awaited I/O round-trip run one at a time in a
- loop where a `gather` / `Promise.all` could fan it out. Advisory — a static
+ loop where a `gather` / `Promise.all` could fan it out. Advisory: a static
analyzer cannot prove the iterations are independent, so the finding suggests
rather than asserts.
- **`membership_test_against_list_in_loop`**: `x in big_list` (or
`big_list.includes(x)`) inside a loop is O(n·m); a set makes each lookup O(1).
- Fires only when the right operand is *provably* a list, never a set or dict.
+ Fires only when the right operand is provably a list, never a set or dict.
- **`nested_loop_with_io`**: an I/O sink in the inner body of a **nested** loop:
O(n·m) round-trips, the quadratic cousin of `io_in_loop`. The nesting itself
raises confidence the finding is real, so it surfaces alongside `io_in_loop`.
- **`blocking_io_under_lock`**: an I/O round-trip reached while a block-scoped
lock is held (a C# `lock(){}` / Java `synchronized(){}` block, directly or
- through a call). Every other thread blocks for the full I/O wait — a throughput
+ through a call). Every other thread blocks for the full I/O wait, a throughput
killer. The cross-function case reuses the same bounded-reachability engine as
- the N+1 moat, with a `lock → io` entry set.
+ the N+1 moat, with a `lock -> io` entry set.
-Two markers use **centrality as a precision gate**, not just a sort key — a
-shape that is noisy when flagged everywhere only fires in a *hot* function (one
+Two markers use centrality as a precision gate rather than only a sort key: a
+shape that is noisy when flagged everywhere only fires in a hot function (one
with top-quintile call-graph in-degree, or in a churny/hotspot file), computed by
a reusable severity ranker over the same call graph the N+1 pass uses:
-- **`hot_path_sync_io`**: a blocking **subprocess / filesystem** call in a hot,
- request-reachable function — **even outside a loop**. Generalizes the pillar
+- **`hot_path_sync_io`**: a blocking subprocess or filesystem call in a hot,
+ request-reachable function, even outside a loop. It generalizes the pillar
beyond loops: its latency is paid on every call through the function. (DB and
- network are excluded — both are awaited in async code, and the un-awaited calls
- a static pass sees are result *materializers* or chained awaits, not blocking
- round-trips; subprocess/filesystem are synchronous by construction.) Advisory —
- a latency signal ranked by centrality, not a defect.
+ network are excluded, since both are awaited in async code, and the un-awaited
+ calls a static pass sees are result materializers or chained awaits, not
+ blocking round-trips; subprocess and filesystem are synchronous by
+ construction.) Advisory: a latency signal ranked by centrality, not a defect.
- **`nested_loop_quadratic`**: a data-dependent loop nested inside another
(O(n²)) in a hot function. The centrality gate makes the list short and
- reviewable (it cut a 13× volume of raw nested loops), but centrality answers
- "is this function important", not "is n large" — so it ships **advisory /
- informational** only, never at a weight that moves the score.
+ reviewable (it cut a 13x volume of raw nested loops), but centrality answers
+ "is this function important", not "is n large", so it ships advisory and
+ informational only, never at a weight that moves the score.
A few markers are language-specific, contributed by that language's dialect (see
below) rather than the shared core:
@@ -199,14 +222,14 @@ below) rather than the shared core:
- **`regex_compile_in_loop`** (Java, Go): a `Pattern.compile` /
`regexp.MustCompile` recompiled every iteration instead of hoisted. Skipped on
Python / .NET, which cache compiled patterns; on Go it fires only for a
- **string-literal pattern** (a dynamic argument may legitimately vary per
- iteration and cannot be hoisted).
+ string-literal pattern (a dynamic argument may legitimately vary per iteration
+ and cannot be hoisted).
- **`defer_in_loop`** (Go): a `defer` inside a loop holds the deferred handle
- until the enclosing function returns, not the iteration: the classic Go file /
+ until the enclosing function returns, not the iteration: the classic Go file or
row-handle leak. A pure syntactic shape, very high precision.
-- **`goroutine_in_unbounded_loop`** (Go): a `go …()` spawned per element of a
- `for k, v := range coll` loop, with no concurrency bound — a spawn explosion
- (use a worker pool / bounded `errgroup`). Restricted to the two-variable
+- **`goroutine_in_unbounded_loop`** (Go): a `go ...()` spawned per element of a
+ `for k, v := range coll` loop, with no concurrency bound: a spawn explosion
+ (use a worker pool or bounded `errgroup`). Restricted to the two-variable
`range` form, which is only legal over a collection (a single-variable
`for i := range n` is a bounded count loop). Advisory.
- **`list_insert_zero_in_loop`** (Python): `lst.insert(0, x)` each iteration
@@ -215,8 +238,8 @@ below) rather than the shared core:
- **`pd_concat_in_loop`** (Python): `pd.concat([acc, chunk])` inside a loop
copies the whole frame each pass (O(n²)); collect chunks and concat once.
- **`json_parse_in_loop`** (JS/TS): the `JSON.parse(JSON.stringify(x))`
- deep-clone idiom in a loop (use `structuredClone`). Restricted to that idiom —
- parsing a *distinct* payload each iteration is necessary work, not waste.
+ deep-clone idiom in a loop (use `structuredClone`). Restricted to that idiom;
+ parsing a distinct payload each iteration is necessary work, not waste.
Advisory.
- **`array_spread_in_reduce`** (JS/TS): `arr.reduce((a, x) => [...a, x], [])`
rebuilds the accumulator every step (O(n²)); push-and-return instead. The
@@ -227,44 +250,44 @@ below) rather than the shared core:
Each performance finding's `details` carry the `boundary_kind` it crosses, a
`cross_function` flag, and the reachability `path` for the cross-function case.
-Severity is ranked by **centrality** (an N+1 in a high-traffic, churny function
+Severity is ranked by centrality (an N+1 in a high-traffic, churny function
outranks one in a leaf), not by raw count.
-**Languages.** The performance signal fires on **Python, TypeScript/JavaScript,
-Java, Go, and C#**. Each language is a self-contained `PerfDialect` plugin
+**Languages.** The performance signal fires on Python, TypeScript/JavaScript,
+Java, Go, and C#. Each language is a self-contained `PerfDialect` plugin
(`analysis/health/perf/dialects/`) that owns its callee-extraction grammar, its
execution-sink lexicon, the loop / string / async predicates, and its own marker
list, registered in `PERF_DIALECTS` like the rest of the per-language pipeline.
A language without a dialect emits no perf findings (never a wrong one). The
db/network/filesystem/subprocess lexicons and the per-language precision hazards
(Java `.find`/`.get`, GORM `Find`/`Save`, C# in-memory-vs-`IQueryable` LINQ) are
-documented in `local-stash/performance-pillar/PHASE6_PLAN.md`. The verb sets are
-gated for precision: distinctive sinks (EF `*Async`, Spring-Data `findBy*`, JDBC
+each handled inside that language's dialect. The verb sets are gated for
+precision: distinctive sinks (EF `*Async`, Spring-Data `findBy*`, JDBC
`executeQuery`) fire on name alone, while ambiguous verbs require file-level
-db-import evidence. **`io_in_loop` is validated across languages** on an 11-repo
-OSS corpus: Go 96.7%, TypeScript 100%, Python 96.2% hand-labeled precision; the
+db-import evidence. `io_in_loop` is validated across languages on an 11-repo OSS
+corpus: Go 96.7%, TypeScript 100%, Python 96.2% hand-labeled precision; the
`blocking_sync_in_async` C# `.Result`/Result-pattern collision and the Go
`*sql.Rows.Scan` cursor FP were caught and fixed by that validation.
`string_concat_in_loop` is validated at 100% (26/26) after a reset-per-iteration
guard (an accumulator re-initialized each iteration is bounded, not O(n²)).
-`nested_loop_quadratic` now fires only on a **same-collection** shape (two nested
+`nested_loop_quadratic` now fires only on a same-collection shape (two nested
loops over the same collection = all-pairs O(n²)) instead of raw nesting depth;
that makes it precision-safe-by-construction but rare, so it stays advisory-only,
as do `blocking_io_under_lock`, `pd_concat_in_loop`, `json_parse_in_loop`, and
`goroutine_in_unbounded_loop` (high-precision by construction, low corpus recall).
-**Soundness limits (honest, by design).** Performance is a *static* signal, so
-it under-reports rather than over-reports (these cap recall, not precision):
-dynamic dispatch / monkeypatching / callbacks-as-values produce no `calls` edge
-and are invisible; ORM lazy-load N+1 fires on attribute access (no visible call)
-and is explicitly out of scope --- this includes Hibernate lazy-load N+1 (fires
-on a getter) and EF Core navigation-property lazy load, so we catch *explicit*
-repository / query calls in loops, not attribute-triggered lazy loads; chains
+**Soundness limits (honest, by design).** Performance is a static signal, so it
+under-reports rather than over-reports (these cap recall, not precision): dynamic
+dispatch, monkeypatching, and callbacks-as-values produce no `calls` edge and are
+invisible; ORM lazy-load N+1 fires on attribute access (no visible call) and is
+explicitly out of scope (this includes Hibernate lazy-load N+1, which fires on a
+getter, and EF Core navigation-property lazy load), so we catch explicit
+repository or query calls in loops, not attribute-triggered lazy loads; chains
longer than three hops from the loop are not followed; and an unmodelled library
-is untyped (`None`), so its sinks don't fire. We call this **performance RISK**,
-never measured performance, and never fold it into the defect score. The
-commit-agreement precision study and its caveats live in
-`local-stash/performance-pillar/VALIDATION.md`.
+is untyped (`None`), so its sinks don't fire. We call this performance RISK, never
+measured performance, and never fold it into the defect score. The
+commit-agreement precision study and its caveats are published in the
+[perf-detection methodology](https://github.com/repowise-dev/repowise-bench/blob/master/perf-detection/METHODOLOGY.md).
Performance surfaces exactly where maintainability does: a `performance_average`
on the overview summary and MCP `kpis`, a per-file `performance_score`, a
@@ -278,17 +301,16 @@ detectors landed). The dimension names are mirrored in `@repowise-dev/types`
The single number repowise surfaces as the headline (the dashboard ring, the
band, the badge, the "does the score find the bugs?" stat) is, and stays, the
-**defect score**. Maintainability and performance are presented as co-equal
-*pillars/views*, not blended into the headline. This is a deliberate decision,
-for three reasons:
+defect score. Maintainability and performance are presented as co-equal pillars,
+not blended into the headline. This is a deliberate decision, for three reasons:
1. **Band calibration.** The Healthy/Warning/Alert cutoffs are calibrated to the
- defect score (Alert ≈ 17× the defect rate). A blended headline would invalidate
- those boundaries with no recalibration corpus behind the new number.
+ defect score (Alert is roughly 17x the defect rate). A blended headline would
+ invalidate those boundaries with no recalibration corpus behind the new number.
2. **Honesty of the validation stat.** "Does the score find the bugs?" is a claim
- about the *defect* pillar; it must stay bound to the number it measures.
+ about the defect pillar; it must stay bound to the number it measures.
3. **Different precision profiles.** Maintainability is expert-set and performance
- is high-precision/low-recall advisory — neither is a calibrated bug predictor,
+ is high-precision/low-recall advisory. Neither is a calibrated bug predictor,
so neither should move the bug-calibrated headline.
A golden test (`tests/unit/health/test_scoring_dimensions`) locks the defect
@@ -298,9 +320,9 @@ and a recalibration plan; until then, overall = defect.
## Bands and distribution
-On top of the 1–10 number, every score falls into one of three **bands**. These
+On top of the 1-10 number, every score falls into one of three **bands**. These
are the single categorical scheme repowise surfaces (there is deliberately no
-letter grade — a letter on top of the number would be a third overlapping scale
+letter grade: a letter on top of the number would be a third overlapping scale
with arbitrary cliffs):
| Band | Score | Meaning |
@@ -309,15 +331,15 @@ with arbitrary cliffs):
| **Warning** | `4.0 – 8.0` | Worth watching; rising complexity or process risk. |
| **Alert** | `< 4.0` | High-risk; concentrates defects. |
-The cutoffs are not arbitrary. On our calibration corpus, **Alert files carry
-roughly 17× the per-file defect rate of Healthy files**, so the band boundaries
+The cutoffs are not arbitrary. On our calibration corpus, Alert files carry
+roughly 17x the per-file defect rate of Healthy files, so the band boundaries
are empirically defensible. They are defined once in core
(`analysis/health/grading.py`) and mirrored in `@repowise-dev/types` for the UI;
a parity test on each side locks the values.
The **health distribution** is the NLOC-weighted split of the repo across the
-three bands — what share of your code (by volume, not file count) is Healthy vs
-Warning vs Alert. `repowise health` prints it as a one-line summary; the
+three bands: what share of your code (by volume, not file count) is Healthy,
+Warning, or Alert. `repowise health` prints it as a one-line summary; the
dashboard renders it as a bar.
```text
@@ -327,8 +349,8 @@ Distribution (by code volume): 8% alert (12 files) · 21% warning (88 files) ·
## Badge
`repowise health --badge` prints ready-to-paste Markdown for a README health
-badge (a Shields-style **color + `N.N/10`** badge — no letter). A running
-Repowise server (or the hosted app) also serves the badge directly:
+badge (a Shields-style color and `N.N/10` badge, no letter). A running Repowise
+server (or the hosted app) also serves the badge directly:
```text
GET /api/repos/{repo_id}/health/badge.svg # self-rendered flat SVG
@@ -354,18 +376,18 @@ last 6 months, 3.3x the 24% baseline (80% vs 24%).
It ranks every file by health score, takes the 20 lowest, and counts how many
were touched by a `fix:` commit in the trailing ~180-day window (the same
-signal the `prior_defect` biomarker uses). That precision is contrasted with
-the repo-wide base rate — the fraction of *all* files with a recent fix — to
-give the lift. The same number appears on the web `health` and `overview`
-dashboards, where it expands into a per-K table (worst 10/20/30), a
-concentration stat (what share of recently-fixed files fall in the
-least-healthy 20%), and the exact flagged files.
+signal the `prior_defect` biomarker uses). That precision is contrasted with the
+repo-wide base rate (the fraction of all files with a recent fix) to give the
+lift. The same number appears on the web `health` and `overview` dashboards,
+where it expands into a per-K table (worst 10/20/30), a concentration stat (what
+share of recently-fixed files fall in the least-healthy 20%), and the exact
+flagged files.
Agents can read the same stat over MCP, so a coding agent can confirm the score
is trustworthy on this repo before acting on it:
```python
-# MCP — dashboard mode, the same precision@K / lift block
+# MCP: dashboard mode, the same precision@K / lift block
get_health(include=["accuracy"])
```
@@ -374,79 +396,102 @@ scored files, or fewer than 5 recently-fixed files). One caveat it discloses:
`prior_defect` is itself one (down-weighted) input to the score, so this is an
association on the indexed history, not a leakage-free forward prediction.
+### Beyond your repo: cross-project validation
+
+The per-repo callout is a quick local check. The score is also validated across
+projects, so the number is not tuned to a single codebase. Every file is graded
+at a commit that precedes the bug window, so no future information leaks in, then
+checked against what actually broke:
+
+- Across 21 repositories, 9 languages, and 2,826 files, the score reaches a mean
+ ROC AUC of **0.737** (95% CI 0.683 to 0.787). ROC AUC measures how often the
+ score ranks a known-buggy file worse than a clean one: 0.5 is a coin flip, 1.0
+ is perfect. It beats raw churn by 0.10 AUC and a prior-defects baseline by 0.117
+ AUC (DeLong p < 1e-9).
+- On the public PROMISE/jEdit defect dataset, which played no part in
+ calibration, the same biomarkers score AUC **0.76 to 0.78**. That held-out
+ result is the main evidence the signal is not overfit.
+- The limits ship with the wins. Among files of similar size the signal is weak
+ (within-size-band AUC near 0.49), so part of the headline is simply that larger
+ files carry more risk; and a prior-defects baseline still finds bugs slightly
+ more efficiently under a fixed review budget (it wins on Popt by 0.085).
+
+Full methodology, confidence intervals, and the named head-to-head against
+CodeScene are in the [benchmark hub](https://github.com/repowise-dev/repowise-bench).
+
## The biomarkers
-**brain_method** — A single function that is simultaneously long, deeply
+**brain_method**: A single function that is simultaneously long, deeply
nested, highly complex, and central to the dependency graph. The strongest
single signal of fragile code. Centrality is judged against the repo's own
dependency density (top-quintile of connected files, with an absolute
-hub bar), so it fires on sparse-graph languages too — not just Python.
+hub bar), so it fires on sparse-graph languages too, not just Python.
-**low_cohesion** — A class whose methods split into groups that share no
+**low_cohesion**: A class whose methods split into groups that share no
fields and don't call each other (LCOM4 ≥ 2). Measured by the walker's
class-level model; a high value usually means several smaller,
single-responsibility classes are hiding inside one.
-**god_class** — A large class (≥ 200 lines, ≥ 15 methods) that also
-contains a brain method. Size alone isn't flagged — the brain-method
+**god_class**: A large class (≥ 200 lines, ≥ 15 methods) that also
+contains a brain method. Size alone isn't flagged: the brain-method
requirement keeps flat data holders and config tables from firing.
-**nested_complexity** — Functions with control-flow nesting ≥ 4 levels.
+**nested_complexity**: Functions with control-flow nesting ≥ 4 levels.
Hard to read, hard to test, hard to refactor.
-**bumpy_road** — Multiple branches stacked at the same depth — usually a
+**bumpy_road**: Multiple branches stacked at the same depth, usually a
sign the function is doing several jobs that should be split.
-**complex_method** — Cyclomatic complexity ≥ 9. Each branch is a path the
+**complex_method**: Cyclomatic complexity ≥ 9. Each branch is a path the
test suite has to cover.
-**large_method** — Long functions that also carry at least some branching.
+**large_method**: Long functions that also carry at least some branching.
A long-but-perfectly-flat body (a big config/data literal, a wall of
sequential assignments) is a layout artefact rather than a complexity smell,
-so it is excluded — the trigger is about length-with-substance, not raw line
+so it is excluded: the trigger is about length-with-substance, not raw line
count.
-**primitive_obsession** — Many primitive parameters in one signature. A
+**primitive_obsession**: Many primitive parameters in one signature. A
dataclass or parameter object would name the inputs. Suppressed in very small
modules (under ~60 non-blank lines), where a wide signature is an idiomatic
config/builder/forwarder rather than a design smell.
-**dry_violation** — Cross-file code clones, detected by a native Rabin–Karp
+**dry_violation**: Cross-file code clones, detected by a native Rabin-Karp
rolling hash over tree-sitter tokens (variable renames don't hide a clone).
Pairs are ranked by co-change so dormant duplicates rank lower than active
ones.
-**untested_hotspot** — A hotspot file with low or zero coverage and many
+**untested_hotspot**: A hotspot file with low or zero coverage and many
dependents. The textbook "write tests before refactoring" case.
-**coverage_gap** — Non-test files with meaningful uncovered surface.
+**coverage_gap**: Non-test files with meaningful uncovered surface.
Severity grades along coverage depth.
-**coverage_gradient** — A continuous coverage deduction that scales with the
+**coverage_gradient**: A continuous coverage deduction that scales with the
uncovered fraction (`4.0 × (1 − line_coverage_pct/100)`, capped), so files stay
penalised in proportion to how much code is untested rather than only when they
-fall below a hard threshold. Fires across the whole 0–100% range for files with
+fall below a hard threshold. Fires across the whole 0-100% range for files with
known coverage; silent (no imputation) where coverage was never ingested.
-**developer_congestion** — Too many active authors touching the same file.
+**developer_congestion**: Too many active authors touching the same file.
Usually an ownership problem dressed up as a code problem.
-**knowledge_loss** — The primary authors of the file are no longer active
+**knowledge_loss**: The primary authors of the file are no longer active
on the project. Refactor while someone still remembers why. Gated on recent
-activity — an abandoned-but-stable file is low risk (the survivor effect),
+activity: an abandoned-but-stable file is low risk (the survivor effect),
so this only fires while the code is still being changed.
-**hidden_coupling** — Files that consistently change in the same commits
+**hidden_coupling**: Files that consistently change in the same commits
without an explicit import or dependency edge between them. Captures
behavioral coupling (shared protocols, parallel config, copy-pasted
constants) that static analysis cannot see. Tier-aware: empty on
ESSENTIAL-tier repos until co-change backfill runs.
-**complex_conditional** — Branch / loop guards that combine three or more
+**complex_conditional**: Branch / loop guards that combine three or more
boolean operators. Severity grows with the operator count (LOW at 3, MED
at 4, HIGH at 5, CRIT at 6+).
-**function_hotspot** — Functions that are both structurally complex and
+**function_hotspot**: Functions that are both structurally complex and
frequently modified. Per-function modification counts come from a
per-line blame index built once per file (FULL git tier) and shared
with `code_age_volatility`. Fires when a function's distinct-commit
@@ -454,72 +499,72 @@ count is at or above the repo-wide p80 AND the function meets a
structural floor (CCN ≥ 10 or max nesting ≥ 3). Tier-aware: returns no
findings on ESSENTIAL-tier repos until `backfill_blame()` runs.
-**code_age_volatility** — Functions whose median line age is at least a
+**code_age_volatility**: Functions whose median line age is at least a
year old that are suddenly being modified. Strong defect predictor:
the editor is usually working in unfamiliar territory. Uses the same
-per-line blame index — `median_age_days` from per-line author
+per-line blame index: `median_age_days` from per-line author
timestamps, `recent_mod_count` from distinct shas inside the last 30
days. Severity escalates with both axes (CRIT when median age ≥ 2y AND
≥ 5 recent commits). Tier-aware: same ESSENTIAL no-op as
`function_hotspot`.
-**ownership_risk** — Long-run ownership dispersion. Counts *minor
-contributors* — authors who each own less than 5% of the file's commits —
-and the dominant owner's share. Many drive-by authors with no clear owner is
+**ownership_risk**: Long-run ownership dispersion. Counts minor
+contributors (authors who each own less than 5% of the file's commits) and
+the dominant owner's share. Many drive-by authors with no clear owner is
the single strongest defect correlate in the literature (Bird et al.). Fires
on files with ≥ 5 commits where ≥ 3 contributors are minor or no owner holds
-40%. Complements `developer_congestion`, which measures *active* (90-day)
+40%. Complements `developer_congestion`, which measures active (90-day)
contention rather than lifetime dispersion.
-**churn_risk** — Relative churn: the fraction of a file's lines rewritten in
+**churn_risk**: Relative churn: the fraction of a file's lines rewritten in
the last 90 days, normalized by file size. A file whose recent window rewrote
more lines than it contains is structurally unstable regardless of how big it
is. Because the trigger is a ratio to NLOC, it does not simply re-flag large
files. Fires when the file is actively churning (≥ 5 recent commits, top
quartile of repo churn) and relative churn ≥ 1.0.
-**change_entropy** — How scattered a file's change history is, adapted from
+**change_entropy**: How scattered a file's change history is, adapted from
Hassan's History Complexity Metric. Each commit is treated as a one-period
window whose entropy is `log2(files-touched)`, distributed across its files and
decayed over time. A file repeatedly caught up in wide, scattered commits
scores high; one changed in focused, single-purpose commits stays low even if
-it changes often — so this is *not* a churn proxy. Fires when the file is
+it changes often, so this is not a churn proxy. Fires when the file is
actively changing (≥ 3 recent commits) and sits in the top 20% of repo change
entropy. Tier-aware: silent on ESSENTIAL-tier repos (no co-change walk).
-**co_change_scatter** — Breadth of coupling. Counts the distinct files a file
+**co_change_scatter**: Breadth of coupling. Counts the distinct files a file
co-changes with above the indexer's recording threshold; a high count means
editing it tends to ripple across the codebase (shotgun surgery). This is the
-breadth complement to `hidden_coupling`, which flags *specific* undeclared
+breadth complement to `hidden_coupling`, which flags specific undeclared
coupled pairs. Fires on actively-changing files (≥ 3 recent commits) coupled to
≥ 8 distinct partners. Tier-aware: silent on ESSENTIAL-tier repos.
## Test quality
-These two fire **only on test files** and live in a deliberately small
-category (cap −0.5), so a noisy test never dominates its own health score.
+These two fire only on test files and live in a deliberately small category
+(cap −0.5), so a noisy test never dominates its own health score.
-**large_assertion_block** — A test that fires 15 or more assertions in one
+**large_assertion_block**: A test that fires 15 or more assertions in one
uninterrupted run. Such a test usually checks several behaviours at once: when
it fails it points at a line, not a cause, and it's brittle to unrelated
changes. Splitting it into focused cases makes failures legible.
-**duplicated_assertion_block** — The same run of assertions copy-pasted across
-tests. Reuses the Rabin–Karp clone detector and keeps only the clone regions
+**duplicated_assertion_block**: The same run of assertions copy-pasted across
+tests. Reuses the Rabin-Karp clone detector and keeps only the clone regions
that overlap an assertion block on a test file. A change to the asserted
-behaviour then has to be edited in several places — and usually isn't, so the
+behaviour then has to be edited in several places, and usually isn't, so the
copies drift.
-**error_handling** — Swallowed-exception and unsafe-unwrap anti-patterns: an
+**error_handling**: Swallowed-exception and unsafe-unwrap anti-patterns: an
empty or comment-only `catch`/`except` body, a Python catch-all `except:` /
`except Exception:`, Rust `.unwrap()` / `.expect()` / `panic!`-family macros,
and Go's empty `if err != nil {}` or blank-identifier discard of a call's
-error. Detection is precision-first — only the unambiguous shapes fire, and an
+error. Detection is precision-first: only the unambiguous shapes fire, and an
unsupported language or parse failure yields no signal rather than a guess.
Each occurrence is a LOW finding anchored to its line, and the whole category
is capped at −0.5 per file: this is an advisory maintainability flag (every
linter is expected to surface `except: pass`), deliberately not a calibrated
-defect predictor — on the 21-repo benchmark it is AUC-neutral, so it is
+defect predictor. On the 21-repo benchmark it is AUC-neutral, so it is
excluded from the weight calibration and bounded so it can never move a file's
score by more than half a point.
@@ -538,7 +583,7 @@ repowise health \
```
Formats are auto-detected: **LCOV**, **Cobertura** XML, **Clover** XML, and a
-**normalized JSON** (`repowise-coverage-v1`) keyed by repo-relative path — the
+**normalized JSON** (`repowise-coverage-v1`) keyed by repo-relative path; the
last lets you feed coverage from any runner once it's mapped to one shape:
```json
@@ -558,33 +603,32 @@ repowise health --refactoring-targets
```
A health score tells you a file is in trouble; a refactoring target names the
-**specific** fix. Repowise emits one structured `RefactoringSuggestion` per
+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
+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. Five 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. |
-| **Extract Method** | A cohesive slice of a long function to lift into a helper, with the inferred parameter (in) and return (out) signature. | Intra-procedural dataflow (CFG + def/use + reaching definitions) over functions a method biomarker already flagged; a single-exit span with a real decision point and no partial branch, `in`/`out` inferred by liveness. Python first. |
+| **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. |
-| **Split File** | The cohesive files an oversized module should decompose into — which symbols move where, plus the import edits in every dependent. | Community detection (Leiden/Louvain) over a weighted intra-file symbol graph, gated on partition **modularity**. Language-agnostic (reads `defines`/`calls` edges); the file-level analog of Extract Class. |
+| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component, then a greedy minimum feedback arc set over the real import edges. |
+| **Split File** | The cohesive files an oversized module should decompose into: which symbols move where, plus the import edits in every dependent. | Community detection (Leiden/Louvain) over a weighted intra-file symbol graph, gated on partition **modularity**. Language-agnostic (reads `defines`/`calls` edges); the file-level analog of Extract Class. |
-Each suggestion is **structured data, not a string**: a `plan` (the split groups,
+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
+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`).
+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:
@@ -598,8 +642,9 @@ The web **Refactoring** tab renders each plan as a card (split groups as a tree,
move arrow, clone occurrences with line links, file-split groups with their
residual core and import-rewrite list) 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:
+unified diff. Code generation runs only on an explicit request, never in the
+indexing hot path. It is enabled by default and can be turned off with
+`refactoring.llm.enabled: false`. Full reference:
**[docs/REFACTORING.md](REFACTORING.md)**.
## Trends
@@ -610,9 +655,9 @@ the history doubles as a per-file record.
Two repo-level alerts run over the history:
-- **Declining Health** — current `hotspot_health` is ≥ 0.5 below the
+- **Declining Health**: current `hotspot_health` is ≥ 0.5 below the
snapshot 5 runs ago.
-- **Predicted Decline** — the three most recent snapshots are each
+- **Predicted Decline**: the three most recent snapshots are each
strictly below the one before.
Inspect from the CLI:
@@ -629,13 +674,13 @@ get_health(include=["trend"])
### Per-file score over time
-The same snapshots power a per-file trajectory — a file's score plotted
+The same snapshots power a per-file trajectory: a file's score plotted
across runs (CodeScene's signature view). It surfaces on the file's Health
tab and in the health drawer as a sparkline, with a delta vs. the previous
-run and a **Declining** flag (the per-file version of the alerts above:
+run and a Declining flag (the per-file version of the alerts above:
≥ 0.5 below the run 5 snapshots back, or three consecutive drops).
-A trend is **silent on thin history** — it needs at least two snapshots that
+A trend is silent on thin history: it needs at least two snapshots that
both carry the file, otherwise the UI shows "no score history yet" rather
than a misleading single dot. Gaps (a file absent from some snapshots) are
skipped, not zero-filled.
@@ -643,12 +688,12 @@ skipped, not zero-filled.
Fetch it directly:
```bash
-# REST — one file's series + current delta + declining flag
+# REST: one file's series + current delta + declining flag
GET /api/repos/{repo_id}/health/files/trend?file_path=path/to/file.py
```
```python
-# MCP — targeted mode attaches a per-file `trends` block
+# MCP: targeted mode attaches a per-file `trends` block
get_health(targets=["path/to/file.py"])
```
@@ -657,13 +702,13 @@ get_health(targets=["path/to/file.py"])
Every file carries process, people, and topology signals we already compute
during indexing. They answer "should I worry about this file?" with context
the score alone can't, and they surface together on the file's Health tab and
-in the health drawer — grouped, captioned, and **silent ("no signal") when the
-underlying data is absent** rather than imputed.
+in the health drawer, grouped, captioned, and silent ("no signal") when the
+underlying data is absent rather than imputed.
| Group | Signal | Means |
|-------|--------|-------|
| Process | Prior defects | Bug-fix commits touching this file in the last ~6 months. `0` is a real, reassuring signal. |
-| Process | Change scatter | `change_entropy_pct` (0-100) — how spread out its edits are across commits. High = chaotic change. |
+| Process | Change scatter | `change_entropy_pct` (0-100): how spread out its edits are across commits. High = chaotic change. |
| Process | 90-day churn | Commits and lines added/deleted in the trailing 90 days. |
| Process | Age | How long the file has existed in git history. |
| People | Primary owner | The all-time top committer and their commit share. |
@@ -671,25 +716,25 @@ underlying data is absent** rather than imputed.
| Topology | Dependents | How many files depend on this one (graph in-degree). |
| Topology | Dependencies | How many files this one depends on (graph out-degree). |
-These are pure surfacing — no new measurement, no scoring. Fetch them directly:
+These are pure surfacing: no new measurement, no scoring. Fetch them directly:
```bash
-# REST — embedded in the file-detail aggregate and the drawer breakdown
+# REST: embedded in the file-detail aggregate and the drawer breakdown
GET /api/repos/{repo_id}/files/{path} # data.health.signals
GET /api/repos/{repo_id}/health/files/breakdown?file_path=path/to/file.py
```
```python
-# MCP — attached to the get_context health block (null fields dropped)
+# MCP: attached to the get_context health block (null fields dropped)
get_context(targets=["path/to/file.py"], include=["health"])
-# MCP — also on get_health targeted mode, one `signals` object per metric
+# MCP: also on get_health targeted mode, one `signals` object per metric
get_health(targets=["path/to/file.py"], include=["signals"])
```
## Hotspot anatomy
-Two views dissect *where* risk concentrates, both plotted from data already on
+Two views dissect where risk concentrates, both plotted from data already on
disk (churn from the git indexer, complexity from the walker, blame at function
granularity).
@@ -698,18 +743,18 @@ granularity).
One dot per recently-changed file: the x-axis is its 90-day commit count
(churn), the y-axis is its max cyclomatic complexity, dot size is NLOC, and dot
color is the health band. Dashed guides sit at the repo's median churn and
-median complexity, so the tinted top-right corner reads "busier **and** more
-complex than a typical file here" — the refactor zone, where volatility and
+median complexity, so the tinted top-right corner reads "busier and more
+complex than a typical file here", the refactor zone, where volatility and
tangle collide and defects concentrate. It lives on the **Hotspots & churn**
dashboard tab, toggleable with the churn × bus-factor view.
```bash
-# REST — repo-level point list (one point per churned file)
+# REST: repo-level point list (one point per churned file)
GET /api/repos/{repo_id}/health/churn-complexity
```
```python
-# MCP — the same point list, dashboard mode
+# MCP: the same point list, dashboard mode
get_health(include=["churn_complexity"])
```
@@ -720,7 +765,7 @@ still shows in the bottom-right ("changes constantly but stays simple").
### Functions by churn
The file's Health tab lists its functions ranked by modification count, with
-the 90-day recent-mod count, median age, and blame owner per function — the
+the 90-day recent-mod count, median age, and blame owner per function, the
same `git_function_blame` rollup the symbol page uses. It promotes per-function
ownership and volatility out of the buried biomarker cards into a first-class
table, so "which function in this file is the actual hotspot" is one glance away.
@@ -751,7 +796,7 @@ Per-file overrides live in `.repowise/health-rules.json`:
### Severity overrides and profiles
A team can soften a signal it treats as advisory without disabling it
-outright by remapping its severity (typically a *demotion*). Overrides apply
+outright by remapping its severity (typically a demotion). Overrides apply
repo-wide and per-path; an explicit per-path entry wins over the repo-wide one.
```json
@@ -769,16 +814,16 @@ Accepted severity values are `low`, `medium`, `high`, `critical`. The named
noisier structural signals a 1-3 person repo can't support; an explicit
`severity_overrides` key always wins over the preset.
-Only the severity *label* is tunable. The per-biomarker weight multipliers and
+Only the severity label is tunable. The per-biomarker weight multipliers and
the category caps are the calibrated constants the benchmark numbers rest on
-and are deliberately **not** overridable, so a team's local policy never
-changes what the published accuracy claims mean. Biomarkers that carry a
-continuous deduction (`coverage_gradient`) are unaffected by severity remaps.
+and are deliberately not overridable, so a team's local policy never changes
+what the published accuracy claims mean. Biomarkers that carry a continuous
+deduction (`coverage_gradient`) are unaffected by severity remaps.
## Incremental updates
`repowise update` only re-scores the changed files. Findings and metrics for
-unchanged files stay put — no nightly full re-index needed.
+unchanged files stay put, no nightly full re-index needed.
## Status one-liner
@@ -791,23 +836,45 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts) · 7.0
## Comparison
-| Feature | Repowise | CodeScene | DeepSource | Sourcery |
-|----------------------------------|:--:|:--:|:--:|:--:|
-| Code health score (1–10) | ✅ 25 biomarkers | ✅ 25–30 | ❌ | ❌ |
-| Brain Method detection | ✅ | ✅ | ❌ | ❌ |
-| Low cohesion (LCOM4) / god class | ✅ | ✅ | ❌ | ❌ |
-| Test coverage intelligence | ✅ LCOV/Cobertura/Clover/JSON | ❌ | ❌ | ❌ |
-| Untested hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ |
-| DRY violation detection | ✅ native (no npm) | ✅ | ❌ | ❌ |
-| Health trend tracking | ✅ | ✅ | ❌ | ❌ |
-| Declining health alerts | ✅ | ✅ | ❌ | ❌ |
-| Refactoring recommendations | ✅ deterministic | ✅ | ❌ | ❌ |
-| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Method / Move Method / Break Cycle / Split File, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file |
-| Free for internal use | ✅ AGPL-3.0 | ❌ $15–30/author | ✅ public repos | ❌ |
+How the code-health signal compares to the tools it is most often placed next
+to. The honest dividing line: each of these has a rules or linter engine and a
+definitional rating; repowise predicts which files harbor the next bug and
+validates that forward in time against a labeled bug corpus. Each tool also has
+real strengths repowise does not claim to beat, noted under the table.
+
+| Capability | Repowise | CodeScene | SonarQube | Code Climate / Qlty¹ | Codacy |
+|---|---|---|---|---|---|
+| Per-file health / maintainability score | ✅ 1-10, 25 biomarkers | ✅ 1-10 Code Health | ⚠️ A-E ratings from rule counts | ✅ A-F grade | ✅ A-F grade |
+| Score uses git / behavioral signals (churn, ownership, co-change, hotspots) | ✅ | ✅ its core | ❌ static rules only | ⚠️ churn-vs-complexity, no co-change | ❌ |
+| Cross-file / call-graph analysis | ✅ interprocedural call graph | ⚠️ git temporal coupling, not a static call graph | ⚠️ cross-file taint (security only) | ❌ file-local | ❌ file-local |
+| Defect-validated score vs a real bug corpus (published numbers) | ✅ mean ROC AUC 0.737, held-out 0.76-0.78 | ⚠️ "Code Red" study (defect density / cycle time), no per-file AUC | ❌ | ❌ | ❌ |
+| Static performance risk (N+1 / IO-in-loop across the call graph) | ✅ | ❌ | ❌ | ❌ | ❌ |
+| Test-coverage ingestion | ✅ LCOV/Cobertura/Clover/JSON | ✅ JaCoCo/Cobertura/LCov/Clover | ⚠️ imports reports | ✅ | ✅ |
+| Untested-hotspot detection (coverage × risk) | ✅ | ✅ | ❌ | ⚠️ coverage beside hotspots, no composite | ❌ |
+| Concrete cross-file refactoring plans (Extract Class / Move Method / Split File) | ✅ + opt-in LLM code-gen | ⚠️ AI fixes 5 in-function smells, no cross-file plan | ❌ flags + AI CodeFix | ❌ flags only | ❌ flags + per-issue AI autofix |
+| Health trend tracking + declining-health alerts | ✅ | ✅ | ✅ quality gates, new-code focus | ✅ | ✅ quality gates |
+| AI-agent / MCP integration | ✅ MCP tools | ✅ Code Health MCP server | ✅ official MCP server | ❌ | ✅ official MCP + Guardrails |
+| Security scanning (adjacent axis) | ⚠️ separate security layer | ⚠️ secondary | ✅ strong (cross-file taint) | ❌ | ✅ full SAST/SCA/secrets/IaC |
+| License | ✅ AGPL-3.0, free internal use | ⚠️ free OSS; paid per active author | ⚠️ Community free; paid by LOC | ⚠️ free OSS; paid teams | ⚠️ free OSS; paid per dev |
+
+¹ Code Climate Quality was spun out as Qlty Software in November 2024; "Code
+Climate" now sells the Velocity engineering-analytics product. This row tracks
+the Quality / Qlty capabilities. SonarQube "Security Hotspots" are
+static-analysis security flags, not git-churn hotspots.
+
+What each tool does that repowise does not: **SonarQube** has the broadest
+security scanning (cross-file taint analysis), the widest language coverage, and
+the most widely adopted merge-gate model. **CodeScene** is the most mature
+behavioral-analysis product (knowledge maps, off-boarding simulation, 28+
+languages) and has the only published empirical defect study in this group (the
+"Code Red" correlation study, Tornhill and Borg, TechDebt 2022). **Code Climate /
+Qlty** defined the churn-vs-complexity quadrant and pairs with Velocity for DORA
+analytics. **Codacy** has the widest security suite of the four and polished PR
+automation.
## See also
-- [`packages/core/src/repowise/core/analysis/health/README.md`][hr] —
+- [`packages/core/src/repowise/core/analysis/health/README.md`][hr]:
developer overview of the layer.
- Sub-package READMEs: `complexity/`, `coverage/`, `duplication/`,
`biomarkers/`.
diff --git a/docs/COMPUTED_GLOSSARY.md b/docs/COMPUTED_GLOSSARY.md
index 8c21e0099..f4ac31641 100644
--- a/docs/COMPUTED_GLOSSARY.md
+++ b/docs/COMPUTED_GLOSSARY.md
@@ -246,6 +246,14 @@ workspace overlays, MCP responses, and CLI output.
| Risk summary | One-line synthesized risk sentence for MCP. | `tool_risk._assess_one_target()` | `src/auth.py - hotspot score 88% (increasing), 6 dependents...` |
| Top hotspots | Highest churn/hotspot files returned for context. | `get_risk()` | `[{file_path: "src/db.py", hotspot_score: 0.94}]` |
+## Code Health And Defect-Score Benchmark Metrics
+
+| Term | Definition | Computed by | Example |
+| --- | --- | --- | --- |
+| ROC AUC (Area Under the ROC Curve) | A ranking-quality measure for a binary classifier. Given one file that later received a bug fix and one that did not, it is the probability the model scores the buggy file as riskier. 0.5 is random, 1.0 is perfect separation. Repowise's defect score reaches a cross-project mean of 0.737 across 21 repositories. | Defect-score benchmark harness (cross-project validation) | `roc_auc: 0.737` |
+| Popt (effort-aware ranking) | A normalized cumulative-lift (Alberg-curve) score that ranks files by predicted risk against review effort measured in lines of code. It rewards a model that concentrates real defects in the fewest lines a reviewer would read. 0 is worst, 1 is best. It complements ROC AUC, which ignores file size. | Defect-score benchmark harness (cross-project validation) | `popt: 0.58` |
+| LCOM4 (Lack of Cohesion of Methods, version 4) | The number of connected components formed by a class's methods when two methods are linked if they share a field or one calls the other. 1 means a cohesive class; a value of 2 or more means the methods split into groups that share nothing, a signal the class should be split (the basis of the low_cohesion biomarker and the Extract Class refactoring). | `analysis/health/biomarkers/low_cohesion.py`, `analysis/health/complexity/class_analysis.py` | `lcom4: 3` |
+
## Search, Answer Cache, And Retrieval
| Term | Definition | Computed by | Example |
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index d6eb4a00c..75b8bf3ab 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -11,7 +11,7 @@ repo root on first `init`.
```
.repowise/
-├── wiki.db # SQLite database — all pages, symbols, graph, git metadata, decisions
+├── wiki.db # SQLite database: all pages, symbols, graph, git metadata, decisions
├── lancedb/ # Vector search index (LanceDB)
├── omissions/ # Distill omission store + savings ledger (omissions.db)
├── config.yaml # Provider, model, embedder, exclude patterns
@@ -21,7 +21,7 @@ repo root on first `init`.
```
repowise adds `.repowise/` to your `.gitignore` automatically. The directory
-should not be committed — it's a local cache, not a source of truth.
+should not be committed; it's a local cache, not a source of truth.
---
@@ -61,10 +61,10 @@ or models that cannot translate an explicit mode fail before making an API call.
regenerates the wiki). Power users can define their own style under
`.repowise/styles/<name>/style.yaml`. Full guide: [WIKI_STYLES.md](WIKI_STYLES.md).
Note: hand-editing `wiki_style` here and running `update` does not regenerate
-existing pages — use `restyle`.
+existing pages, use `restyle`.
> **Code-health rules** are configured separately in
-> `.repowise/health-rules.json` (per-file biomarker overrides) — see
+> `.repowise/health-rules.json` (per-file biomarker overrides); see
> [CODE_HEALTH.md](CODE_HEALTH.md#configuration).
### The `distill:` block
@@ -77,7 +77,7 @@ distill:
enabled: true # master switch for this repo
commands:
enabled: true # the command path (CLI + hook rewrites)
- permission: ask # ask | allow | off — rewrite-hook posture
+ permission: ask # ask | allow | off (rewrite-hook posture)
families: # per-filter overrides
test_output: allow # auto-allow rewrites for test runs
git_diff: deny # never rewrite git diff here
@@ -119,27 +119,28 @@ mcp:
### The `refactoring:` block
-Controls the refactoring-intelligence layer — the structured Extract Class /
-Extract Helper / Move Method / Break Cycle plans surfaced by `repowise health
+Controls the refactoring-intelligence layer: the structured Extract Class /
+Extract Helper / Move Method / Break Cycle / Split File 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.
+this block only tunes which fire and the optional 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
+ min_confidence: medium # low | medium | high (the surface gate)
llm:
- enabled: false # opt-in code generation; gates the generate-code endpoint
+ enabled: true # code generation, on by default; set false to disable
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).
+ health pass. Code generation is the only part that calls a provider: it is on
+ by default but never runs during indexing, only on an explicit request (set
+ `llm.enabled: false` to disable it).
- Per-path disables reuse the `.repowise/health-rules.json` glob mechanism (the
same one biomarkers use).
- Full reference: [REFACTORING.md](REFACTORING.md).
@@ -156,7 +157,7 @@ export ANTHROPIC_API_KEY="sk-ant-..."
| Model | Notes |
|-------|-------|
-| `claude-sonnet-4-6` | Default — best balance of quality and cost |
+| `claude-sonnet-4-6` | Default, best balance of quality and cost |
| `claude-opus-4-6` | Highest quality, higher cost |
| `claude-haiku-4-5-20251001` | Fastest, lowest cost |
@@ -194,7 +195,7 @@ repowise init --provider gemini
Gemini is also the default embedding provider when `GEMINI_API_KEY` is set.
-### Ollama (local — no API key)
+### Ollama (local, no API key)
```bash
export OLLAMA_BASE_URL="http://localhost:11434"
@@ -228,7 +229,7 @@ The embedder is separate from the LLM provider.
|----------|---------|-------|
| `gemini` | `GEMINI_API_KEY` | Default when key is present |
| `openai` | `OPENAI_API_KEY` | OpenAI `text-embedding-3-small` |
-| `mock` | — | Dummy embeddings, no semantic search |
+| `mock` | n/a | Dummy embeddings, no semantic search |
```bash
repowise init --embedder openai
@@ -241,9 +242,9 @@ repowise reindex --embedder gemini # switch embedder and rebuild index
API keys are resolved in this order:
-1. **Environment variable** — set before running repowise
-2. **`.repowise/.env`** — persisted from interactive setup, loaded automatically
-3. **Interactive prompt** — repowise asks during `init` if no key is found, then saves to `.repowise/.env`
+1. **Environment variable**: set before running repowise
+2. **`.repowise/.env`**: persisted from interactive setup, loaded automatically
+3. **Interactive prompt**: repowise asks during `init` if no key is found, then saves to `.repowise/.env`
The `.repowise/.env` file is gitignored automatically.
@@ -264,18 +265,18 @@ The `.repowise/.env` file is gitignored automatically.
| `REPOWISE_HOST` | API server host (default: `127.0.0.1`) |
| `REPOWISE_PORT` | API server port (default: `7337`) |
| `REPOWISE_MCP_PORT` | MCP SSE server port (default: `7338`) |
-| `REPOWISE_API_URL` | Frontend only — backend URL for the web UI (default: `http://localhost:7337`) |
+| `REPOWISE_API_URL` | Frontend only; backend URL for the web UI (default: `http://localhost:7337`) |
---
## Exclude patterns
repowise respects your `.gitignore` automatically (same `gitwildmatch` format git
-uses). Like git, it reads **nested `.gitignore` files** too — a `.gitignore` in
+uses). Like git, it reads **nested `.gitignore` files** too, so a `.gitignore` in
any subdirectory applies to that directory's contents. This matters for
monorepos and yarn/npm workspaces, where a package keeps its own `.gitignore`
excluding that package's build output (e.g. `dist/`, `coverage/`, generated
-bundles) — those exclusions are now honoured without duplicating them at the
+bundles), so those exclusions are now honoured without duplicating them at the
repo root.
On top of that, add extra patterns via `--exclude` / `-x`:
@@ -350,9 +351,9 @@ conformance:
target: db # matcher
allow: false # optional, default false (deny). true = exception
description: "..." # optional, shown in reports
- - source: "tag:ui" # matcher: tag:<name> — repos carrying that tag
+ - source: "tag:ui" # matcher: tag:<name> (repos carrying that tag)
target: "tag:data"
- - source: "*" # matcher: * — any service
+ - source: "*" # matcher: * (any service)
target: legacy-payments
```
diff --git a/docs/INTELLIGENCE_LAYERS.md b/docs/INTELLIGENCE_LAYERS.md
index 4285704e3..34e755861 100644
--- a/docs/INTELLIGENCE_LAYERS.md
+++ b/docs/INTELLIGENCE_LAYERS.md
@@ -1,14 +1,14 @@
# The Five Intelligence Layers
repowise indexes your codebase **once**, builds five intelligence layers, then
-keeps them in sync on every commit. This document is the deep dive — the README
+keeps them in sync on every commit. This document is the deep dive; the README
gives 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%" />
+<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,
+The layers 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.
@@ -20,8 +20,8 @@ make all of it searchable in natural language.
Two cross-cutting capabilities sit on top of the layers:
-- [Proactive context enrichment — hooks](#proactive-context-enrichment--hooks)
-- [Auto-sync — five ways to stay current](#auto-sync--five-ways-to-stay-current)
+- [Proactive context enrichment: hooks](#proactive-context-enrichment-hooks)
+- [Auto-sync: five ways to stay current](#auto-sync-five-ways-to-stay-current)
- [Auto-generated CLAUDE.md](#auto-generated-claudemd)
---
@@ -29,7 +29,7 @@ Two cross-cutting capabilities sit on top of the layers:
## Graph Intelligence
tree-sitter parses every file across 15 languages into a **two-tier dependency
-graph** — file nodes and symbol nodes (functions, classes, methods). A 3-tier
+graph**: file nodes and symbol nodes (functions, classes, methods). A 3-tier
call resolver with confidence scoring handles import aliases, barrel
re-exports, and namespace imports. Heritage extraction covers `extends`,
`implements`, trait impls, derive macros, mixins, and extension conformance.
@@ -53,36 +53,36 @@ and [`docs/COMPUTED_GLOSSARY.md`](COMPUTED_GLOSSARY.md) for every derived metric
repowise mines your git history (per-file, configurable depth) to produce
signals no static analysis can find.
-**Hotspots** — files in the top 25% of *both* churn and complexity. These are
+**Hotspots**: files in the top 25% of *both* churn and complexity. These are
where bugs live. Flagged in the dashboard, in `CLAUDE.md`, and surfaced by
`get_risk()` before your agent touches them.
-**Ownership** — `git blame` aggregated into ownership percentages per author.
+**Ownership**: `git blame` aggregated into ownership percentages per author.
Know who to ping. Know where knowledge silos exist.
-**Co-change pairs** — files that change together in the same commit *without* an
+**Co-change pairs**: files that change together in the same commit *without* an
import link. Hidden coupling that AST parsing cannot detect. `get_context()`
surfaces co-change partners alongside direct dependencies.
-**Bus factor** — files owned >80% by a single author. Shown in the ownership
+**Bus factor**: files owned >80% by a single author. Shown in the ownership
view, surfaced in `CLAUDE.md` as knowledge risk.
-**Significant commits** — the last 10 meaningful commit messages per file
+**Significant commits**: the last 10 meaningful commit messages per file
(filtered: no merges, no dependency bumps, no lint) feed generation prompts, so
the wiki explains *why* code is structured the way it is.
-**Contributor profiles** — every author with commits gets a profile page:
+**Contributor profiles**: every author with commits gets a profile page:
modules they own, top files, co-authors, commit category mix
(feat / fix / refactor / docs / test / chore / perf), silo modules they're
solely on, bus-factor risk files, and dead-code burden. Surfaced via
`/repos/<id>/owners` and linked from every owner reference.
-**Module health** — a composite 0–100 score per top-level module derived from
+**Module health**: a composite 0–100 score per top-level module derived from
silo penalty, hotspot density, dead-code percentage, average churn, doc
coverage, and median bus factor. Surfaced on the Risk page and the per-module
detail page, with cross-links to owners, hotspots, and governing decisions.
-**Reviewer suggestions** — paste a PR file list into Blast Radius and get a
+**Reviewer suggestions**: paste a PR file list into Blast Radius and get a
ranked list of likely reviewers, scored by direct authorship (×1.0), co-change
partners (×0.5), and recency (×0.4), capped at the 5 strongest co-change signals
per file.
@@ -94,24 +94,24 @@ per file.
An LLM-generated wiki for every module and file, rebuilt **incrementally** on
every commit.
-- **Coverage tracking** — what's documented and what isn't.
-- **Freshness scoring** per page — confidence scores show how current each page
+- **Coverage tracking**: what's documented and what isn't.
+- **Freshness scoring** per page: confidence scores show how current each page
is relative to the underlying code.
-- **Semantic search via RAG** — hybrid retrieval (full-text + vector merged via
+- **Semantic search via RAG**: hybrid retrieval (full-text + vector merged via
Reciprocal Rank Fusion) with PageRank bias and 1-hop graph expansion.
A typical single-commit update touches 3–10 pages and completes in under 30
-seconds — only the pages your change actually touched are regenerated.
+seconds; only the pages your change actually touched are regenerated.
---
## Decision Intelligence
-**The layer nobody else has.** Architectural decisions mined from **eight
-sources** — ADR files (Nygard/MADR), CHANGELOG entries, PR and squash-commit
-bodies, inline markers, git archaeology, README/docs, centrality-bounded code
-comments, and the LLM doc-generation pass itself — linked to the graph nodes
-they govern and tracked for staleness as code evolves.
+Architectural decisions mined from **eight sources**: ADR files (Nygard/MADR),
+CHANGELOG entries, PR and squash-commit bodies, inline markers, git archaeology,
+README/docs, centrality-bounded code comments, and the LLM doc-generation pass
+itself. These are linked to the graph nodes they govern and tracked for
+staleness as code evolves.
```python
# WHY: JWT chosen over sessions — API must be stateless for k8s horizontal scaling
@@ -121,16 +121,16 @@ they govern and tracked for staleness as code evolves.
Every decision is **evidence-backed**: each rationale traces to a verbatim
source span (ADR quote, commit body, code comment), and an anti-hallucination
-substring gate stamps each as **verified / fuzzy / unverified** — corroborating
+substring gate stamps each as **verified / fuzzy / unverified**: corroborating
sources raise confidence rather than overwrite each other.
Decisions form a **graph**: typed edges (`supersedes` / `refines` /
`relates_to` / `conflicts_with`) let `get_why()` answer *"why is auth structured
-this way?"* with a lineage chain (sessions → JWT → OAuth2), auto-detect when a
+this way?"* with a lineage chain (sessions -> JWT -> OAuth2), auto-detect when a
new commit reverses an old decision, and flag two active decisions that
contradict each other.
-These structured records surface everywhere your agent already looks —
+These structured records surface everywhere your agent already looks:
`get_why()` for the full archaeology, governing decisions in `get_context()`, a
`governance_risk` flag in `get_risk()` PR review, a Key Decisions section in
`get_overview()`, and `ungoverned_hotspot` / `stale_governance` /
@@ -156,7 +156,7 @@ repowise decision health
→ payments/processor.ts — 47 commits/month, no architectural decisions recorded
```
-The "why" usually walks out the door — when a teammate leaves, or when you
+The "why" usually walks out the door: when a teammate leaves, or when you
reopen your own repo six months later. Decision intelligence keeps it in the
codebase.
@@ -165,25 +165,25 @@ codebase.
## Code Health Intelligence
repowise computes a **1–10 health score for every file** from **25 deterministic
-biomarkers** — McCabe complexity, deep nesting, brain methods, class cohesion
+biomarkers**: McCabe complexity, deep nesting, brain methods, class cohesion
(LCOM4), god classes, native Rabin–Karp clone detection, untested hotspots,
function-level churn, code-age volatility, ownership dispersion, change entropy,
co-change scatter, prior-defect history, test-quality smells, and more.
-**Zero LLM calls. Zero cloud requirement. Zero new runtime dependencies** —
+**Zero LLM calls. Zero cloud requirement. Zero new runtime dependencies**:
pure Python over tree-sitter and git data, designed to finish in under 30
seconds on a 3,000-file repo.
The biomarker **weights are calibrated offline against a real defect corpus, not
hand-tuned**: each file is scored at the pre-window commit (T0, no leakage) and
-an L2-logistic regression — with NLOC as an explicit control — fits each
+an L2-logistic regression (with NLOC as an explicit control) fits each
biomarker's defect lift *beyond* file size. Only the learned constants ship; the
runtime 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**
+The same biomarker stream produces three orthogonal signals: defect risk
+(the calibrated headline number), maintainability, and performance risk. These
+are co-equal views, never blended into one number. It does not stop at scoring:
+the layer closes the loop into concrete, graph-aware refactoring plans
(see below) an agent can execute.
```bash
@@ -194,12 +194,12 @@ repowise health --trend # last 10 snapshots + declining/predicted-
repowise status # one-line summary in the status report
```
-- **Coverage ingestion** — LCOV, Cobertura, Clover, or normalized JSON light up
+- **Coverage ingestion**: LCOV, Cobertura, Clover, or normalized JSON light up
the test-coverage biomarkers (`untested_hotspot`, `coverage_gap`,
`coverage_gradient`).
-- **Trend tracking** — a rolling 50-row snapshot history powers `Declining
+- **Trend tracking**: a rolling 50-row snapshot history powers `Declining
Health` and `Predicted Decline` alerts.
-- **Refactoring plans** — deterministic, structured, **graph-aware**: Extract
+- **Refactoring plans**: deterministic, structured, **graph-aware**: Extract
Class (LCOM4 cohesion split), Extract Helper (clone dedup), Move Method (feature
envy), Break Cycle (minimum feedback arc set), and Split File (modularity-gated
module decomposition with the import-rewrite blast radius), each carrying its
@@ -210,7 +210,7 @@ repowise status # one-line summary in the status report
[`docs/REFACTORING.md`](REFACTORING.md).
- **Per-file overrides** via `.repowise/health-rules.json`.
-Validated against real defect history — see
+Validated against real defect history; see
[`docs/CODE_HEALTH.md`](CODE_HEALTH.md) for the full user guide, the per-biomarker
reference, and the calibration story, and
[repowise-bench](https://github.com/repowise-dev/repowise-bench) for the
@@ -218,17 +218,17 @@ reproducible defect-prediction and head-to-head benchmarks.
---
-## Proactive context enrichment — hooks
+## Proactive context enrichment: hooks
-Most MCP tools are passive — the agent has to know to call them. repowise hooks
-are **active**. They inject graph context into every search automatically, so
+Most MCP tools are passive: the agent has to know to call them. repowise hooks
+are active. They inject graph context into every search automatically, so
agents are smarter even when they don't explicitly ask for help. Hooks are
installed automatically during `repowise init`.
-### PreToolUse — every search gets graph context
+### PreToolUse: every search gets graph context
When your AI agent runs `Grep` or `Glob`, repowise intercepts the call and
-enriches it with the top 3 related files — found via multi-signal search (symbol
+enriches it with the top 3 related files, found via multi-signal search (symbol
name match, file-path match, full-text search on wiki content), ranked by
relevance then PageRank. No LLM calls. No network. Pure local SQLite queries.
@@ -241,7 +241,7 @@ relevance then PageRank. No LLM calls. No network. Pure local SQLite queries.
Uses: src/core/analysis/communities.py, src/core/analysis/execution_flows.py
```
-### PostToolUse — auto-detect stale wiki
+### PostToolUse: auto-detect stale wiki
After a successful `git commit`, repowise checks whether the wiki is out of date
and notifies the agent:
@@ -253,12 +253,12 @@ Run `repowise update` to refresh documentation and graph context.
> **Related capability:** [Distill](DISTILL.md) reuses these layers' index
> (symbol bounds, centrality, hotspots) to compress noisy command output and
-> large file reads before the agent sees them — a capability built *on* the
+> large file reads before the agent sees them, a capability built *on* the
> five layers, not a sixth layer.
---
-## Auto-sync — five ways to stay current
+## Auto-sync: five ways to stay current
repowise keeps your intelligence layers in sync with your code. Pick the method
that fits your workflow:
@@ -287,7 +287,7 @@ seconds. Full guide: [`docs/AUTO_SYNC.md`](AUTO_SYNC.md).
## Auto-generated CLAUDE.md
After every `repowise init` and `repowise update`, repowise regenerates your
-`CLAUDE.md` from actual codebase intelligence — not a template. No LLM calls.
+`CLAUDE.md` from actual codebase intelligence, not a template. No LLM calls.
Under 5 seconds.
```bash
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 0eef9ed43..a71f81f54 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -28,7 +28,7 @@ pipeline stages produce meaningful output.
¹ **Code-health biomarkers** require a per-language complexity-walker map
(`analysis/health/complexity/languages.py`), independent of `.scm` parsing.
A language is only listed **Full** once it clears the
-[code-health checklist](#code-health-biomarker-coverage) below — except
+[code-health checklist](#code-health-biomarker-coverage) below, except
**Go**, whose class-level metrics (LCOM4 / god-class) are not computable
because Go methods attach to a type via an external receiver rather than
nesting in a class body; Go gets the function- and assertion-level
@@ -47,7 +47,7 @@ call resolution, named bindings, heritage extraction, and docstrings.
|----------|-----------|-------------|-------------|
| **Python** | `.py` `.pyi` | `main.py` `app.py` `__main__.py` `manage.py` `wsgi.py` `asgi.py` | `import x` / `from x import y` |
| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `export { x } from 'y'` & `export * from 'y'` re-export barrels / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |
-| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` incl. CommonJS re-export shapes (`module.exports = require('./x')`, `exports.foo = require('./y')`, `Object.assign(module.exports, require('./z'), …)` — flagged as re-export hubs like ESM barrels) and member picks (`var x = require('./m').member`) |
+| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` incl. CommonJS re-export shapes (`module.exports = require('./x')`, `exports.foo = require('./y')`, `Object.assign(module.exports, require('./z'), …)`, flagged as re-export hubs like ESM barrels) and member picks (`var x = require('./m').member`) |
| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` / `import pkg.*` / `import static pkg.Class.*` with Maven `pom.xml` reactor + Gradle `settings.gradle(.kts)` source-sets + `gradle/libs.versions.toml` discovery, JPMS `module-info.java` / `package-info.java` recognition, fan-out to every file in the imported package (siblings share importers), same-package implicit identifier resolution; JDK namespaces (`java.` / `javax.` / `jdk.`) are filtered with no node, `jakarta.` classifies as an external dependency |
| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` / `import com.example.*` sharing the JVM workspace index with Java (cross-language resolution, `.kt` under `src/main/java` recognised); `kotlin.` stdlib filtered with no node, `kotlinx.` classifies as an external dependency; same-package implicit identifier resolution |
| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match); a package import fans out to **all** `.go` files in the package directory |
@@ -61,39 +61,39 @@ All nine languages support:
- Named binding extraction (mapping imported names to source symbols)
- Heritage extraction (class/interface/trait/record inheritance chains)
- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)
-- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router + stdlib `net/http` (`http.HandleFunc` / `mux.Handle`) + gRPC `RegisterXxxServer` → handler/impl files for Go; Axum/Actix `.route` → handler files for Rust)
-- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`; Alpine.js `Alpine.data`/`store`/`magic`/`directive` registrations → handler files for JS)
-- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields → PascalCase property, `[RelayCommand]` methods → `<Name>Command`)
-- For Go only: a package-granular workspace index (`GoPackageIndex`) built as a warmup phase — a package import resolves to every file in the package directory, and package-qualified calls (`pkg.Func`) / same-package bare calls resolve across all of a package's files; type-reference resolution emits `type_use` edges for field / parameter / return / composite-literal types (unwrapping `*T` / `[]T` / `map[K]V` / `pkg.T` / generics); package-aware dead-code reachability (a file is reachable when its package is imported or is a `package main` entry); structural interface satisfaction — concrete types are matched to the interfaces their method set satisfies (embedded interfaces expanded) and emit `method_implements` edges so interfaces reached only through implementors are not flagged dead; and Go never-flag conventions (`*_test.go`, `cmd/**/main.go`, `doc.go`, `magefile.go`, generated `*.pb.go` / `*_string.go` / `zz_generated*` / `bindata.go`) plus `init` / `TestMain` / `Test*` / `Benchmark*` / `Example*` / `Fuzz*` entry handling
-- For C/C++ only: a unified `CppWorkspaceIndex` warmup parses CMake reactors (`add_subdirectory`, `add_executable` / `add_library`, `target_sources`, `target_include_directories`, `target_compile_definitions`, `target_link_libraries`, `option`/`if(...)` conditional sources, CMake File API `build/.cmake/api/v1/reply/` JSON), Bazel `BUILD` files (`cc_binary` / `cc_library` / `cc_test` / `cc_proto_library` / `cc_grpc_library` / `cc_fuzz_test`), and `compile_commands.json`; the index drives a six-step include resolver (compile_commands → workspace public-header map → per-target include-dirs → importer-relative → stdlib filter → stem fallback) and fans `#include` edges out to every sibling TU in the same target so internal headers are reachable without a direct importer; project-specific export macros (`LEVELDB_EXPORT` / `SEASTAR_API` / `*_EXPORT` / `*_API` / `*_PUBLIC`) are discovered from `target_compile_definitions` and `#define X __declspec(dllexport)` patterns and re-applied as visibility markers during the warmup, alongside the literal `__declspec(dllexport)` / `__attribute__((visibility("default")))` / `EMSCRIPTEN_KEEPALIVE` / `WASM_EXPORT` / `export_name` / `((used))` markers (so JS↔WASM exports and project-macro-exported public APIs are not flagged dead); type-reference resolution emits `type_use` edges for parameter / field / return / template-argument types (unwrapping `std::vector` / `std::optional` / `std::shared_ptr` / friends and stripping pointer / reference / array tails) and consults the workspace's same-target sibling set for unqualified resolution; static-initialiser registration macros (`PYBIND11_MODULE`, `BOOST_PYTHON_MODULE`, `REGISTER_OP`, `REGISTER_KERNEL_BUILDER`, `BOOST_CLASS_EXPORT`, `PLUGINLIB_EXPORT_CLASS`, `RCLCPP_COMPONENTS_REGISTER_NODE`, `Q_OBJECT` / `Q_GADGET` / `QML_ELEMENT`, gflags `DEFINE_*`, `ABSL_FLAG`, `__attribute__((constructor/used))`, `[[gnu::retain/used]]`, `JNI_OnLoad`, `NAPI_MODULE`) synthesize the symbols they emit at compile time and stamp their TU as an entry point so the file is not flagged unreachable; framework edges cover the C++ test, benchmark, and fuzzing ecosystem — **GoogleTest** (`TEST` / `TEST_F` / `TEST_P` / `TYPED_TEST` with `TEST_F(FixtureClass, …)` emitting a `type_use` edge to the fixture's defining header), **Catch2** (`TEST_CASE` / `TEST_CASE_METHOD` / `SCENARIO`), **Boost.Test** (`BOOST_AUTO_TEST_CASE` / `BOOST_FIXTURE_TEST_CASE(case, Fixture)` with fixture rescue), **doctest** (`DOCTEST_TEST_CASE`), **Google Benchmark** (`BENCHMARK` / `BENCHMARK_F` / `BENCHMARK_MAIN`), **libFuzzer** (`LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize`); C++ dynamic-hint extractor (function-pointer assignments, designated-initializer field tables, `dlopen` / `dlsym` / `LoadLibrary` / `GetProcAddress`, Qt old-style `connect(SIGNAL(sig()), SLOT(slot()))` and new-style `connect(&Sender::sig, &Recv::slot)`); C++ contract methods (constructor / destructor / operator overloads, conversion operators (`operator bool`, `operator T`), STL customisation points (`begin` / `end` / `cbegin` / `cend` / `rbegin` / `rend` / `size` / `empty` / `data` / `swap` / `hash_value` / `to_string`), coroutine machinery (`await_ready` / `await_suspend` / `await_resume` / `promise_type` / `initial_suspend` / `final_suspend` / `return_void` / `return_value` / `yield_value` / `unhandled_exception`), `std::format` / `std::error_code` customisation); directory-granular reachability with **header-reached-by-symbol-reference rescue**, `int main` / `WinMain` / `wWinMain` / `wmain` / `LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize` / `DllMain` binary-entry recognition, sibling-rescue (internal header reached via its `.cc` neighbour), same-directory main-carrier rescue (helper files alongside `main.cc` are not dead), and conditional-compile alternative pairing (`env_posix.cc` ↔ `env_windows.cc`, `crypto_openssl.cc` ↔ `crypto_gnutls.cc`); never-flag conventions for `apps/**`, `demos/**`, `examples/**`, `samples/**`, `benchmarks/**`, `bench/**`, `tools/**`, `tests/{perf,fuzz,unit,manual,integration}/**`, `*_test.{cc,cpp}` / `*_unittest.*` / `*_perf.*` / `*_benchmark.*` / `*_fuzz.*` suffix globs, skeleton convention headers (`port_example.h`, `*_example.{h,hpp,cc}`), build directory roots (`build/**`, `cmake-build-*/**`, `_deps/**`, `out/{build,Debug,Release}/**`), generated source patterns (`moc_*.{cpp,cc}`, `ui_*.h`, `qrc_*.{cpp,cc}`, `*.moc`, `*.pb.{cc,h}`, `*.pb-c.{c,h}`, `*.grpc.pb.{cc,h}`, `*.capnp.{c++,h}`, `*.flatbuffers.h`, `*_generated.h`, `*.tab.{c,h}`, `*.yy.c`, `*_lex.cc`, `*_wrap.{cxx,cpp}`, `*.cython.cpp`), vendor roots (`external/**`, `extern/**`, `contrib/**`, `submodules/**`, `vendor/**`, `third_party/**`, `deps/**`), precompiled-header conventions (`pch.{h,cc,cpp}`, `stdafx.*`, `PrecompiledHeader.{cc,cpp}`), and Windows COM / ATL DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`); a per-symbol-use dead-code check rescues headers whose declared types are referenced as parameter / field / return / template-argument / `extends` / `implements` even with no `#include` chain
+- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router + stdlib `net/http` (`http.HandleFunc` / `mux.Handle`) + gRPC `RegisterXxxServer` -> handler/impl files for Go; Axum/Actix `.route` -> handler files for Rust)
+- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`; Alpine.js `Alpine.data`/`store`/`magic`/`directive` registrations -> handler files for JS)
+- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace -> file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields -> PascalCase property, `[RelayCommand]` methods -> `<Name>Command`)
+- For Go only: a package-granular workspace index (`GoPackageIndex`) built as a warmup phase: a package import resolves to every file in the package directory, and package-qualified calls (`pkg.Func`) / same-package bare calls resolve across all of a package's files; type-reference resolution emits `type_use` edges for field / parameter / return / composite-literal types (unwrapping `*T` / `[]T` / `map[K]V` / `pkg.T` / generics); package-aware dead-code reachability (a file is reachable when its package is imported or is a `package main` entry); structural interface satisfaction: concrete types are matched to the interfaces their method set satisfies (embedded interfaces expanded) and emit `method_implements` edges so interfaces reached only through implementors are not flagged dead; and Go never-flag conventions (`*_test.go`, `cmd/**/main.go`, `doc.go`, `magefile.go`, generated `*.pb.go` / `*_string.go` / `zz_generated*` / `bindata.go`) plus `init` / `TestMain` / `Test*` / `Benchmark*` / `Example*` / `Fuzz*` entry handling
+- For C/C++ only: a unified `CppWorkspaceIndex` warmup parses CMake reactors (`add_subdirectory`, `add_executable` / `add_library`, `target_sources`, `target_include_directories`, `target_compile_definitions`, `target_link_libraries`, `option`/`if(...)` conditional sources, CMake File API `build/.cmake/api/v1/reply/` JSON), Bazel `BUILD` files (`cc_binary` / `cc_library` / `cc_test` / `cc_proto_library` / `cc_grpc_library` / `cc_fuzz_test`), and `compile_commands.json`; the index drives a six-step include resolver (compile_commands -> workspace public-header map -> per-target include-dirs -> importer-relative -> stdlib filter -> stem fallback) and fans `#include` edges out to every sibling TU in the same target so internal headers are reachable without a direct importer; project-specific export macros (`LEVELDB_EXPORT` / `SEASTAR_API` / `*_EXPORT` / `*_API` / `*_PUBLIC`) are discovered from `target_compile_definitions` and `#define X __declspec(dllexport)` patterns and re-applied as visibility markers during the warmup, alongside the literal `__declspec(dllexport)` / `__attribute__((visibility("default")))` / `EMSCRIPTEN_KEEPALIVE` / `WASM_EXPORT` / `export_name` / `((used))` markers (so JS↔WASM exports and project-macro-exported public APIs are not flagged dead); type-reference resolution emits `type_use` edges for parameter / field / return / template-argument types (unwrapping `std::vector` / `std::optional` / `std::shared_ptr` / friends and stripping pointer / reference / array tails) and consults the workspace's same-target sibling set for unqualified resolution; static-initialiser registration macros (`PYBIND11_MODULE`, `BOOST_PYTHON_MODULE`, `REGISTER_OP`, `REGISTER_KERNEL_BUILDER`, `BOOST_CLASS_EXPORT`, `PLUGINLIB_EXPORT_CLASS`, `RCLCPP_COMPONENTS_REGISTER_NODE`, `Q_OBJECT` / `Q_GADGET` / `QML_ELEMENT`, gflags `DEFINE_*`, `ABSL_FLAG`, `__attribute__((constructor/used))`, `[[gnu::retain/used]]`, `JNI_OnLoad`, `NAPI_MODULE`) synthesize the symbols they emit at compile time and stamp their TU as an entry point so the file is not flagged unreachable; framework edges cover the C++ test, benchmark, and fuzzing ecosystem: **GoogleTest** (`TEST` / `TEST_F` / `TEST_P` / `TYPED_TEST` with `TEST_F(FixtureClass, …)` emitting a `type_use` edge to the fixture's defining header), **Catch2** (`TEST_CASE` / `TEST_CASE_METHOD` / `SCENARIO`), **Boost.Test** (`BOOST_AUTO_TEST_CASE` / `BOOST_FIXTURE_TEST_CASE(case, Fixture)` with fixture rescue), **doctest** (`DOCTEST_TEST_CASE`), **Google Benchmark** (`BENCHMARK` / `BENCHMARK_F` / `BENCHMARK_MAIN`), **libFuzzer** (`LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize`); C++ dynamic-hint extractor (function-pointer assignments, designated-initializer field tables, `dlopen` / `dlsym` / `LoadLibrary` / `GetProcAddress`, Qt old-style `connect(SIGNAL(sig()), SLOT(slot()))` and new-style `connect(&Sender::sig, &Recv::slot)`); C++ contract methods (constructor / destructor / operator overloads, conversion operators (`operator bool`, `operator T`), STL customisation points (`begin` / `end` / `cbegin` / `cend` / `rbegin` / `rend` / `size` / `empty` / `data` / `swap` / `hash_value` / `to_string`), coroutine machinery (`await_ready` / `await_suspend` / `await_resume` / `promise_type` / `initial_suspend` / `final_suspend` / `return_void` / `return_value` / `yield_value` / `unhandled_exception`), `std::format` / `std::error_code` customisation); directory-granular reachability with **header-reached-by-symbol-reference rescue**, `int main` / `WinMain` / `wWinMain` / `wmain` / `LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize` / `DllMain` binary-entry recognition, sibling-rescue (internal header reached via its `.cc` neighbour), same-directory main-carrier rescue (helper files alongside `main.cc` are not dead), and conditional-compile alternative pairing (`env_posix.cc` ↔ `env_windows.cc`, `crypto_openssl.cc` ↔ `crypto_gnutls.cc`); never-flag conventions for `apps/**`, `demos/**`, `examples/**`, `samples/**`, `benchmarks/**`, `bench/**`, `tools/**`, `tests/{perf,fuzz,unit,manual,integration}/**`, `*_test.{cc,cpp}` / `*_unittest.*` / `*_perf.*` / `*_benchmark.*` / `*_fuzz.*` suffix globs, skeleton convention headers (`port_example.h`, `*_example.{h,hpp,cc}`), build directory roots (`build/**`, `cmake-build-*/**`, `_deps/**`, `out/{build,Debug,Release}/**`), generated source patterns (`moc_*.{cpp,cc}`, `ui_*.h`, `qrc_*.{cpp,cc}`, `*.moc`, `*.pb.{cc,h}`, `*.pb-c.{c,h}`, `*.grpc.pb.{cc,h}`, `*.capnp.{c++,h}`, `*.flatbuffers.h`, `*_generated.h`, `*.tab.{c,h}`, `*.yy.c`, `*_lex.cc`, `*_wrap.{cxx,cpp}`, `*.cython.cpp`), vendor roots (`external/**`, `extern/**`, `contrib/**`, `submodules/**`, `vendor/**`, `third_party/**`, `deps/**`), precompiled-header conventions (`pch.{h,cc,cpp}`, `stdafx.*`, `PrecompiledHeader.{cc,cpp}`), and Windows COM / ATL DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`); a per-symbol-use dead-code check rescues headers whose declared types are referenced as parameter / field / return / template-argument / `extends` / `implements` even with no `#include` chain
- For JavaScript only: esbuild/rollup bundle outputs (`*.bundle.js`), minified artifacts (`*.min.js`), LiveReload generated browser-global scripts (`livereload/gen/*`, `livereload.js`) and WASM JS glue (`*wasm_exec.js`) are never flagged as dead (build products / browser-loaded, never module-imported)
-- For TypeScript / JavaScript only: a workspace-granular index (`TsWorkspaceIndex`) built as a warmup phase that surfaces every file reachable through a `package.json` `exports` map (including `"./locales/*"`-style wildcards) as an entry point so downstream npm consumers don't read as unreachable; type-reference resolution emits `type_use` edges for parameter / field / return / generic-constraint / type-alias-RHS / heritage clauses (unwrapping `Promise<T>`, `T[]`, `Pick<T,K>`, union/intersection, conditional/mapped types) so interfaces consumed only as types are not flagged dead; same-file rescue exempts symbols whose only consumer is another declaration in the same module; convention never-flag globs for `*.test.*` / `*.spec.*` / `*.stories.*` / `*.bench.*` / `__tests__/**` / `__mocks__/**` / Next.js app-router files (`page.tsx`, `layout.tsx`, `route.ts`, `middleware.ts`, `instrumentation.ts`, route segment configs) / SvelteKit `+page` / `+layout` / `+server` / Remix `entry.client` / `entry.server` / `next-env.d.ts` / `*.gen.ts` / `generated/**`; experimental sub-package rescue marks every source file in directories named `bench` / `benchmarks` / `treeshake` / `examples` / `demos` / `samples` / `playground` / `scratch` / `scripts` as a live entry (these dirs invoke their files via runtime CLI arguments no static scan can follow); npm-script entry detection — parses every `package.json` `scripts.*` command for paths (`tsx X.ts` / `bun run X.mts` / `rollup -c X.js`), quoted glob arguments (prettier / eslint scopes), and bare directory tokens; MDX `import` scan + `vitest.config` `include` glob scan as belt-and-suspenders for entry surfaces the static parser can't see; framework edges for Next.js App Router (`app/**/{page,layout,route,middleware,…}`), Hono / Fastify / Koa / Elysia router DSLs (`.get('/x', handler)`), Remix / SvelteKit / Astro filesystem-convention routes, and tRPC procedure registries (`.query(handler)` / `.mutation(handler)`); JSX-namespace types declared inside a `namespace JSX` file are exempt from `unused_export` (consumed by tsc via `jsxImportSource`, never imported as values)
-- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml→xaml `dynamic_uses` edges
-- For JVM (Java + Kotlin together) only: a unified `JvmWorkspaceIndex` warmup parsing Maven `pom.xml` reactors and Gradle `settings.gradle(.kts)` + source-sets + `gradle/libs.versions.toml` version catalogs; one walk groups every `.java` and `.kt` file by package directory so `import com.foo.Bar` fans out to every defining file in the package (siblings share importers), `import com.foo.*` / `import static com.foo.Bar.*` expand to all matching files, same-package implicit identifier access is honoured, and Kotlin↔Java cross-language resolution links callers across both source-roots (including `.kt` files hosted under `src/main/java`); type-reference resolution emits `type_use` edges for parameter / field / return / generic / `new T()` types (unwrapping arrays, generics, nullables), plus Kotlin `companion object` / `object` singleton / method-reference (`Foo::bar`) / `sealed … permits` resolution; source-generator-equivalent synthesis emits the symbols Lombok (`@Data` / `@Value` / `@Builder` / `@RequiredArgsConstructor` / `@Slf4j` / `@UtilityClass` / friends), Java `record`, Kotlin `data class` / `enum class` / `object`, and MapStruct / AutoValue / Immutables would produce at compile time — so a Lombok-only Spring service no longer reads its injected fields as unused; framework edges cover Spring (stereotypes with meta-annotation resolution; `@RequestMapping` family routing; Spring Data `JpaRepository` / `Crud` / `Mongo` / `R2dbc` / `Elasticsearch` / `Neo4j` / `Couchbase` / `Cassandra` interfaces and their derived-query methods as entry points; `@Bean` factories; single-constructor + `@Autowired` / `@Inject` / `@Resource` DI; Lombok-RAC/AAC constructor inference), Jakarta (JAX-RS `@Path`, CDI scopes, Servlet 3+ `@WebServlet`/`@WebFilter`/`@WebListener`, JPA `@Entity` + `@OneToMany`/`@ManyToOne`/`@ManyToMany`/`@OneToOne` association edges; both `javax.*` and `jakarta.*`), Quarkus (entry stereotypes + SmallRye `@Incoming("topic")` ↔ `@Outgoing("topic")` cross-linking), Micronaut (DI / routing, gated on Micronaut imports to disambiguate Spring's collisions), and Android (`AndroidManifest.xml` `android:name` references emit edges to the named class); JVM dynamic hints capture `Class.forName`, Mockito / mockk, MapStruct `Mappers.getMapper`, `SpringApplication.run` and Kotlin `runApplication<>`, Jackson / Gson `readValue` / `fromJson` / `treeToValue`; package-aware dead-code reachability rescues sibling-rescued packages, stereotype-annotated classes, `main(String[])` carriers, and FQNs listed in `META-INF/services/*` / `META-INF/spring.factories` (Boot 2) / `META-INF/spring/...AutoConfiguration.imports` (Boot 3) / JPMS `provides … with …` — all resolved during the workspace warmup; JVM never-flag patterns cover `module-info.java`, `package-info.java`, every conventional test source-set (`src/test/**`, `src/integrationTest/**`, `src/intTest/**`, `src/it/**`, `src/jmh/**`, generic `src/*Test/**`), generated source roots (`build/generated/**`, KAPT/KSP, `target/generated-sources/**`, GraalVM `aotSources`), generated suffix conventions (`Dagger*`, `AutoValue_*`, JPA `*_.java` metamodel, `*Grpc.java`, protoc `*OuterClass.java`), JUnit / TestNG / Spock / ArchUnit test-naming + annotation-marked entry points (`@Test` / `@PostConstruct` / `@EventListener` / `@Scheduled` / `@JmsListener` / `@KafkaListener` / `@RabbitListener` / `@SqsListener` / `@Incoming` / `@Outgoing` / `@Mojo` / `@Bean` / …), and JVM contract methods (`equals` / `hashCode` / `toString` / `compareTo` / `clone` / serialization `readObject` / `writeObject` / `serialVersionUID` / Lombok `canEqual` / Kotlin `componentN` / `copy` / enum `values` / `valueOf`)
+- For TypeScript / JavaScript only: a workspace-granular index (`TsWorkspaceIndex`) built as a warmup phase that surfaces every file reachable through a `package.json` `exports` map (including `"./locales/*"`-style wildcards) as an entry point so downstream npm consumers don't read as unreachable; type-reference resolution emits `type_use` edges for parameter / field / return / generic-constraint / type-alias-RHS / heritage clauses (unwrapping `Promise<T>`, `T[]`, `Pick<T,K>`, union/intersection, conditional/mapped types) so interfaces consumed only as types are not flagged dead; same-file rescue exempts symbols whose only consumer is another declaration in the same module; convention never-flag globs for `*.test.*` / `*.spec.*` / `*.stories.*` / `*.bench.*` / `__tests__/**` / `__mocks__/**` / Next.js app-router files (`page.tsx`, `layout.tsx`, `route.ts`, `middleware.ts`, `instrumentation.ts`, route segment configs) / SvelteKit `+page` / `+layout` / `+server` / Remix `entry.client` / `entry.server` / `next-env.d.ts` / `*.gen.ts` / `generated/**`; experimental sub-package rescue marks every source file in directories named `bench` / `benchmarks` / `treeshake` / `examples` / `demos` / `samples` / `playground` / `scratch` / `scripts` as a live entry (these dirs invoke their files via runtime CLI arguments no static scan can follow); npm-script entry detection parses every `package.json` `scripts.*` command for paths (`tsx X.ts` / `bun run X.mts` / `rollup -c X.js`), quoted glob arguments (prettier / eslint scopes), and bare directory tokens; MDX `import` scan + `vitest.config` `include` glob scan as belt-and-suspenders for entry surfaces the static parser can't see; framework edges for Next.js App Router (`app/**/{page,layout,route,middleware,…}`), Hono / Fastify / Koa / Elysia router DSLs (`.get('/x', handler)`), Remix / SvelteKit / Astro filesystem-convention routes, and tRPC procedure registries (`.query(handler)` / `.mutation(handler)`); JSX-namespace types declared inside a `namespace JSX` file are exempt from `unused_export` (consumed by tsc via `jsxImportSource`, never imported as values)
+- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml-to-xaml `dynamic_uses` edges
+- For JVM (Java + Kotlin together) only: a unified `JvmWorkspaceIndex` warmup parsing Maven `pom.xml` reactors and Gradle `settings.gradle(.kts)` + source-sets + `gradle/libs.versions.toml` version catalogs; one walk groups every `.java` and `.kt` file by package directory so `import com.foo.Bar` fans out to every defining file in the package (siblings share importers), `import com.foo.*` / `import static com.foo.Bar.*` expand to all matching files, same-package implicit identifier access is honoured, and Kotlin↔Java cross-language resolution links callers across both source-roots (including `.kt` files hosted under `src/main/java`); type-reference resolution emits `type_use` edges for parameter / field / return / generic / `new T()` types (unwrapping arrays, generics, nullables), plus Kotlin `companion object` / `object` singleton / method-reference (`Foo::bar`) / `sealed … permits` resolution; source-generator-equivalent synthesis emits the symbols Lombok (`@Data` / `@Value` / `@Builder` / `@RequiredArgsConstructor` / `@Slf4j` / `@UtilityClass` / friends), Java `record`, Kotlin `data class` / `enum class` / `object`, and MapStruct / AutoValue / Immutables would produce at compile time, so a Lombok-only Spring service no longer reads its injected fields as unused; framework edges cover Spring (stereotypes with meta-annotation resolution; `@RequestMapping` family routing; Spring Data `JpaRepository` / `Crud` / `Mongo` / `R2dbc` / `Elasticsearch` / `Neo4j` / `Couchbase` / `Cassandra` interfaces and their derived-query methods as entry points; `@Bean` factories; single-constructor + `@Autowired` / `@Inject` / `@Resource` DI; Lombok-RAC/AAC constructor inference), Jakarta (JAX-RS `@Path`, CDI scopes, Servlet 3+ `@WebServlet`/`@WebFilter`/`@WebListener`, JPA `@Entity` + `@OneToMany`/`@ManyToOne`/`@ManyToMany`/`@OneToOne` association edges; both `javax.*` and `jakarta.*`), Quarkus (entry stereotypes + SmallRye `@Incoming("topic")` ↔ `@Outgoing("topic")` cross-linking), Micronaut (DI / routing, gated on Micronaut imports to disambiguate Spring's collisions), and Android (`AndroidManifest.xml` `android:name` references emit edges to the named class); JVM dynamic hints capture `Class.forName`, Mockito / mockk, MapStruct `Mappers.getMapper`, `SpringApplication.run` and Kotlin `runApplication<>`, Jackson / Gson `readValue` / `fromJson` / `treeToValue`; package-aware dead-code reachability rescues sibling-rescued packages, stereotype-annotated classes, `main(String[])` carriers, and FQNs listed in `META-INF/services/*` / `META-INF/spring.factories` (Boot 2) / `META-INF/spring/...AutoConfiguration.imports` (Boot 3) / JPMS `provides … with …`, all resolved during the workspace warmup; JVM never-flag patterns cover `module-info.java`, `package-info.java`, every conventional test source-set (`src/test/**`, `src/integrationTest/**`, `src/intTest/**`, `src/it/**`, `src/jmh/**`, generic `src/*Test/**`), generated source roots (`build/generated/**`, KAPT/KSP, `target/generated-sources/**`, GraalVM `aotSources`), generated suffix conventions (`Dagger*`, `AutoValue_*`, JPA `*_.java` metamodel, `*Grpc.java`, protoc `*OuterClass.java`), JUnit / TestNG / Spock / ArchUnit test-naming + annotation-marked entry points (`@Test` / `@PostConstruct` / `@EventListener` / `@Scheduled` / `@JmsListener` / `@KafkaListener` / `@RabbitListener` / `@SqsListener` / `@Incoming` / `@Outgoing` / `@Mojo` / `@Bean` / ...), and JVM contract methods (`equals` / `hashCode` / `toString` / `compareTo` / `clone` / serialization `readObject` / `writeObject` / `serialVersionUID` / Lombok `canEqual` / Kotlin `componentN` / `copy` / enum `values` / `valueOf`)
#### Code-health biomarker coverage
The code-health layer scores every source file from deterministic
-biomarkers (complexity, cohesion, test-quality, …). These run off a
+biomarkers (complexity, cohesion, test-quality, ...). These run off a
per-language complexity-walker map
(`analysis/health/complexity/languages.py`) that is **independent** of the
-`.scm` ingestion queries — a language can parse perfectly for the graph yet
+`.scm` ingestion queries: a language can parse perfectly for the graph yet
still need this map before health biomarkers fire. To keep "Full" meaning
"health works", a language must clear this checklist (each item has a green
fixture under `tests/fixtures/lang_samples/<lang>/` + a walker test):
-1. **Control flow** — `if` / loop / `switch`/`match`/`when` / `try`-`catch`
- nodes mapped → McCabe CCN, nesting depth, cognitive complexity.
-2. **Boolean operators** — `&&` / `||` (or their text form) counted toward
+1. **Control flow**: `if` / loop / `switch`/`match`/`when` / `try`-`catch`
+ nodes mapped -> McCabe CCN, nesting depth, cognitive complexity.
+2. **Boolean operators**: `&&` / `||` (or their text form) counted toward
CCN and `complex_conditional`.
-3. **Class metrics** — `class_kinds` set so `method_count` / `total_nloc` /
- `max_method_ccn` aggregate (feeds `god_class`). *(N/A for Go — no
+3. **Class metrics**: `class_kinds` set so `method_count` / `total_nloc` /
+ `max_method_ccn` aggregate (feeds `god_class`). *(N/A for Go: no
class-grouping node.)*
-4. **LCOM4 cohesion** — `self_identifiers` + `member_access_kinds` set so
+4. **LCOM4 cohesion**: `self_identifiers` + `member_access_kinds` set so
explicit-receiver member access is detected (feeds `low_cohesion`).
Receiver-less idioms degrade to "no signal", never a false positive.
*(N/A for Go.)*
-5. **Assertion blocks** — `assert_kinds` / `assert_call_kinds` set so runs
+5. **Assertion blocks**: `assert_kinds` / `assert_call_kinds` set so runs
of consecutive assertions are detected on test files (feeds
`large_assertion_block` / `duplicated_assertion_block`).
@@ -103,7 +103,7 @@ fixture under `tests/fixtures/lang_samples/<lang>/` + a walker test):
| TypeScript / JavaScript | Y | Y | Y | Y |
| Java | Y | Y | Y | Y |
| Kotlin | Y | Y | Y | Y |
-| Go | Y | — | — | Y |
+| Go | Y | n/a | n/a | Y |
| Rust | Y | Y | Y | Y |
| C++ | Y | Y | Y | Y |
| C# | Y | Y | Y | Y |
@@ -118,9 +118,9 @@ resolvers for each language.
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
| **C** | `.c` | `main.c` | `#include` with `compile_commands.json` (shares C++ grammar) |
-| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` with `$LOAD_PATH` convention probing (`require 'sinatra/base'` → `lib/sinatra/base.rb`, including every sub-gem's `lib/` in monorepos), Ruby-stdlib requires filtered with no node, Gemfile/gemspec dependencies labelled as gem externals, rspec directory-mirror edges (`spec/lib/x_spec.rb` → `lib/x.rb`), plus Rails / Zeitwerk autoloading (gated on `config/application.rb`) |
-| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` with SPM `Package.swift` `targets:` → directory mapping; intra-module type references link same-target files (Swift has no intra-module imports by design); `@main` / `@UIApplicationMain` / `@NSApplicationMain` flag entry points; `@_exported import` marks re-exports |
-| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.Foo`, brace imports `{A, B => C}` (expanded per selected name, hidden imports skipped), wildcards (`pkg._` / Scala 3 `pkg.*`), and package imports — resolved through the shared JVM workspace index (chained package clauses, Scala ↔ Java cross-language, same-package implicit identifiers) with SBT `build.sbt` / Mill `build.sc` multi-project parsing as fallback; `scala.` and JDK namespaces filtered |
+| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` with `$LOAD_PATH` convention probing (`require 'sinatra/base'` -> `lib/sinatra/base.rb`, including every sub-gem's `lib/` in monorepos), Ruby-stdlib requires filtered with no node, Gemfile/gemspec dependencies labelled as gem externals, rspec directory-mirror edges (`spec/lib/x_spec.rb` -> `lib/x.rb`), plus Rails / Zeitwerk autoloading (gated on `config/application.rb`) |
+| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` with SPM `Package.swift` `targets:` -> directory mapping; intra-module type references link same-target files (Swift has no intra-module imports by design); `@main` / `@UIApplicationMain` / `@NSApplicationMain` flag entry points; `@_exported import` marks re-exports |
+| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.Foo`, brace imports `{A, B => C}` (expanded per selected name, hidden imports skipped), wildcards (`pkg._` / Scala 3 `pkg.*`), and package imports, resolved through the shared JVM workspace index (chained package clauses, Scala ↔ Java cross-language, same-package implicit identifiers) with SBT `build.sbt` / Mill `build.sc` multi-project parsing as fallback; `scala.` and JDK namespaces filtered |
| **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` with composer.json `autoload.psr-4` longest-prefix resolution |
### Config / Data
@@ -144,7 +144,7 @@ endpoints or targets where applicable.
| **SQL** | `.sql` | -- |
| **Shell** | `.sh` `.bash` `.zsh` | -- |
-### Partial (Luau — Roblox)
+### Partial (Luau, Roblox)
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
@@ -166,17 +166,17 @@ These languages have no AST parsing (no symbols, calls, or heritage) but
get a real file-level import graph from a regex tier: import statements
are extracted with per-language regexes and resolved against a declared
module-name index (declaration scan + path-convention inverse). The
-knowledge graph runs in flow/sparse mode on the resulting density —
+knowledge graph runs in flow/sparse mode on the resulting density:
honest file-to-file dependencies, no symbol-level claims.
| Language | Extensions | Import Forms Resolved |
|----------|-----------|----------------------|
-| **Elixir** | `.ex` `.exs` | `alias` / `import` / `use` / `require` (incl. `Foo.{Bar, Baz}` brace groups) → `defmodule` index + Mix `lib/` path convention (umbrella `apps/*/lib` included); Elixir/OTP stdlib filtered after local-miss |
-| **Dart** | `.dart` | `import` / `export` (re-export) / `part` / `part of` URIs; `package:` URIs via every `pubspec.yaml` `name:` (monorepos included); `dart:` SDK URIs filtered; foreign packages → `external:pub:<name>` |
-| **Clojure** | `.clj` `.cljc` `.cljs` | `(:require …)` / `(:use …)` vectors and bare specs (string/comment-safe) → `(ns …)` index + classpath convention (dashes ↔ underscores); `clojure.*`/`cljs.*` filtered |
-| **Haskell** | `.hs` `.lhs` | `import [safe] [qualified] ["pkg"] Foo.Bar` → `module` declaration index + trailing-PascalCase path inverse (handles any hs-source-dirs without parsing `.cabal`); base-ish namespaces filtered after local-miss |
-| **Erlang** | `.erl` `.hrl` | `-include` / `-include_lib` / `-behaviour` + module-qualified calls (`mod:fun(`) → `-module()` index; qualified calls are strict local-hit-or-drop (never mint externals) |
-| **F#** | `.fs` `.fsi` `.fsx` | `open` → file-level `namespace`/`module` index (unambiguous single-file declarations only), plus the fsproj `<Compile Include>` compile-order dependency spine (a real F# constraint: files may only reference earlier files) |
+| **Elixir** | `.ex` `.exs` | `alias` / `import` / `use` / `require` (incl. `Foo.{Bar, Baz}` brace groups) -> `defmodule` index + Mix `lib/` path convention (umbrella `apps/*/lib` included); Elixir/OTP stdlib filtered after local-miss |
+| **Dart** | `.dart` | `import` / `export` (re-export) / `part` / `part of` URIs; `package:` URIs via every `pubspec.yaml` `name:` (monorepos included); `dart:` SDK URIs filtered; foreign packages -> `external:pub:<name>` |
+| **Clojure** | `.clj` `.cljc` `.cljs` | `(:require …)` / `(:use …)` vectors and bare specs (string/comment-safe) -> `(ns …)` index + classpath convention (dashes ↔ underscores); `clojure.*`/`cljs.*` filtered |
+| **Haskell** | `.hs` `.lhs` | `import [safe] [qualified] ["pkg"] Foo.Bar` -> `module` declaration index + trailing-PascalCase path inverse (handles any hs-source-dirs without parsing `.cabal`); base-ish namespaces filtered after local-miss |
+| **Erlang** | `.erl` `.hrl` | `-include` / `-include_lib` / `-behaviour` + module-qualified calls (`mod:fun(`) -> `-module()` index; qualified calls are strict local-hit-or-drop (never mint externals) |
+| **F#** | `.fs` `.fsi` `.fsx` | `open` -> file-level `namespace`/`module` index (unambiguous single-file declarations only), plus the fsproj `<Compile Include>` compile-order dependency spine (a real F# constraint: files may only reference earlier files) |
### Structural (git + file tree only)
@@ -184,7 +184,7 @@ These languages are tracked in git history (blame, hotspot analysis,
co-change detection) but have no AST parsing or import resolution. Files
appear in the wiki as traversal-level entries, and the knowledge graph
runs in **structural mode** for repos dominated by them: the tour
-orients by directory structure, naming conventions, and git evidence —
+orients by directory structure, naming conventions, and git evidence:
it never claims an execution flow it cannot see.
Objective-C, R, Zig, Julia, Elm, OCaml, Crystal, Nim, D
@@ -246,7 +246,7 @@ Adding a new language touches these places:
### Step 1: Add a `LanguageSpec` module
-Language identity data lives in the `languages/specs/` package — **one module
+Language identity data lives in the `languages/specs/` package: **one module
per language**. Create
`packages/core/src/repowise/core/ingestion/languages/specs/mylang.py` exporting
a single `SPEC`:
@@ -273,7 +273,7 @@ SPEC = LanguageSpec(
```
Then register it in `languages/specs/__init__.py` by importing the module and
-slotting it into the `ALL_SPECS` tuple. **Order matters** — `LanguageRegistry`
+slotting it into the `ALL_SPECS` tuple. **Order matters**: `LanguageRegistry`
builds its extension map first-spec-wins, so place more specific languages
ahead of ones that share an extension (e.g. TypeScript before JavaScript).
The `LanguageRegistry` in `registry.py` consumes `ALL_SPECS`; you never edit
@@ -406,13 +406,13 @@ without touching the shared pipeline files:
without extending the hardcoded glob list. Used today by `_warmup_jvm`
to exempt every file under a Gradle non-`main` source set
(`testFixtures`, `integrationTest`, `javaPoet`, `jcstress`, `jmh`,
- custom names) — Caffeine's `javaPoet/` and `jcstress/` are picked up
+ custom names); Caffeine's `javaPoet/` and `jcstress/` are picked up
automatically without us knowing the names exist. The same shape fits
Rust (`[[example]]` / `[[bench]]` / `[[bin]]` targets in `Cargo.toml`),
C# (projects with `<Sdk>Microsoft.NET.Sdk.Test</Sdk>` or
`Microsoft.NET.Test.Sdk` references), TS/JS (workspace `packages/*`
declared `"private": true`), and Go (`//go:build integration`-gated
- files) — any language that already builds a workspace index can opt
+ files): any language that already builds a workspace index can opt
in by stamping the attribute during its warmup.
- `analysis/health/complexity/languages.py` --- the code-health
complexity walker keeps its own per-language node-type map
@@ -422,7 +422,7 @@ without touching the shared pipeline files:
`class_kinds` / `self_identifiers` / `member_access_kinds` to also get
class-level metrics (LCOM4 cohesion, god-class), and
`assert_kinds` / `assert_call_kinds` to get test-quality assertion-block
- smells. All tiers are purely additive and degrade safely — an unmapped
+ smells. All tiers are purely additive and degrade safely: an unmapped
language simply produces no health findings rather than wrong ones.
Control-flow and assertion maps ship for all nine full-tier languages
(Python, TypeScript, JavaScript, Go, Java, Kotlin, Rust, C++, C#);
@@ -469,19 +469,18 @@ findings.
The Rust dialect classifies `sqlx` executor verbs (db), `reqwest::get` /
`reqwest::post` and `std::fs` (network / filesystem) as sinks; `io_in_loop` is
multi-repo validated (85% on bevy / rtk / deepwiki-rs). `string_concat_in_loop`
-is intentionally absent — Rust `String::push_str` / `+=` are amortized O(1), so
+is intentionally absent: Rust `String::push_str` / `+=` are amortized O(1), so
it would be a guaranteed false positive. Kotlin will be nearly free once it
rides the JVM lexicon; C++ is later. What each dialect classifies as a db /
network / filesystem / subprocess sink, and the per-language precision hazards,
-lives in `docs/CODE_HEALTH.md` and
-`local-stash/performance-pillar/PHASE6_PLAN.md`.
+lives in `docs/CODE_HEALTH.md`.
---
## Architecture
The language pipeline is fully modular. Per-language code lives in
-dedicated subpackages — adding a new language means dropping a file
+dedicated subpackages: adding a new language means dropping a file
into each subpackage rather than editing monoliths.
```
@@ -550,7 +549,7 @@ relevant `__init__.py` dispatcher / dict.
## Workspace contract extraction
In **workspace mode** (multiple repos indexed together), repowise links
-service-to-service API contracts — HTTP routes and gRPC services — so a
+service-to-service API contracts (HTTP routes and gRPC services) so a
provider endpoint in one repo connects to its consumers in another. The
extractors live in `core/workspace/extractors/` and follow the same
dialect-plugin shape as the rest of the language pipeline: the orchestrator
@@ -576,13 +575,13 @@ workspace/extractors/
A dialect declares the file extensions it understands (via `langs.py`) and
turns regex matches into `Contract`s through the shared builders, so every
dialect emits identically-shaped providers/consumers and the path-normalization
-rules live in one place. Framework-specific quirks stay local to the dialect —
-Spring/ASP.NET class-prefix stitching, Go `HandleFunc` → `*` method, fetch
+rules live in one place. Framework-specific quirks stay local to the dialect:
+Spring/ASP.NET class-prefix stitching, Go `HandleFunc` -> `*` method, fetch
GET/method de-duplication.
**Adding a framework or client** means dropping one module into `http/` or
`grpc/` and appending its dialect to the relevant registry tuple
-(`PROVIDER_DIALECTS`, `CONSUMER_DIALECTS`, or `DIALECTS`) — no orchestrator
+(`PROVIDER_DIALECTS`, `CONSUMER_DIALECTS`, or `DIALECTS`): no orchestrator
edits. The current coverage:
| Contract | Providers | Consumers |
@@ -596,6 +595,6 @@ edits. The current coverage:
| Language | Target Tier | Status |
|----------|------------|--------|
-| Dart | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-dart` available |
-| Elixir | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-elixir` available |
-| F# | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-f-sharp` available |
+| Dart | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-dart` available) |
+| Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) |
+| F# | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-f-sharp` available) |
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 5e32f6e92..1468d62d1 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -1,6 +1,6 @@
# MCP Tools Reference
-repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions. A single-repo server advertises 10 tools by default; workspace mode adds 3 more automatically. The surface is configurable — see [Configuring the tool surface](#configuring-the-tool-surface).
+repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence: dependency graph, git history, documentation, and architectural decisions. A single-repo server advertises 10 tools by default; workspace mode adds 3 more automatically. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).
**Start the MCP server:**
@@ -26,7 +26,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport
| `get_risk` | Modification risk | Before changing hotspot files |
| `get_why` | Architectural decisions | Before structural changes |
| `get_dead_code` | Unreachable code | Cleanup tasks |
-| `get_health` | Code-health biomarker scores | Before refactoring — find the worst files |
+| `get_health` | Code-health biomarker scores | Before refactoring, find the worst files |
| `list_repos` | List the repos a server is serving | Discovering workspace repo aliases |
| `get_blast_radius` | Cross-repo downstream impact (workspace only) | Before changing a service other repos consume |
| `get_conformance` | Architecture rule violations + cycles (workspace only) | Auditing or before changing service boundaries |
@@ -38,7 +38,7 @@ Two further tools are **off by default** and opt-in (see below): `get_dependency
## Configuring the tool surface
-The default surface is deliberately small — fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's defaults, whether the server is in workspace mode, and an optional override.
+The default surface is deliberately small: fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's defaults, whether the server is in workspace mode, and an optional override.
- **Default (single-repo):** the 10 tools above (every tool except the workspace-only three).
- **Default (workspace):** those 10 plus `get_blast_radius`, `get_conformance`, and `get_architecture`, which are added automatically when the server is started inside a workspace. They are never advertised outside one.
@@ -74,7 +74,7 @@ Workspace-only tools named explicitly in single-repo mode are ignored (they cann
---
-## Reversible truncation — `_meta.omitted`
+## Reversible truncation: `_meta.omitted`
Tool responses are token-budgeted. When a response is truncated, the dropped
content is no longer silently lost: it is stored in the repo's
@@ -94,7 +94,7 @@ envelope lists how to get it back:
Truncated skeleton blocks are replaced in place by a `[repowise#<ref>: ...]`
marker; everything else is captured into one combined document per response.
Resolve refs with `repowise expand <ref>` from a shell, or
-`get_symbol("repowise#<ref>")` from any MCP client — the tool count stays at
+`get_symbol("repowise#<ref>")` from any MCP client; the tool count stays at
nine. See [DISTILL.md](DISTILL.md) for the full reversibility model.
---
@@ -134,7 +134,7 @@ One-call RAG: retrieves over the wiki, gates synthesis on confidence, and return
**Returns:** A synthesized answer with file/symbol citations and a confidence label (`high`, `medium`, `low`). High-confidence answers can be cited directly. Low-confidence answers return ranked wiki excerpts instead.
-**When to use:** First call on any code question. Collapses search → read → reason into one round-trip. If confidence is low, follow up with `search_codebase` to discover candidate pages.
+**When to use:** First call on any code question. Collapses search, read, and reason into one round-trip. If confidence is low, follow up with `search_codebase` to discover candidate pages.
**Example call:**
@@ -153,7 +153,7 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. |
-| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this — symbol targets), `"callees"` (what this calls — symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only — the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens) |
+| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens) |
| `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
@@ -182,7 +182,7 @@ this replaces a full file read at a fraction of the cost.
## `get_symbol`
-Raw source bytes for one indexed symbol with exact line bounds — cheaper and
+Raw source bytes for one indexed symbol with exact line bounds, cheaper and
safer than `Read` + offset math. The only tool that returns actual source code.
Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.
@@ -191,7 +191,7 @@ Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `symbol_id` | string | Yes | Canonical `"path/to/file.py::SymbolName"` from `get_context`'s symbol list (normalises `::` / `.` / `/` separators across languages), **or** an omission ref `"repowise#<12-hex>"` / a pasted whole `[repowise#…]` marker. |
-| `query` | string | No | Omission refs only — return just the stored lines matching this regex (or substring). Ignored for symbol ids. |
+| `query` | string | No | Omission refs only: return just the stored lines matching this regex (or substring). Ignored for symbol ids. |
| `context_lines` | int | No | Extra source lines before/after the symbol (0–50, default 0) |
| `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |
@@ -200,7 +200,7 @@ its exact start/end line numbers, kind, and a `truncated` flag; on a miss, an
`error` with the closest matches. For an omission ref: the stored content plus
provenance (`source`, `created_at`, `original_tokens`).
-**When to use:** When you need the body of one function or class — pipe the
+**When to use:** When you need the body of one function or class: pipe the
`symbol_id` straight from `get_context`'s symbol list. Or when a response's
`_meta.omitted` lists refs you want back and you have no shell for
`repowise expand` (e.g. Claude Desktop).
@@ -220,7 +220,7 @@ get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")
Hybrid code search over RepoWise's indexes. A single tool that, depending on
the shape of the query, searches the indexed **symbols**, **file paths**, or
-the **wiki** — instead of forcing a fallback to Grep for identifiers.
+the **wiki**, instead of forcing a fallback to Grep for identifiers.
**Parameters:**
@@ -230,31 +230,31 @@ the **wiki** — instead of forcing a fallback to Grep for identifiers.
| `limit` | int | No | Max results (default 5) |
| `mode` | string | No | `auto` (default) \| `concept` \| `symbol` \| `path` \| `hybrid` |
| `kind` | string | No | `implementation` \| `test` \| `config` \| `doc` |
-| `symbol_kind` | string | No | Restrict symbol hits by kind (`function`, `class`, `method`, …) |
+| `symbol_kind` | string | No | Restrict symbol hits by kind (`function`, `class`, `method`, ...) |
| `page_type` | string | No | `file_page` \| `module_page` \| `symbol_spotlight` (concept mode) |
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` to search across workspace |
**Modes:**
- **`auto`** (default) routes by query shape:
- - an **identifier** (`GitIndexer`, `index_repo`) → searches indexed symbols;
- - a **path** (`core/ingestion/indexer.py`) → searches file pages;
- - **prose** ("how do we handle retries?") → wiki-semantic search;
- - mixed prose + identifier → **hybrid** (symbol hits first, then concept pages).
+ - an **identifier** (`GitIndexer`, `index_repo`) -> searches indexed symbols;
+ - a **path** (`core/ingestion/indexer.py`) -> searches file pages;
+ - **prose** ("how do we handle retries?") -> wiki-semantic search;
+ - mixed prose + identifier -> **hybrid** (symbol hits first, then concept pages).
- **`concept`** forces the original wiki-semantic behavior.
- **`symbol`** / **`path`** force the structural search.
**Returns:**
-- *Symbol hits* — `{type: "symbol", symbol_id, name, kind, file, start_line, end_line, signature, next: "get_symbol"}`. Ranked by exact-name/qualified-name match, query-token coverage, then graph centrality (PageRank / betweenness / entry-point); non-test before test unless `kind="test"`.
-- *File hits* — `{type: "file", page_id, file, title, next: "get_context"}`.
-- *Concept hits* — ranked wiki pages with `relevance_score`, `snippet`, `target_path`, and a `search_method` (`embedding` vs `bm25` fallback).
+- *Symbol hits*: `{type: "symbol", symbol_id, name, kind, file, start_line, end_line, signature, next: "get_symbol"}`. Ranked by exact-name/qualified-name match, query-token coverage, then graph centrality (PageRank / betweenness / entry-point); non-test before test unless `kind="test"`.
+- *File hits*: `{type: "file", page_id, file, title, next: "get_context"}`.
+- *Concept hits*: ranked wiki pages with `relevance_score`, `snippet`, `target_path`, and a `search_method` (`embedding` vs `bm25` fallback).
Tombstoned and `exclude_patterns`-excluded results are filtered. In workspace
mode, structural and concept searches both federate across repos and merge.
**When to use:** Locating a function/class/method by name, resolving a
-path-shaped query, or discovering pages by topic — the symbol/file shapes pipe
+path-shaped query, or discovering pages by topic: the symbol/file shapes pipe
directly into `get_symbol` / `get_context`.
**Example calls:**
@@ -284,13 +284,13 @@ Modification risk assessment for files or a set of changed files.
When `changed_files` is passed, the response leads with a `directive` block. In workspace mode that directive also carries the cross-repo fallout of the changed repo:
-- `will_break_consumers` — services in *other* repos that depend on this one (structural impact), each with `repo`, `service`, `distance`, `score`, and the edge kinds carrying the impact.
-- `missing_cross_repo_cochanges` — services in other repos that historically co-change with this one but aren't in the diff.
-- `breaking_changes` — provider contracts in this repo that changed *incompatibly* since the last index (a removed route or field, a type or field-number change, a newly-required field), each with the changed `contract_id`, the change `kind`/`severity`, and the `impacted_consumers` (repo, service, file) it endangers across repos. Schema-level truth, distinct from the topology-level `will_break_consumers`; non-breaking changes (added optional field, new endpoint) never appear. See [Breaking-Change Guard](WORKSPACES.md#breaking-change-guard).
-- `conformance_violations` — declared dependency-rule breaches the diff's repo participates in, each with the offending `source`/`target` services, the `rule` (e.g. `frontend !-> db`), and `edge_kind`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).
-- `dependency_cycles` — circular service dependencies involving this repo, each with the participating `nodes` and `length`.
+- `will_break_consumers`: services in *other* repos that depend on this one (structural impact), each with `repo`, `service`, `distance`, `score`, and the edge kinds carrying the impact.
+- `missing_cross_repo_cochanges`: services in other repos that historically co-change with this one but aren't in the diff.
+- `breaking_changes`: provider contracts in this repo that changed *incompatibly* since the last index (a removed route or field, a type or field-number change, a newly-required field), each with the changed `contract_id`, the change `kind`/`severity`, and the `impacted_consumers` (repo, service, file) it endangers across repos. Schema-level truth, distinct from the topology-level `will_break_consumers`; non-breaking changes (added optional field, new endpoint) never appear. See [Breaking-Change Guard](WORKSPACES.md#breaking-change-guard).
+- `conformance_violations`: declared dependency-rule breaches the diff's repo participates in, each with the offending `source`/`target` services, the `rule` (e.g. `frontend !-> db`), and `edge_kind`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).
+- `dependency_cycles`: circular service dependencies involving this repo, each with the participating `nodes` and `length`.
-**When to use:** Before modifying files — especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.
+**When to use:** Before modifying files, especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.
**Example calls:**
@@ -315,7 +315,7 @@ get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])
**Returns:** The impacted services ranked by impact `score`, each with `distance` (hops), `structural` (a real dependency vs co-change only), and the edge kinds that carried the impact; plus `impacted_repos`, `structural_count` / `behavioral_count`, `total_impacted`, and any `unresolved_targets`.
-**When to use:** Before changing a high-fan-out provider — see who consumes it across repo boundaries. Structural impact (`will break`) outweighs behavioral co-change (`may drift`). Reads the same system graph the [Live System Map](WORKSPACES.md#live-system-map) renders.
+**When to use:** Before changing a high-fan-out provider, see who consumes it across repo boundaries. Structural impact (`will break`) outweighs behavioral co-change (`may drift`). Reads the same system graph the [Live System Map](WORKSPACES.md#live-system-map) renders.
**Example calls:**
@@ -380,13 +380,13 @@ Architectural decision intelligence. Three modes depending on parameters.
**Modes:**
-1. **NL search** — pass a question: `get_why(query="why JWT over sessions?")` → searches decision records
-2. **Path-based** — pass a file path: `get_why(query="src/auth/service.ts")` → returns decisions governing that file
-3. **Health dashboard** — no args: `get_why()` → stale decisions, conflicts, ungoverned hotspots
+1. **NL search**: pass a question: `get_why(query="why JWT over sessions?")` -> searches decision records
+2. **Path-based**: pass a file path: `get_why(query="src/auth/service.ts")` -> returns decisions governing that file
+3. **Health dashboard**: no args: `get_why()` -> stale decisions, conflicts, ungoverned hotspots
**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.
-**When to use:** Before architectural changes — understand existing intent and constraints. After changes — record new decisions.
+**When to use:** Before architectural changes, understand existing intent and constraints. After changes, record new decisions.
**Example calls:**
@@ -412,7 +412,7 @@ Unreachable code sorted by confidence tier with cleanup impact estimates.
**Returns:** Dead code findings grouped by confidence tier (`safe_to_delete` ≥ 0.70, `review_first` < 0.70). Each finding includes: file path, kind (unreachable_file, unused_export, unused_internal, zombie_package), confidence score, line count, and cleanup impact estimate.
-**When to use:** Cleanup tasks. Conservative by design — `safe_to_delete` excludes dynamically-loaded patterns and framework-decorated functions.
+**When to use:** Cleanup tasks. Conservative by design: `safe_to_delete` excludes dynamically-loaded patterns and framework-decorated functions.
**Example calls:**
@@ -425,18 +425,18 @@ get_dead_code(min_confidence=0.8, include_internals=true)
## `get_health`
-Code-health biomarker scores — the same deterministic biomarkers the
-`repowise health` CLI computes, across three signals (defect risk ·
-maintainability · performance), exposed for agentic workflows. Zero LLM calls.
-Use it to **self-check a change before opening a PR** — the same signals a
+Code-health biomarker scores: the same deterministic biomarkers the
+`repowise health` CLI computes, across three signals (defect risk,
+maintainability, performance), exposed for agentic workflows. Zero LLM calls.
+Use it to **self-check a change before opening a PR**: the same signals a
code-health merge-gate judges it on.
**Parameters:**
| 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"` (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. |
+| `targets` | list[string] | No | File paths, or `module:foo` to expand a module's file set. Empty means dashboard mode. |
+| `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) |
@@ -449,31 +449,31 @@ scores, and the score breakdown. Each finding carries a `dimension`
The opt-in enrichments:
-- **`accuracy`** → a `defect_accuracy` block: of the K least-healthy files, how
+- **`accuracy`** returns a `defect_accuracy` block: of the K least-healthy files, how
many were recently bug-fixed vs the repo-wide base rate (precision@K + `lift`),
with a per-K table and the flagged files. Silent (`null`) on repos with too
little history to be honest (< 25 scored files or < 5 recently-fixed files).
-- **`signals`** → a `signals` object on each targeted metric: prior-defect count,
+- **`signals`** adds a `signals` object on each targeted metric: prior-defect count,
change scatter, 90-day churn, primary / recent owner, and graph in / out
degree. Honest `null` per field when the underlying row is absent (never an
imputed zero).
-- **`churn_complexity`** → `churn_complexity` points (one per recently-changed
- file: 90-day commit count, max CCN, NLOC, score, churn percentile) — the
+- **`churn_complexity`** returns `churn_complexity` points (one per recently-changed
+ file: 90-day commit count, max CCN, NLOC, score, churn percentile): the
refactor zone where volatility and tangle collide.
-- **`refactoring`** → ranked, structured refactoring plans (not template
+- **`refactoring`** returns 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
+- **dimension filter** narrows the returned findings to one pillar. Pair with
`"biomarkers"` for the full (uncapped) finding set, e.g.
`include=["biomarkers", "performance"]`.
**When to use:** Before opening a PR, to self-check the files you changed
(`targets=[...], include=["signals"]`) and confirm you are not regressing the
-worst files. Before refactoring — find the worst-scoring files and what to fix
+worst files. Before refactoring, find the worst-scoring files and what to fix
first (`include=["accuracy", "churn_complexity"]`). Pair with `get_risk` on
hotspots.
@@ -493,18 +493,18 @@ get_health(targets=["module:src.api"], include=["trend", "refactoring"])
In workspace mode (initialized with `repowise init .`), all tools accept an optional `repo` parameter:
-- **Omit `repo`** — queries the default (primary) repo
-- **`repo="backend"`** — targets a specific repo by alias
-- **`repo="all"`** — queries across all workspace repos (supported by `search_codebase`, `get_context`, `get_overview`; not supported by `get_symbol`)
+- **Omit `repo`**: queries the default (primary) repo
+- **`repo="backend"`**: targets a specific repo by alias
+- **`repo="all"`**: queries across all workspace repos (supported by `search_codebase`, `get_context`, `get_overview`; not supported by `get_symbol`)
The MCP server automatically enriches responses with cross-repo intelligence:
- **Co-change partners** from other repos surfaced in `get_context` and `get_risk`
- **API contract links** (HTTP, gRPC, topics) between repos
- **Package dependencies** between repos
- **Cross-repo blast radius** via the workspace-only `get_blast_radius` tool, and a cross-repo `directive` in `get_risk` PR-mode
-- **Breaking-change guard** — incompatible provider-contract changes and the consumers they endanger, in the `get_risk` PR-mode `breaking_changes` directive
-- **Architecture conformance** — declared dependency-rule violations and dependency cycles via the workspace-only `get_conformance` tool, and `conformance_violations` / `dependency_cycles` in the `get_risk` PR-mode directive
-- **Architecture metrics** — whole-system coupling (propagation cost), the cyclic core, per-service roles, and a deterministic 1-10 architecture score via the workspace-only `get_architecture` tool
+- **Breaking-change guard**: incompatible provider-contract changes and the consumers they endanger, in the `get_risk` PR-mode `breaking_changes` directive
+- **Architecture conformance**: declared dependency-rule violations and dependency cycles via the workspace-only `get_conformance` tool, and `conformance_violations` / `dependency_cycles` in the `get_risk` PR-mode directive
+- **Architecture metrics**: whole-system coupling (propagation cost), the cyclic core, per-service roles, and a deterministic 1-10 architecture score via the workspace-only `get_architecture` tool
---
@@ -512,8 +512,8 @@ The MCP server automatically enriches responses with cross-repo intelligence:
In addition to the MCP tools above, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:
-- **Claude Code PostToolUse** — broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.
-- **Codex SessionStart/UserPromptSubmit** — Codex receives concise Repowise MCP workflow guidance when a session or prompt starts.
-- **Codex PostToolUse** — after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.
+- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.
+- **Codex SessionStart/UserPromptSubmit**: Codex receives concise Repowise MCP workflow guidance when a session or prompt starts.
+- **Codex PostToolUse**: after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.
Hooks are lightweight reminders. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](AUTO_SYNC.md) and [Codex Integration](CODEX.md) for details.
diff --git a/docs/REFACTORING.md b/docs/REFACTORING.md
index 42886675f..b68163398 100644
--- a/docs/REFACTORING.md
+++ b/docs/REFACTORING.md
@@ -3,11 +3,11 @@
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*,
+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*,
*decompose this 900-line module into these four files and rewrite the imports in
-the six that depend on it* — computed deterministically from the same graph,
+the six that depend on it*, computed deterministically from the same graph,
class model, and git data the score is built on.
```bash
@@ -16,34 +16,33 @@ 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
+computed with 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%" />
+<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 six detectors
+## The five 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.
+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 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. |
-| **Extract Method** | A cohesive slice of a long function to lift into a helper, with the inferred parameter (in) and return (out) signature. | An intra-procedural dataflow pass (CFG + def/use + reaching definitions) over functions a method biomarker already flagged. A candidate span cuts at statement boundaries within one block (no partial branch / mid-`try`), carries no control-flow jump (single clean exit) and a real decision point, and infers `in`/`out` by line-based liveness over the def/use facts. Python first. |
| **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. |
-| **Split File** | The cohesive files an oversized module should decompose into — which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |
+| **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |
The algorithms are derived from public academic literature (Fokaefs-Tsantalis
HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking,
Newman-Girvan modularity for module decomposition), not from any product.
-**Split File is the cross-file wedge made concrete.** It is language-agnostic —
+**Split File is the cross-file wedge made concrete.** It is language-agnostic:
it reads only the already-built graph (`defines` / `calls` edges), so it works
the same on every language with call resolution, and it covers the gap LCOM4
leaves for Go (top-level functions, not class methods). Splitting Go files in the
@@ -52,7 +51,7 @@ back-compat re-export shim, surfaced as `shim_required` on the plan.
## Anatomy of a suggestion
-Every suggestion is **structured data, not a string** — the structure is the
+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).
@@ -65,13 +64,13 @@ web).
| `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. |
+| `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
+## 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
@@ -81,7 +80,7 @@ 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
+ × (1 + log1p(blast radius)) # how much else moves, a mild amplifier
× confidence_weight # high 1.25 · medium 1.0 · low 0.75
```
@@ -104,31 +103,31 @@ repowise health --refactoring-targets # ranked table
```
```python
-# MCP — the same structured plans, ranked
+# 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
+# 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
+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, the file-split
-groups tree with its residual core and import-rewrite list — over an impact/effort
+groups tree with its residual core and import-rewrite list) over an impact/effort
quadrant, with per-type filter chips (URL-synced) and a distinct accent color per
type carried consistently across the quadrant dots, card rails, and chips. 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
+## Optional 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`:
+The deterministic plan is the product. The LLM code-generation step is **never
+in the indexing hot path**: it runs only when you ask for code for a specific
+plan, and it is on by default. Configure it in `.repowise/config.yaml`:
```yaml
refactoring:
@@ -137,20 +136,18 @@ refactoring:
disabled: [] # e.g. [move_method]
min_confidence: medium # low | medium | high
llm:
- enabled: false # opt-in; gates the generate-code endpoint
+ enabled: true # on by default; set false to disable
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
+When code generation is enabled (the default), 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. Where a self-check is cheap and meaningful it
runs one: Extract Class re-walks the generated classes for an **LCOM4 before/after
-delta**, Extract Method re-walks the generated code to confirm the **residual
-method's cyclomatic complexity dropped** below the original's, and Split File
-re-walks the generated files to assert each is **below the
+delta**, and Split File re-walks the generated files to assert each is **below the
size floor** and the symbols are **partitioned with no duplication**. Results are
cached on disk by a content hash (plan + source + model), so the same plan never
pays twice.
@@ -163,7 +160,7 @@ PUT /api/repos/{repo_id}/refactoring/settings # toggle it from the dashb
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
+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
@@ -182,9 +179,9 @@ the same way a biomarker is:
## See also
-- [`docs/CODE_HEALTH.md`](CODE_HEALTH.md) — the biomarkers and the three health
+- [`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
+- [`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"])`
+- [`docs/MCP_TOOLS.md`](MCP_TOOLS.md): the `get_health(include=["refactoring"])`
response shape.
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index bbed9b8c1..ab98ca581 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -1,4 +1,4 @@
-# Code Health — Architecture & Internals
+# Code Health: Architecture & Internals
Companion to the user-facing [`docs/CODE_HEALTH.md`](../CODE_HEALTH.md). This
document is for contributors: where every piece lives, how data flows from
@@ -6,9 +6,9 @@ parsed source to the dashboard, and the extension points for adding
biomarkers, languages, coverage formats, or alerts.
> **TL;DR.** Health analysis is a deterministic, zero-LLM Python pipeline:
-> tree-sitter walks every file once → biomarkers vote → scores aggregate per
-> category → results land in four SQLAlchemy tables. The MCP server, CLI,
-> and Next.js dashboard all read from those tables — no JSON cache, no
+> tree-sitter walks every file once -> biomarkers vote -> scores aggregate per
+> category -> results land in four SQLAlchemy tables. The MCP server, CLI,
+> and Next.js dashboard all read from those tables: no JSON cache, no
> intermediate files, no LLM in the loop.
---
@@ -55,7 +55,7 @@ Three architectural rules govern the whole layer:
## 2. Where things live
-### Python — `packages/core/src/repowise/core/`
+### Python: `packages/core/src/repowise/core/`
```
analysis/health/
@@ -151,7 +151,7 @@ cli/src/repowise/cli/commands/
└── update_cmd.py # incremental path: HealthAnalyzer.analyze(changed_files=...)
```
-### Server — MCP + REST
+### Server: MCP + REST
```
server/src/repowise/server/
@@ -329,7 +329,7 @@ return HealthReport(findings=..., metrics=..., kpis=kpis)
Duplication runs **once up-front** (cross-file by nature). Each `FileContext`
gets a slice of the global clone report. The `dry_violation` biomarker
reads `ctx.clones` to rank pairs by co-change frequency from
-`git_meta_map[path]["co_change_partners_json"]` — active clones rank
+`git_meta_map[path]["co_change_partners_json"]`: active clones rank
higher than dormant ones.
---
@@ -361,13 +361,13 @@ class Biomarker(Protocol):
**test-quality** smells (see §5.3). They fire only on test files and sit in
a deliberately small category so a noisy test can't dominate its own score.
`large_method` is now gated on a minimal CCN floor (≥ 2) so a long-but-flat
-body (a big data literal) reads as layout, not a complexity smell — a small
+body (a big data literal) reads as layout, not a complexity smell: a small
step toward decoupling the score from raw file size.
`ownership_risk` (long-run minor-contributor dispersion, Bird et al.) and
`churn_risk` (size-normalized relative churn, Nagappan-Ball) are git-only
process signals computed from `top_authors_json` / `lines_added_90d` /
-`churn_percentile` — fields the git indexer already produces. `change_entropy`
+`churn_percentile`: fields the git indexer already produces. `change_entropy`
(Hassan's History Complexity Metric) and `co_change_scatter` (breadth of
co-change coupling, D'Ambros) are likewise git-only and read the
`change_entropy` / `change_entropy_pct` fields (see §5.1) and
@@ -380,26 +380,26 @@ file in the trailing ~6-month window, read from `prior_defect_count`. The
git indexer classifies a commit as a fix with the **same keyword rule the
defect benchmark labels fixes with** (`_constants.is_fix_commit`), counts only
non-merge commits inside the window, and anchors the window to the index's
-`as_of` reference (`REPOWISE_GIT_WINDOW_ANCHOR`) — so scoring a historical T0
+`as_of` reference (`REPOWISE_GIT_WINDOW_ANCHOR`): so scoring a historical T0
checkout measures the fixes *before* T0, never leaking the post-T0 fixes that
form the benchmark's labels. It carries a **neutral (1.0) weight by design**:
on the calibration corpus prior-defect history is largely redundant with the
existing process signals (correlation ≈ +0.59 with `change_entropy`, +0.38 with
churn; calibrated coefficient ≈ +0.02, effort-aware Popt gain within bootstrap
noise), so it is not boosted as a predictor. It ships for its **explanatory**
-value — "this file was bug-fixed N times recently" is immediately actionable,
-and it uniquely flags a few files the other signals miss — not for a measured
-accuracy lift.
+value, not for a measured accuracy lift: "this file was bug-fixed N times
+recently" is immediately actionable, and it uniquely flags a few files the
+other signals miss.
`coverage_gradient` makes the test-coverage signal **continuous**. The two
binary coverage gates (`untested_hotspot`, `coverage_gap`) only fire below hard
-thresholds (≈40–60% line coverage), so on a well-tested codebase — where most
-files sit at 85–99% — the score is effectively blind to coverage even though the
+thresholds (≈40–60% line coverage), so on a well-tested codebase (where most
+files sit at 85–99%) the score is effectively blind to coverage even though the
uncovered fraction still carries defect signal. `coverage_gradient` deducts
health in direct proportion to that fraction: `4.0 × (1 − line_coverage_pct/100)`
health points, clamped by its category cap (binding at ≥50% uncovered). It uses
-the `deduction` override on `BiomarkerResult` — a continuous magnitude that
-replaces the discrete severity → deduction table for that finding — so it stays
+the `deduction` override on `BiomarkerResult` (a continuous magnitude that
+replaces the discrete severity-to-deduction table for that finding) so it stays
**linear and per-finding attributable** (the `health_impact` contract holds). It
is **silent when no coverage report was ingested** (`line_coverage_pct is None`):
absent coverage is never imputed as uncovered. It lives in its own capped
@@ -407,7 +407,7 @@ category (`test_coverage_gradient`, −2.0) so the additive continuous signal
neither squeezes nor is squeezed by the binary gates, and it skips test files.
Calibrated offline against the defect corpus, it recovers **+0.043 corpus AUC
[95% CI +0.023, +0.061]** on the covered subset (≈65% of the continuous-feature
-ceiling), Popt-neutral, and is exactly zero on repos without ingested coverage —
+ceiling), Popt-neutral, and is exactly zero on repos without ingested coverage:
a purely additive improvement.
`low_cohesion` (LCOM4) and `god_class` are the two **class-level**
@@ -416,21 +416,21 @@ the walker now emits alongside per-function metrics (see §5.2).
`brain_method`'s centrality gate is **language-agnostic**: instead of a
fixed `dependents ≥ 8`, it fires when a file is in the repo's top quintile
of connected files (`repo_dependents_p80`, computed once per analyze) or
-clears the absolute hub bar of 8 — so it no longer goes silent on
+clears the absolute hub bar of 8: so it no longer goes silent on
sparse-graph languages (TS barrels, Rust) whose in-degrees are lower than
Python's.
### 5.1 Change-entropy git-layer fields
`change_entropy` is computed during the **single** FULL-tier co-change walk
-(`ingestion/git_indexer/co_change.py::compute_co_changes_and_entropy`) — no
+(`ingestion/git_indexer/co_change.py::compute_co_changes_and_entropy`): no
extra `git log` subprocess. For each commit touching a set of tracked files
`F` (with `2 ≤ |F| ≤ 30`; wider commits are dropped as noise, Hassan's filter),
the commit's entropy is `log2(|F|)`, distributed uniformly (`1/|F|` per file)
and decayed with the same τ=180d half-life as co-change. The decay-weighted sum
per file is `git_meta["change_entropy"]`. `enrich.compute_percentiles` then
derives `change_entropy_pct` by ranking **only files with positive entropy**
-(zero-entropy files — the ESSENTIAL tier, or files only ever changed alone —
+(zero-entropy files, the ESSENTIAL tier or files only ever changed alone,
keep pct 0.0 so the biomarker stays silent). Both fields are persisted on
`git_metadata` (migration `0025`) and the additive-reconcile path back-fills
them on legacy DBs.
@@ -446,7 +446,7 @@ Member references are detected per-language via `self`/`this`/`$this`
member-access nodes. **Safety valve:** a class with no detected member
references (a static utility, or an unmapped language) reports `lcom4 = 1`
("no signal") rather than `len(methods)`, so adding a language can only
-turn signal on — never produce a false-positive flood. See
+turn signal on, never produce a false-positive flood. See
`complexity/README.md` for the full heuristic and its limits.
`error_handling` is the **advisory maintainability** biomarker: swallowed
@@ -454,7 +454,7 @@ catches (an empty/comment-only `catch` / `except: pass` body), Python
catch-all `except:` / `except Exception:`, Rust `.unwrap()` / `.expect()` /
panic-family macros, and Go's empty `if err != nil {}` or blank-identifier
discard of a call's error. The walker collects each occurrence (with its
-line) in a whole-tree pass — module-level code included — reusing the
+line) in a whole-tree pass (module-level code included) reusing the
`LanguageNodeMap` catch kinds for the seven catch-shaped languages and
dedicated recognizers for Rust/Go; an unsupported language or parse failure
yields no hits ("no signal", never a guess). The biomarker emits one LOW
@@ -463,7 +463,7 @@ finding per occurrence (0.15 after its floored 0.5 weight) in its own
advisory framing. It is deliberately **excluded from the defect-weight
calibration**: on the 21-repo / 9-language T0 benchmark it is AUC-neutral
(OOF delta ≈ 0, CI crosses zero) but size-orthogonal and the least redundant
-signal tested, and it ships because users expect `except: pass` flagged —
+signal tested, and it ships because users expect `except: pass` flagged:
bounded so it can never move a file by more than half a point.
### 5.3 Assertion-block walker metrics (test-quality)
@@ -473,15 +473,15 @@ The same single walker pass records `assertion_blocks` on each
`(start_line, end_line, count)`. A statement counts as an assertion when it
is a bare `assert` (`LanguageNodeMap.assert_kinds`) or its expression is a
call (`assert_call_kinds`) whose callee name starts with `assert` or
-`expect` — covering `assertEqual` / `assert_eq!` / `expect(...).toBe(...)`
-across xUnit and BDD styles. Opt-in per language (all nine full-tier
-languages — Python, TS/JS, Java, Kotlin, Go, Rust, C++, C# — are mapped);
+`expect`: covering `assertEqual` / `assert_eq!` / `expect(...).toBe(...)`
+across xUnit and BDD styles. Opt-in per language, with all nine full-tier
+languages (Python, TS/JS, Java, Kotlin, Go, Rust, C++, C#) mapped;
a language that maps neither field simply emits no blocks.
`large_assertion_block` flags a single run ≥ 15; `duplicated_assertion_block`
intersects the clone report with assertion spans. Both gate on
`coverage.is_test_file(path)` so production code is never touched.
-`biomarkers/registry.py` is an **explicit list**, not auto-discovery —
+`biomarkers/registry.py` is an **explicit list**, not auto-discovery:
keeps the registration order deterministic and lets tests inject extras
via `registered_biomarkers(extra=...)`.
@@ -491,7 +491,7 @@ via `registered_biomarkers(extra=...)`.
Every file starts at **10.0**. Each finding contributes a per-severity
deduction (`low=0.3, medium=0.7, high=1.2, critical=2.0`). Deductions are
-**capped per category** — so even ten critical structural findings can
+**capped per category**, so even ten critical structural findings can
drive structural complexity down by at most 3.5 points, not 20.
```python
@@ -505,10 +505,10 @@ drive structural complexity down by at most 3.5 points, not 20.
```
The per-finding scaled deduction lands on `HealthFinding.health_impact`
-via `attach_impacts()` — that's what the dashboard's "−2.0" badge shows.
+via `attach_impacts()`: that's what the dashboard's "−2.0" badge shows.
Snapshot tests in `tests/unit/health/test_scoring_snapshot.py` lock the
-category caps, severity deductions, biomarker→category mapping, and two
+category caps, severity deductions, biomarker-to-category mapping, and two
known-fixture scores. A retune intentionally requires updating the
snapshot in the same PR.
@@ -518,10 +518,10 @@ snapshot in the same PR.
Three repo-level numbers, computed in `compute_kpis()`:
-- **Hotspot Health** — NLOC-weighted average over files where
+- **Hotspot Health**: NLOC-weighted average over files where
`git_meta_map[path]["is_hotspot"]` is true.
-- **Average Health** — NLOC-weighted average over all files.
-- **Worst Performer** — lowest-scoring file + its score.
+- **Average Health**: NLOC-weighted average over all files.
+- **Worst Performer**: lowest-scoring file + its score.
These flow into `HealthSnapshot` rows (rolling 50 per repo) and feed the
CLI status one-liner, the `get_overview()` MCP block, and the dashboard
@@ -531,13 +531,13 @@ KPI cards.
## 8. Trends (`trends.py`)
-State-free — callers pass an oldest-first list of snapshot rows. Two
+State-free: callers pass an oldest-first list of snapshot rows. Two
alerts:
-- **Declining Health** — current is ≥ `DECLINE_THRESHOLD` (default 0.5)
+- **Declining Health**: current is ≥ `DECLINE_THRESHOLD` (default 0.5)
below the snapshot `DECLINE_LOOKBACK` (5) positions back. Fires on the
6th+ snapshot.
-- **Predicted Decline** — the three most recent snapshots are each
+- **Predicted Decline**: the three most recent snapshots are each
strictly below the one before. Magnitude is not required; direction is
the signal.
@@ -549,11 +549,11 @@ for the CLI table and MCP `get_health(include=["trend"])` response.
Snapshots also store a compact `{path: score}` map (`per_file_scores_json`),
so the same window yields a single file's score-over-time series:
-- `file_score_series(history, path)` — oldest-first `FileTrendPoint`s,
+- `file_score_series(history, path)`: oldest-first `FileTrendPoint`s,
skipping snapshots that don't carry the file. Returns `[]` below two
points (silent on thin history). This is the exact function the PR bot
reuses for its in-comment sparkline.
-- `file_trend(history, path)` — wraps the series with `current` / `previous`
+- `file_trend(history, path)`: wraps the series with `current` / `previous`
/ `delta` and a `declining` flag (the per-file mirror of the alerts above:
≥ `DECLINE_THRESHOLD` below the lookback point, or
`PREDICTED_DECLINE_CONSECUTIVE` consecutive drops). `snapshot_count` is the
@@ -572,11 +572,11 @@ entirely). `file_signals(git_meta, degrees)` joins one `GitMetadata` row with
the file's graph degree into a `FileSignals` grouped as **Process**
(`prior_defect_count`, `change_entropy_pct` normalized 0-100, 90-day line
churn, `age_days`), **People** (recent vs all-time owner + commit share), and
-**Topology** (`in_degree` / `out_degree`). No recompute — pure surfacing.
+**Topology** (`in_degree` / `out_degree`). No recompute: pure surfacing.
The honesty rule mirrors the trend: a field is `None` only when its *source
-row* is absent (no git history → process/people silent; not a graph node →
-topology silent), never imputed; a genuine `prior_defect_count` of `0` is kept
+row* is absent (no git history means process/people silent; not a graph node
+means topology silent), never imputed; a genuine `prior_defect_count` of `0` is kept
as a real signal. The server serialises it via `_file_signals_to_dict` and
embeds it in the file-detail health block and the breakdown response (§13); MCP
attaches a null-dropped copy to the `get_context` health block (§12). Mirrored
@@ -585,7 +585,7 @@ as `FileSignals` in `@repowise-dev/types/health`; rendered by the shared
---
-## 9. Incremental analysis — the `repowise update` path
+## 9. Incremental analysis: the `repowise update` path
Full re-analysis would be wasteful on commit-sized diffs. `HealthAnalyzer`
accepts `changed_files`:
@@ -613,7 +613,7 @@ async def _persist_partial_health(session, repo_id, report):
```
The full-init writers (`save_health_findings`, `save_health_metrics`)
-still use delete-then-insert — simpler, and the cost is amortised across
+still use delete-then-insert: simpler, and the cost is amortised across
the whole `repowise init`.
---
@@ -695,7 +695,7 @@ repowise health --safe-only # confidence ≥ 0.8 only (placeholde
Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: packages/server/.../app.py)
```
-`repowise update` is unchanged from the user's perspective — health is
+`repowise update` is unchanged from the user's perspective: health is
silently re-scored for changed files only.
---
@@ -706,11 +706,11 @@ silently re-scored for changed files only.
Defined in `tool_health.py`. Modes:
-- **Dashboard mode** (`targets=None`) — returns repo-level KPIs (with the
+- **Dashboard mode** (`targets=None`): returns repo-level KPIs (with the
repo `band`) + the NLOC-weighted `distribution` across the 3 bands +
`worst_files` (top N lowest-scoring) + `top_findings` + a per-module
`modules` rollup.
-- **Targeted mode** (`targets=[...]`) — returns full `metrics` +
+- **Targeted mode** (`targets=[...]`): returns full `metrics` +
`findings` for the listed paths, plus a per-file `trends` block (compact
score series + `current` + `delta` + `declining`) for any target with at
least two snapshots of history. Targets prefixed `module:foo` expand to
@@ -727,13 +727,13 @@ Defined in `tool_health.py`. Modes:
### Enrichments on existing tools
-- `get_risk(targets)` — each per-target row carries `health_score`,
+- `get_risk(targets)`: each per-target row carries `health_score`,
`top_biomarkers`, `coverage_pct`, `branch_coverage_pct`.
-- `get_context(targets, include=["health"])` — per-file `score`,
+- `get_context(targets, include=["health"])`: per-file `score`,
`max_ccn`, `max_nesting`, `nloc`, `module`, `duplication_pct`, top
2 biomarkers (each with a `suggestion` string), a coverage block, and a
- null-dropped `signals` block (process/people/topology — see §8).
-- `get_overview()` — adds a `code_health` block: avg, repo `band`, hotspot,
+ null-dropped `signals` block (process/people/topology, see §8).
+- `get_overview()`: adds a `code_health` block: avg, repo `band`, hotspot,
worst performer, open finding count, and the NLOC-weighted `distribution`.
Every response carries the standard `_meta` envelope via `build_meta()`.
@@ -777,14 +777,14 @@ Three routes under `/repos/[id]/health/`:
| `/health/refactoring-targets` | Cards sorted by impact-per-effort, each with severity, biomarker, score, NLOC, effort bucket, **deterministic suggestion** |
Plus a sidecar `HealthRisksPanel` on the Hotspots, Ownership, and Graph
-pages — surfaces the lowest-scoring files inline without touching the
+pages: surfaces the lowest-scoring files inline without touching the
shared table/graph components. The **Hotspots & churn** tab carries the
`ChurnComplexityQuadrant` (fed by `GET /churn-complexity`), toggleable in
place with the existing churn × bus-factor scatter; the file Health tab
carries the per-function "Functions by churn" blame table.
All visual primitives live in `packages/ui/src/health/` so the hosted
-`frontend/` repo (separate git checkout) can reuse them — port is mostly
+`frontend/` repo (separate git checkout) can reuse them: port is mostly
data fetching + auth.
---
@@ -792,7 +792,7 @@ data fetching + auth.
## 15. CLAUDE.md integration
The auto-generated `CLAUDE.md` includes a `## Code health` section when
-the health tables are populated. The block is intentionally short —
+the health tables are populated. The block is intentionally short;
filter rules in `core/generation/editor_files/data.py`:
- Score ≤ 5.0 **and** file is a hotspot
@@ -807,7 +807,7 @@ agent in noise. The Jinja stanza lives in
---
-## 16. Configuration — `.repowise/health-rules.json`
+## 16. Configuration: `.repowise/health-rules.json`
User-authored (the **only** JSON file in the layer). Loaded by
`HealthConfig.load(repo_path)`:
@@ -864,17 +864,17 @@ Other perf notes:
| Suite | What it locks |
|---|---|
| `tests/unit/health/test_complexity_walker.py` | Per-language CCN, nesting, cognitive assertions on handcrafted fixtures |
-| `tests/unit/health/test_<biomarker>.py` | Each biomarker — positive in two languages + one negative |
+| `tests/unit/health/test_<biomarker>.py` | Each biomarker: positive in two languages + one negative |
| `tests/unit/health/test_duplication.py` | Tokenizer normalization, rolling-hash determinism, co-change weighting |
| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover / repowise-JSON happy paths + edge cases |
| `tests/unit/health/test_scoring.py` | Deduction caps, clamping, KPI math |
-| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard** — caps, severity table, biomarker→category mapping, two known fixture scores |
+| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard**: caps, severity table, biomarker-to-category mapping, two known fixture scores |
| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering, per-file series + `file_trend` |
-| `tests/unit/health/test_signals.py` | `file_signals` join — no-signal vs real-zero, entropy 0-1→0-100, owner handoff |
-| `tests/unit/health/test_churn_complexity.py` | `churn_complexity_points` — no-churn omission, complexity never filters, danger-product sort, percentile scaling |
+| `tests/unit/health/test_signals.py` | `file_signals` join: no-signal vs real-zero, entropy 0-1 to 0-100, owner handoff |
+| `tests/unit/health/test_churn_complexity.py` | `churn_complexity_points`: no-churn omission, complexity never filters, danger-product sort, percentile scaling |
| `tests/unit/health/test_suggestions.py` | Suggestion strings keyed correctly |
| `tests/unit/health/test_health_config.py` | `.repowise/health-rules.json` parsing + glob matching |
-| `tests/integration/test_health_coverage_integration.py` | End-to-end LCOV → analyzer → coverage_gap fires |
+| `tests/integration/test_health_coverage_integration.py` | End-to-end LCOV -> analyzer -> coverage_gap fires |
| `tests/integration/test_health_perf_benchmark.py` | 30 s budget on 3,000 synthetic files (`-m slow`) |
99 unit tests + 2 integration tests at time of writing. Run with
@@ -888,7 +888,7 @@ Other perf notes:
1. New file under `biomarkers/` implementing the `Biomarker` Protocol.
2. Append to `_DETECTOR_FACTORIES` in `biomarkers/registry.py`.
-3. Add the biomarker→category mapping in
+3. Add the biomarker-to-category mapping in
`scoring._BIOMARKER_CATEGORY`.
4. Add a suggestion template in `suggestions._TEMPLATES`.
5. Add at least three test cases (two positive in different languages,
@@ -900,7 +900,7 @@ Other perf notes:
Add one `LanguageNodeMap` entry to `complexity/languages.py` mapping the
language's tree-sitter control-flow node-type names to abstract `BRANCH`
/ `LOOP` / `TRY` / `BOOLEAN_OP` categories. Add a fixture under
-`tests/fixtures/lang_samples/<lang>/`. **No `.scm` files needed** — those
+`tests/fixtures/lang_samples/<lang>/`. **No `.scm` files needed**: those
are owned by the ingestion parser.
### Add a coverage format
@@ -910,9 +910,9 @@ from `coverage/detector.parse`. Stdlib-only (no extra XML libraries).
### Add a per-file override
-Users — not contributors — author `.repowise/health-rules.json`. To add
+Users (not contributors) author `.repowise/health-rules.json`. To add
a new override key (beyond `disabled_biomarkers`), extend
-`HealthConfig` and thread it through `to_analyzer_config()` →
+`HealthConfig` and thread it through `to_analyzer_config()` ->
`engine._evaluate_file()`.
---
@@ -941,23 +941,23 @@ phases may revisit; the constraints kept v1 shippable.
`grading.py`); a letter on top would be a third overlapping scale with
arbitrary cliffs. The legacy 4-step `scoreBand` in `ui/health/tokens.ts`
is retained only as a finer color ramp for file-table pills, not a
- labeling scheme — surfaced band labels and the distribution use the 3
+ labeling scheme: surfaced band labels and the distribution use the 3
bands.
---
-## 21. Quick lookup — where do I edit X?
+## 21. Quick lookup: where do I edit X?
| I want to... | Edit... |
|---|---|
-| Tweak a category cap | `scoring.CATEGORY_CAPS` (snapshot test will fail — update it) |
+| Tweak a category cap | `scoring.CATEGORY_CAPS` (snapshot test will fail; update it) |
| Tweak a severity deduction | `scoring._SEVERITY_DEDUCTION` (ditto) |
| Add a new biomarker | `biomarkers/*.py`, `registry.py`, `scoring.py`, `suggestions.py` |
| Change the suggestion text for a biomarker | `suggestions._TEMPLATES` |
| Adjust the trend-alert threshold | `trends.DECLINE_THRESHOLD` / `DECLINE_LOOKBACK` |
| Change snapshot retention | `crud.HEALTH_SNAPSHOT_RETENTION` |
-| Add a new MCP `include` flag | `tool_health.py` — append handling near the existing `"coverage"` / `"refactoring"` branches |
-| Add a new REST route | `routers/code_health.py` — auth is wired at the router level |
+| Add a new MCP `include` flag | `tool_health.py`: append handling near the existing `"coverage"` / `"refactoring"` branches |
+| Add a new REST route | `routers/code_health.py`: auth is wired at the router level |
| Add a new dashboard view | new file under `packages/web/src/app/repos/[id]/health/`, primitives under `packages/ui/src/health/` |
| Add a CLI flag | `packages/cli/src/repowise/cli/commands/health_cmd.py` |
| Wire the analyzer into a new entry point | call `HealthAnalyzer.analyze()` directly; persist via the upsert variants if your caller is incremental |
@@ -966,7 +966,7 @@ phases may revisit; the constraints kept v1 shippable.
## See also
-- [`docs/CODE_HEALTH.md`](../CODE_HEALTH.md) — user-facing guide.
-- [`packages/core/src/repowise/core/analysis/health/README.md`](../../packages/core/src/repowise/core/analysis/health/README.md) — developer overview at the layer root.
+- [`docs/CODE_HEALTH.md`](../CODE_HEALTH.md): user-facing guide.
+- [`packages/core/src/repowise/core/analysis/health/README.md`](../../packages/core/src/repowise/core/analysis/health/README.md): developer overview at the layer root.
- Sub-package READMEs under `complexity/`, `coverage/`, `duplication/`, `biomarkers/`.
-- [`docs/architecture/graph-algorithms.md`](./graph-algorithms.md) — the graph layer health depends on.
+- [`docs/architecture/graph-algorithms.md`](./graph-algorithms.md): the graph layer health depends on.