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
fix(health): use gross gap as share_of_repo_gap_pct denominator (#1452)
404 Ameyyb44f07b04925
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 55a114e83..25898728f 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -624,7 +624,10 @@ per-dimension scores, and the score breakdown. Each finding carries a `dimension**Lead with `directive`.** Dashboard mode opens with the single file to fixfirst, its dominant finding, `recovers_points` / `share_of_repo_gap_pct` (what-fixing it buys the headline), and `then`, the next two by leverage. Every other+fixing it buys the headline; the share is bounded by 100% and sums to 100%+across `high_leverage_files` — the gross deficit of below-target files is the+denominator, not the net gap, so a single file cannot read as closing more than+the whole remaining gap), and `then`, the next two by leverage. Every otherblock ranks and describes; this one recommends. Same role as `get_risk`'s`directive`. Rank by `weighted_deficit`, not `score` — the score floors at 1.0.@@ -689,8 +692,10 @@ make that actionable rather than a mystery:`gap_analysis.weighted_gap_points` share one unit — *score-points x NLOC* —which compares against itself and nothing else. Every `high_leverage_files`row and the `directive` also carry `share_of_repo_gap_pct`, the same quantity- with a denominator; that plus `gap_analysis.files_to_reach_target` is what- answers "is this worth doing".+ over the gross deficit of all below-target files+ (`gap_analysis.weighted_gross_gap_points`), so the shares are bounded by 100%+ and sum to 100% by construction; that plus+ `gap_analysis.files_to_reach_target` is what answers "is this worth doing".- `kpis.non_code_files` and `kpis.average_health_code_only` say how much of theheadline is markdown/JSON/YAML. No biomarker walks those files, so they scorea mechanical 10.0 meaning "nothing looked at this" — on this repo, 233 ofdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 0b4f74936..c026f494d 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -605,9 +605,14 @@ def _directive("reason": lead.get("primary_reason") or f"scores {round(top.score, 2)}",# Points the repo headline recovers if this one file reaches Healthy,# and what share of the total gap that is — the "few files, not the- # long tail" argument made concrete for a single file.+ # long tail" argument made concrete for a single file. The denominator+ # is the *gross* deficit of all below-target files (not the net gap,+ # which healthy files cushion): per-file shares are then bounded by+ # 100% and sum to 100% by construction (issue #1437)."recovers_points": recovers,- "share_of_repo_gap_pct": (round(100.0 * recovers / gap_points, 1) if gap_points else None),+ "share_of_repo_gap_pct": (+ round(100.0 * recovers / gap_points, 1) if gap_points else None+ ),"then": [m.file_path for m in by_leverage[1:3]],# Projected, not bare. ``include`` adds a block without subtracting the# dashboard, and five ranked lists at the default ``limit`` compose: the@@ -672,12 +677,26 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:"""How few files must reach 8.0 for the *weighted average* to reach 8.0.Answers what the bare KPI cannot: the NLOC-weighted average is held down by a- *few large low-scoring files*, not the long tail. The gap here is the **net**- points the average needs (``8.0 * total_nloc - Σ score*nloc``) — healthy files- already sit above 8.0 and cushion it, so this is smaller than the gross- all-files-healthy deficit and is the number that matches the goal "move the- average". ``files_to_reach_target`` is the punchline: lift the worst-deficit N- files to 8.0 and the headline crosses 8.0. Pure over the metrics in hand.+ *few large low-scoring files*, not the long tail. Two gaps are computed and+ kept deliberately distinct:++ - ``weighted_gap_points`` — the **net** points the average needs+ (``8.0 * total_nloc - Σ score*nloc``). Healthy files already sit above 8.0+ and cushion it, so this is smaller than the gross all-files-healthy+ deficit and is the number that matches the goal "move the average".+ ``files_to_reach_target`` is the punchline: lift the worst-deficit N files+ to 8.0 and the headline crosses 8.0. This can be 0 or negative on a+ mostly-healthy repo (the average is already above 8.0).+ - ``weighted_gross_gap_points`` — the **gross** deficit,+ ``Σ max(8.0 - score, 0) * nloc`` over files below 8.0. This is the+ denominator ``share_of_repo_gap_pct`` uses: it is positive whenever any+ file is below target (unlike the net gap), so a share is meaningful even+ when the average is already healthy, and per-file shares sum to exactly+ 100% by construction. The net gap is not used there precisely because+ healthy files cushion it — one large low file could then read as closing+ more than the whole remaining gap (issue #1437).++ Pure over the metrics in hand."""total_nloc = sum(max(m.nloc, 1) for m in metrics)weighted_sum = sum(m.score * max(m.nloc, 1) for m in metrics)@@ -690,11 +709,13 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:),reverse=True,)- if net_gap <= 0 or not below:+ gross_gap = sum(below)+ if not below:return {"target_score": HEALTHY_MIN,"weighted_gap_points": 0,- "files_below_target": len(below),+ "weighted_gross_gap_points": 0,+ "files_below_target": 0,"files_to_reach_target": 0,"files_for_half_gap": 0,}@@ -707,15 +728,23 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:return ireturn len(below)+ # ``files_to_reach_target`` needs the net gap to mean "the headline crosses+ # 8.0". When the net gap is <= 0 (average already healthy) there is nothing+ # to reach, so those fields are 0 — but the gross gap is still reported+ # because per-file shares are meaningful whenever any file is below target.+ reachable = max(net_gap, 0)return {"target_score": HEALTHY_MIN,# Net weighted points the average must recover to reach 8.0.- "weighted_gap_points": round(net_gap),+ "weighted_gap_points": round(max(net_gap, 0)),+ # Gross deficit of all below-target files: the share_of_repo_gap_pct+ # denominator (see docstring for why it is not the net gap).+ "weighted_gross_gap_points": round(gross_gap),"files_below_target": len(below),# The reframe: lift this many worst-deficit files to 8.0 and the weighted# average reaches 8.0; half that gap needs even fewer.- "files_to_reach_target": _files_for(net_gap),- "files_for_half_gap": _files_for(0.5 * net_gap),+ "files_to_reach_target": _files_for(reachable),+ "files_for_half_gap": _files_for(0.5 * reachable),}@@ -1448,7 +1477,7 @@ async def get_health("directive": _directive(by_leverage,leads,- gap.get("weighted_gap_points") or 0,+ gap.get("weighted_gross_gap_points") or 0,plan_biomarkers_by_path,plan_count_by_path,),@@ -1472,7 +1501,11 @@ async def get_health(# one place ``weighted_deficit`` gets a denominator. The bare number# is score-points x NLOC and answers "which is bigger" but never "is# this worth doing"; the same quantity as a share of the repo's total- # gap does, and it is the unit ``directive`` already speaks.+ # gap does, and it is the unit ``directive`` already speaks. The+ # denominator is the gross deficit of all below-target files, so a+ # share is bounded by 100% and the rows sum to 100% by construction+ # — the net gap would let healthy files cushion the total and push a+ # single large file over 100% (issue #1437)."high_leverage_files": [{**_serialize_metric(@@ -1483,10 +1516,10 @@ async def get_health(100.0* max(HEALTHY_MIN - m.score, 0.0)* max(m.nloc, 1)- / gap["weighted_gap_points"],+ / gap["weighted_gross_gap_points"],1,)- if gap.get("weighted_gap_points")+ if gap.get("weighted_gross_gap_points")else None),}diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 9dba3915c..8d38c92a9 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -369,12 +369,204 @@ async def test_get_health_dashboard_leads_with_a_directive(setup_mcp, health_datassert d["fix_first"] == "src/auth/service.py"assert d["reason"] == "authenticate has cyclomatic complexity 15"assert d["recovers_points"] == 700 # (8.0 - 4.5) * 200- # 700 of the repo's 675 net gap points: the healthy file's surplus is- # credited in the denominator, so one file can exceed 100%.- assert d["share_of_repo_gap_pct"] == pytest.approx(103.7)+ # The only below-target file holds the whole gross deficit (700/700), so+ # the share is 100% by construction — the net gap (675) is not the+ # denominator, since healthy files would cushion it (issue #1437).+ assert d["share_of_repo_gap_pct"] == pytest.approx(100.0)assert d["then"] == [] # only one below-target file in the fixture+async def test_directive_share_bounded_when_gross_exceeds_net_gap(+ session, setup_mcp+):+ """Regression guard for #1437: the share uses the gross deficit of all+ below-target files as its denominator, so it is bounded by 100% and sums to+ 100% by construction — the net gap (which healthy files cushion) would let+ a single file read as closing more than the whole remaining gap."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ rid = setup_mcp+ await save_health_metrics(+ session,+ rid,+ [+ # One big low file: gross deficit (8.0 - 3.0) * 400 = 2000.+ {+ "file_path": "src/legacy/blob.py",+ "score": 3.0,+ "max_ccn": 20,+ "max_nesting": 6,+ "nloc": 400,+ "has_test_file": False,+ "module": "legacy",+ "defect_score": 3.0,+ "maintainability_score": 4.0,+ "performance_score": 8.0,+ },+ # Many small healthy files: surplus 8.5-8.0 = 0.5 * 100 each.+ *[+ {+ "file_path": f"src/ok/module{i}.py",+ "score": 8.5,+ "max_ccn": 3,+ "max_nesting": 1,+ "nloc": 100,+ "has_test_file": True,+ "module": "ok",+ "defect_score": 8.5,+ "maintainability_score": 9.0,+ "performance_score": 10.0,+ }+ for i in range(4)+ ],+ ],+ )++ result = await get_health()+ d = result["directive"]+ # Net gap = 8.0*800 - (3.0*400 + 8.5*400) = 6400 - 4600 = 1800, and the+ # single below-target file owns the whole gross deficit: 2000/2000 = 100%.+ assert d["recovers_points"] == 2000+ assert d["share_of_repo_gap_pct"] == pytest.approx(100.0)+ # The gross gap is the reported denominator.+ assert result["gap_analysis"]["weighted_gross_gap_points"] == 2000+ assert result["gap_analysis"]["weighted_gap_points"] == 1800+++async def test_directive_absent_when_no_file_below_target(+ session, setup_mcp+):+ """When no file is below the Healthy floor there is no gross gap, nothing to+ recommend, and no share to report — the directive is absent entirely."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ rid = setup_mcp+ await save_health_metrics(+ session,+ rid,+ [+ {+ "file_path": "src/ok/module.py",+ "score": 8.5,+ "max_ccn": 3,+ "max_nesting": 1,+ "nloc": 100,+ "has_test_file": True,+ "module": "ok",+ "defect_score": 8.5,+ "maintainability_score": 9.0,+ "performance_score": 10.0,+ }+ ],+ )++ result = await get_health()+ # No file is below the Healthy floor, so there is nothing to recommend and+ # no gross gap to share — the directive is absent entirely.+ assert result["directive"] is None+ assert result["gap_analysis"]["weighted_gross_gap_points"] == 0+++async def test_high_leverage_rows_sum_to_100_with_negative_net_gap(+ session, setup_mcp+):+ """The microdot scenario from #1437: several files below target against a+ negative net gap. The gross gap is the denominator, so rows are distinct,+ each bounded by 100%, and they sum to 100% by construction — whereas the+ net gap (0, since the average is above 8.0) would report nothing at all."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ rid = setup_mcp+ await save_health_metrics(+ session,+ rid,+ [+ # Three below-target files of different sizes.+ {+ "file_path": "src/a/big.py",+ "score": 6.0,+ "max_ccn": 10,+ "max_nesting": 4,+ "nloc": 400,+ "has_test_file": False,+ "module": "a",+ "defect_score": 6.0,+ "maintainability_score": 7.0,+ "performance_score": 9.0,+ },+ {+ "file_path": "src/b/mid.py",+ "score": 7.0,+ "max_ccn": 6,+ "max_nesting": 3,+ "nloc": 200,+ "has_test_file": False,+ "module": "b",+ "defect_score": 7.0,+ "maintainability_score": 8.0,+ "performance_score": 9.5,+ },+ {+ "file_path": "src/c/small.py",+ "score": 7.5,+ "max_ccn": 4,+ "max_nesting": 2,+ "nloc": 100,+ "has_test_file": True,+ "module": "c",+ "defect_score": 7.5,+ "maintainability_score": 8.5,+ "performance_score": 10.0,+ },+ # One healthy file, large enough that the weighted average is+ # already above 8.0 (negative net gap — the microdot shape).+ {+ "file_path": "src/d/ok.py",+ "score": 9.0,+ "max_ccn": 2,+ "max_nesting": 1,+ "nloc": 1200,+ "has_test_file": True,+ "module": "d",+ "defect_score": 9.0,+ "maintainability_score": 9.5,+ "performance_score": 10.0,+ },+ ],+ )++ result = await get_health()+ gap = result["gap_analysis"]+ rows = result["high_leverage_files"]+ assert len(rows) == 3++ # Gross deficits: (8-6)*400=800, (8-7)*200=200, (8-7.5)*100=50 → 1050.+ assert gap["weighted_gross_gap_points"] == 1050+ # Net gap is negative: 8*1900 - (6*400+7*200+7.5*100+9*1200) = 15200 - 15350.+ assert gap["weighted_gap_points"] == 0+ # Rows are distinct (ranking survives) and bounded, summing to 100%.+ shares = {r["file_path"]: r["share_of_repo_gap_pct"] for r in rows}+ assert shares == pytest.approx(+ {+ "src/a/big.py": round(100.0 * 800 / 1050, 1),+ "src/b/mid.py": round(100.0 * 200 / 1050, 1),+ "src/c/small.py": round(100.0 * 50 / 1050, 1),+ }+ )+ assert len({v for v in shares.values()}) == 3 # distinct, not collapsed+ assert sum(shares.values()) == pytest.approx(100.0, abs=0.1)+ # The directive quotes the same lead-file share.+ assert result["directive"]["share_of_repo_gap_pct"] == pytest.approx(+ shares["src/a/big.py"], abs=0.1+ )++@pytest.mark.asyncioasync def test_get_health_only_projects_the_response(setup_mcp, health_data):"""``only`` subtracts blocks; ``include`` could only ever add them."""@@ -1252,13 +1444,14 @@ async def test_high_leverage_rows_carry_share_of_repo_gap(setup_mcp, health_datafrom repowise.server.mcp_server import get_healthresult = await get_health()- gap = result["gap_analysis"]["weighted_gap_points"]+ gap = result["gap_analysis"]["weighted_gross_gap_points"]rows = result["high_leverage_files"]assert rows, "fixture must have at least one file below the healthy band"for row in rows:- assert row["share_of_repo_gap_pct"] == pytest.approx(- round(100.0 * row["weighted_deficit"] / gap, 1), abs=0.11- )+ expected = round(100.0 * row["weighted_deficit"] / gap, 1)+ # Shares are bounded by 100% and sum to 100% by construction: the gross+ # deficit of all below-target files is the denominator (issue #1437).+ assert row["share_of_repo_gap_pct"] == pytest.approx(expected, abs=0.11)# The lead file's share is the same number the directive quotes. Not exact# equality: `_directive` rounds `recovers_points` to an integer before# dividing, the row divides the raw deficit, so the two agree to the