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
feat(health): rename the bumpy_road biomarker to repeated_nesting (#4113)
Raghav Chamadiya90e7fdb3dce2
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 93afddacb..cb94ceef0 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -2354,7 +2354,7 @@ This release rebuilds how wikis are generated. Every page now renders from struc## [0.10.0] — 2026-05-18### Added-- **Code health layer — a fifth intelligence layer alongside graph / git / docs / decisions.** New `repowise health` command, `health_*` SQLite tables, biomarker engine, and `/repos/[id]/health` web UI surface what hotspots actually *cost* to maintain. Tree-sitter complexity walker feeds 10+ biomarkers across structural (`large_method`, `nested_complexity`, `bumpy_road`, `complex_method`, `brain_method`, `primitive_obsession`), organizational (`developer_congestion`, `knowledge_loss`), test (`untested_hotspot`, `coverage_gap`), and DRY (`dry_violation`, backed by a tokenizer + Rabin-Karp clone detector with co-change correlation) categories. A composite 0–10 score is rolled up per file, per module (NLOC-weighted), and per repo. Findings persist with deterministic refactoring suggestions and an `acknowledged | resolved | false_positive` lifecycle. `HealthSnapshot` writer + trend detector surface declining-health alerts. `.repowise/health-rules.json` supports per-file overrides. `repowise update` runs an incremental upsert so the dashboard stays fresh without re-running the full pipeline. New `repowise health --trend`, `--refactoring-targets`, `--module`, `--file`, and `--coverage` flags; `repowise status` prints a one-line health digest. Parallel biomarker analysis via `asyncio.gather`. Full architecture deep-dive in `docs/layers/CODE_HEALTH.md` (#212).+- **Code health layer — a fifth intelligence layer alongside graph / git / docs / decisions.** New `repowise health` command, `health_*` SQLite tables, biomarker engine, and `/repos/[id]/health` web UI surface what hotspots actually *cost* to maintain. Tree-sitter complexity walker feeds 10+ biomarkers across structural (`large_method`, `nested_complexity`, `repeated_nesting`, `complex_method`, `brain_method`, `primitive_obsession`), organizational (`developer_congestion`, `knowledge_loss`), test (`untested_hotspot`, `coverage_gap`), and DRY (`dry_violation`, backed by a tokenizer + Rabin-Karp clone detector with co-change correlation) categories. A composite 0–10 score is rolled up per file, per module (NLOC-weighted), and per repo. Findings persist with deterministic refactoring suggestions and an `acknowledged | resolved | false_positive` lifecycle. `HealthSnapshot` writer + trend detector surface declining-health alerts. `.repowise/health-rules.json` supports per-file overrides. `repowise update` runs an incremental upsert so the dashboard stays fresh without re-running the full pipeline. New `repowise health --trend`, `--refactoring-targets`, `--module`, `--file`, and `--coverage` flags; `repowise status` prints a one-line health digest. Parallel biomarker analysis via `asyncio.gather`. Full architecture deep-dive in `docs/layers/CODE_HEALTH.md` (#212).- **Coverage ingestion (LCOV / Cobertura / Clover).** `repowise health --coverage report.lcov` parses one or more reports (format auto-detected, override with `--coverage-format`), persists per-file line + branch + covered-line sets to a new `coverage_files` table, and feeds two coverage-aware biomarkers — `untested_hotspot` (hotspot files with low coverage *or*, when no coverage is ingested, no paired test file) and `coverage_gap` (significant uncovered surface area on non-test files). New `/api/repos/{id}/health/coverage` endpoint + `/repos/[id]/health/coverage` page with risk × coverage scatter, module rollup, and per-file drilldown (#212).- **Code-health web UX overhaul — tabbed chrome, trend, scatter quadrants, file drawer.** `/health` is now a four-tab surface (Overview / Trend / Coverage / Refactoring) with shared `HealthPageChrome`, sparklines pulled from `/health/trend`, a 5th "Hotspot Health" KPI card, server-side paginated file table with sortable headers + filter chips (Hotspots / Untested / Failing) + path search, biomarker glossary tooltips, severity-distribution bars, slide-over `HealthFileDrawer` with score breakdown by category, impact × effort quadrant on the refactoring page, and one-click status mutation (Acknowledge / Resolved / False positive) wired to a new `PATCH /health/findings/{id}` endpoint. Inline `HealthBadge` chips appear on the hotspots / ownership / graph views so health context follows you across the app (#212).- **AI fix / test prompts on the refactoring and coverage pages.** Per-row `AI fix prompt` / `AI test prompt` buttons open a modal that picks a target agent (Generic / Claude Code / Cursor), previews the generated prompt (with biomarkers, line ranges, severities, score deductions, suggested directions, hard constraints, completion contract — and the explicit "verify each finding against the real code; treat analyzer output as leads, not ground truth" preamble), and copies to clipboard. Prompt builder is generic (`buildAiPrompt` / `buildCoverageAiPrompt`) so future surfaces can reuse it (#212).diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex e5c982c3a..0e9082e99 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -104,7 +104,7 @@ analysis/health/├── low_cohesion.py├── god_class.py├── nested_complexity.py- ├── bumpy_road.py+ ├── repeated_nesting.py├── complex_method.py├── large_method.py├── primitive_obsession.py@@ -202,7 +202,7 @@ packages/web/src/components/health/tests/unit/health/ # 99+ tests├── test_complexity_walker.py # per-language CCN/nesting assertions├── test_biomarkers.py-├── test_structural_biomarkers.py # bumpy_road, large_method, primitive_obsession+├── test_structural_biomarkers.py # repeated_nesting, large_method, primitive_obsession├── test_coverage_biomarkers.py # untested_hotspot, coverage_gap├── test_organizational_biomarkers.py├── test_dry_violation.py@@ -323,7 +323,7 @@ golden guarantee (§6).| Category | Cap | Markers ||------------------------|------|------------|| Organizational | −3.5‡ | developer_congestion, knowledge_loss, function_hotspot, code_age_volatility, ownership_risk, churn_risk, change_entropy, co_change_scatter, prior_defect, ungoverned_hotspot†, stale_governance†, contradictory_decision† |-| Structural complexity | −2.5 | low_cohesion, god_class, nested_complexity, bumpy_road, complex_conditional |+| Structural complexity | −2.5 | low_cohesion, god_class, nested_complexity, repeated_nesting, complex_conditional || Test coverage | −2.0 | untested_hotspot, coverage_gap || Test coverage gradient | −2.0 | coverage_gradient || Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |@@ -518,7 +518,7 @@ corpus. Precision is measured per language because it does not transfer:that is mostly one dispatch on one value (a `switch`, `match` or same-subject `if`chain holding at least 60% of its decision points) is judged by the code around thedispatch and its heaviest arm: `nested_complexity` skips the two levels the-`switch` and its `case` open, and `complex_method`, `brain_method` and `bumpy_road`+`switch` and its `case` open, and `complex_method`, `brain_method` and `repeated_nesting`read the CCN outside the dispatch plus the CCN of its most complex arm.In TypeScript and JavaScript (TSX / JSX included) a ternary opens no nesting level@@ -577,7 +577,7 @@ full calibration, with confidence intervals, is published in the| 1.1–1.33 | remaining structural complexity / size markers | Moderate calibrated lift. || 1.3 / 1.2 / 1.1 | `untested_hotspot` / `churn_risk` / `code_age_volatility` | Coverage-dependent and rarely-firing; keep prior weights the corpus could not fairly measure. || 1.0 | `prior_defect` | Neutral by design: largely redundant with the other process signals, kept for its explanatory value. |-| 0.5 (floored) | `developer_congestion`, `dry_violation`, `low_cohesion`, `primitive_obsession`, `bumpy_road` | Fire widely but proved weak under leakage-free scoring; kept as maintainability and parity signals, not disabled. |+| 0.5 (floored) | `developer_congestion`, `dry_violation`, `low_cohesion`, `primitive_obsession`, `repeated_nesting` | Fire widely but proved weak under leakage-free scoring; kept as maintainability and parity signals, not disabled. || 0.4 (de-rated) | `knowledge_loss` | Weakest of the floored set. || 0.5 (not fitted) | `error_handling` | Excluded from calibration (AUC-neutral); floored and capped at 0.5 per file. |diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 908d6f1b2..58f16dce6 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -195,7 +195,7 @@ dominating a file.| Family | Detectors | Cap | Catches ||---|---:|---|---|-| Structural complexity | 6 | 2.5 | Deep nesting, brain methods (listed, not scored), god classes, low cohesion, bumpy roads, complex conditions |+| Structural complexity | 6 | 2.5 | Deep nesting, brain methods (listed, not scored), god classes, low cohesion, repeated nesting, 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 |diff --git a/packages/core/alembic/versions/0114_rename_repeated_nesting.py b/packages/core/alembic/versions/0114_rename_repeated_nesting.pynew file mode 100644index 000000000..37df9cb17--- /dev/null+++ b/packages/core/alembic/versions/0114_rename_repeated_nesting.py@@ -0,0 +1,51 @@+"""Rename the stored biomarker id ``bumpy_road`` to ``repeated_nesting``.++Rewrites every column that stores a biomarker id. Public ids hash the marker's+first id, so ``public_id`` columns stay as they are. Local SQLite stores never+run Alembic; their rows are rewritten by the health re-score that follows an+analyzer version change.++Revision ID: 0114+Revises: 0113+Create Date: 2026-10-18+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "0114"+down_revision: str | None = "0113"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_OLD = "bumpy_road"+_NEW = "repeated_nesting"++_COLUMNS: tuple[tuple[str, str], ...] = (+ ("health_findings", "biomarker_type"),+ ("git_commit_health_findings", "biomarker_type"),+ ("performance_opportunities", "biomarker_type"),+ ("refactoring_suggestions", "source_biomarker"),+ ("refactoring_opportunities", "lead_biomarker"),+)+++def _rename(old: str, new: str) -> None:+ for table, column in _COLUMNS:+ op.execute(+ sa.text(f'UPDATE "{table}" SET "{column}" = :new WHERE "{column}" = :old').bindparams(+ old=old, new=new+ )+ )+++def upgrade() -> None:+ _rename(_OLD, _NEW)+++def downgrade() -> None:+ _rename(_NEW, _OLD)diff --git a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py b/packages/core/src/repowise/core/analysis/health/biomarker_labels.pyindex 2cdacc3ea..585655e47 100644--- a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py+++ b/packages/core/src/repowise/core/analysis/health/biomarker_labels.py@@ -7,10 +7,12 @@ glossary, which keeps its categories and descriptions beside them.from __future__ import annotations+from .biomarker_names import canonical_biomarker+BIOMARKER_LABELS: dict[str, str] = {"brain_method": "Brain method","nested_complexity": "Nested complexity",- "bumpy_road": "Bumpy road",+ "repeated_nesting": "Repeated nesting","complex_method": "Complex method","large_method": "Large method","primitive_obsession": "Long parameter list",@@ -63,4 +65,5 @@ BIOMARKER_LABELS: dict[str, str] = {def biomarker_label(name: str) -> str:"""The glossary label; an id it does not know reads with spaces for underscores."""+ name = canonical_biomarker(name)return BIOMARKER_LABELS.get(name) or name.replace("_", " ")diff --git a/packages/core/src/repowise/core/analysis/health/biomarker_names.py b/packages/core/src/repowise/core/analysis/health/biomarker_names.pynew file mode 100644index 000000000..fccda966b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarker_names.py@@ -0,0 +1,31 @@+"""Renamed biomarker ids: old ids still work as input, and public ids stay stable.++Public ids hash a renamed marker's first id, so finding and plan ids, and the+triage recorded against them, hold across a rename.+"""++from __future__ import annotations++from collections.abc import Iterable++LEGACY_BIOMARKER_NAMES: dict[str, str] = {+ "bumpy_road": "repeated_nesting",+} # old id -> current id; append only++_FIRST_NAMES: dict[str, str] = {new: old for old, new in LEGACY_BIOMARKER_NAMES.items()}+++def canonical_biomarker(name: str) -> str:+ """The current id for *name*; ids that were never renamed pass through."""+ return LEGACY_BIOMARKER_NAMES.get(name, name)+++def canonical_biomarkers(names: Iterable[str]) -> list[str]:+ """:func:`canonical_biomarker` over *names*, order kept."""+ return [canonical_biomarker(n) for n in names]+++def identity_biomarker(name: str) -> str:+ """The id a public-id hash reads for *name*: the marker's first id."""+ current = canonical_biomarker(name)+ return _FIRST_NAMES.get(current, current)diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.mdindex ea1099641..fa3bbfc40 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md@@ -20,7 +20,7 @@ Structural complexity (cap −2.5):- `god_class` — a large class (≥ 200 NLOC, ≥ 15 methods) that also hides abrain method.- `nested_complexity` — functions with deep nesting (≥ 4 levels).-- `bumpy_road` — multiple branches at the same nesting depth.+- `repeated_nesting` — multiple branches at the same nesting depth.- `complex_conditional` — compound boolean expressions with ≥ 3 ops.Size & complexity (cap −1.5):diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.pyindex 3a7d917f3..f059f5ae2 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py@@ -17,7 +17,6 @@ from .base import Biomarker, BiomarkerResult, FileContextfrom .blocking_io_under_lock import BlockingIoUnderLockDetectorfrom .blocking_sync_in_async import BlockingSyncInAsyncDetectorfrom .brain_method import BrainMethodDetector-from .bumpy_road import BumpyRoadDetectorfrom .change_entropy import ChangeEntropyDetectorfrom .churn_risk import ChurnRiskDetectorfrom .co_change_scatter import CoChangeScatterDetector@@ -56,6 +55,7 @@ from .pd_concat_in_loop import PdConcatInLoopDetectorfrom .primitive_obsession import PrimitiveObsessionDetectorfrom .prior_defect import PriorDefectDetectorfrom .regex_compile_in_loop import RegexCompileInLoopDetector+from .repeated_nesting import RepeatedNestingDetectorfrom .resource_construction_in_loop import ResourceConstructionInLoopDetectorfrom .serial_await_in_loop import SerialAwaitInLoopDetectorfrom .sql_cartesian_join import SqlCartesianJoinDetector@@ -72,7 +72,7 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [GodClassDetector, # type: ignore[list-item]NestedComplexityDetector, # type: ignore[list-item]ComplexMethodDetector, # type: ignore[list-item]- BumpyRoadDetector, # type: ignore[list-item]+ RepeatedNestingDetector, # type: ignore[list-item]LargeMethodDetector, # type: ignore[list-item]PrimitiveObsessionDetector, # type: ignore[list-item]DryViolationDetector, # type: ignore[list-item]diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py b/packages/core/src/repowise/core/analysis/health/biomarkers/repeated_nesting.pysimilarity index 69%rename from packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.pyrename to packages/core/src/repowise/core/analysis/health/biomarkers/repeated_nesting.pyindex 2b580b1c3..b84a7d192 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/repeated_nesting.py@@ -1,13 +1,9 @@-"""Bumpy Road — many independent regions of nested control flow.+"""Repeated nesting: several separate nested blocks side by side in one function.-A "bumpy road" function is one with several distinct nesting humps —-not one deep block (that's `nested_complexity`) and not one big linear-list of branches (that's `complex_method`) but multiple medium-depth-blocks sitting side by side.--We use the walker's ``bumps`` metric — the count of top-level body-statements that reach nesting depth ≥ 2 — and fire when it crosses a-configurable threshold while CCN is also non-trivial.+Not one deep block (``nested_complexity``) and not one long list of branches+(``complex_method``): multiple medium-depth blocks in sequence. Reads the+walker's ``bumps`` count, the top-level body statements that reach nesting+depth 2 or more, and fires when it crosses a threshold while CCN is non-trivial."""from __future__ import annotations@@ -17,8 +13,8 @@ from ..models import Severityfrom .base import BiomarkerResult, FileContext-class BumpyRoadDetector:- name = "bumpy_road"+class RepeatedNestingDetector:+ name = "repeated_nesting"category = "structural_complexity"_BUMP_THRESHOLD = 3@@ -51,11 +47,11 @@ class BumpyRoadDetector:"max_nesting": fn.max_nesting,},reason=(- f"{fn.name} has {fn.bumps} nested blocks at the same level (bumpy road)"+ f"{fn.name} has {fn.bumps} nested blocks at the same level"),))return out-BIOMARKER = BumpyRoadDetector()+BIOMARKER = RepeatedNestingDetector()diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.mdindex 931885369..1ac969c8b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md@@ -36,7 +36,7 @@ Tree-sitter AST walker. Single AST pass per file computes:(each level adds an incrementing penalty, plus +1 for each break incontrol flow).- **bumps** — count of branches at the same nesting depth as their- sibling branches. Feeds `bumpy_road`.+ sibling branches. Feeds `repeated_nesting`.- **param_count** — formal parameter count. Feeds `primitive_obsession`.- **nloc** — non-comment lines of code per function.- **assertion_blocks** — runs of ≥ 2 consecutive assertion statements,diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex a5e2b8e35..e07cefa6d 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -369,7 +369,7 @@ def _walk_function_body(``bumps`` counts how many *direct* children of the function bodycontain nested control flow that reaches a depth of ≥ 2. A function- with several heavy independent branches is "bumpy".+ with several heavy independent branches has repeated nesting.``complex_conditions`` is an additive side-channel — collected forevery branch/loop/case construct encountered. The CCN / cognitivediff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex c6e7ce6e1..482584cc3 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -43,7 +43,7 @@ class FunctionComplexity:cognitive: intnloc: int # non-blank lines inside the body# Number of top-level body sub-blocks whose internal nesting reached- # ≥ 2 — used by ``bumpy_road``. A flat function has 0 bumps.+ # ≥ 2 — used by ``repeated_nesting``. A flat function has 0 bumps.bumps: int = 0# Number of declared parameters on the function signature — used by# ``primitive_obsession``. Counted via the tree-sitter ``parameters``diff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.pyindex 1f5ed9d8c..5176331f6 100644--- a/packages/core/src/repowise/core/analysis/health/config.py+++ b/packages/core/src/repowise/core/analysis/health/config.py@@ -51,6 +51,7 @@ import structlogfrom repowise.core.repo_config import get_repowise_dir, load_repo_config+from .biomarker_names import canonical_biomarker, canonical_biomarkersfrom .models import Severitylog = structlog.get_logger(__name__)@@ -81,7 +82,7 @@ _PROFILES: dict[str, dict[str, Severity]] = {"change_entropy": Severity.LOW,"co_change_scatter": Severity.LOW,"primitive_obsession": Severity.LOW,- "bumpy_road": Severity.LOW,+ "repeated_nesting": Severity.LOW,},}@@ -128,7 +129,7 @@ def _coerce_severity_map(raw: object) -> dict[str, Severity]:if sev is None:log.warning("health_rules_bad_severity", biomarker=name, value=value)continue- out[name] = sev+ out[canonical_biomarker(name)] = sevreturn out@@ -347,7 +348,9 @@ class HealthConfig:def from_dict(cls, raw: object) -> HealthConfig:if not isinstance(raw, dict):return cls()- disabled = _string_list(raw.get("disabled_biomarkers"), field="disabled_biomarkers")+ disabled = canonical_biomarkers(+ _string_list(raw.get("disabled_biomarkers"), field="disabled_biomarkers")+ )rules: list[HealthRule] = []raw_rules = raw.get("rules")if raw_rules is not None and not isinstance(raw_rules, list | tuple):@@ -362,8 +365,8 @@ class HealthConfig:glob = entry.get("path") or entry.get("path_glob") or entry.get("glob")if not isinstance(glob, str) or not glob:continue- disabled_for = _string_list(- entry.get("disabled_biomarkers"), field="rules[].disabled_biomarkers"+ disabled_for = canonical_biomarkers(+ _string_list(entry.get("disabled_biomarkers"), field="rules[].disabled_biomarkers"))# A rule written against the old matching may now cover less than# its author meant, which would quietly un-silence biomarkers theydiff --git a/packages/core/src/repowise/core/analysis/health/file_evaluator.py b/packages/core/src/repowise/core/analysis/health/file_evaluator.pyindex 22c461052..28ca9feb1 100644--- a/packages/core/src/repowise/core/analysis/health/file_evaluator.py+++ b/packages/core/src/repowise/core/analysis/health/file_evaluator.py@@ -54,7 +54,7 @@ def _mark_function_facts(#: Function-size findings whose fix starts at the deepest nested block._DEEPEST_BLOCK_MARKERS = frozenset(- {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}+ {"complex_method", "nested_complexity", "brain_method", "large_method", "repeated_nesting"})diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.pyindex 6e3c366ea..f97fa274d 100644--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py@@ -28,6 +28,7 @@ from typing import Anyfrom repowise.core.references import path_identity+from .biomarker_names import identity_biomarkerfrom .rows import detail_map, fieldFINDING_ID_VERSION = 2@@ -127,7 +128,7 @@ def finding_public_id(row: Any) -> str:"kernel_version": FINDING_ID_VERSION,"dimension": field(row, "dimension", None) or "defect","path": path_identity(field(row, "file_path", "") or ""),- "kind": kind,+ "kind": identity_biomarker(kind),"symbol": symbol,**location,"details": _identity_details(kind, details, anchor),@@ -151,7 +152,7 @@ def legacy_finding_public_id(row: Any) -> str:"kernel_version": 1,"dimension": field(row, "dimension", None) or "defect","path": path_identity(field(row, "file_path", "") or ""),- "kind": field(row, "biomarker_type", "") or "",+ "kind": identity_biomarker(field(row, "biomarker_type", "") or ""),"symbol": field(row, "function_name", None) or "","line_start": field(row, "line_start", None),"line_end": field(row, "line_end", None),diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.pyindex edb44447c..803857e18 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py@@ -28,7 +28,7 @@ PROBLEM: dict[str, str] = {"brain_method": f"is long and branchy; {SPLIT_GAIN}","complex_method": f"has many paths; {SPLIT_GAIN}","nested_complexity": f"nests deeply; {SPLIT_GAIN}",- "bumpy_road": f"does several jobs side by side; {SPLIT_GAIN}",+ "repeated_nesting": f"does several jobs side by side; {SPLIT_GAIN}","large_method": f"is long; {SPLIT_GAIN}","god_class": f"holds much of its subsystem; {SPLIT_GAIN}","low_cohesion": "holds groups of methods that share little state",@@ -48,7 +48,7 @@ FINDING_TITLE: dict[str, str] = {"brain_method": "Split {where} into smaller functions","complex_method": "Reduce the branching in {where}","nested_complexity": "Flatten the nesting in {where}",- "bumpy_road": "Split {where} into stages",+ "repeated_nesting": "Split {where} into stages","large_method": "Shorten {where}","god_class": "Break up the {where} class","low_cohesion": "Split {where} along its unrelated method groups",diff --git a/packages/core/src/repowise/core/analysis/health/impact_effort.py b/packages/core/src/repowise/core/analysis/health/impact_effort.pyindex 8e8daf3ba..aef6567f2 100644--- a/packages/core/src/repowise/core/analysis/health/impact_effort.py+++ b/packages/core/src/repowise/core/analysis/health/impact_effort.py@@ -22,6 +22,7 @@ from collections.abc import Callable, Iterable, Mappingfrom dataclasses import asdict, dataclassfrom typing import Any, Literal+from repowise.core.analysis.health.biomarker_names import canonical_biomarkerfrom repowise.core.analysis.health.effort import EFFORT_WEIGHT, effort_bucketfrom repowise.core.analysis.health.models import primary_finding, split_by_originfrom repowise.core.analysis.health.queue.eligibility import MIN_WORTH@@ -199,9 +200,10 @@ def _finding_filter(# serialization from silently emptying the queue behind a 200.picked = {v.strip().lower() for v in (severity or "").split(",") if v.strip()}floor = _SEVERITY_ORDER.get(min_severity, 0) if min_severity else None+ marker = canonical_biomarker(biomarker) if biomarker else Nonedef keep(f: Any) -> bool:- if biomarker and f.biomarker_type != biomarker:+ if marker and f.biomarker_type != marker:return Falseif picked:return (f.severity or "").lower() in pickeddiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py b/packages/core/src/repowise/core/analysis/health/refactoring/identity.pyindex 556d78fe5..06fda8fcf 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py@@ -22,6 +22,7 @@ import jsonimport refrom typing import Any+from ..biomarker_names import identity_biomarkerfrom ..rows import fieldREFACTORING_MODEL_VERSION = 4@@ -229,7 +230,7 @@ def refactoring_kernel(suggestion: Any) -> RefactoringKernel:"""kind = str(field(suggestion, "refactoring_type") or "")file_path = str(field(suggestion, "file_path") or "")- biomarker = str(field(suggestion, "source_biomarker") or "")+ biomarker = identity_biomarker(str(field(suggestion, "source_biomarker") or ""))if kind == "performance_fix":# The performance layer already owns a versioned causal id for thisdiff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex a3f69479c..91cf8d6cc 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -169,7 +169,7 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {# --- floored: fired widely but weak / non-predictive at T0 ---"developer_congestion": 0.5, # was 1.5 - the HEAD-leakage hero; weak under T0"low_cohesion": 0.5,- "bumpy_road": 0.5,+ "repeated_nesting": 0.5,"primitive_obsession": 0.5,"dry_violation": 0.5,"knowledge_loss": 0.4, # confirmed weak-negative since Phase 1@@ -195,7 +195,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {"low_cohesion": "structural_complexity","god_class": "structural_complexity","nested_complexity": "structural_complexity",- "bumpy_road": "structural_complexity",+ "repeated_nesting": "structural_complexity","complex_conditional": "structural_complexity","complex_method": "size_and_complexity","large_method": "size_and_complexity",@@ -286,7 +286,7 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {# maintainability problem whether or not it is also a defect predictor."complex_method": {"defect", "maintainability"},"complex_conditional": {"defect", "maintainability"},- "bumpy_road": {"defect", "maintainability"},+ "repeated_nesting": {"defect", "maintainability"},# Performance-risk detectors contribute to ``performance`` ONLY. They are# NOT defect predictors and must never move the surfaced (defect) score -# that exclusion is what keeps the defect golden guarantee intact.@@ -350,7 +350,7 @@ _MAINTAINABILITY_WEIGHT_MULTIPLIER: dict[str, float] = {"nested_complexity": 1.0,"complex_method": 1.0,"complex_conditional": 1.0,- "bumpy_road": 1.0,+ "repeated_nesting": 1.0,# SQL smells ship advisory (0.7) pending a precision spot-check on a# migrations-heavy corpus, mirroring how new perf markers land."sql_high_complexity": 0.7,@@ -366,7 +366,7 @@ _MAINTAINABILITY_CATEGORY: dict[str, str] = {"nested_complexity": "structural_complexity","large_method": "structural_complexity","complex_conditional": "structural_complexity",- "bumpy_road": "structural_complexity",+ "repeated_nesting": "structural_complexity","complex_method": "size_and_complexity","primitive_obsession": "size_and_complexity","dry_violation": "duplication",diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.pyindex efbaa8504..9abac6b9c 100644--- a/packages/core/src/repowise/core/analysis/health/suggestions.py+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py@@ -48,11 +48,10 @@ _TEMPLATES: dict[str, str] = {"conditional axes; if it dispatches on a type tag, replace the ""if/elif ladder with polymorphism or a lookup table."),- "bumpy_road": (- "Smooth the road. Multiple branches at the same nesting depth "- "usually means the function is doing several jobs — split it "- "into stages so each stage stays at a single level of "- "abstraction."+ "repeated_nesting": (+ "Several nested blocks side by side usually mean the function "+ "does several jobs. Split it into stages so each stage stays at "+ "a single level of abstraction."),"large_method": ("Shorten the function. Extract paragraphs (each comment block "diff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.pyindex d2d2ea014..e20ae3956 100644--- a/packages/core/src/repowise/core/analysis/health/worth.py+++ b/packages/core/src/repowise/core/analysis/health/worth.py@@ -28,7 +28,7 @@ SIZE_NLOC = (100, 200, 400, 800)SIZE_NESTING = (5, 6, 8, 99)#: Findings that measure one function's size.SIZE_MARKERS = frozenset(- {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}+ {"complex_method", "nested_complexity", "brain_method", "large_method", "repeated_nesting"})#: How far past its bars (see :func:`worth_size`) a function must sit to be#: worth doing first: CCN 40, 200 lines or nesting 6. The same size from whichdiff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health/findings.py b/packages/core/src/repowise/core/persistence/crud/analysis/health/findings.pyindex ac10e5c58..7309ad79a 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health/findings.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health/findings.py@@ -12,6 +12,7 @@ from sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom .....analysis.finding_registry import excluded_types+from .....analysis.health.biomarker_names import canonical_biomarkerfrom .....analysis.health.finding_identity import (finding_public_id,legacy_finding_public_id,@@ -342,7 +343,9 @@ async def get_health_findings(# Accept a comma-separated list so a caller can pull several biomarker# types in one request (e.g. the function-level + coupling panels).# A single value with no comma still matches exactly (``IN`` of one).- types = [t.strip() for t in (biomarker_type or "").split(",") if t.strip()]+ types = [+ canonical_biomarker(t.strip()) for t in (biomarker_type or "").split(",") if t.strip()+ ]if types:q = q.where(HealthFinding.biomarker_type.in_(types))if not include_withheld:diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.mdindex 93afddacb..cb94ceef0 100644--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md@@ -2354,7 +2354,7 @@ This release rebuilds how wikis are generated. Every page now renders from struc## [0.10.0] — 2026-05-18### Added-- **Code health layer — a fifth intelligence layer alongside graph / git / docs / decisions.** New `repowise health` command, `health_*` SQLite tables, biomarker engine, and `/repos/[id]/health` web UI surface what hotspots actually *cost* to maintain. Tree-sitter complexity walker feeds 10+ biomarkers across structural (`large_method`, `nested_complexity`, `bumpy_road`, `complex_method`, `brain_method`, `primitive_obsession`), organizational (`developer_congestion`, `knowledge_loss`), test (`untested_hotspot`, `coverage_gap`), and DRY (`dry_violation`, backed by a tokenizer + Rabin-Karp clone detector with co-change correlation) categories. A composite 0–10 score is rolled up per file, per module (NLOC-weighted), and per repo. Findings persist with deterministic refactoring suggestions and an `acknowledged | resolved | false_positive` lifecycle. `HealthSnapshot` writer + trend detector surface declining-health alerts. `.repowise/health-rules.json` supports per-file overrides. `repowise update` runs an incremental upsert so the dashboard stays fresh without re-running the full pipeline. New `repowise health --trend`, `--refactoring-targets`, `--module`, `--file`, and `--coverage` flags; `repowise status` prints a one-line health digest. Parallel biomarker analysis via `asyncio.gather`. Full architecture deep-dive in `docs/layers/CODE_HEALTH.md` (#212).+- **Code health layer — a fifth intelligence layer alongside graph / git / docs / decisions.** New `repowise health` command, `health_*` SQLite tables, biomarker engine, and `/repos/[id]/health` web UI surface what hotspots actually *cost* to maintain. Tree-sitter complexity walker feeds 10+ biomarkers across structural (`large_method`, `nested_complexity`, `repeated_nesting`, `complex_method`, `brain_method`, `primitive_obsession`), organizational (`developer_congestion`, `knowledge_loss`), test (`untested_hotspot`, `coverage_gap`), and DRY (`dry_violation`, backed by a tokenizer + Rabin-Karp clone detector with co-change correlation) categories. A composite 0–10 score is rolled up per file, per module (NLOC-weighted), and per repo. Findings persist with deterministic refactoring suggestions and an `acknowledged | resolved | false_positive` lifecycle. `HealthSnapshot` writer + trend detector surface declining-health alerts. `.repowise/health-rules.json` supports per-file overrides. `repowise update` runs an incremental upsert so the dashboard stays fresh without re-running the full pipeline. New `repowise health --trend`, `--refactoring-targets`, `--module`, `--file`, and `--coverage` flags; `repowise status` prints a one-line health digest. Parallel biomarker analysis via `asyncio.gather`. Full architecture deep-dive in `docs/layers/CODE_HEALTH.md` (#212).- **Coverage ingestion (LCOV / Cobertura / Clover).** `repowise health --coverage report.lcov` parses one or more reports (format auto-detected, override with `--coverage-format`), persists per-file line + branch + covered-line sets to a new `coverage_files` table, and feeds two coverage-aware biomarkers — `untested_hotspot` (hotspot files with low coverage *or*, when no coverage is ingested, no paired test file) and `coverage_gap` (significant uncovered surface area on non-test files). New `/api/repos/{id}/health/coverage` endpoint + `/repos/[id]/health/coverage` page with risk × coverage scatter, module rollup, and per-file drilldown (#212).- **Code-health web UX overhaul — tabbed chrome, trend, scatter quadrants, file drawer.** `/health` is now a four-tab surface (Overview / Trend / Coverage / Refactoring) with shared `HealthPageChrome`, sparklines pulled from `/health/trend`, a 5th "Hotspot Health" KPI card, server-side paginated file table with sortable headers + filter chips (Hotspots / Untested / Failing) + path search, biomarker glossary tooltips, severity-distribution bars, slide-over `HealthFileDrawer` with score breakdown by category, impact × effort quadrant on the refactoring page, and one-click status mutation (Acknowledge / Resolved / False positive) wired to a new `PATCH /health/findings/{id}` endpoint. Inline `HealthBadge` chips appear on the hotspots / ownership / graph views so health context follows you across the app (#212).- **AI fix / test prompts on the refactoring and coverage pages.** Per-row `AI fix prompt` / `AI test prompt` buttons open a modal that picks a target agent (Generic / Claude Code / Cursor), previews the generated prompt (with biomarkers, line ranges, severities, score deductions, suggested directions, hard constraints, completion contract — and the explicit "verify each finding against the real code; treat analyzer output as leads, not ground truth" preamble), and copies to clipboard. Prompt builder is generic (`buildAiPrompt` / `buildCoverageAiPrompt`) so future surfaces can reuse it (#212).diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsxindex 761de286f..4289bd9a3 100644--- a/packages/ui/src/health/biomarker-details.tsx+++ b/packages/ui/src/health/biomarker-details.tsx@@ -313,9 +313,9 @@ export function BiomarkerDetails({: null,);break;- case "bumpy_road":+ case "repeated_nesting":line = joinStats(- num(details.bumps) != null ? `${num(details.bumps)} bumps` : null,+ num(details.bumps) != null ? `${num(details.bumps)} nested blocks` : null,num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,num(details.max_nesting) != null ? `nest ${num(details.max_nesting)}` : null,);diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.tsindex ba73b146e..d81ba246c 100644--- a/packages/ui/src/health/biomarker-glossary.ts+++ b/packages/ui/src/health/biomarker-glossary.ts@@ -74,11 +74,11 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {description:"Deeply nested control flow (≥4 levels). Cognitive load grows non-linearly with nesting; flatten with early returns or extracted helpers.",},- bumpy_road: {- label: BIOMARKER_LABELS.bumpy_road,+ repeated_nesting: {+ label: BIOMARKER_LABELS.repeated_nesting,category: "structural_complexity",description:- "A function with multiple shallow complexity bumps stitched together. No single block is bad, but the whole reads as a sequence of mini-functions.",+ "A function with several separate nested blocks stitched together. No single block is bad, but the whole reads as a sequence of mini-functions.",},complex_method: {label: BIOMARKER_LABELS.complex_method,diff --git a/packages/ui/src/health/generated/biomarker-labels.ts b/packages/ui/src/health/generated/biomarker-labels.tsindex 03f1d0b99..af7b524b1 100644--- a/packages/ui/src/health/generated/biomarker-labels.ts+++ b/packages/ui/src/health/generated/biomarker-labels.ts@@ -6,7 +6,7 @@export const BIOMARKER_LABELS = {brain_method: "Brain method",nested_complexity: "Nested complexity",- bumpy_road: "Bumpy road",+ repeated_nesting: "Repeated nesting",complex_method: "Complex method",large_method: "Large method",primitive_obsession: "Long parameter list",diff --git a/packages/ui/src/health/plain-language.ts b/packages/ui/src/health/plain-language.tsindex a309eea5d..6b935103e 100644--- a/packages/ui/src/health/plain-language.ts+++ b/packages/ui/src/health/plain-language.ts@@ -1,7 +1,7 @@/*** Findings in the words a developer uses, for the file drawer's first screen.*- * The glossary names detectors ("Brain method", "Bumpy road"); those names are+ * The glossary names detectors ("Brain method", "Repeated nesting"); those names are* precise and they are jargon. A reader who has never seen Repowise needs what* is wrong and why it matters, so each detector gets a plain title and a* one-line consequence here, with its category as the fallback. The detector's@@ -70,7 +70,7 @@ const BY_BIOMARKER: Record<string, PlainIssue> = {title: "Deeply nested logic",why: "Each level of nesting is more context a reader has to hold.",},- bumpy_road: {+ repeated_nesting: {title: "Several tangled blocks in one function",why: "It reads as a few functions glued together.",},diff --git a/tests/fixtures/distill/find_paths.txt b/tests/fixtures/distill/find_paths.txtindex 472f856fe..8f6b5e504 100644--- a/tests/fixtures/distill/find_paths.txt+++ b/tests/fixtures/distill/find_paths.txt@@ -27,7 +27,7 @@ packages/core/src/repowise/core/analysis/decision_semantic_match.pypackages/core/src/repowise/core/analysis/execution_flows.pypackages/core/src/repowise/core/analysis/health/biomarkers/base.pypackages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py-packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py+packages/core/src/repowise/core/analysis/health/biomarkers/repeated_nesting.pypackages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.pypackages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.pypackages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.pydiff --git a/tests/unit/health/test_biomarker_rename.py b/tests/unit/health/test_biomarker_rename.pynew file mode 100644index 000000000..2c4abcf70--- /dev/null+++ b/tests/unit/health/test_biomarker_rename.py@@ -0,0 +1,85 @@+"""A renamed biomarker keeps working under its old id everywhere a user can type one."""++from __future__ import annotations++from repowise.core.analysis.health.biomarker_labels import biomarker_label+from repowise.core.analysis.health.biomarkers.registry import registered_biomarkers+from repowise.core.analysis.health.config import HealthConfig+from repowise.core.analysis.health.finding_identity import finding_public_id+from repowise.core.analysis.health.models import Severity+from repowise.core.analysis.health.refactoring.identity import refactoring_public_id++OLD = "bumpy_road"+NEW = "repeated_nesting"+++def test_the_detector_registers_under_the_new_id():+ names = {b.name for b in registered_biomarkers()}+ assert NEW in names+ assert OLD not in names+++def test_health_rules_written_with_the_old_id_read_as_the_new_one():+ cfg = HealthConfig.from_dict(+ {+ "disabled_biomarkers": [OLD],+ "severity_overrides": {OLD: "high"},+ "rules": [+ {+ "path": "src/**",+ "disabled_biomarkers": [OLD],+ "severity_overrides": {OLD: "low"},+ }+ ],+ }+ )+ out = cfg.to_analyzer_config(["src/a.py"])+ assert out["disabled_biomarkers"] == [NEW]+ assert out["severity_overrides"] == {NEW: Severity.HIGH}+ assert out["per_file_disabled"] == {"src/a.py": {NEW}}+ assert out["per_file_severity_overrides"] == {"src/a.py": {NEW: Severity.LOW}}+++def test_the_label_reads_the_same_for_both_ids():+ assert biomarker_label(NEW) == "Repeated nesting"+ assert biomarker_label(OLD) == "Repeated nesting"+++def _finding_row(kind: str) -> dict:+ return {+ "biomarker_type": kind,+ "file_path": "src/a.py",+ "function_name": "walk",+ "line_start": 3,+ "line_end": 40,+ "dimension": "defect",+ "details": {"bumps": 4},+ }+++def test_finding_ids_hold_across_the_rename():+ assert finding_public_id(_finding_row(NEW)) == finding_public_id(_finding_row(OLD))+++def test_plan_ids_hold_across_the_rename():+ def plan(kind: str) -> dict:+ return {+ "refactoring_type": "extract_method",+ "file_path": "src/a.py",+ "target_symbol": "walk",+ "source_biomarker": kind,+ "line_start": 3,+ "line_end": 40,+ }++ assert refactoring_public_id(plan(NEW)) == refactoring_public_id(plan(OLD))+++def test_a_refactoring_target_filter_on_the_old_id_keeps_the_renamed_findings():+ from types import SimpleNamespace++ from repowise.core.analysis.health.impact_effort import _finding_filter++ keep = _finding_filter(OLD, None, None)+ assert keep(SimpleNamespace(biomarker_type=NEW, severity="medium"))+ assert not keep(SimpleNamespace(biomarker_type="large_method", severity="medium"))diff --git a/tests/unit/health/test_health_config.py b/tests/unit/health/test_health_config.pyindex f113a248a..6ff1cdea0 100644--- a/tests/unit/health/test_health_config.py+++ b/tests/unit/health/test_health_config.py@@ -66,13 +66,13 @@ def test_to_analyzer_config_shape(tmp_path: Path):_write(tmp_path,{- "disabled_biomarkers": ["bumpy_road"],+ "disabled_biomarkers": ["repeated_nesting"],"rules": [{"path": "src/*", "disabled_biomarkers": ["large_method"]}],},)cfg = HealthConfig.load(tmp_path)out = cfg.to_analyzer_config(["src/foo.py", "test/bar.py"])- assert out["disabled_biomarkers"] == ["bumpy_road"]+ assert out["disabled_biomarkers"] == ["repeated_nesting"]pfd = out["per_file_disabled"]assert isinstance(pfd, dict)assert pfd["src/foo.py"] == {"large_method"}diff --git a/tests/unit/health/test_scoring_dimensions.py b/tests/unit/health/test_scoring_dimensions.pyindex 12f0408c2..410b64720 100644--- a/tests/unit/health/test_scoring_dimensions.py+++ b/tests/unit/health/test_scoring_dimensions.py@@ -75,7 +75,7 @@ _LEGACY_WEIGHT_MULTIPLIER = {"developer_congestion": 0.5,"low_cohesion": 0.5,"brain_method": 0.5,- "bumpy_road": 0.5,+ "repeated_nesting": 0.5,"primitive_obsession": 0.5,"dry_violation": 0.5,"knowledge_loss": 0.4,@@ -90,7 +90,7 @@ _LEGACY_CATEGORY = {"low_cohesion": "structural_complexity","god_class": "structural_complexity","nested_complexity": "structural_complexity",- "bumpy_road": "structural_complexity",+ "repeated_nesting": "structural_complexity","complex_conditional": "structural_complexity","complex_method": "size_and_complexity","large_method": "size_and_complexity",@@ -216,7 +216,7 @@ def test_code_shape_markers_reach_maintainability():else, which left the pillar a reader watches while refactoring blind to themost common thing a refactor removes."""- for marker in ("complex_method", "complex_conditional", "bumpy_road"):+ for marker in ("complex_method", "complex_conditional", "repeated_nesting"):scores, _ = score_file([_r(marker, Severity.CRITICAL)])assert scores["maintainability"] < 10.0, markerdiff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pyindex c54261b7b..74d296637 100644--- a/tests/unit/health/test_scoring_snapshot.py+++ b/tests/unit/health/test_scoring_snapshot.py@@ -70,7 +70,7 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {# floored - fired widely but weak/non-predictive at T0"developer_congestion": 0.5,"low_cohesion": 0.5,- "bumpy_road": 0.5,+ "repeated_nesting": 0.5,"primitive_obsession": 0.5,"dry_violation": 0.5,"knowledge_loss": 0.4,@@ -89,7 +89,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {"low_cohesion": "structural_complexity","god_class": "structural_complexity","nested_complexity": "structural_complexity",- "bumpy_road": "structural_complexity",+ "repeated_nesting": "structural_complexity","complex_conditional": "structural_complexity","complex_method": "size_and_complexity","large_method": "size_and_complexity",diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.pyindex 283c29748..6150bafd6 100644--- a/tests/unit/health/test_structural_biomarkers.py+++ b/tests/unit/health/test_structural_biomarkers.py@@ -3,11 +3,11 @@from __future__ import annotationsfrom repowise.core.analysis.health.biomarkers import FileContext-from repowise.core.analysis.health.biomarkers.bumpy_road import BumpyRoadDetectorfrom repowise.core.analysis.health.biomarkers.large_method import LargeMethodDetectorfrom repowise.core.analysis.health.biomarkers.primitive_obsession import (PrimitiveObsessionDetector,)+from repowise.core.analysis.health.biomarkers.repeated_nesting import RepeatedNestingDetectorfrom repowise.core.analysis.health.complexity import FunctionComplexity, walk_file@@ -25,25 +25,25 @@ def _ctx(fns: list[FunctionComplexity]) -> FileContext:)-# ---- bumpy_road ----------------------------------------------------------+# ---- repeated_nesting -----------------------------------------------------------def test_bumpy_road_flags_multi_hump_function():+def test_repeated_nesting_flags_several_nested_blocks():fn = FunctionComplexity("rough", 1, 80, ccn=8, max_nesting=3, cognitive=15, nloc=50, bumps=4)- results = BumpyRoadDetector().detect(_ctx([fn]))+ results = RepeatedNestingDetector().detect(_ctx([fn]))assert len(results) == 1assert results[0].details["bumps"] == 4-def test_bumpy_road_skips_flat_function():+def test_repeated_nesting_skips_flat_function():fn = FunctionComplexity("flat", 1, 10, ccn=3, max_nesting=1, cognitive=2, nloc=8, bumps=0)- assert BumpyRoadDetector().detect(_ctx([fn])) == []+ assert RepeatedNestingDetector().detect(_ctx([fn])) == []-def test_bumpy_road_requires_ccn_floor():+def test_repeated_nesting_requires_ccn_floor():# Lots of bumps but very low CCN — could happen on synthetic inputs.fn = FunctionComplexity("toy", 1, 20, ccn=2, max_nesting=2, cognitive=2, nloc=18, bumps=4)- assert BumpyRoadDetector().detect(_ctx([fn])) == []+ assert RepeatedNestingDetector().detect(_ctx([fn])) == []# ---- large_method --------------------------------------------------------diff --git a/tests/unit/persistence/test_biomarker_alias_filter.py b/tests/unit/persistence/test_biomarker_alias_filter.pynew file mode 100644index 000000000..400398878--- /dev/null+++ b/tests/unit/persistence/test_biomarker_alias_filter.py@@ -0,0 +1,32 @@+"""A findings filter written with a renamed biomarker's old id still matches."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.models import HealthFindingData, Severity+from repowise.core.persistence.crud.analysis import get_health_findings, save_health_findings+from tests.unit.persistence.helpers import insert_repo++OLD = "bumpy_road"+NEW = "repeated_nesting"+++async def test_a_findings_filter_on_the_old_id_returns_the_renamed_rows(async_session):+ repo = await insert_repo(async_session)+ finding = HealthFindingData(+ biomarker_type=NEW,+ severity=Severity.MEDIUM,+ file_path="src/a.py",+ function_name="walk",+ line_start=3,+ line_end=40,+ details={"bumps": 4},+ health_impact=0.5,+ )+ await save_health_findings(async_session, repo.id, [finding])+ await async_session.commit()++ rows = await get_health_findings(async_session, repo.id, biomarker_type=f"{OLD},large_method")+ assert [r.biomarker_type for r in rows] == [NEW]diff --git a/tests/unit/persistence/test_repeated_nesting_migration.py b/tests/unit/persistence/test_repeated_nesting_migration.pynew file mode 100644index 000000000..2a2a09b6d--- /dev/null+++ b/tests/unit/persistence/test_repeated_nesting_migration.py@@ -0,0 +1,73 @@+"""Migration 0114: the renamed biomarker id on every column that stores one."""++from __future__ import annotations++import sqlite3+from pathlib import Path++OLD = "bumpy_road"+NEW = "repeated_nesting"++_COLUMNS = (+ ("health_findings", "biomarker_type"),+ ("git_commit_health_findings", "biomarker_type"),+ ("performance_opportunities", "biomarker_type"),+ ("refactoring_suggestions", "source_biomarker"),+ ("refactoring_opportunities", "lead_biomarker"),+)+++def _alembic_config(db_path: Path):+ from alembic.config import Config++ root = Path(__file__).resolve().parents[3] / "packages" / "core"+ config = Config()+ config.set_main_option("script_location", str(root / "alembic"))+ config.set_main_option("sqlalchemy.url", f"sqlite+aiosqlite:///{db_path}")+ return config+++def _filler(table: str, name: str, kind: str | None) -> object:+ numeric = any(k in (kind or "").upper() for k in ("INT", "FLOAT", "BOOL"))+ return 0 if numeric else f"{table}-{name}"+++def _seed(db_path: Path) -> None:+ """One row per column holding the old id, with every NOT NULL column filled."""+ conn = sqlite3.connect(db_path)+ try:+ for table, column in _COLUMNS:+ info = conn.execute(f'PRAGMA table_info("{table}")').fetchall()+ values = {+ name: OLD if name == column else _filler(table, name, kind)+ for _, name, kind, notnull, default, _pk in info+ if name == column or (notnull and default is None)+ }+ names = ", ".join(f'"{n}"' for n in values)+ marks = ", ".join("?" for _ in values)+ conn.execute(f'INSERT INTO "{table}" ({names}) VALUES ({marks})', list(values.values()))+ conn.commit()+ finally:+ conn.close()+++def _stored(db_path: Path) -> set[str]:+ conn = sqlite3.connect(db_path)+ try:+ return {conn.execute(f'SELECT "{c}" FROM "{t}"').fetchone()[0] for t, c in _COLUMNS}+ finally:+ conn.close()+++def test_the_migration_renames_and_restores_the_id(tmp_path: Path) -> None:+ from alembic import command++ db_path = tmp_path / "wiki.db"+ config = _alembic_config(db_path)+ command.upgrade(config, "0113")+ _seed(db_path)++ command.upgrade(config, "0114")+ assert _stored(db_path) == {NEW}+ command.downgrade(config, "0113")+ assert _stored(db_path) == {OLD}