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): say when a file's history is too short to count beside its score (#4117)
Raghav Chamadiya9f34e7c2beea
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex b5d54ff79..948f4c5e3 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -377,7 +377,7 @@ Items are ordered by value first, then tier. History markers (churn, ownership,| `worst_files`, `test_worst_files` | Lowest raw scores, production and test || `high_leverage_files` | Ranked by `weighted_deficit`, with `share_of_repo_gap_pct` || `top_findings` / `findings`, `test_findings` | Production and test findings; their totals sum to the whole open set |-| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction` and `history_deduction` (the score is 10 minus both, before the 1.0 floor; history reads 0.0 under `counts="code_shape"`), and `withheld_deduction` when part of it comes from a withheld finding type |+| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction` and `history_deduction` (the score is 10 minus both, before the 1.0 floor; history reads 0.0 under `counts="code_shape"`), `history: "short"` only when the file has fewer than 5 recorded commits (new, split out, or renamed without follow), where most history markers cannot fire yet, and `withheld_deduction` when part of it comes from a withheld finding type |`weighted_deficit` and the gap fields share one unit, score points x NLOC; they compare only with each other. Non-code files score a mechanical 10.0 because no marker reads them; `average_health_code_only` shows the headline without them. `primary_biomarker` prefers a discrete finding over the continuous `coverage_gradient`. Each finding carries a `dimension`; `advisory` findings (`assertion_free_test`, `mock_saturated_test`) never deduct and appear only with `include=["advisory"]`.diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 33d5cfd60..cab5f5260 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -40,6 +40,7 @@ from repowise.core.analysis.health.ranking import deduction_by_pathfrom repowise.core.analysis.health.rows import detail_map, split_unscoredfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scopefrom repowise.core.analysis.health.scoring import compute_kpis+from repowise.core.analysis.health.signals import HISTORY_MIN_COMMITSfrom repowise.core.persistence.crud.analysis.health import open_finding_countfrom .codegen import _generate_refactoring_code@@ -48,6 +49,7 @@ from .persist import (_load_persisted_coverage_map,_load_queue_counts,_load_recommendations,+ _load_short_history,_load_stored_report,_persist_health,)@@ -431,6 +433,7 @@ def _render_json(repo_path: Path, report: Any, metrics_sorted: list[Any], findings: list[Any], opts: _Options) -> None:excluded = excluded_types()+ short_history = _load_short_history(repo_path)click.echo(json.dumps({@@ -440,20 +443,7 @@ def _render_json(# Findings, causes, plans and Fix first items, as every# surface counts them; ``shown`` is 0, nothing is listed."queue_counts": _load_queue_counts(repo_path),- "metrics": [- {- "file_path": m.file_path,- "score": m.score,- "max_ccn": m.max_ccn,- "max_nesting": m.max_nesting,- "nloc": m.nloc,- "has_test_file": m.has_test_file,- "line_coverage_pct": m.line_coverage_pct,- "branch_coverage_pct": m.branch_coverage_pct,- "duplication_pct": m.duplication_pct,- }- for m in metrics_sorted- ],+ "metrics": [_json_metric(m, short_history) for m in metrics_sorted],"findings": [{"biomarker_type": f.biomarker_type,@@ -473,6 +463,21 @@ def _render_json()+def _json_metric(m: Any, short_history: set[str]) -> dict[str, Any]:+ return {+ "file_path": m.file_path,+ "score": m.score,+ "max_ccn": m.max_ccn,+ "max_nesting": m.max_nesting,+ "nloc": m.nloc,+ "has_test_file": m.has_test_file,+ "line_coverage_pct": m.line_coverage_pct,+ "branch_coverage_pct": m.branch_coverage_pct,+ "duplication_pct": m.duplication_pct,+ **({"history": "short"} if m.file_path in short_history else {}),+ }++def _render_md(report: Any, findings: list[Any]) -> None:click.echo("# Code Health Report\n")for k, v in report.kpis.items():@@ -508,7 +513,7 @@ def _render_table(# Lead with the finding count, density and coverage, not the bounded /10# average. Metrics carry no language, so it comes with the report._render_performance_section(report, findings, languages)- _render_files_table(metrics_sorted)+ _render_files_table(metrics_sorted, _load_short_history(repo_path))_render_findings_table(findings)@@ -545,7 +550,7 @@ def _render_headline(kpis: dict[str, Any], code_shape: bool, unanalysed: int) ->console.print(f"[dim]Code health {note}.[/dim]")-def _render_files_table(metrics_sorted: list[Any]) -> None:+def _render_files_table(metrics_sorted: list[Any], short_history: set[str]) -> None:from repowise.core.analysis.health.grading import BAND_TERMINAL_COLOR, band_fortable = Table(title=f"Lowest-scoring files ({min(len(metrics_sorted), 20)})")@@ -559,13 +564,19 @@ def _render_files_table(metrics_sorted: list[Any]) -> None:score_color = BAND_TERMINAL_COLOR[band_for(m.score)]table.add_row(m.file_path,- f"[{score_color}]{m.score:.1f}[/{score_color}]",+ f"[{score_color}]{m.score:.1f}[/{score_color}]"+ + ("*" if m.file_path in short_history else ""),str(m.max_ccn),str(m.max_nesting),str(m.nloc),"✓" if m.has_test_file else "—",)console.print(table)+ if any(m.file_path in short_history for m in metrics_sorted[:20]):+ console.print(+ f"[dim]* Short history (under {HISTORY_MIN_COMMITS} commits): most history "+ "markers need more, so the score is mostly code shape.[/dim]"+ )def _render_findings_table(findings: list[Any]) -> None:diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex b9c76624b..bd43eaa19 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -96,6 +96,27 @@ def _load_queue_counts(repo_path: object) -> dict[str, Any] | None:return None+def _load_short_history(repo_path: object) -> set[str]:+ """Files whose recorded history is too thin to count; empty when the store cannot answer."""+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.cli.helpers import repo_index_session+ from repowise.core.persistence.crud import get_short_history_paths++ async def _do() -> set[str]:+ async with repo_index_session(Path(str(repo_path))) as opened:+ if opened is None:+ return set()+ session, repo_id = opened+ return await get_short_history_paths(session, repo_id)++ try:+ return run_async(_do())+ except (SQLAlchemyError, OSError):+ # A marker beside the score, never a reason to fail the report.+ return set()++def _load_stored_report(repo_path: object) -> tuple[Any, set[str], dict[str, str]] | None:"""The health analysis the last ``init``/``update`` stored, read without writing.diff --git a/packages/core/src/repowise/core/analysis/health/signals.py b/packages/core/src/repowise/core/analysis/health/signals.pyindex cb966c71a..32c711070 100644--- a/packages/core/src/repowise/core/analysis/health/signals.py+++ b/packages/core/src/repowise/core/analysis/health/signals.py@@ -28,6 +28,11 @@ from typing import Protocol# these", short enough to sit inside an MCP response without a budget argument._TOP_FIX_SYMBOLS = 5+#: Below this many recorded commits churn and the blame-based markers cannot fire+#: and the rest rarely do, so the history half reads near zero whatever the past:+#: a new file, one split out of another, or a rename git did not follow.+HISTORY_MIN_COMMITS = 5+class GitMetaLike(Protocol):"""The git-metadata fields the signals view reads (duck-typed).@@ -84,6 +89,8 @@ class FileSignals:bug_magnet: bool | Nonelast_fix_at: str | Nonefix_symbol_counts: dict[str, int] | None+ # ``"short"`` below ``HISTORY_MIN_COMMITS`` recorded commits.+ history: str | None@propertydef has_any(self) -> bool:@@ -143,6 +150,18 @@ def _top_fix_symbols(raw: str | None) -> dict[str, int] | None:return {str(k): int(v) for k, v in list(counts.items())[:_TOP_FIX_SYMBOLS]}+def history_basis(git_meta: object | None) -> str | None:+ """``"short"`` below :data:`HISTORY_MIN_COMMITS` recorded commits, else ``None``.++ ``None`` too when nothing was recorded (no row, no count) or the row is a+ non-code file's, which carries no score to qualify.+ """+ total = getattr(git_meta, "commit_count_total", None)+ if total is None or getattr(git_meta, "history_only", False):+ return None+ return "short" if total < HISTORY_MIN_COMMITS else None++def file_signals(git_meta: GitMetaLike | None,degrees: dict[str, int] | None,@@ -185,4 +204,5 @@ def file_signals(fix_symbol_counts=_top_fix_symbols(getattr(g, "fix_symbol_counts_json", None))if gelse None,+ history=history_basis(g),)diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 11d1a6bd2..65e0f19c5 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -14,6 +14,8 @@ from sqlalchemy import ColumnElement, and_, delete, func, or_, select, text, updfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import AsyncSession+from ...analysis.health.signals import HISTORY_MIN_COMMITS as _HISTORY_MIN_COMMITS+from ...analysis.health.signals import history_basis as _history_basisfrom ...co_change import CoChangePartner, parse_partnersfrom ..models import (Change,@@ -167,6 +169,19 @@ async def get_hotspot_file_paths(session: AsyncSession, repository_id: str) -> sreturn {row[0] for row in result.all() if row[0] is not None}+async def get_short_history_paths(session: AsyncSession, repository_id: str) -> set[str]:+ """The files whose recorded history ``signals.history_basis`` reads as short."""+ result = await session.execute(+ select(+ GitMetadata.file_path, GitMetadata.commit_count_total, GitMetadata.history_only+ ).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.commit_count_total < _HISTORY_MIN_COMMITS,+ )+ )+ return {row.file_path for row in result.all() if _history_basis(row)}++#: The only git fields dead-code confidence is scored from#: (``analyzer._make_unreachable_finding`` and its sibling detectors)._DEAD_CODE_GIT_FIELDS = (diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.pyindex 42d5efb79..2ffd84c4c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py@@ -9,7 +9,7 @@ from repowise.core.analysis.health.aggregation import module_rollups as _module_from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracyfrom repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.health.grading import distribution as health_distribution-from repowise.server.mcp_server.tool_health.loading import HealthData+from repowise.server.mcp_server.tool_health.loading import HealthData, history_offrom repowise.server.mcp_server.tool_health.paging import Pagerfrom repowise.server.mcp_server.tool_health.request import FIX_FIRST_CAP, HealthRequestfrom repowise.server.mcp_server.tool_health.serialize import _serialize_finding, _serialize_metric@@ -170,7 +170,12 @@ def _finding_rows(data: HealthData, rows: list[Any]) -> list[dict[str, Any]]:def _metric_row(data: HealthData, m: Any) -> dict[str, Any]:- return _serialize_metric(m, data.leads.get(m.file_path), is_test=m.file_path in data.test_paths)+ return _serialize_metric(+ m,+ data.leads.get(m.file_path),+ is_test=m.file_path in data.test_paths,+ history=history_of(data, m.file_path),+ )def _high_leverage_rows(data: HealthData, gap: dict[str, Any]) -> list[dict[str, Any]]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.pyindex 62cfed81e..9515d95ce 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py@@ -36,6 +36,7 @@ from repowise.core.persistence.crud import (get_git_metadata_bulk,get_hotspot_file_paths,get_node_degree_counts_bulk,+ get_short_history_paths,get_test_file_paths,list_health_snapshots,load_coverage_for_repo,@@ -114,6 +115,8 @@ class HealthData:gated: dict[str, dict] = field(default_factory=dict)#: Open findings of a withheld type: never listed, but the score counted them.withheld_rows: list[Any] = field(default_factory=list)+ #: Files whose recorded history is too thin for the history half to count.+ short_history_paths: set[str] = field(default_factory=set)async def load_health_data(@@ -177,6 +180,8 @@ async def load_health_data(session, repository, pop, req)data.signals_by_path = await _read_signals(session, repository, pop, req)+ if _lists_file_rows(req):+ data.short_history_paths = await get_short_history_paths(session, repository.id)data.drift_rows, data.drift_unavailable = await _read_doc_drift(session, repository, pop, req)@@ -220,6 +225,17 @@ async def _read_gated(session: Any, req: HealthRequest, data: HealthData) -> dicreturn {layer: counts for layer, counts in layers.items() if counts}+def history_of(data: HealthData, path: str) -> str | None:+ """A file row's ``history`` value: ``"short"`` or absent."""+ return "short" if path in data.short_history_paths else None+++def _lists_file_rows(req: HealthRequest) -> bool:+ return any(+ req.wants(k) for k in ("metrics", "worst_files", "test_worst_files", "high_leverage_files")+ )++def _scope_reasons(metrics: list[HealthFileMetric]) -> dict[str, str | None]:"""Each file's scope exclusion (``test``, ``tooling``, ``generated``...), ``None``in scope: Fix first's rule on Fix first's inputs, the row's flag and origin.diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.pyindex ea332ab8e..a0e809ce5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py@@ -165,6 +165,7 @@ def _serialize_metric(lead: dict[str, Any] | None = None,*,is_test: bool = False,+ history: str | None = None,) -> dict[str, Any]:return {"file_path": m.file_path,@@ -188,6 +189,8 @@ def _serialize_metric(# The score's two halves (``10 - structure - history``, before the floor)."structure_deduction": _round_opt(getattr(m, "structure_deduction", None)),"history_deduction": _round_opt(getattr(m, "history_deduction", None)),+ # ``"short"``: too few recorded commits for most history markers.+ **({"history": history} if history else {}),# Dominant cause and pre-clamp magnitude; null when the file has no findings."primary_biomarker": lead.get("primary_biomarker") if lead else None,"primary_reason": lead.get("primary_reason") if lead else None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py b/packages/server/src/repowise/server/mcp_server/tool_health/targeted.pyindex b92ab67b7..543d7f630 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py@@ -7,7 +7,7 @@ from typing import Anyfrom repowise.core.analysis.health.aggregation import module_rollups as _module_rollupsfrom repowise.core.analysis.health.trends import file_trend-from repowise.server.mcp_server.tool_health.loading import HealthData+from repowise.server.mcp_server.tool_health.loading import HealthData, history_offrom repowise.server.mcp_server.tool_health.paging import Pagerfrom repowise.server.mcp_server.tool_health.request import HealthRequestfrom repowise.server.mcp_server.tool_health.serialize import _serialize_finding, _serialize_metric@@ -85,7 +85,10 @@ def _metric_payload(data: HealthData) -> list[dict[str, Any]]:rows = []for m in data.metric_rows:row = _serialize_metric(- m, data.leads.get(m.file_path), is_test=m.file_path in data.test_paths+ m,+ data.leads.get(m.file_path),+ is_test=m.file_path in data.test_paths,+ history=history_of(data, m.file_path),)if m.file_path in data.signals_by_path:row["signals"] = data.signals_by_path[m.file_path]diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.pyindex ee005cf19..a34ef90ce 100644--- a/packages/server/src/repowise/server/routers/code_health/serializers.py+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py@@ -160,6 +160,7 @@ def _file_signals_to_dict(s: FileSignals) -> dict:"lines_deleted_90d": s.lines_deleted_90d,"commit_count_90d": s.commit_count_90d,"age_days": s.age_days,+ "history": s.history,"primary_owner_name": s.primary_owner_name,"primary_owner_commit_pct": s.primary_owner_commit_pct,"recent_owner_name": s.recent_owner_name,diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex ef26a41f0..d99bc6a6b 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -1067,6 +1067,8 @@ export interface FileSignals {bug_magnet: boolean | null;last_fix_at: string | null;fix_symbol_counts: Record<string, number> | null;+ // "short": too few recorded commits for most history markers to fire.+ history?: "short" | null;}/* ------------------------------------------------------------------ *diff --git a/tests/unit/cli/test_health_cmd_short_history.py b/tests/unit/cli/test_health_cmd_short_history.pynew file mode 100644index 000000000..6c06f6671--- /dev/null+++ b/tests/unit/cli/test_health_cmd_short_history.py@@ -0,0 +1,36 @@+"""``repowise health`` says when a file's score has almost no history half."""++from __future__ import annotations++import io+from unittest.mock import patch++from rich.console import Console++from repowise.cli.commands.health_cmd import command as health_module+from repowise.core.analysis.health.models import HealthFileMetricData+++def _metric(path: str) -> HealthFileMetricData:+ return HealthFileMetricData(+ file_path=path, score=7.0, max_ccn=3, max_nesting=1, nloc=40,+ has_test_file=False, defect_score=7.0,+ )+++def test_json_rows_carry_history_short_only_for_thin_history() -> None:+ short = {"src/new.py"}+ assert health_module._json_metric(_metric("src/new.py"), short)["history"] == "short"+ assert "history" not in health_module._json_metric(_metric("src/old.py"), short)+++def test_table_marks_the_score_and_explains_the_mark() -> None:+ console = Console(file=io.StringIO(), width=400, force_terminal=False)+ with patch.object(health_module, "console", console):+ health_module._render_files_table([_metric("src/new.py")], {"src/new.py"})+ marked = console.file.getvalue()+ console.file = io.StringIO()+ health_module._render_files_table([_metric("src/old.py")], {"src/new.py"})+ plain = console.file.getvalue()+ assert "7.0*" in marked and "Short history" in marked+ assert "*" not in plain and "Short history" not in plaindiff --git a/tests/unit/cli/test_health_cmd_withheld.py b/tests/unit/cli/test_health_cmd_withheld.pyindex 2b7261a82..d96c43fe7 100644--- a/tests/unit/cli/test_health_cmd_withheld.py+++ b/tests/unit/cli/test_health_cmd_withheld.py@@ -70,6 +70,7 @@ def _run(monkeypatch, *args: str) -> tuple[str, str]:patch.object(health_module, "resolve_command_target") as resolve,patch.object(health_module, "_load_fix_first", return_value=None),patch.object(health_module, "_load_queue_counts", return_value=None),+ patch.object(health_module, "_load_short_history", return_value=set()),patch.object(health_module, "console", console),):resolve.return_value = SimpleNamespace(diff --git a/tests/unit/health/test_signals.py b/tests/unit/health/test_signals.pyindex d55e89236..dbaff000d 100644--- a/tests/unit/health/test_signals.py+++ b/tests/unit/health/test_signals.py@@ -167,3 +167,25 @@ def test_naive_timestamps_are_serialized_with_an_explicit_utc_offset():s = file_signals(_GitNaive(prior_defect_count=1), None)assert s.last_fix_at == "2026-06-02T10:30:00+00:00"+++def test_history_reads_short_below_the_commits_the_history_markers_need():+ from types import SimpleNamespace++ from repowise.core.analysis.health.signals import HISTORY_MIN_COMMITS, history_basis++ def git(total, history_only=False):+ return SimpleNamespace(commit_count_total=total, history_only=history_only)++ assert history_basis(git(HISTORY_MIN_COMMITS - 1)) == "short"+ assert history_basis(git(HISTORY_MIN_COMMITS)) is None+ # No row, no count, or a non-code row: nothing measured, so nothing claimed.+ assert history_basis(None) is None+ assert history_basis(git(None)) is None+ assert history_basis(git(1, history_only=True)) is None++ @dataclass+ class _GitYoung(_Git):+ commit_count_total: int | None = 1++ assert file_signals(_GitYoung(), None).history == "short"diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 48e6972d7..e72fce769 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -154,6 +154,29 @@ async def test_get_health_dashboard_surfaces_performance(setup_mcp, health_data)]+async def test_a_file_with_short_history_says_so_beside_its_score(+ setup_mcp, session, health_data+):+ """Most history markers need more commits than it has."""+ from sqlalchemy import update++ from repowise.core.persistence.models import GitMetadata+ from repowise.server.mcp_server import get_health++ await session.execute(+ update(GitMetadata)+ .where(GitMetadata.file_path == "src/db/models.py")+ .values(commit_count_total=2)+ )+ await session.commit()+ rows = {m["file_path"]: m for m in (await get_health(only=["worst_files"]))["worst_files"]}+ assert rows["src/db/models.py"]["history"] == "short"+ assert "history" not in rows["src/auth/service.py"]+ targeted = await get_health(targets=["src/db/models.py"], only=["metrics"])+ assert targeted["metrics"][0]["history"] == "short"++@pytest.mark.asyncioasync def test_get_health_dashboard_surfaces_leverage(setup_mcp, health_data):"""Leverage view: which files move the NLOC-weighted headline, not just which score low."""diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.pyindex 802bb9937..6ad1f8fc6 100644--- a/tests/unit/server/test_health_badge.py+++ b/tests/unit/server/test_health_badge.py@@ -143,6 +143,7 @@ def test_file_signals_to_dict_no_data_all_null() -> None:"lines_deleted_90d": None,"commit_count_90d": None,"age_days": None,+ "history": None,"primary_owner_name": None,"primary_owner_commit_pct": None,"recent_owner_name": None,