Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
docs(health): split performance into its own page and lighten code health (#3264)
Raghav Chamadiya8d2c3739bd21
diff --git a/README.md b/README.mdindex f816a8d4c..719a5d270 100644--- a/README.md+++ b/README.md@@ -138,11 +138,11 @@ the page that answers it.|---|---|| *What should we fix first?* | A ranked queue weighing impact against effort, using churn, fan-in, coverage and bug history. [Fix first](docs/layers/CODE_HEALTH.md#fix-first) || *Where is the debt?* | A 1 to 10 score for every file from 53 deterministic detectors, split into defect risk, maintainability and performance, validated against real bug history. [Code health](docs/layers/CODE_HEALTH.md) |-| *Why is this slow?* | N+1 queries, I/O in loops, blocking calls inside async code and quadratic loops, traced across function and file boundaries. [Performance](docs/layers/CODE_HEALTH.md#performance-findings) |+| *Why is this slow?* | N+1 queries, I/O in loops, blocking calls inside async code and quadratic loops, traced across function and file boundaries. [Performance](docs/layers/PERFORMANCE.md) || *How do I break this up safely?* | Concrete refactoring plans: Extract Method, Extract Class, Move Method, Split File, Break Cycle, with the exact symbols that move and what moves with them. Ready to hand to an agent. [Refactoring](docs/layers/REFACTORING.md) || *What can we delete?* | Unreachable files, unused exports and unused packages, each with a confidence tier and the evidence behind it. [Dead code](docs/layers/DEAD_CODE.md) || *Where do bugs keep landing?* | Bug-fix commits traced to files and symbols, and a warning when your agent edits a bug magnet. [Bug history](docs/layers/BUG_HISTORY.md) |-| *Are our tests testing anything?* | Tests with no assertions, tests that only check their own mocks, and untested hotspots. [Test-quality smells](docs/layers/CODE_HEALTH.md#test-quality-smells) |+| *Are our tests testing anything?* | Tests with no assertions, tests that only check their own mocks, and untested hotspots. [Test-quality smells](docs/layers/CODE_HEALTH.md#findings) |<details><summary><strong>Things people do not expect it to do</strong></summary>diff --git a/docs/README.md b/docs/README.mdindex defef53b9..fea7fecd5 100644--- a/docs/README.md+++ b/docs/README.md@@ -41,6 +41,7 @@ For a map of every layer and how they feed each other, read| Doc | What it covers ||-----|----------------|| [layers/CODE_HEALTH.md](layers/CODE_HEALTH.md) | Defect risk, maintainability and performance risk per file, and the Fix first queue |+| [layers/PERFORMANCE.md](layers/PERFORMANCE.md) | N+1 queries, I/O in loops and blocking calls, grouped into plans and a default queue || [layers/REFACTORING.md](layers/REFACTORING.md) | Graph-aware refactoring plans, from Extract Method to Performance Fix || [layers/OWNERSHIP.md](layers/OWNERSHIP.md) | Owners, bus factor, and where knowledge is at risk || [start/DASHBOARD.md](start/DASHBOARD.md) | Every view in the local dashboard |diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex 5cdc1e775..687d9a746 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -702,6 +702,8 @@ growing data.### 6.4 Performance opportunities (`perf/`)+User guide: [PERFORMANCE.md](../layers/PERFORMANCE.md).+**Sinks.** `io_in_loop` resolves a call inside a loop through the graph'sresolver and classifies the target against the I/O-boundary lexicon(`io_boundaries.py`: db, network, filesystem, subprocess, lock). It fires only on adiff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 8d1f36cc9..42d2308d8 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -1,15 +1,13 @@# Code Health-Repowise scores every source file from 1 to 10 and reports three co-equal-signals: **code health** (the defect-risk score, calibrated against real bug-history), **maintainability** and **performance risk**. It reads the parse tree,-the dependency graph and git history. It needs no LLM key and no network, and it-runs as part of `repowise init` and `repowise update`. The analysis is budgeted at-under 30 seconds for a 3,000-file repository, a budget a test enforces.+Repowise scores every source file from 1 to 10 and lists which files to fix+first. It reads the parse tree, the dependency graph and git history, needs no LLM+key or network, and runs inside `repowise init` and `repowise update`. The+analysis is budgeted at under 30 seconds for 3,000 files, and a test enforces it.It finds code shapes and change patterns that go with bugs, slow code and code-that is hard to change. It does not run your code, measure runtime, or prove a-bug exists. A low score means "look here first", not "this is broken".+that is hard to change. It does not run your code or prove a bug exists. A low+score means "look here first", not "this is broken".## Quick start@@ -23,48 +21,40 @@ repowise update # re-scores only the files that changed```pythonget_health() # repo KPIs, worst files, top findingsget_health(targets=["src/api/server.py"]) # one file in detail-get_health(include=["refactoring", "accuracy"])```-In the dashboard (`repowise serve`), open **Code Health** for a repository:-`/repos/<id>/code-health`. Its tabs are Overview, Performance, Findings, Tests,-Dead code, Doc drift, Security and Blast radius.--Illustrative `repowise health` output:+The dashboard (`repowise serve`) has a Code Health page per repository at+`/repos/<id>/code-health`.```Fix first (3 of 41 eligible; tests, tooling and history-only files left out)- 1. Extract the retry branch from parse_config now · effort M · +1.4 health+ 1. Extract the retry branch from parse_config now, effort M, +1.4 healthsrc/config/loader.py:212CCN 47 and nesting 6 in a file changed 19 times this quarter.verify: pytest tests/unit/test_loader.py-Code health: 7.4/10 [Good] · Hotspot: 6.1/10 · Worst: 2.3/10 (src/config/loader.py)+Code health: 7.4/10 [Good], Hotspot: 6.1/10, Worst: 2.3/10 (src/config/loader.py)```## The three signals-All three are computed from one stream of findings by one scoring routine, each-with its own weights and caps. They are never blended into one number.+They come from one stream of findings, each with its own weights and caps. They+are never blended into one number.-| Signal | What it answers | How its weights were set |+| Signal | What it answers | Weights ||---|---|---|-| **Code health** (defect risk) | Which files are most likely to carry the next bug | Fitted against a defect corpus; the headline number, the band and the badge |-| **Maintainability** | How hard the code is to read and change | Set by hand against its own caps; never fitted to bugs |-| **Performance risk** | Where the code's structure wastes work (I/O in loops, quadratic building, blocking calls) | Per-marker precision weights in one capped category |+| **Code health** (defect risk) | Which files are most likely to carry the next bug | Fitted against a defect corpus; the headline number, band and badge |+| **Maintainability** | How hard the code is to read and change | Set by hand; never fitted to bugs |+| **Performance risk** | Where the structure wastes work | Per-marker precision weights; see [PERFORMANCE.md](PERFORMANCE.md) |-Some smells fire often but predict bugs weakly (low cohesion, brain methods,-duplicated code, broad error handling). They are down-weighted in code health-and counted at full weight in maintainability, where they belong.+Smells that fire often but predict bugs weakly (low cohesion, brain methods,+duplicated code, broad error handling) are down-weighted in code health and counted+in full in maintainability.## Reading the score-Each file starts at 10. Every finding deducts by its severity times its marker-weight, deductions are capped per category, and the result is clamped to 1-10.-When a category passes its cap, its findings are scaled down together, so each-finding's reported impact still adds up to the file's score.--### Bands+Each file starts at 10. Every finding deducts its severity times its marker weight,+deductions are capped per category, and the result is clamped to 1-10.| Band | Score | Meaning ||---|---|---|@@ -74,234 +64,138 @@ finding's reported impact still adds up to the file's score.| **Needs work** | 4.0 to 5.5 | Worth scheduling || **At risk** | under 4.0 | Where defects concentrate |-Bands are absolute, not percentiles, so a 6.2 means the same thing in every-repository. The 4.0 cutoff is the measured one: on the 2,770-file paired+Bands are absolute, so a 6.2 means the same in every repository. On the 2,770-filebenchmark corpus, files under 4.0 carried 16.9 times the per-file defect rate of-files at 8.0 and above, and 2.18 times the defects per thousand lines once size is-taken out. The other edges are reading points on the same scale.--Repository KPIs: **average health** and **hotspot health** (both weighted by code-lines; hotspot health covers only the files the git layer marks as hotspots), plus-the **worst performer**. A file in a language health has no support for is counted-as not analysed, never scored as a 10.--### What moves the score--The **53 registered detectors** fall into these families. Category caps keep any-one family from dominating a file.--| Family | Detectors | Cap on code health | What it catches |-|---|---:|---|---|-| Structural complexity | 6 | 2.5 | Deep nesting, brain methods, god classes, low cohesion, bumpy roads, complex conditions |-| Size and complexity | 3 | 1.5 | Long or high-CCN functions, primitive obsession |-| Duplication | 1 | 1.0 | Cloned blocks |-| Error handling | 1 | 0.5 | Swallowed or catch-all handlers, `unwrap`/panic, discarded Go errors |-| Change history | 10 | 1.0 to 3.5 | Churn, change entropy, co-change scatter, ownership, knowledge loss, prior bug fixes |-| Test coverage | 3 | 2.0 + 2.0 | Untested hotspots, coverage gaps, a continuous deduction for uncovered lines (needs a coverage report) |-| Test quality | 4 | 0.5 | Oversized or duplicated assertion blocks; two advisory markers (below) |-| SQL | 4 | maintainability or performance only | Overly complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins |-| Performance | 21 | performance only | See [Performance findings](#performance-findings) |--Twenty-five detectors move code health. The SQL and performance detectors move-only their own signals. Three markers are **advisory**: they are measured and-listed, carry an impact of exactly zero, and stay out of impact-ranked lists unless-you ask for the advisory dimension. Three more **governance** findings (an-ungoverned hotspot, stale governance, a contradictory decision) come from the-[decisions layer](DECISIONS.md) and never deduct.--**History amplifies code risk; it does not stand alone.** Git history can cost a-file at most 1.0 point, plus one point for each point its code-shape findings-deduct, up to 3.5. A simple file that changes often reads as busy, not broken, and-never drops below 9.0 from history alone. Each file stores its deduction in two-halves (structure and history) so you can see which one holds it down.--<details>-<summary>All 53 detectors by family</summary>--| Family | Detector ids |-|---|---|-| Structural complexity | `nested_complexity`, `brain_method`, `god_class`, `low_cohesion`, `bumpy_road`, `complex_conditional` |-| Size and complexity | `complex_method`, `large_method`, `primitive_obsession` |-| Duplication | `dry_violation` |-| Error handling | `error_handling` |-| Change history | `change_entropy`, `churn_risk`, `co_change_scatter`, `code_age_volatility`, `developer_congestion`, `function_hotspot`, `knowledge_loss`, `ownership_risk`, `prior_defect`, `hidden_coupling` (advisory) |-| Test coverage | `untested_hotspot`, `coverage_gap`, `coverage_gradient` |-| Test quality | `large_assertion_block`, `duplicated_assertion_block`, `assertion_free_test` (advisory), `mock_saturated_test` (advisory) |-| SQL | `sql_high_complexity`, `sql_select_star`, `sql_update_delete_without_where` (maintainability); `sql_cartesian_join` (performance) |-| Performance | `io_in_loop`, `nested_loop_with_io`, `serial_await_in_loop`, `blocking_sync_in_async`, `hot_path_sync_io`, `blocking_io_under_lock`, `lock_in_loop`, `resource_construction_in_loop`, `lazy_load_in_loop`, `unbounded_read_reduced_in_memory`, `string_concat_in_loop`, `nested_loop_quadratic`, `membership_test_against_list_in_loop`, `list_insert_zero_in_loop`, `regex_compile_in_loop`, `json_parse_in_loop`, `defer_in_loop`, `goroutine_in_unbounded_loop`, `array_spread_in_reduce`, `pd_concat_in_loop`, `pandas_iterrows_in_loop` |--</details>--### Ownership and knowledge-loss signals--Three history detectors read who has worked on a file, from git authorship alone:--| Detector | Fires when |-|---|---|-| `knowledge_loss` | A file that is still changing has one real author (bus factor 1), and that author is gone from recent commits or now makes under 20% of them |-| `ownership_risk` | A file with 5 or more commits has 3 or more minor contributors (each under 5% of commits) or no author above 40% |-| `developer_congestion` | 5 or more contributors, the file is in the top quarter of churn for the repository, and nobody owns half of it |--A file nobody touches never fires `knowledge_loss`: stable code with a departed-author is low risk. On a small team (few active contributors) the first two are-capped at low severity unless the file is a hotspot, since one owner per file is-the normal way such a team works. The `small-team` profile (see-[Configuration](#configuration)) lowers them further. Ownership and bus factor per-file also appear in `get_context(include=["ownership"])` and on the dashboard.--### Test-quality smells--`large_assertion_block` and `duplicated_assertion_block` fire only in test files-and share a 0.5 cap. Two advisory markers ask harder questions with no defect-corpus to calibrate against, so they never deduct:--- `assertion_free_test` (Python, TypeScript/JavaScript): a test that runs code and- checks nothing. No assertion, no mock verification, no hand-written raise, no- call to an assertion helper.-- `mock_saturated_test` (Python, TypeScript/JavaScript): mock setup statements per- assertion in a test function.+files at 8.0 and above.-Add house assertion helpers with the `assertions:` block in-[CONFIG.md](../reference/CONFIG.md#the-assertions-block). Per-language coverage is-in [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).+Repository KPIs are **average health**, **hotspot health** (hotspot files only; both+weighted by code lines) and the **worst performer**. A file in an unsupported+language is counted as not analysed, never scored as a 10.-### Scope and counts--Two controls decide what a figure describes. Both work on the CLI, MCP and every-dashboard page, and every response echoes them.+Two controls decide what a figure describes. Every response echoes them.| Control | Values | Effect ||---|---|---|-| `scope` | `all` (default), `production` | `production` drops test files. It lowers the headline because tests usually score higher than the code they cover. |-| `counts` | `everything` (default), `code_shape` | `code_shape` removes the history half of each deduction. Use it to ask "is my code getting better" after a week of refactoring raised churn. |+| `scope` | `all` (default), `production` | `production` drops test files, which lowers the headline because tests usually score higher |+| `counts` | `everything` (default), `code_shape` | `code_shape` removes the git-history half of each deduction, to see whether your code improved after a refactor raised churn |-`everything` is the calibrated number every accuracy claim refers to, and the-badge always reports it.+`everything` is the calibrated number every accuracy claim refers to, and the badge+always reports it.## Fix first-**Fix first** is one ranked list of what to fix. `repowise health` prints the top-3, `get_health()` and the dashboard Overview tab show more, and `repowise next`-mixes its top items with work from other layers. Each item is one unit of work: a-file's refactoring plan, one performance intervention, or the strongest code-shape-finding in a file with no plan. It says what to change and where, why, the first-edit, the expected gain, the effort and the tests to run afterwards.--What stays out, and is counted as excluded with a reason: test files, tooling,-generated and vendored code, docs and examples, files whose only findings come-from git history, changes that would recover under half a point, items with no-concrete first edit, kinds that reviewers found not worth doing, code a sure-dead-code finding covers (the fix is to delete it), and functions a constant flag-switches off. A function counts as switched off when its body opens with-`if not FLAG: return ...` (or is one `if FLAG:` block) and `FLAG` is a-module-level `False`, `0` or `None` (`const FLAG = false` in TypeScript or-JavaScript) that nothing in the same file assigns again. Those functions are-counted as **dormant** next to the excluded totals rather than dropped silently.-Only the file itself is read: a flag imported from another module, or flipped-from outside with `setattr` or a test's monkeypatch, still reads as off, and the-function is counted as dormant, not hidden.--Items rank by value first (health recovered, or how far the code sits past size-and complexity bars), then by tier: `now` (worth doing, safe to start), `next`-(worth doing, needs judgment), `later` (real but can wait; the reason is shown).-No single kind takes more than 3 of the first 5 places while another kind has work-worth doing.--### Do next: `repowise next`--`repowise next` prints the short cross-layer list the dashboard calls **Do next**-and `get_overview` returns as `next_actions`. It reads stored actions from the-index, so it is instant and makes no analysis pass. Fix first items sit beside-work from other layers: a live secret, fresh regressions, fragile files, files+**Fix first** is one ranked list of what to fix. `repowise health` prints the top 3;+`get_health()` and the dashboard Overview tab show more. Each item is one unit of+work: a refactoring plan, one performance intervention, or the strongest code-shape+finding in a file with no plan. It gives what to change and where, why, the first+edit, the expected gain, the effort and the tests to run.++Left out, and counted with a reason:++- test files, tooling, generated and vendored code, docs and examples+- files whose only findings come from git history+- changes that would recover under half a point, and items with no concrete first+ edit+- kinds that reviewers found not worth doing+- code a sure dead-code finding covers (the fix is to delete it)+- dormant functions, which a constant flag switches off++A function is dormant when its body opens with `if not FLAG: return ...` (or is one+`if FLAG:` block) and `FLAG` is a module-level `False`, `0` or `None` (`const FLAG =+false` in TypeScript or JavaScript) that nothing in the same file assigns again.+Dormant functions are counted next to the excluded totals, not dropped silently.+Only the file itself is read: a flag imported from another module, or flipped from+outside with `setattr` or a test's monkeypatch, still reads as off.++Items rank by value first (health recovered, or how far the code sits past size and+complexity bars), then by tier. No single kind takes more than 3 of the first 5+places while another kind has work worth doing.++| Tier | Meaning |+|---|---|+| `now` | Worth doing, safe to start |+| `next` | Worth doing, needs judgment |+| `later` | Real but can wait; the reason is shown |++### Do next++`repowise next` prints the cross-layer list the dashboard calls **Do next** and+`get_overview` returns as `next_actions`. It reads stored actions, so it is instant.+Fix first items sit beside a live secret, fresh regressions, fragile files, fileswith knowledge loss, broken doc references, a dead-code batch, missing or stale-coverage, and decisions waiting for review.+coverage, and decisions waiting for review. Rows are grouped as **Now**, **Worth+planning** and **Improve what Repowise can see**. Dismissing or snoozing a row takes effect at once.++A fragile file asks for tests only when no measured coverage and no test in the+code graph reaches it; otherwise the row asks you to simplify its lead function.+An index with fewer than five commits leaves out the rows ranked by history.```bash-repowise next # top 5 for this week (or the quarter when the week is empty)+repowise next # top 5 for this week (or the quarter when the week is empty)repowise next --horizon quarter --all-repowise next --json # the whole stored view+repowise next --json # the whole stored view```-Rows are grouped as **Now**, **Worth planning** and **Improve what Repowise can-see** (steps such as adding a coverage report that make other answers sharper).-Run `repowise update` to refresh the list after you change code. Dismissing or-snoozing a row takes effect at once.+## Findings-A fragile file asks for tests only when it has no measured coverage and no test-reaches it in the code graph. When tests do reach it, the row asks you to-simplify its lead function instead. An index with fewer than five commits leaves-out the rows ranked by history: fragile files, bug-fix concentration and-knowledge loss.+Findings are the observations behind the score. The dashboard **Findings** tab lists+them by dimension and severity, and `get_health(targets=[...])` returns them per+file. Each has a stable id that survives edits above it. Mark one `acknowledged`,+`false_positive` or `resolved` in the dashboard, over REST, or with the opt-in+`set_finding_status` MCP tool. Triage survives re-indexing, and a `resolved` finding+that is detected again reopens.-## Performance findings+The 53 detectors fall into families. Category caps keep any one family from+dominating a file.-Performance risk flags structure that wastes work. It does not measure runtime.+| Family | Detectors | Cap | Catches |+|---|---:|---|---|+| Structural complexity | 6 | 2.5 | Deep nesting, brain methods, god classes, low cohesion, bumpy roads, complex conditions |+| Size and complexity | 3 | 1.5 | Long or high-CCN functions, primitive obsession |+| Duplication | 1 | 1.0 | Cloned blocks |+| Error handling | 1 | 0.5 | Swallowed or catch-all handlers, `unwrap`/panic, discarded Go errors |+| Change history | 10 | 1.0 to 3.5 | Churn, change entropy, co-change scatter, ownership, knowledge loss, prior bug fixes |+| Test coverage | 3 | 2.0 + 2.0 | Untested hotspots, coverage gaps, uncovered lines (needs a coverage report) |+| Test quality | 4 | 0.5 | Oversized or duplicated assertion blocks; two advisory markers |+| SQL | 4 | none | Complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins; maintainability or performance only |+| Performance | 21 | none | See [PERFORMANCE.md](PERFORMANCE.md); performance only |++Twenty-five detectors move code health. Three markers are **advisory**: they are+listed, carry zero impact, and stay out of impact-ranked lists unless you ask for the+advisory dimension. Three **governance** findings (an ungoverned hotspot, stale+governance, a contradictory decision) come from the [decisions layer](DECISIONS.md)+and never deduct. Every detector id: [architecture/code-health.md](../architecture/code-health.md#the-full-roster).++**History amplifies code risk; it does not stand alone.** Git history costs a file at+most 1.0 point, plus one point for each point its code-shape findings deduct, up to+3.5. A simple file that changes often reads as busy, not broken, and never drops+below 9.0 from history alone.-| Kind | Examples |+| Detector | Fires when ||---|---|-| I/O per loop iteration (N+1) | `io_in_loop`, `nested_loop_with_io`, `lazy_load_in_loop` (Django and sync SQLAlchemy) |-| Concurrency | `serial_await_in_loop`, `blocking_sync_in_async`, `blocking_io_under_lock`, `lock_in_loop`, `goroutine_in_unbounded_loop` |-| Repeated setup | `resource_construction_in_loop`, `regex_compile_in_loop`, `json_parse_in_loop`, `defer_in_loop` |-| Quadratic or wasteful data work | `string_concat_in_loop`, `nested_loop_quadratic`, `membership_test_against_list_in_loop`, `list_insert_zero_in_loop`, `array_spread_in_reduce`, pandas `concat`/`iterrows` in loops |-| Over-fetch | `unbounded_read_reduced_in_memory`, `sql_cartesian_join` |--The loop and the I/O call do not have to sit in the same function: Repowise follows-the resolved call graph up to three hops and attaches the caller-to-sink path.-Per-function linters cannot see that case.--Findings group into **opportunities**, one per place you would edit (the function-holding the loop, or a helper every caller goes through). Each opportunity carries-one state: `plan_ready` (a proven fix strategy), `advisory` (a strategy with-unproven prerequisites), `investigate` (no supported strategy) or `expected` (the-repetition is real and nothing should change, such as deleting N files; reason-`gated_off` when a constant flag switches the function off, `cold_path` when it is-named for a migration, startup, shutdown or crash recovery and so runs once per-deploy, boot or incident). The default queue holds production `plan_ready` and-`advisory` opportunities whose cost is measured, ranked by cost first; state only-breaks ties. Everything left out is counted by reason. A loop whose size nothing-measured never leads and stays out of the list unless you ask for it with the-`proof=unproven` filter.--Performance analysis covers Python, TypeScript/JavaScript (including Vue and Svelte-scripts), Java, Go, C# (including Razor), Rust, Kotlin, Scala, Ruby, C++, Dart and-Pascal. A language without support emits no performance findings, never a guessed-one. Dynamic dispatch, monkeypatching and callbacks passed as values leave no call-edge, so those cases are missed.--## Refactoring--Each low-scoring file can carry deterministic refactoring plans (Extract Method,-Split File, Break Cycle, Performance Fix and others) with evidence, gain, effort and-blast radius. `repowise health --refactoring-targets` prints the stored queue.-Break Cycle is advisory: it is shown beside a file's steps, never as one, and-never in Fix first. A Split File or Extract Class plan with an unnamed group is-held the same way (`needs_design`). See [REFACTORING.md](REFACTORING.md).+| `knowledge_loss` | A file still changing has one real author (bus factor 1) who is gone from recent commits or makes under 20% of them |+| `ownership_risk` | 5 or more commits and either 3 or more minor contributors (each under 5%) or no author above 40% |+| `developer_congestion` | 5 or more contributors, top quarter of churn, and nobody owns half |+| `assertion_free_test` | Advisory. A Python or TypeScript/JavaScript test that checks nothing |+| `mock_saturated_test` | Advisory. Many mock setup statements per assertion (same languages) |++On a small team, `knowledge_loss` and `ownership_risk` are capped at low severity+unless the file is a hotspot, and the `small-team` profile lowers them further.+`large_assertion_block` and `duplicated_assertion_block` fire only in test files.+House assertion helpers go in the [`assertions:` block](../reference/CONFIG.md#the-assertions-block).+Per-language coverage: [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).## Trends, coverage and badges-Every `init`, `update` and `health --recompute` stores a snapshot (the last 50 per repository) with repository KPIs and-per-file scores. Alerts read them: **declining** (the score fell 0.5 or more-against five snapshots back), **predicted decline** (three falls in a row), and-**history drag** (either of those, where only the git-history half moved, so there-is nothing in the code to act on).-`repowise health --trend` prints the last 10 snapshots. Trends stay quiet on thin-history.--Coverage reports feed the test-coverage detectors. LCOV, Cobertura, Clover,-JaCoCo, Go coverprofile and a Repowise JSON format are detected automatically.-With no report, only `untested_hotspot` runs, judging a hotspot by whether any test-reaches it; the line-coverage detectors stay silent, so no file is treated as-uncovered.--```bash-pytest --cov --cov-report=lcov:coverage.lcov-repowise coverage add coverage.lcov-repowise health --recompute-```+Every `init`, `update` and `health --recompute` stores a snapshot (the last 50 per repository). Alerts: **declining** (fell+0.5 or more against five snapshots back), **predicted decline** (three falls in a+row) and **history drag** (either, where only the git-history half moved, so there+is nothing in the code to act on). `repowise health --trend` prints the last 10.-`repowise health --badge` prints README Markdown: a static shields.io badge for the-current score and the live form served by a running Repowise server-(`/api/repos/<id>/health/badge.json`, or `badge.svg`).+Coverage reports (LCOV, Cobertura, Clover, JaCoCo, Go coverprofile, Repowise JSON)+feed the coverage detectors: `repowise coverage add coverage.lcov`. With no report,+only `untested_hotspot` runs, and no file is treated as uncovered.+`repowise health --badge` prints README badge Markdown. After adding a report, run `repowise health --recompute`, which analyzes the working tree instead of reading the stored analysis and, on a whole-repo table run, writes the result to the index.## Configuration@@ -318,96 +212,37 @@ Per-file rules live in `.repowise/health-rules.json`:}```-- `path` uses gitignore semantics over the repo-relative path. Every matching rule- applies. A single `*` stops at a directory, so write `src/legacy/**` for a whole- subtree.-- `small-team` lowers the people and process signals a 1-3 person repository- cannot support. An explicit `severity_overrides` entry wins over the profile.-- Only severity labels are tunable. Weights and category caps are the calibrated- constants the published accuracy rests on, so local policy cannot change what- those numbers mean.--Full schema: [CONFIG.md](../reference/CONFIG.md#the-health-rulesjson-file).-Refactoring detectors and their confidence floor are set in the `refactoring:`-block of `.repowise/config.yaml`.--**Triage.** Each finding has a stable id that survives edits above it and changes-in its metric values. Mark a finding `acknowledged`, `false_positive` or `resolved`-in the dashboard, over REST, or with the opt-in `set_finding_status` MCP tool.-Triage survives re-indexing; a `resolved` finding that is detected again reopens.+`path` uses gitignore semantics, and every matching rule applies. `small-team`+lowers the people signals a 1-3 person repository cannot support, and an explicit+`severity_overrides` entry wins over it. Only severity labels are tunable; weights+and caps are the calibrated constants the published accuracy rests on. Full schema:+[CONFIG.md](../reference/CONFIG.md#the-health-rulesjson-file).## Accuracy and limits-Measured leakage-free: each file scored at a commit before the bug window, then-checked against the bug fixes of the next six months.--- **Defect prediction:** ROC AUC **0.737** (95% CI 0.683 to 0.787) across 21- repositories, 9 languages and 2,826 files; per-repository range 0.55 to 0.86.-- **Held-out data:** 0.761 and 0.776 on PROMISE jEdit 4.0 and 4.1, a public dataset- with no git history that played no part in calibration.-- **Against CodeScene** (same 2,770 files, same commit, same labels): recall at a- 20%-of-lines review budget **0.173 vs 0.074** (p = 0.003), surfacing 2.3 times the- defects. AUC 0.731 vs 0.705 is not significant (p = 0.054), and CodeScene's- precision at that budget is a tie (0.636 vs 0.580, p = 0.64).-- **Calibration:** marker weights come from a regression on that defect corpus with- file size as an explicit control, so a marker earns weight only for risk beyond- being big.-- **Not better than file size at discrimination:** lines of code alone scores AUC- 0.742 (a tie). The gain is in ordering a fixed review budget and in saying why.-- **Weak among files of similar size:** within size quartiles AUC runs 0.525 to- 0.718; the signal holds cleanly only in the largest quartile.-- **Business impact not replicated:** the score did not track GitHub merge time on- open data.-- **On your repository:** after an index, Repowise reports how many of the 20- lowest-scoring files had a bug fix in the last 180 days against the repository's- base rate (`get_health(include=["accuracy"])`). It is an association on indexed- history, not a forward test, and stays silent below 25 scored files or 5 fixed- ones.-- **Performance risk** is a static, high-precision, low-recall signal. It- under-reports by design.--Method, sample sizes and every test: [BENCHMARKS.md](../BENCHMARKS.md#code-health-predicts-defects).-How the calibration works: [architecture/code-health.md](../architecture/code-health.md#62-validation-and-calibration).--## Where it shows up--| Surface | What you get |-|---|---|-| CLI | `repowise health`, `repowise next`, a line in `repowise status` |-| MCP | `get_health`; health fields on `get_risk`, `get_context(include=["health"])` and `get_overview` |-| Dashboard | Code Health page: Overview (Fix first), Performance, Findings, Tests |-| CLAUDE.md | Health KPIs and Fix first items in the generated file |-| Editor | Per-file findings in the [VS Code extension](../agent/VSCODE.md) |+Measured without leakage: files scored before the bug window, checked against the+next six months of bug fixes.-## Reference+- ROC AUC 0.737 (95% CI 0.683 to 0.787) across 21 repositories, 9 languages and+ 2,826 files. Held out on PROMISE jEdit: 0.761 and 0.776.+- Against CodeScene on the same files, recall at a 20%-of-lines review budget is+ 0.173 vs 0.074 (p = 0.003), 2.3 times the defects. AUC and precision are ties.+- Lines of code alone scores AUC 0.742, a tie. The gain is in ordering a fixed+ review budget and saying why. Within size quartiles AUC is 0.525 to 0.718.+- The score did not track GitHub merge time on open data.+- `get_health(include=["accuracy"])` reports how many of your 20 lowest-scoring files+ had a bug fix in the last 180 days against the base rate. It is an association,+ not a forward test, and stays silent below 25 scored files or 5 fixed ones.-`repowise health [PATH]`+Every test: [BENCHMARKS.md](../BENCHMARKS.md#code-health-predicts-defects).-| Flag | Effect |+## More++| Where | What ||---|---|-| `--file PATH` | Report one file (repo-relative path) |-| `--module PREFIX` | Report only files under this path prefix |-| `--scope all\|production` | Population to report on (default `all`) |-| `--counts everything\|code_shape` | Include or drop the history half of the deduction (default `everything`) |-| `--format table\|json\|md` | Output format |-| `--refactoring-targets` | Print the stored refactoring queue |-| `--recompute` | Analyze the working tree in-process instead of reading the stored analysis; a whole-repo `table` run writes the result to the index |-| `--generate-code SELECTOR` | Opt-in: generate code and a diff for one suggestion with the configured LLM (needs an API key) |-| `--trend` | Print the last 10 snapshots |-| `--badge` | Print README badge Markdown |-| `--repo ALIAS` / `--no-workspace` | Pick a workspace repository, or force single-repo mode |-| `-v`, `--verbose` | Show pipeline debug logs |--`repowise next [PATH]` takes `--horizon week|quarter`, `--all` (20 rows, not 5),-`--repo`, `--no-workspace` and `--format`/`--json`.--MCP: [`get_health`](../agent/MCP_TOOLS.md#get_health).--## See also--- [architecture/code-health.md](../architecture/code-health.md): internals, weight- tables, calibration, Fix first and performance ranking rules.-- [BENCHMARKS.md](../BENCHMARKS.md): every published number with its sample and test.-- [REFACTORING.md](REFACTORING.md) · [TEST_INTELLIGENCE.md](TEST_INTELLIGENCE.md) ·- [BUG_HISTORY.md](BUG_HISTORY.md) · [DOC_DRIFT.md](DOC_DRIFT.md) ·- [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage)+| CLI | `repowise health`, `repowise next`, `repowise status`; flags in [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-health-path) |+| MCP | [`get_health`](../agent/MCP_TOOLS.md#get_health); health fields on `get_risk`, `get_context` and `get_overview` |+| Editor | Per-file findings in the [VS Code extension](../agent/VSCODE.md) |+| Refactoring | Plans per file, from `repowise health --refactoring-targets`. Break Cycle is advisory: shown beside a file's steps, never as one, and never in Fix first. A Split File or Extract Class plan with an unnamed group is held the same way (`needs_design`). See [REFACTORING.md](REFACTORING.md) |+| Layers | [PERFORMANCE.md](PERFORMANCE.md), [REFACTORING.md](REFACTORING.md), [TEST_INTELLIGENCE.md](TEST_INTELLIGENCE.md), [BUG_HISTORY.md](BUG_HISTORY.md), [DOC_DRIFT.md](DOC_DRIFT.md) |+| Internals | [architecture/code-health.md](../architecture/code-health.md) |diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.mdindex 9b38998a5..7a629e849 100644--- a/docs/layers/INTELLIGENCE_LAYERS.md+++ b/docs/layers/INTELLIGENCE_LAYERS.md@@ -89,7 +89,7 @@ against real bug history. The same machinery judges a change before it merges.|---|---|---|| Code health score | Per-file score, bands, trends, badges | [CODE_HEALTH.md](CODE_HEALTH.md) || Fix first | A ranked queue of what to fix, by impact and effort (`repowise next`) | [CODE_HEALTH.md](CODE_HEALTH.md#fix-first) |-| Performance findings | N+1 queries, I/O in loops, blocking calls in async code, traced across functions | [CODE_HEALTH.md](CODE_HEALTH.md#performance-findings) |+| Performance findings | N+1 queries, I/O in loops, blocking calls in async code, traced across functions | [PERFORMANCE.md](PERFORMANCE.md) || Refactoring plans | Extract Class, Extract Method, Extract Helper, Move Method, Break Cycle, Split File, Performance Fix | [REFACTORING.md](REFACTORING.md) || Change risk | Where a commit or range ranks against the repo's recent history, and what it made worse | [CHANGE_RISK.md](CHANGE_RISK.md) || Tests and coverage gates | Impacted tests, patch coverage, untested hotspots | [TEST_INTELLIGENCE.md](TEST_INTELLIGENCE.md), [CI.md](../start/CI.md) |diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.mdnew file mode 100644index 000000000..9539f7c0c--- /dev/null+++ b/docs/layers/PERFORMANCE.md@@ -0,0 +1,105 @@+# Performance++The performance layer finds code structure that wastes work: a database call+inside a loop, a blocking call in async code, a string rebuilt on every+iteration. It reads the parse tree and the call graph. It does not run your code+or measure time, so a finding means "this shape is slow when the data grows", not+"this was slow in production".++It is high precision and low recall. It misses cases rather than guessing.+Performance risk is one of the three signals in [Code Health](CODE_HEALTH.md).++## What it finds++| Kind | Examples |+|---|---|+| I/O per loop iteration (N+1) | `io_in_loop`, `nested_loop_with_io`, `lazy_load_in_loop` (Django and sync SQLAlchemy) |+| Concurrency | `serial_await_in_loop`, `blocking_sync_in_async`, `hot_path_sync_io`, `blocking_io_under_lock`, `lock_in_loop`, `goroutine_in_unbounded_loop` |+| Repeated setup | `resource_construction_in_loop`, `regex_compile_in_loop`, `json_parse_in_loop`, `defer_in_loop` |+| Quadratic or wasteful data work | `string_concat_in_loop`, `nested_loop_quadratic`, `membership_test_against_list_in_loop`, `list_insert_zero_in_loop`, `array_spread_in_reduce`, `pd_concat_in_loop`, `pandas_iterrows_in_loop` |+| Over-fetch | `unbounded_read_reduced_in_memory`, `sql_cartesian_join` |++That is 21 performance detectors plus `sql_cartesian_join`. They move only the+performance signal, never the defect score.++The loop and the I/O call do not have to be in the same function. Repowise+follows the resolved call graph up to three hops and attaches the+caller-to-sink path. Per-function linters cannot see that case.++Performance analysis covers Python, TypeScript/JavaScript (including Vue and+Svelte scripts), Java, Go, C# (including Razor), Rust, Kotlin, Scala, Ruby, C++,+Dart and Pascal. A language without support emits no performance findings.++## From findings to a plan++Several findings often share one cause. Repowise groups them into an+**opportunity**: one place you would edit, such as the function that holds the+loop, a helper every caller goes through, or the module body for top-level code.+Two loops in one function are one opportunity.++Each opportunity gets one state:++| State | Meaning |+|---|---|+| `plan_ready` | A fix strategy whose transformation is proven safe |+| `advisory` | A strategy with a prerequisite Repowise cannot prove, such as bounded concurrency before parallelizing awaits against a database |+| `investigate` | No supported strategy; a person has to decide |+| `expected` | The repetition is real and nothing should change, such as deleting N files, or the function is switched off by a constant flag (reason `gated_off`) or runs once per deploy, boot or incident (reason `cold_path`) |++A plan lists its edits, one step per call site and loop, each naming the call it+repeats. When every site reaches one sink, the step that adds a bulk form of that+sink comes first. The plan also lists tests to run, found from coverage, the call+graph and the import graph. An opportunity with a supported shared fix links to a+`performance_fix` plan in [REFACTORING.md](REFACTORING.md).++## The default queue++The default queue holds production opportunities in the `plan_ready` and+`advisory` states. They are ranked by cost first; state only breaks ties.+Only opportunities whose cost is measured are in it. A loop whose size nothing measured is `cost_proof = unproven`, never leads, and shows only with the `proof=unproven` filter.++Everything else is counted by reason, not hidden:++| Reason | Left out because |+|---|---|+| `test` | The code is test code |+| `tooling` | The code is build, migration or developer tooling |+| `unknown` | Repowise cannot tell whether the code ships |+| `expected` | The repetition is intended |+| `gated_off` | The function is switched off by a constant flag; see [dormant functions](CODE_HEALTH.md#fix-first) |+| `cold_path` | The function is named for a migration, startup, shutdown or crash recovery, so it runs rarely |+| `no_strategy` | The state is `investigate`: there is no supported fix to offer |++To see them, widen the filter (below). Performance work also appears in+[Fix first](CODE_HEALTH.md#fix-first), where it competes with other kinds of work.++## Reading it++| Surface | How |+|---|---|+| CLI | `repowise health` and `repowise next` list performance work inside Fix first |+| MCP | `get_health(include=["performance"])`; open one cause with `opportunity_id` |+| Dashboard | Code Health, **Performance** tab: each cause with its steps and the raw observations as evidence |++MCP filters: `performance_view` (`detail` or `summary`), `performance_context`+(`production` by default; `tooling`, `test`, `unknown` or `all`),+`performance_boundary`, `performance_confidence`, `performance_actionability` and+`performance_sort`. Parameters are listed in+[MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_health).++```python+get_health(include=["performance"], only=["performance_summary"])+get_health(opportunity_id="perf...")+```++## Limits++- Dynamic dispatch, monkeypatching and callbacks passed as values leave no call+ edge, so those cases are missed.+- Chains longer than three hops are not followed.+- ORM lazy loads are reported only where the loop's rows resolve to one model.+- A library Repowise does not model has no classified I/O calls.++Internals (sinks, gates, dialects, weights): [architecture/code-health.md](../architecture/code-health.md#64-performance-opportunities-perf).+Linter comparison and ranking quality:+[repowise-bench/perf-detection](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).