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): severity overrides + small-team profile in health-rules.json (#569)
Raghav Chamadiyab164b498d50e
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 7b2cb0b09..a0c504bdd 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -689,6 +689,33 @@ Per-file overrides live in `.repowise/health-rules.json`:`path` holds an fnmatch-style glob over the repo-relative POSIX path(`path_glob` and `glob` are accepted aliases).+### Severity overrides and profiles++A team can soften a signal it treats as advisory without disabling it+outright by remapping its severity (typically a *demotion*). Overrides apply+repo-wide and per-path; an explicit per-path entry wins over the repo-wide one.++```json+{+ "profile": "small-team",+ "severity_overrides": { "complex_method": "low" },+ "rules": [+ { "path": "src/generated/**", "severity_overrides": { "large_method": "low" } }+ ]+}+```++Accepted severity values are `low`, `medium`, `high`, `critical`. The named+`small-team` profile expands to a preset demotion of the process/people and+noisier structural signals a 1-3 person repo can't support; an explicit+`severity_overrides` key always wins over the preset.++Only the severity *label* is tunable. The per-biomarker weight multipliers and+the category caps are the calibrated constants the benchmark numbers rest on+and are deliberately **not** overridable, so a team's local policy never+changes what the published accuracy claims mean. Biomarkers that carry a+continuous deduction (`coverage_gradient`) are unaffected by severity remaps.+## Incremental updates`repowise update` only re-scores the changed files. Findings and metrics fordiff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.pyindex eeeafcb3c..fa7276ba6 100644--- a/packages/core/src/repowise/core/analysis/health/config.py+++ b/packages/core/src/repowise/core/analysis/health/config.py@@ -8,14 +8,27 @@ detector list. Decisions deliberately kept narrow in v1:- Per-path ``rules``: a list of glob → ``disabled_biomarkers`` entries.First matching glob wins. Patterns use ``fnmatch`` semantics over therepo-relative POSIX path (``src/legacy/**.py``).+- Repo-wide and per-path ``severity_overrides``: remap a biomarker's+ severity (typically a *demotion*, e.g. ``complex_method`` → ``low``) so a+ team can soften a signal it considers advisory without disabling it+ outright. This is the policy surface the PR Checks gate reads. Numeric+ weights and category caps are deliberately NOT overridable — they are the+ calibrated constants the benchmark claims rest on, so only the severity+ *label* (which the scorer turns into a deduction via a fixed table) can be+ tuned. Biomarkers that carry a continuous ``deduction`` override+ (``coverage_gradient``) ignore the severity remap by design.+- A named ``profile`` ("small-team") expands to a preset override map. An+ explicit ``severity_overrides`` entry wins over the profile preset.Schema (validated on load, errors logged but never raised):{+ "profile": "small-team","disabled_biomarkers": ["dry_violation"],+ "severity_overrides": {"complex_method": "low"},"rules": [{"path": "src/legacy/**", "disabled_biomarkers": ["complex_method"]},- {"path": "**/*.generated.ts", "disabled_biomarkers": ["large_method"]}+ {"path": "**/*.generated.ts", "severity_overrides": {"large_method": "low"}}]}"""@@ -31,11 +44,51 @@ import structlogfrom repowise.core.repo_config import get_repowise_dir+from .models import Severity+log = structlog.get_logger(__name__)HEALTH_RULES_FILENAME = "health-rules.json"+# Accepted severity labels for ``severity_overrides`` values, normalized to+# the ``Severity`` enum. Anything else is dropped with a warning on load.+_SEVERITY_BY_NAME: dict[str, Severity] = {s.value: s for s in Severity}++# Named presets. A profile expands to a repo-wide severity-override map;+# explicit ``severity_overrides`` keys take precedence over the preset. The+# "small-team" profile demotes the process/people signals that a 1-3 person+# repo cannot support (already floored in scoring, but a team may want them+# off the headline entirely) plus the structural smells most prone to noise+# on a small codebase. Numeric weights stay untouched — only labels move.+_PROFILES: dict[str, dict[str, Severity]] = {+ "small-team": {+ "developer_congestion": Severity.LOW,+ "knowledge_loss": Severity.LOW,+ "ownership_risk": Severity.LOW,+ "change_entropy": Severity.LOW,+ "co_change_scatter": Severity.LOW,+ "primitive_obsession": Severity.LOW,+ "bumpy_road": Severity.LOW,+ },+}+++def _coerce_severity_map(raw: object) -> dict[str, Severity]:+ """Parse a ``{biomarker: "severity"}`` dict, dropping invalid entries."""+ if not isinstance(raw, dict):+ return {}+ out: dict[str, Severity] = {}+ for name, value in raw.items():+ if not isinstance(name, str) or not isinstance(value, str):+ continue+ sev = _SEVERITY_BY_NAME.get(value.strip().lower())+ if sev is None:+ log.warning("health_rules_bad_severity", biomarker=name, value=value)+ continue+ out[name] = sev+ return out+@dataclassclass HealthRule:@@ -43,6 +96,7 @@ class HealthRule:path_glob: strdisabled_biomarkers: list[str] = field(default_factory=list)+ severity_overrides: dict[str, Severity] = field(default_factory=dict)@dataclass@@ -51,6 +105,10 @@ class HealthConfig:disabled_biomarkers: list[str] = field(default_factory=list)rules: list[HealthRule] = field(default_factory=list)+ # Repo-wide biomarker → severity remap. Merged on top of the ``profile``+ # preset (explicit keys win). Per-path remaps live on each ``HealthRule``.+ severity_overrides: dict[str, Severity] = field(default_factory=dict)+ profile: str | None = None@classmethoddef load(cls, repo_path: Path | str) -> HealthConfig:@@ -89,8 +147,27 @@ class HealthConfig:disabled_for = [str(b) for b in (entry.get("disabled_biomarkers") or []) if isinstance(b, str)]- rules.append(HealthRule(path_glob=glob, disabled_biomarkers=disabled_for))- return cls(disabled_biomarkers=disabled, rules=rules)+ rules.append(+ HealthRule(+ path_glob=glob,+ disabled_biomarkers=disabled_for,+ severity_overrides=_coerce_severity_map(entry.get("severity_overrides")),+ )+ )+ profile = raw.get("profile")+ profile = profile if isinstance(profile, str) and profile in _PROFILES else None+ return cls(+ disabled_biomarkers=disabled,+ rules=rules,+ severity_overrides=_coerce_severity_map(raw.get("severity_overrides")),+ profile=profile,+ )++ def _repo_severity_overrides(self) -> dict[str, Severity]:+ """Profile preset with explicit repo-wide overrides layered on top."""+ merged: dict[str, Severity] = dict(_PROFILES.get(self.profile or "", {}))+ merged.update(self.severity_overrides)+ return mergeddef per_file_disabled(self, file_paths: list[str]) -> dict[str, set[str]]:"""Materialize per-path overrides.@@ -112,9 +189,33 @@ class HealthConfig:out[path] = disabledreturn out+ def per_file_severity_overrides(self, file_paths: list[str]) -> dict[str, dict[str, Severity]]:+ """Materialize per-path severity remaps.++ Returns ``{path: {biomarker: Severity}}`` for files matched by at+ least one rule that carries a ``severity_overrides`` map. Later+ matching rules win per biomarker (consistent with how+ ``per_file_disabled`` unions, but here a key can be re-pointed).+ """+ rules_with_sev = [r for r in self.rules if r.severity_overrides]+ if not rules_with_sev:+ return {}+ out: dict[str, dict[str, Severity]] = {}+ for path in file_paths:+ norm = path.replace("\\", "/")+ overrides: dict[str, Severity] = {}+ for rule in rules_with_sev:+ if fnmatch.fnmatchcase(norm, rule.path_glob):+ overrides.update(rule.severity_overrides)+ if overrides:+ out[path] = overrides+ return out+def to_analyzer_config(self, file_paths: list[str]) -> dict[str, object]:"""Return the dict accepted by ``HealthAnalyzer.analyze``."""return {"disabled_biomarkers": list(self.disabled_biomarkers),"per_file_disabled": self.per_file_disabled(file_paths),+ "severity_overrides": dict(self._repo_severity_overrides()),+ "per_file_severity_overrides": self.per_file_severity_overrides(file_paths),}diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex cd4fb7049..d3013063b 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -36,7 +36,7 @@ from .biomarkers.base import HasEdgefrom .complexity import FileComplexity, FunctionComplexity, walk_filefrom .coverage import is_test_file as _coverage_is_test_filefrom .duplication import DuplicationReport, detect_clones-from .models import HealthFileMetricData, HealthFindingData, HealthReport+from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severityfrom .perf import (CallGraphIndex,PerfRanker,@@ -44,7 +44,7 @@ from .perf import (collect_centrality_gated,collect_crossfn_io_in_loop,)-from .scoring import attach_impacts, compute_kpis, score_file+from .scoring import attach_impacts, compute_kpis, remap_severities, score_filelog = structlog.get_logger(__name__)@@ -314,6 +314,10 @@ class HealthAnalyzer:cfg = config or {}disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}+ repo_severity_overrides: dict[str, Severity] = cfg.get("severity_overrides", {}) or {}+ per_file_severity_overrides: dict[str, dict[str, Severity]] = (+ cfg.get("per_file_severity_overrides", {}) or {}+ )changed_set: set[str] | None = set(changed_files) if changed_files is not None else None# PageRank is optional — graph_builder.symbol_pagerank exists but@@ -384,6 +388,8 @@ class HealthAnalyzer:for name in extra:if name not in file_disabled:file_disabled.append(name)+ file_severity_overrides = dict(repo_severity_overrides)+ file_severity_overrides.update(per_file_severity_overrides.get(pf.file_info.path, {}))file_metric, file_findings = self._evaluate_file(pf,fcx,@@ -395,6 +401,7 @@ class HealthAnalyzer:repo_function_mod_p80=repo_fn_mod_p80,repo_dependents_p80=repo_dependents_p80,repo_active_contributors_90d=repo_active_contributors,+ severity_overrides=file_severity_overrides or None,)metrics.append(file_metric)findings.extend(file_findings)@@ -443,6 +450,10 @@ class HealthAnalyzer:cfg = config or {}disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}+ repo_severity_overrides: dict[str, Severity] = cfg.get("severity_overrides", {}) or {}+ per_file_severity_overrides: dict[str, dict[str, Severity]] = (+ cfg.get("per_file_severity_overrides", {}) or {}+ )changed_set: set[str] | None = set(changed_files) if changed_files is not None else Nonepath_basenames = _path_basenames({pf.file_info.path for pf in self.parsed_files})@@ -529,6 +540,8 @@ class HealthAnalyzer:for name in extra:if name not in file_disabled:file_disabled.append(name)+ file_severity_overrides = dict(repo_severity_overrides)+ file_severity_overrides.update(per_file_severity_overrides.get(pf.file_info.path, {}))file_metric, file_findings = self._evaluate_file(pf,fcx,@@ -540,6 +553,7 @@ class HealthAnalyzer:repo_function_mod_p80=repo_fn_mod_p80,repo_dependents_p80=repo_dependents_p80,repo_active_contributors_90d=repo_active_contributors,+ severity_overrides=file_severity_overrides or None,)metrics.append(file_metric)findings.extend(file_findings)@@ -659,6 +673,7 @@ class HealthAnalyzer:repo_function_mod_p80: int | None = None,repo_dependents_p80: int | None = None,repo_active_contributors_90d: int | None = None,+ severity_overrides: dict[str, Severity] | None = None,) -> tuple[HealthFileMetricData, list[HealthFindingData]]:file_path = pf.file_info.path@@ -723,6 +738,7 @@ class HealthAnalyzer:)biomarker_results = detect_all(ctx, disabled=disabled)+ biomarker_results = remap_severities(biomarker_results, severity_overrides)scores, deductions = score_file(biomarker_results)findings = attach_impacts(biomarker_results, deductions)for f in findings:diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex 104883a00..f5bec726a 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -20,6 +20,7 @@ empirical predictors are no longer suppressed by uniform severity values.from __future__ import annotationsfrom collections.abc import Callable, Iterable+from dataclasses import replacefrom .biomarkers.base import BiomarkerResultfrom .models import HealthFileMetricData, HealthFindingData, Severity@@ -482,6 +483,32 @@ def _score_dimension(return score, per_result+def remap_severities(+ results: list[BiomarkerResult],+ overrides: dict[str, Severity] | None,+) -> list[BiomarkerResult]:+ """Return *results* with biomarker severities relabeled per *overrides*.++ A user ``severity_overrides`` map (from ``.repowise/health-rules.json``)+ relabels a biomarker's severity, which changes its deduction via the fixed+ ``_SEVERITY_DEDUCTION`` table — the only sanctioned tuning knob. Numeric+ weight multipliers and category caps are NEVER affected (they are the+ calibrated constants the benchmark rests on). Findings that carry a+ continuous ``deduction`` override (``coverage_gradient``) are left+ untouched: their magnitude does not come from the severity table.+ """+ if not overrides:+ return results+ out: list[BiomarkerResult] = []+ for r in results:+ target = overrides.get(r.biomarker_type)+ if target is not None and r.deduction is None and target != r.severity:+ out.append(replace(r, severity=target))+ else:+ out.append(r)+ return out++def score_file(results: Iterable[BiomarkerResult]) -> tuple[dict[str, float | None], list[float]]:"""Aggregate biomarker hits into per-dimension scores in ``[1.0, 10.0]``.diff --git a/tests/unit/health/test_health_config.py b/tests/unit/health/test_health_config.pyindex a225a043f..f688848f3 100644--- a/tests/unit/health/test_health_config.py+++ b/tests/unit/health/test_health_config.py@@ -6,6 +6,7 @@ import jsonfrom pathlib import Pathfrom repowise.core.analysis.health.config import HealthConfig+from repowise.core.analysis.health.models import Severitydef _write(tmp_path: Path, payload: dict) -> Path:@@ -93,6 +94,72 @@ def test_glob_and_path_glob_aliases_accepted(tmp_path: Path):assert pfd["src/legacy/old.py"] == {"dry_violation"}+def test_repo_wide_severity_overrides_parsed_and_normalized(tmp_path: Path):+ _write(+ tmp_path,+ {"severity_overrides": {"complex_method": "low", "god_class": "MEDIUM"}},+ )+ cfg = HealthConfig.load(tmp_path)+ assert cfg.severity_overrides == {+ "complex_method": Severity.LOW,+ "god_class": Severity.MEDIUM,+ }+ out = cfg.to_analyzer_config(["src/foo.py"])+ assert out["severity_overrides"] == {+ "complex_method": Severity.LOW,+ "god_class": Severity.MEDIUM,+ }+++def test_invalid_severity_value_dropped(tmp_path: Path):+ _write(+ tmp_path,+ {"severity_overrides": {"complex_method": "bogus", "god_class": "high"}},+ )+ cfg = HealthConfig.load(tmp_path)+ assert cfg.severity_overrides == {"god_class": Severity.HIGH}+++def test_per_path_severity_overrides_materialize(tmp_path: Path):+ _write(+ tmp_path,+ {+ "rules": [+ {"path": "src/legacy/*", "severity_overrides": {"large_method": "low"}},+ ]+ },+ )+ cfg = HealthConfig.load(tmp_path)+ pfso = cfg.per_file_severity_overrides(["src/legacy/old.py", "src/modern/api.py"])+ assert pfso["src/legacy/old.py"] == {"large_method": Severity.LOW}+ assert "src/modern/api.py" not in pfso+++def test_small_team_profile_expands_with_explicit_override_winning(tmp_path: Path):+ _write(+ tmp_path,+ {+ "profile": "small-team",+ # Explicit entry overrides the profile preset for this biomarker.+ "severity_overrides": {"ownership_risk": "medium"},+ },+ )+ cfg = HealthConfig.load(tmp_path)+ assert cfg.profile == "small-team"+ resolved = cfg.to_analyzer_config([])["severity_overrides"]+ # Preset entry present...+ assert resolved["developer_congestion"] == Severity.LOW+ # ...and the explicit key won over the preset's ownership_risk=LOW.+ assert resolved["ownership_risk"] == Severity.MEDIUM+++def test_unknown_profile_ignored(tmp_path: Path):+ _write(tmp_path, {"profile": "enterprise"})+ cfg = HealthConfig.load(tmp_path)+ assert cfg.profile is None+ assert cfg.to_analyzer_config([])["severity_overrides"] == {}++def test_malformed_file_falls_back_silently(tmp_path: Path):repowise = tmp_path / ".repowise"repowise.mkdir()diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.pyindex a3d7005bf..556992351 100644--- a/tests/unit/health/test_scoring.py+++ b/tests/unit/health/test_scoring.py@@ -7,6 +7,7 @@ from repowise.core.analysis.health.models import HealthFileMetricData, Severityfrom repowise.core.analysis.health.scoring import (CATEGORY_CAPS,compute_kpis,+ remap_severities,score_file,)@@ -23,6 +24,42 @@ def _r(name: str, severity: Severity) -> BiomarkerResult:)+def test_remap_severities_demotes_and_lowers_deduction():+ # A HIGH complex_method deducts more than a LOW one; remapping to LOW+ # must raise the resulting score (smaller deduction).+ high = [_r("complex_method", Severity.HIGH)]+ base_score, _ = score_file(high)+ remapped = remap_severities(high, {"complex_method": Severity.LOW})+ low_score, _ = score_file(remapped)+ assert low_score["defect"] > base_score["defect"]+ # Original list is not mutated in place.+ assert high[0].severity is Severity.HIGH+++def test_remap_severities_noop_without_overrides():+ results = [_r("complex_method", Severity.HIGH)]+ assert remap_severities(results, None) is results+ assert remap_severities(results, {}) is results+++def test_remap_severities_skips_continuous_deduction_findings():+ # coverage_gradient-style findings carry a ``deduction`` override; their+ # magnitude is not severity-derived, so a remap must not touch them.+ r = BiomarkerResult(+ biomarker_type="coverage_gradient",+ severity=Severity.HIGH,+ function_name=None,+ line_start=1,+ line_end=10,+ details={},+ reason="",+ deduction=2.0,+ )+ out = remap_severities([r], {"coverage_gradient": Severity.LOW})+ assert out[0] is r # untouched+ assert out[0].deduction == 2.0++def test_score_clean_file_is_ten():scores, deductions = score_file([])assert scores["defect"] == 10.0diff --git a/tests/unit/health/test_severity_overrides_integration.py b/tests/unit/health/test_severity_overrides_integration.pynew file mode 100644index 000000000..9f503d6d3--- /dev/null+++ b/tests/unit/health/test_severity_overrides_integration.py@@ -0,0 +1,76 @@+"""End-to-end: ``severity_overrides`` flows config -> engine -> score.++Proves the wiring between ``HealthConfig.to_analyzer_config`` and the engine's+per-file remap (``_evaluate_file(severity_overrides=...)``), not just the two+ends in isolation.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.duplication import DuplicationReport+from repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.models import Severity++# A single high-CCN function: many independent branches drive ccn >= 9, which+# trips ``complex_method`` (HIGH-ish). Demoting its severity must raise the+# file score.+_HIGH_CCN_SOURCE = b"""+def tangled(x):+ total = 0+ if x == 1:+ total += 1+ elif x == 2:+ total += 2+ elif x == 3:+ total += 3+ elif x == 4:+ total += 4+ elif x == 5:+ total += 5+ elif x == 6:+ total += 6+ elif x == 7:+ total += 7+ elif x == 8:+ total += 8+ elif x == 9:+ total += 9+ return total+"""+++def _evaluate(severity_overrides):+ fcx = walk_file("/tmp/tangled.py", "python", _HIGH_CCN_SOURCE)+ if fcx.file_nloc == 0 or not fcx.functions:+ pytest.skip("python tree-sitter pack missing")+ pf = SimpleNamespace(+ file_info=SimpleNamespace(+ path="src/tangled.py", language="python", abs_path="/tmp/tangled.py"+ ),+ symbols=[],+ )+ metric, findings = HealthAnalyzer(graph=None)._evaluate_file(+ pf,+ fcx,+ path_basenames=set(),+ disabled=[],+ dup_report=DuplicationReport(),+ severity_overrides=severity_overrides,+ )+ return metric, findings+++def test_complex_method_fires_then_demotion_raises_score():+ base_metric, base_findings = _evaluate(None)+ types = {f.biomarker_type for f in base_findings}+ if "complex_method" not in types:+ pytest.skip("complex_method did not fire on the fixture")++ demoted_metric, _ = _evaluate({"complex_method": Severity.LOW})+ # Demoting the only meaningful finding to LOW deducts less -> higher score.+ assert demoted_metric.defect_score > base_metric.defect_score