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): measure co-change breadth instead of counting a capped list (#2437)
Raghav Chamadiya9851dc4a5385
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.pyindex 3b06ce464..8cdc7a691 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py@@ -12,9 +12,9 @@ from repowise.cli.helpers import consoledef _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> None:- """Honest performance headline: finding count + density + coverage + scope.+ """Honest performance headline: risk count + density + coverage + scope.- Leads with the open-finding count and how much of the analyzed code a perf+ Leads with the open-risk count and how much of the analyzed code a perfdetector actually ran on, so a mostly-unsupported-language repo reads a lowcoverage % rather than a meaningless bounded 10/10. Silent when no code filecarries a supported language (nothing to say).@@ -29,14 +29,16 @@ def _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> No)perf_avg = report.kpis.get("performance_average")- parts = [f"[bold]{perf_findings}[/bold] finding{'s' if perf_findings != 1 else ''}"]+ parts = [f"[bold]{perf_findings}[/bold] risk{'s' if perf_findings != 1 else ''}"]if coverage.covered_nloc > 0:density = round(10000.0 * perf_findings / coverage.covered_nloc, 2)parts.append(f"{density}/10K covered LOC")if isinstance(perf_avg, (int, float)):- parts.append(f"avg {perf_avg:.1f}/10")+ parts.append(f"avg score {perf_avg:.1f}/10")console.print(- "\n[bold]Performance risk[/bold] "+ # "risk" sits on the count, where more is worse, not on a heading over+ # a score where more is better.+ "\n[bold]Performance[/bold] ""[dim](static, high-precision/low-recall)[/dim]: " + " · ".join(parts))diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 7af385851..002939765 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -150,15 +150,19 @@ async def _coverage_for_rescore(return coverage_map, [], source_format, False-async def _persist_partial_health(session: Any, repo_id: str, report: Any) -> None:+async def _persist_partial_health(+ session: Any, repo_id: str, report: Any, repo_path: Any = None+) -> None:"""Upsert health findings + metrics for the changed-files subset.Delegates to :mod:`repowise.core.pipeline.incremental` — the logic moved- to core so workspace updates can reuse the incremental path.+ to core so workspace updates can reuse the incremental path. ``repo_path``+ is what lets it also re-score the git-derived markers on files this run did+ not walk; without it those markers keep whatever the last full index said."""from repowise.core.pipeline.incremental import persist_partial_health- await persist_partial_health(session, repo_id, report)+ await persist_partial_health(session, repo_id, report, repo_path)async def _persist_incremental_commits(session: Any, repo_id: str, repo_path: Any) -> None:@@ -1117,7 +1121,9 @@ async def _persist_full_update_async(if partial_health_report is not None:try:with timed(timings, "persist.health"):- await _persist_partial_health(session, repo_id, partial_health_report)+ await _persist_partial_health(+ session, repo_id, partial_health_report, repo_path+ )except Exception as exc:_skip("Health persist", exc)diff --git a/packages/core/alembic/versions/0071_git_co_change_breadth.py b/packages/core/alembic/versions/0071_git_co_change_breadth.pynew file mode 100644index 000000000..db5971445--- /dev/null+++ b/packages/core/alembic/versions/0071_git_co_change_breadth.py@@ -0,0 +1,51 @@+"""git_metadata: measure co-change breadth instead of counting a capped list.++``co_change_partners_json`` keeps only the strongest ``MAX_PARTNERS_PER_FILE``+partners, so counting it saturates. These three are measured over every partner+before that truncation, with ``co_change_scatter_pct`` ranking the mass+repo-relative as ``change_entropy_pct`` does. They default to 0 and cannot be+backfilled -- the counts above the cap were discarded at write time -- so+``co_change_scatter`` stays silent until the next walk repopulates them.++Local SQLite stores never run Alembic -- ``init_db``'s reconciler issues+additive DDL for missing columns -- so this migration exists for managed+Postgres.++Revision ID: 0071+Revises: 0070+Create Date: 2026-09-19+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0071"+down_revision: str | None = "0070"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "git_metadata",+ sa.Column("co_change_partner_count", sa.Integer, nullable=False, server_default="0"),+ )+ op.add_column(+ "git_metadata",+ sa.Column("co_change_mass", sa.Float, nullable=False, server_default="0.0"),+ )+ op.add_column(+ "git_metadata",+ sa.Column("co_change_scatter_pct", sa.Float, nullable=False, server_default="0.0"),+ )+++def downgrade() -> None:+ op.drop_column("git_metadata", "co_change_scatter_pct")+ op.drop_column("git_metadata", "co_change_mass")+ op.drop_column("git_metadata", "co_change_partner_count")diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py b/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.pyindex 78210b2f5..93c00b2f0 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py@@ -7,36 +7,54 @@ rippling across the codebase. This is the breadth complement toflag a file coupled to *many* others regardless of whether the links aredeclared.-Reads ``git_meta["co_change_partners_json"]`` (the partner list the git indexer-already stores). **scatter** = the number of distinct partners recorded for the-file, which the indexer has already filtered to pairs sharing real commits.+**Not the length of ``co_change_partners_json``.** That list is truncated to+the strongest ``MAX_PARTNERS_PER_FILE`` partners, so its length is a storage+cap: above it every file looks identical, and since the cap sat above the old+"high" cutoff, almost everything that fired fired high. A raw count also never+retires a partner the file stopped changing with, so it could only go up.-Fires when the file is actively changing and broadly coupled:+The gate is ``co_change_scatter_pct``, the repo-relative rank of+``co_change_mass`` — accumulated over every partner and decayed on a commit+clock. ``co_change_partner_count`` is the true total, for a human to read.-- ``scatter`` ≥ 8 (shotgun-surgery territory), AND+Fires when the file is actively changing and broadly coupled *for this repo*:++- ``co_change_scatter_pct`` ≥ 0.80 (top fifth), AND- ``commit_count_90d`` ≥ 3.-Tier-aware: when ``co_change_partners_json`` is empty (ESSENTIAL git tier) the-detector emits nothing.+Repo-relative, matching ``change_entropy`` and ``churn_risk``; the absolute+``scatter >= 8`` it replaces made this the one history biomarker whose reach+grew with the size and pace of the repo rather than staying a fixed share.++Test material and barrel files are exempt: both co-change with their subject by+design, which is why ``hidden_coupling`` exempts tests too.++Tier-aware: without the breadth columns the percentile is 0.0 and the detector+emits nothing — "no signal" rather than a guess off the truncated list."""from __future__ import annotations+from pathlib import PurePosixPathfrom typing import Anyfrom ....co_change import parse_partners+from ....test_paths import is_test_related_path+from ...dead_code.file_reachability import BARREL_FILENAMESfrom ..models import Severity+from ..semantics import format_top_percentilefrom .base import BiomarkerResult, FileContext-_SCATTER_THRESHOLD = 8-_HIGH_SCATTER = 15+_MIN_PERCENTILE = 0.80+_HIGH_PERCENTILE = 0.95_MIN_COMMITS_90D = 3-def _count_scatter(meta: dict[str, Any]) -> int:- # No second cutoff here: the indexer already dropped pairs that share too- # few commits, so every recorded partner counts.- return len(parse_partners(meta.get("co_change_partners_json")))+def _as_float(value: object, default: float = 0.0) -> float:+ try:+ return float(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return defaultdef _as_int(value: object, default: int = 0) -> int:@@ -46,6 +64,18 @@ def _as_int(value: object, default: int = 0) -> int:return default+def _is_barrel(path: str) -> bool:+ """Whether *path* is a re-export barrel, by the repo's canonical name set.++ The filename alone, deliberately. Corroborating it structurally would be+ more precise but is unavailable to ``history_refresh``, which re-scores from+ git metadata without a parse, so the answer would depend on which pass ran.+ A barrel-named file that grew real logic loses this one signal and keeps+ every other biomarker.+ """+ return PurePosixPath(path).name in BARREL_FILENAMES++class CoChangeScatterDetector:name = "co_change_scatter"category = "organizational"@@ -53,15 +83,24 @@ class CoChangeScatterDetector:def detect(self, ctx: FileContext) -> list[BiomarkerResult]:meta: dict[str, Any] = ctx.git_meta or {}- scatter = _count_scatter(meta)- if scatter < _SCATTER_THRESHOLD:+ if is_test_related_path(ctx.file_path, ctx.language) or _is_barrel(ctx.file_path):+ return []++ percentile = _as_float(meta.get("co_change_scatter_pct"))+ if percentile < _MIN_PERCENTILE:return []commits_90d = _as_int(meta.get("commit_count_90d"))if commits_90d < _MIN_COMMITS_90D:return []- severity = Severity.HIGH if scatter >= _HIGH_SCATTER else Severity.MEDIUM+ # Both numbers travel, so a reader can see when the stored list is a+ # truncation of the real breadth rather than all of it.+ partner_count = _as_int(meta.get("co_change_partner_count"))+ recorded = len(parse_partners(meta.get("co_change_partners_json")))+ scatter = partner_count or recorded++ severity = Severity.HIGH if percentile >= _HIGH_PERCENTILE else Severity.MEDIUMreturn [BiomarkerResult(@@ -72,11 +111,17 @@ class CoChangeScatterDetector:line_end=None,details={"scatter": scatter,+ "recorded_partners": recorded,+ "co_change_mass": round(_as_float(meta.get("co_change_mass")), 4),+ # 0-100, as every other emitted percentile; the column is 0-1.+ "co_change_scatter_pct": round(percentile * 100.0, 1),"commit_count_90d": commits_90d,},reason=(- f"co-changes with {scatter} distinct files — editing this "- "file tends to ripple across the codebase (shotgun surgery)"+ f"co-changes with {scatter} distinct files "+ f"({format_top_percentile(percentile, 'files with any co-change history')}) "+ "— editing this file tends to ripple across the codebase "+ "(shotgun surgery)"),)]diff --git a/packages/core/src/repowise/core/co_change.py b/packages/core/src/repowise/core/co_change.pyindex e6673a2f7..7258131f0 100644--- a/packages/core/src/repowise/core/co_change.py+++ b/packages/core/src/repowise/core/co_change.py@@ -28,6 +28,7 @@ import jsonfrom dataclasses import dataclass, field__all__ = [+ "CO_CHANGE_COMMIT_DECAY_TAU","CO_CHANGE_DECAY_TAU","MAX_PARTNERS_PER_FILE","MIN_CO_CHANGE_SUPPORT",@@ -45,8 +46,18 @@ __all__ = [# Defined here rather than in the indexer because two independent producers# apply it (per-repo history and the cross-repo session miner), and a drift# between them would silently change what a weight means.+# Two consumers now: change entropy, and the cross-repo session miner, whose+# output is a self-normalising share in which the decay largely cancels.CO_CHANGE_DECAY_TAU: float = 180.0+# Tau in ``exp(-commits_ago / tau)`` for the per-repo co-change PAIR weight,+# where ``commits_ago`` is the commit's position in the newest-first walk.+# Calendar time is the wrong clock for a mass the health score reads directly:+# on a fast repo nothing in the indexed history is older than a 180-day tau, so+# the decay retires nothing and partners only accumulate. Counting in commits+# makes the clock the repo's own rate of change.+CO_CHANGE_COMMIT_DECAY_TAU: float = 500.0+# Minimum number of shared commits for a pair to be worth recording. Counted# raw, so it keeps its meaning if the weighting changes.MIN_CO_CHANGE_SUPPORT: int = 2diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.pyindex dbc0f3bce..cf7e5ff2f 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py@@ -26,7 +26,7 @@ from .agent_provenance import (classifier_from_repo_config,)from .backfill import BACKFILL_PHASE, backfill_full_tier-from .co_change import compute_co_changes_and_entropy+from .co_change import CoChangeWalk, compute_co_changes_and_entropyfrom .enrich import (compute_percentiles,count_active_contributors,@@ -69,6 +69,7 @@ __all__ = ["_RECORD_SEP","AgentProvenance","AgentProvenanceClassifier",+ "CoChangeWalk","FixCommit","FixWalk","GitIndexSummary",diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.pyindex 55b087161..eedb23a93 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py@@ -11,6 +11,7 @@ import refrom typing import Anyfrom ...co_change import (+ CO_CHANGE_COMMIT_DECAY_TAU,CO_CHANGE_DECAY_TAU,MAX_PARTNERS_PER_FILE,MIN_CO_CHANGE_SUPPORT,@@ -339,9 +340,13 @@ def classify_commit_category(subject: str) -> str:return "other"-# Co-change temporal decay: half-life ~125 days (lambda for exp(-t/tau)).+# Change-entropy temporal decay: half-life ~125 days (lambda for exp(-t/tau)).+# Keeps the co-change name; the pair weight uses the commit clock below._CO_CHANGE_DECAY_TAU: float = CO_CHANGE_DECAY_TAU+# Co-change pair decay, measured in commits rather than days.+_CO_CHANGE_COMMIT_DECAY_TAU: float = CO_CHANGE_COMMIT_DECAY_TAU+# Hotspot temporal decay: half-life for exponentially weighted churn score.HOTSPOT_HALFLIFE_DAYS: float = 180.0diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py b/packages/core/src/repowise/core/ingestion/git_indexer/co_change.pyindex 6a9edb310..38869a953 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/co_change.py@@ -19,12 +19,15 @@ import mathimport timefrom collections import defaultdictfrom collections.abc import Callable+from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Anyimport structlog+from ...co_change import canonical_pairfrom ._constants import (+ _CO_CHANGE_COMMIT_DECAY_TAU,_CO_CHANGE_DECAY_TAU,_DEFAULT_CO_CHANGE_COMMIT_LIMIT,_MAX_FILES_PER_COMMIT_FOR_COCHANGE,@@ -35,7 +38,64 @@ from ._constants import (logger = structlog.get_logger(__name__)-__all__ = ["compute_co_changes_and_entropy"]+__all__ = ["CoChangeWalk", "compute_co_changes_and_entropy"]+++@dataclass+class CoChangeWalk:+ """Everything one ``git log --name-only`` walk yields, keyed by file path.++ A record rather than a tuple, like ``PriorDefects`` and ``FixWalk`` in the+ orchestrator that consumes this, because the walk keeps acquiring signals.++ ``partners`` is the truncated top-``max_partners`` list that reaches+ ``co_change_partners_json``; its length is a storage cap, not a quantity.+ ``partner_count`` and ``partner_mass`` are measured over every qualifying+ partner before that truncation — the count for a human to read, the decayed+ mass for ranking, since only the mass can fall again.+ """++ partners: dict[str, list[dict]] = field(default_factory=dict)+ entropy: dict[str, float] = field(default_factory=dict)+ partner_count: dict[str, int] = field(default_factory=dict)+ partner_mass: dict[str, float] = field(default_factory=dict)+++def _partner_records(+ kept: dict[str, list[tuple[float, str]]],+ pair_support: dict[tuple[str, str], int],+ pair_last_date: dict[tuple[str, str], int],+ file_commits: dict[str, int],+) -> dict[str, list[dict]]:+ """The persisted partner list per file, strongest first.++ ``self_commits`` / ``partner_commits`` are each file's commit total over+ this same walk, so a reader can state a directional confidence without+ borrowing a denominator computed over a different window.+ """+ out: dict[str, list[dict]] = {}+ for owner, heap in kept.items():+ records = []+ for score, other in heap:+ pair = canonical_pair(owner, other)+ last_ts = pair_last_date.get(pair, 0)+ records.append(+ {+ "file_path": other,+ "co_change_count": round(score, 4),+ "frequency": pair_support[pair],+ "self_commits": file_commits[owner],+ "partner_commits": file_commits[other],+ "last_co_change": (+ datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")+ if last_ts > 0+ else None+ ),+ }+ )+ records.sort(key=lambda x: x["co_change_count"], reverse=True)+ out[owner] = records+ return outdef compute_co_changes_and_entropy(@@ -46,18 +106,26 @@ def compute_co_changes_and_entropy(on_commit_done: Callable[[], None] | None = None,on_co_change_start: Callable[[int], None] | None = None,as_of_ts: float | None = None,-) -> tuple[dict[str, list[dict]], dict[str, float]]:- """Walk recent commits once, returning ``(co_changes, change_entropy)``.+) -> CoChangeWalk:+ """Walk recent commits once, returning every history signal it yields.Uses a single ``git log --name-only`` call instead of spawning one``git diff`` subprocess per commit — O(1) processes vs O(commit_limit).- **Co-change** applies exponential temporal decay so recent co-changes weigh- more than ancient ones, and divides each commit's weight by ``n - 1`` so a- pair carries the same mass whether it was seen alone or alongside a hundred+ **Co-change** applies exponential decay so recent co-changes weigh more+ than ancient ones, and divides each commit's weight by ``n - 1`` so a pair+ carries the same mass whether it was seen alone or alongside a hundredother files. Without that, a commit contributes ``O(n^2)`` pairs at fullweight and wide commits drown the signal.+ That decay is measured in COMMITS, not days: the exponent is the commit's+ position in this newest-first walk (see ``CO_CHANGE_COMMIT_DECAY_TAU``).+ Change entropy keeps the calendar clock it was calibrated on, because its+ consumer gates on a percentile that a near-uniform haircut barely reorders.++ ``partner_count`` and ``partner_mass`` are accumulated over every pair that+ clears ``_MIN_CO_CHANGE_SUPPORT``, BEFORE the ``max_partners`` truncation.+Each pair also keeps ``frequency`` (shared commits, undecayed) and bothfiles' commit totals from this same walk, so a caller can state adirectional confidence without borrowing a denominator computed over a@@ -80,6 +148,8 @@ def compute_co_changes_and_entropy(value maps ``file_path → decayed HCM sum`` (only files with a positive sum)."""pair_scores: defaultdict[tuple[str, str], float] = defaultdict(float)+ partner_count: defaultdict[str, int] = defaultdict(int)+ partner_mass: defaultdict[str, float] = defaultdict(float)pair_support: defaultdict[tuple[str, str], int] = defaultdict(int)pair_last_date: dict[tuple[str, str], int] = {} # pair → latest Unix tsfile_commits: defaultdict[str, int] = defaultdict(int)@@ -99,7 +169,7 @@ def compute_co_changes_and_entropy("--format=%x00%ct",)except Exception:- return {}, {}+ return CoChangeWalk()actual_commits = raw.count("\x00")if on_co_change_start is not None:@@ -107,6 +177,9 @@ def compute_co_changes_and_entropy(current: set[str] = set()current_ts: int = 0+ # Position in the newest-first walk (0 is HEAD): the pair decay's clock.+ current_ordinal: int = 0+ commits_seen: int = 0def _flush_commit() -> None:nonlocal current_ts@@ -119,7 +192,10 @@ def compute_co_changes_and_entropy(if n < 2:returnage_days = max((now_ts - current_ts) / 86400.0, 0.0)+ # Calendar clock, for change entropy only.weight = math.exp(-age_days / _CO_CHANGE_DECAY_TAU)+ # Commit clock, for the co-change pair mass.+ pair_decay = math.exp(-current_ordinal / _CO_CHANGE_COMMIT_DECAY_TAU)# Change entropy (Hassan HCM). The commit-as-period entropy is# ``log2(n)``; each of its files gets the uniform ``1/n`` share, so the@@ -141,7 +217,7 @@ def compute_co_changes_and_entropy(return# Split the commit's weight across the files it touched, so a pair from# a two-file commit outweighs one from a fifty-file commit.- pair_weight = weight / (n - 1)+ pair_weight = pair_decay / (n - 1)sorted_files = sorted(current)for i in range(len(sorted_files)):for j in range(i + 1, len(sorted_files)):@@ -161,6 +237,8 @@ def compute_co_changes_and_entropy(current_ts = int(ts_part)except (ValueError, TypeError):current_ts = 0+ current_ordinal = commits_seen+ commits_seen += 1if on_commit_done is not None:on_commit_done()else:@@ -185,31 +263,15 @@ def compute_co_changes_and_entropy(if pair_support[pair] < _MIN_CO_CHANGE_SUPPORT:continuea, b = pair+ # Past the support filter, before the heap: breadth over every partner.+ partner_count[a] += 1+ partner_count[b] += 1+ partner_mass[a] += score+ partner_mass[b] += score_offer(a, b, score)_offer(b, a, score)- result: dict[str, list[dict]] = {}- for owner, heap in kept.items():- records = []- for score, other in heap:- pair = (owner, other) if owner < other else (other, owner)- last_ts = pair_last_date.get(pair, 0)- records.append(- {- "file_path": other,- "co_change_count": round(score, 4),- "frequency": pair_support[pair],- "self_commits": file_commits[owner],- "partner_commits": file_commits[other],- "last_co_change": (- datetime.fromtimestamp(last_ts, tz=UTC).strftime("%Y-%m-%d")- if last_ts > 0- else None- ),- }- )- records.sort(key=lambda x: x["co_change_count"], reverse=True)- result[owner] = records+ result = _partner_records(kept, pair_support, pair_last_date, file_commits)entropy = {fp: round(score, 6) for fp, score in entropy_scores.items() if score > 0.0}@@ -221,9 +283,16 @@ def compute_co_changes_and_entropy(pairs_above_support=sum(1 for c in pair_support.values() if c >= _MIN_CO_CHANGE_SUPPORT),files_with_partners=len(result),files_with_entropy=len(entropy),+ # Logged so the truncation is visible rather than silent.+ files_at_partner_cap=sum(1 for recs in result.values() if len(recs) >= max_partners),min_support=_MIN_CO_CHANGE_SUPPORT,max_partners=max_partners,commit_limit=commit_limit,)- return result, entropy+ return CoChangeWalk(+ partners=result,+ entropy=entropy,+ partner_count=dict(partner_count),+ partner_mass={fp: round(mass, 6) for fp, mass in partner_mass.items()},+ )diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.pyindex 938ef0a44..d5409162e 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py@@ -188,11 +188,37 @@ def count_active_contributors(metadata_list: list[dict], *, window_days: int = 9return sum(1 for ts in author_last_ts.values() if ts >= cutoff)+def _rank_within_eligible(+ metadata_list: list[dict],+ *,+ source_key: str,+ target_key: str,+) -> None:+ """Rank *source_key* among the files that carry a positive value for it.++ Files without the signal keep ``target_key`` at 0.0 rather than entering the+ ranking: a percentile over a mostly-zero population hands the topmost zero a+ high rank. Shared by both percentile-gated history signals.+ """+ for meta in metadata_list:+ meta.setdefault(target_key, 0.0)+ eligible = [i for i, m in enumerate(metadata_list) if (m.get(source_key) or 0.0) > 0.0]+ if not eligible:+ return+ eligible.sort(key=lambda i: metadata_list[i].get(source_key) or 0.0)+ n = len(eligible)+ for rank, idx in enumerate(eligible):+ metadata_list[idx][target_key] = rank / n++def compute_percentiles(metadata_list: list[dict]) -> None:- """Compute churn_percentile and is_hotspot. Mutates in place.+ """Compute churn_percentile, is_hotspot, and the history percentiles.- Primary sort key is temporal_hotspot_score (exponentially decayed churn);- commit_count_90d is used as a tiebreak, matching the SQL PERCENT_RANK path.+ Primary sort key for churn is temporal_hotspot_score (exponentially decayed+ churn); commit_count_90d is used as a tiebreak, matching the SQL+ PERCENT_RANK path. ``change_entropy_pct`` and ``co_change_scatter_pct`` are+ ranked among the files that carry the signal at all -- see+ :func:`_rank_within_eligible`."""if not metadata_list:return@@ -217,21 +243,16 @@ def compute_percentiles(metadata_list: list[dict]) -> None:# rank loop so the list is scanned once.if churn_pct >= 0.75 and meets_hotspot_floors(meta):meta["is_hotspot"] = True- # change_entropy percentile default — overwritten below for files- # carrying a positive entropy signal.- meta.setdefault("change_entropy_pct", 0.0)-- # change_entropy percentile (mirrors churn_percentile). Rank ONLY files- # that carry a positive entropy signal; files with zero entropy — every- # file on the ESSENTIAL tier, plus FULL-tier files that only ever changed- # alone — keep pct 0.0 so the change_entropy biomarker stays silent. (A- # naive rank-everything would hand the topmost zero-entropy file a high- # percentile when most files are zero.)- entropy_idxs = [- i for i in range(total) if (metadata_list[i].get("change_entropy") or 0.0) > 0.0- ]- n_ent = len(entropy_idxs)- if n_ent > 0:- entropy_idxs.sort(key=lambda i: metadata_list[i].get("change_entropy") or 0.0)- for rank, idx in enumerate(entropy_idxs):- metadata_list[idx]["change_entropy_pct"] = rank / n_ent++ # Files with zero entropy — every file on the ESSENTIAL tier, plus+ # FULL-tier files that only ever changed alone — stay at 0.0 so the+ # change_entropy biomarker is silent for them.+ _rank_within_eligible(+ metadata_list, source_key="change_entropy", target_key="change_entropy_pct"+ )++ # Ranked on the decayed partner mass, not the count: a count saturates at+ # the storage cap and never retires, so it can only ever ratchet up.+ _rank_within_eligible(+ metadata_list, source_key="co_change_mass", target_key="co_change_scatter_pct"+ )diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.pyindex 3e02af245..77fc71a5c 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py@@ -71,7 +71,8 @@ __all__ = ["DECAY_REFRESH_KEYS", "index_file", "new_meta"]# incremental update recomputes just these for idle (unchanged) files off the# repo-wide walk and persists a decay-only partial row, leaving ownership / age# / authorship (which need full history and are only correct from the init-# walk) untouched. ``co_change_partners_json`` / ``change_entropy`` /+# walk) untouched. ``co_change_partners_json`` / ``co_change_partner_count`` /+# ``co_change_mass`` / ``change_entropy`` /# ``prior_defect_*`` are merged onto the metadata after the per-file pass, so# they refresh together with the window churn fields ``index_file`` computes.DECAY_REFRESH_KEYS = (@@ -85,6 +86,8 @@ DECAY_REFRESH_KEYS = ("prior_defect_raw_count","change_entropy","co_change_partners_json",+ "co_change_partner_count",+ "co_change_mass",)@@ -147,6 +150,12 @@ def new_meta(file_path: str) -> dict[str, Any]:# the signal silent on the ESSENTIAL tier / files that never co-changed."change_entropy": 0.0,"change_entropy_pct": 0.0,+ # Co-change breadth over every partner the repo-wide walk found, not+ # the length of the truncated partner list. Defaults leave+ # ``co_change_scatter`` silent when the walk did not run.+ "co_change_partner_count": 0,+ "co_change_mass": 0.0,+ "co_change_scatter_pct": 0.0,}diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex cdf4ba443..18e2f76bb 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -28,7 +28,7 @@ from ._constants import (_FILE_INDEX_TIMEOUT_SECS,_MAX_PARTNERS_PER_FILE,)-from .co_change import compute_co_changes_and_entropy+from .co_change import CoChangeWalk, compute_co_changes_and_entropyfrom .enrich import compute_percentilesfrom .file_history import DECAY_REFRESH_KEYS, index_filefrom .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defects@@ -325,7 +325,7 @@ class GitIndexer:file_tasks = [index_one(fp) for fp in indexable_files]- async def _co_change_task() -> tuple[dict[str, list[dict]], dict[str, float]]:+ async def _co_change_task() -> CoChangeWalk:# ESSENTIAL tier defers co-change entirely (the expensive repo-wide# walk) — return empty and let a FULL backfill fill it in. Change# entropy rides the same walk, so it's deferred together.@@ -333,7 +333,7 @@ class GitIndexer:if on_co_change_done is not None:with contextlib.suppress(Exception):on_co_change_done()- return {}, {}+ return CoChangeWalk()result = await loop.run_in_executor(executor,compute_co_changes_and_entropy,@@ -351,7 +351,7 @@ class GitIndexer:return resulttry:- metadata_list, (co_changes, change_entropy) = await asyncio.gather(+ metadata_list, walk = await asyncio.gather(asyncio.gather(*file_tasks, return_exceptions=True),_co_change_task(),)@@ -402,10 +402,13 @@ class GitIndexer:# share into metadata.for meta in results:fp = meta["file_path"]- if fp in co_changes:- meta["co_change_partners_json"] = json.dumps(co_changes[fp])- if fp in change_entropy:- meta["change_entropy"] = change_entropy[fp]+ if fp in walk.partners:+ meta["co_change_partners_json"] = json.dumps(walk.partners[fp])+ if fp in walk.entropy:+ meta["change_entropy"] = walk.entropy[fp]+ if fp in walk.partner_count:+ meta["co_change_partner_count"] = walk.partner_count[fp]+ meta["co_change_mass"] = walk.partner_mass.get(fp, 0.0)if fp in prior_defects.counts:meta["prior_defect_count"] = prior_defects.counts[fp]if fp in prior_defects.raw_counts:@@ -714,7 +717,7 @@ class GitIndexer:if self.tier.includes_co_change and all_files:try:with timed(timings, "rebuild.git.co_change"):- co_changes, change_entropy = await loop.run_in_executor(+ walk = await loop.run_in_executor(executor,compute_co_changes_and_entropy,repo,@@ -727,12 +730,15 @@ class GitIndexer:)for meta in results:fp = meta["file_path"]- if fp in co_changes:- meta["co_change_partners_json"] = json.dumps(co_changes[fp])- if fp in change_entropy:- meta["change_entropy"] = change_entropy[fp]+ if fp in walk.partners:+ meta["co_change_partners_json"] = json.dumps(walk.partners[fp])+ if fp in walk.entropy:+ meta["change_entropy"] = walk.entropy[fp]+ if fp in walk.partner_count:+ meta["co_change_partner_count"] = walk.partner_count[fp]+ meta["co_change_mass"] = walk.partner_mass.get(fp, 0.0)if co_change_sink is not None:- co_change_sink.update(co_changes)+ co_change_sink.update(walk.partners)# Idle-file decay refresh (#728): recompute only the# anchor-dependent window/decay fields for every idle file with@@ -751,8 +757,7 @@ class GitIndexer:commit_index,as_of_ts,prov_clf,- co_changes,- change_entropy,+ walk,prior_defects,))@@ -777,8 +782,7 @@ class GitIndexer:commit_index: dict[str, list[_CommitRec]],as_of_ts: float | None,prov_clf: Any,- co_changes: dict[str, list[dict]],- change_entropy: dict[str, float],+ walk: CoChangeWalk,prior_defects: PriorDefects,) -> dict[str, dict]:"""Decay-only partial rows for *idle_paths* (see ``index_changed_files``).@@ -804,8 +808,10 @@ class GitIndexer:as_of_ts=as_of_ts,provenance_classifier=prov_clf,)- meta["change_entropy"] = change_entropy.get(fp, 0.0)- meta["co_change_partners_json"] = json.dumps(co_changes.get(fp, []))+ meta["change_entropy"] = walk.entropy.get(fp, 0.0)+ meta["co_change_partners_json"] = json.dumps(walk.partners.get(fp, []))+ meta["co_change_partner_count"] = walk.partner_count.get(fp, 0)+ meta["co_change_mass"] = walk.partner_mass.get(fp, 0.0)meta["prior_defect_count"] = prior_defects.counts.get(fp, 0)meta["prior_defect_raw_count"] = prior_defects.raw_counts.get(fp, 0)out[fp] = {"file_path": fp, **{k: meta[k] for k in DECAY_REFRESH_KEYS}}diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex d75778d60..7c49f3478 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -191,6 +191,8 @@ async def get_dead_code_git_fields(session: AsyncSession, repository_id: str) -># wiped the init-computed values for exactly the files that change most._WALK_FIELD_EMPTIES: dict[str, tuple] = {"co_change_partners_json": ("[]", "", None),+ "co_change_partner_count": (0, None),+ "co_change_mass": (0, 0.0, None),"change_entropy": (0, 0.0, None),# AI line share comes from the whole trace file, merged only into files# reindexed this pass. Preserve a prior non-empty share when a transient@@ -245,18 +247,22 @@ async def recompute_git_percentiles(session: AsyncSession,repository_id: str,) -> int:- """Recompute churn_percentile, is_hotspot, and change_entropy_pct using SQL- PERCENT_RANK window functions.+ """Recompute churn_percentile, is_hotspot, and the history percentiles in SQL.Called after incremental updates so that percentile rankings stay freshwithout a full ``repowise init``. Returns the number of rows updated.Primary churn ranking signal is temporal_hotspot_score (exponentially decayed- churn); commit_count_90d is the tiebreak. change_entropy_pct ranks files by- change_entropy ascending — zero-entropy files tie at the minimum (0.0), so- they stay below the biomarker's ≥0.80 gate. Works on both SQLite (3.25+) and+ churn); commit_count_90d is the tiebreak. Works on both SQLite (3.25+) andPostgreSQL.+ ``change_entropy_pct`` and ``co_change_scatter_pct`` mirror+ ``enrich._rank_within_eligible``: ``ROW_NUMBER`` over the files carrying a+ positive signal, over how many of them there are. Ranking them over the+ whole table instead gives a file a different percentile here than the+ Python path gives it, and a gate at 0.80 turns that into findings that+ appear and disappear on an unchanged tree.+Hotspot classification mirrors ``enrich.meets_hotspot_floors`` (issue #361):the repo-relative top-quartile gate AND the absolute activity floors —keep the two paths in sync.@@ -282,13 +288,25 @@ WITH ranked AS (PERCENT_RANK() OVER (PARTITION BY repository_idORDER BY COALESCE(temporal_hotspot_score, 0.0), commit_count_90d- ) AS prank,- PERCENT_RANK() OVER (- PARTITION BY repository_id- ORDER BY COALESCE(change_entropy, 0.0)- ) AS erank+ ) AS prankFROM git_metadataWHERE repository_id = :repo_id+),+entropy_ranked AS (+ SELECT id,+ (ROW_NUMBER() OVER (ORDER BY COALESCE(change_entropy, 0.0)) - 1) * 1.0+ / (SELECT COUNT(*) FROM git_metadata+ WHERE repository_id = :repo_id AND COALESCE(change_entropy, 0.0) > 0.0) AS erank+ FROM git_metadata+ WHERE repository_id = :repo_id AND COALESCE(change_entropy, 0.0) > 0.0+),+scatter_ranked AS (+ SELECT id,+ (ROW_NUMBER() OVER (ORDER BY COALESCE(co_change_mass, 0.0)) - 1) * 1.0+ / (SELECT COUNT(*) FROM git_metadata+ WHERE repository_id = :repo_id AND COALESCE(co_change_mass, 0.0) > 0.0) AS crank+ FROM git_metadata+ WHERE repository_id = :repo_id AND COALESCE(co_change_mass, 0.0) > 0.0)UPDATE git_metadataSET churn_percentile = (SELECT prank FROM ranked WHERE ranked.id = git_metadata.id),@@ -297,7 +315,10 @@ SET churn_percentile = (SELECT prank FROM ranked WHERE ranked.id = git_metadata.AND (git_metadata.commit_count_90d >= :high_commits_90dOR COALESCE(git_metadata.temporal_hotspot_score, 0.0)>= :min_temporal_score)),- change_entropy_pct = (SELECT erank FROM ranked WHERE ranked.id = git_metadata.id)+ change_entropy_pct = COALESCE(+ (SELECT erank FROM entropy_ranked WHERE entropy_ranked.id = git_metadata.id), 0.0),+ co_change_scatter_pct = COALESCE(+ (SELECT crank FROM scatter_ranked WHERE scatter_ranked.id = git_metadata.id), 0.0)WHERE repository_id = :repo_id;"""await session.execute(diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 507683dcb..c06b536c2 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -642,6 +642,15 @@ class GitMetadata(Base):change_entropy: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)change_entropy_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ # Co-change breadth, measured over every partner rather than over the+ # truncated ``co_change_partners_json`` list: the distinct-partner total,+ # the commit-decayed sum of their pair weights, and the repo-relative rank+ # of that mass among files that have any (as ``change_entropy_pct`` does).+ # All zero when the walk did not run, which keeps the biomarker silent.+ co_change_partner_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ co_change_mass: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ co_change_scatter_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+# Agent-provenance rollup: how much of this file's indexed history is# agent-attributed (deterministic local-channel classification — identity# fields, message footers, co-author trailers; seediff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsxindex a09557561..070688c5a 100644--- a/packages/ui/__tests__/health/map-lens.test.tsx+++ b/packages/ui/__tests__/health/map-lens.test.tsx@@ -415,7 +415,7 @@ describe("the inspector", () => {<MapInspector file={row} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,);expect(getByText("Open opportunities")).toBeInTheDocument();- expect(getByText(/defect risk 7\.0/)).toBeInTheDocument();+ expect(getByText(/code health 7\.0/)).toBeInTheDocument();// The score badge, which is the defect ramp, is not the leading mark.const leading = container.querySelector("section > div")?.firstElementChild;expect(leading?.textContent).toBe("");diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsxindex 82b879d05..81e15d0e0 100644--- a/packages/ui/src/health/biomarker-details.tsx+++ b/packages/ui/src/health/biomarker-details.tsx@@ -459,16 +459,20 @@ export function BiomarkerDetails({);break;}- case "co_change_scatter":+ case "co_change_scatter": {+ // The percentile is the gate, so it is what makes the count meaningful.+ const p = num(details.co_change_scatter_pct);line = joinStats(num(details.scatter) != null? `co-changes with ${num(details.scatter)} files`: null,+ p != null ? `${formatTopPercentile(p)} coupling` : null,num(details.commit_count_90d) != null? `${num(details.commit_count_90d)} commits/90d`: null,);break;+ }case "prior_defect": {const count = num(details.prior_defect_count);const windowDays = num(details.window_days);diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsxindex 3cd7acd9e..643501f9e 100644--- a/packages/ui/src/health/code-health-lede.tsx+++ b/packages/ui/src/health/code-health-lede.tsx@@ -217,8 +217,11 @@ export function CodeHealthLede({{perf != null && (<>{" "}- Static performance risk is scored separately at {perf.toFixed(1)} out- of 10 and never blended into the health score.+ {/* Not "performance risk": this is a score on the same ladder+ as the health number, so a risk noun inverts it. "risk" belongs+ to the findings count in the ribbon. Matches HealthLede. */}+ Static performance is scored separately at {perf.toFixed(1)} out of+ 10 and never blended into the health score.</>)}</p>diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsxindex 56dbecda0..5991d8f07 100644--- a/packages/ui/src/health/findings-view.tsx+++ b/packages/ui/src/health/findings-view.tsx@@ -335,7 +335,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {)}options={[{ value: "all", label: "All dimensions" },- { value: "defect", label: "Defect risk" },+ { value: "defect", label: "Code health" },{ value: "maintainability", label: "Maintainability" },{ value: "performance", label: "Performance" },{ value: "advisory", label: "Advisory" },diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsxindex a215cbf4b..83bad498b 100644--- a/packages/ui/src/health/map/inspector.tsx+++ b/packages/ui/src/health/map/inspector.tsx@@ -262,7 +262,7 @@ export function MapInspector({{overlay === "performance" ? (// Still available, but as one supporting figure among several rather// than as the headline the lens is not about.- <span className="tabular-nums">defect risk {file.score.toFixed(1)}</span>+ <span className="tabular-nums">code health {file.score.toFixed(1)}</span>) : null}<span className="tabular-nums">{file.nloc.toLocaleString()} NLOC</span>{file.line_coverage_pct != null ? (diff --git a/packages/ui/src/overview/health-lede.tsx b/packages/ui/src/overview/health-lede.tsxindex 1bf210e40..f77239a1d 100644--- a/packages/ui/src/overview/health-lede.tsx+++ b/packages/ui/src/overview/health-lede.tsx@@ -3,7 +3,7 @@ import { healthBand } from "../health/tokens";import { LedeLink, PageLede } from "../shared/page-lede";export interface HealthLedeProps {- /** Defect-risk headline, 1–10. Null until the first health run. */+ /** Code-health headline, 1–10. Higher is better. Null before the first run. */score: number | null;maintainability?: number | null | undefined;/** Static performance score, 1–10. Higher is better, like the other two. */@@ -96,7 +96,7 @@ export function HealthLede({<strong className="font-semibold text-[var(--color-text-primary)]">{score.toFixed(1)} out of 10</strong>{" "}- on defect risk, which we rate {band.label.toLowerCase()}.+ for code health, which we rate {band.label.toLowerCase()}.{pillarSentence && ` ${pillarSentence}`}{/* This used to open "The files you change most are the weak spot",which reads as an indictment of something every codebase does. Hotdiff --git a/packages/ui/src/overview/overview-model.ts b/packages/ui/src/overview/overview-model.tsindex fdd6456b1..179247b35 100644--- a/packages/ui/src/overview/overview-model.ts+++ b/packages/ui/src/overview/overview-model.ts@@ -113,7 +113,7 @@ export function buildChangeStats(summary: OverviewSummaryResponse): ChangeStat[]// than news: both figures render to one decimal, so anything smaller shows// as "+0.0".for (const [value, label] of [- [deltas.average_health, "defect risk"],+ [deltas.average_health, "code health"],[deltas.hotspot_health, "hotspot health"],] as const) {if (value != null && Math.abs(value) >= 0.05) {diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex d2b507682..8b2674d2f 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -45,6 +45,7 @@ export {type ChartSkeletonProps,} from "./loading-skeletons";export { PageShell, type PageShellProps } from "./page-shell";+export { ReleaseNotice, type ReleaseNoticeProps } from "./release-notice";export { ViewTabs, type ViewTab, type ViewTabsProps } from "./view-tabs";export { MetricCard, type MetricCardProps } from "./metric-card";export {diff --git a/packages/ui/src/shared/release-notice.tsx b/packages/ui/src/shared/release-notice.tsxnew file mode 100644index 000000000..ff43c9fa0--- /dev/null+++ b/packages/ui/src/shared/release-notice.tsx@@ -0,0 +1,80 @@+"use client";++import * as React from "react";+import { Info, X } from "lucide-react";+import { cn } from "../lib/cn";++const STORAGE_PREFIX = "repowise:release-notice-dismissed:";++export interface ReleaseNoticeProps {+ /** Stable id for this notice, e.g. `"health-scoring"`. Combined with+ * `version` to key the dismissal, so a later release that changes the same+ * thing again shows its notice once more. */+ id: string;+ /** The release this notice belongs to. Omit only if the notice is not tied+ * to one, in which case dismissal is permanent. */+ version?: string | null;+ children: React.ReactNode;+ className?: string;+}++/**+ * A one-time, dismissible "this changed in the release you just installed"+ * notice. Lives in the shared package so both the web app and hosted can show+ * it; the web app's `UpgradeBanner` does a different job (an upgrade is+ * *available*) and is not what this replaces.+ *+ * Dismissal is best-effort `localStorage`: blocked site data leaves the notice+ * showing rather than throwing, which is the right failure for something whose+ * purpose is to be read once.+ */+export function ReleaseNotice({ id, version, children, className }: ReleaseNoticeProps) {+ const storageKey = STORAGE_PREFIX + id + (version ? `:v${version}` : "");+ // Start dismissed so it does not flash in before the stored answer is read.+ const [dismissed, setDismissed] = React.useState(true);++ React.useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ setDismissed(!!window.localStorage.getItem(storageKey));+ } catch {+ setDismissed(false);+ }+ }, [storageKey]);++ if (dismissed) return null;++ const dismiss = () => {+ try {+ window.localStorage.setItem(storageKey, "1");+ } catch {+ /* localStorage unavailable - hide for this session only. */+ }+ setDismissed(true);+ };++ return (+ <div+ role="status"+ className={cn(+ "flex items-start gap-3 rounded-md border border-[var(--color-border-default)]",+ "bg-[var(--color-bg-elevated)] px-4 py-3 text-sm",+ className,+ )}+ >+ <Info+ className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]"+ aria-hidden="true"+ />+ <div className="flex-1 text-[var(--color-text-secondary)]">{children}</div>+ <button+ type="button"+ onClick={dismiss}+ aria-label="Dismiss"+ className="rounded p-1 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-4 w-4" />+ </button>+ </div>+ );+}diff --git a/packages/vscode/src/features/fileDecorations.ts b/packages/vscode/src/features/fileDecorations.tsindex aa5c93ba1..d878816c7 100644--- a/packages/vscode/src/features/fileDecorations.ts+++ b/packages/vscode/src/features/fileDecorations.ts@@ -61,7 +61,7 @@ export function registerFileDecorations(ctx: RepowiseContext): vscode.Disposableif (defect > maxScore()) return undefined;return {badge: BADGE,- tooltip: `Repowise defect score ${defect.toFixed(1)}`,+ tooltip: `Repowise code health ${defect.toFixed(1)}`,color: errorColor,propagate: false,};diff --git a/packages/vscode/src/features/fileScoreStatus.ts b/packages/vscode/src/features/fileScoreStatus.tsindex bc7d4cb95..3a606f978 100644--- a/packages/vscode/src/features/fileScoreStatus.ts+++ b/packages/vscode/src/features/fileScoreStatus.ts@@ -51,7 +51,7 @@ export function registerFileScoreStatus(ctx: RepowiseContext): vscode.Disposableconst tooltip = new vscode.MarkdownString();tooltip.appendMarkdown("**Repowise health**\n\n");tooltip.appendMarkdown(- `Defect ${fmt(defect)} · Maintainability ${fmt(+ `Code health ${fmt(defect)} · Maintainability ${fmt(entry.maintainabilityScore,)} · Performance ${fmt(entry.performanceScore)}\n\n`,);diff --git a/packages/vscode/src/features/hovers.ts b/packages/vscode/src/features/hovers.tsindex 3dfb9dad5..534c54c18 100644--- a/packages/vscode/src/features/hovers.ts+++ b/packages/vscode/src/features/hovers.ts@@ -117,7 +117,7 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {const md = new vscode.MarkdownString();md.appendMarkdown("**Repowise health**\n\n");md.appendMarkdown(- `Defect ${fmt(metric.defect_score ?? metric.score)} · Maintainability ${fmt(+ `Code health ${fmt(metric.defect_score ?? metric.score)} · Maintainability ${fmt(metric.maintainability_score,)} · Performance ${fmt(metric.performance_score)}\n\n`,);diff --git a/packages/vscode/src/features/trees/health.ts b/packages/vscode/src/features/trees/health.tsindex 87e538899..d7864f383 100644--- a/packages/vscode/src/features/trees/health.ts+++ b/packages/vscode/src/features/trees/health.ts@@ -55,7 +55,7 @@ export class HealthTreeProvider extends RepowiseTreeProvider {private fileNode(row: HealthFileMetric): RepoTreeNode {const tooltip = new vscode.MarkdownString();tooltip.appendMarkdown(`\`${row.file_path}\`\n\n`);- tooltip.appendMarkdown(`- Defect risk: ${score(row.defect_score ?? row.score)}\n`);+ tooltip.appendMarkdown(`- Code health: ${score(row.defect_score ?? row.score)}\n`);tooltip.appendMarkdown(`- Maintainability: ${score(row.maintainability_score)}\n`);tooltip.appendMarkdown(`- Performance: ${score(row.performance_score)}\n`);return {diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex a0dca4975..252ebb40b 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -40,6 +40,7 @@ import {type LucideIcon,} from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { ReleaseNotice } from "@repowise-dev/ui/shared/release-notice";import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";import { OverviewSection } from "@repowise-dev/ui/overview";import { Button } from "@repowise-dev/ui/ui/button";@@ -531,6 +532,17 @@ export default function CodeHealthPage() {</div>}>+ {/* Keyed by id alone: this notice is about one scoring change, so it is+ dismissible for good and a later change introduces its own. */}+ <ReleaseNotice id="health-cochange-scoring">+ <span className="font-medium text-[var(--color-text-primary)]">+ Health scores changed in this release.+ </span>{" "}+ Co-change coupling is now measured relative to your repository and decays with+ commit history rather than calendar time, so roughly one file in ten moves a+ band. Scores are not comparable to snapshots taken before this release.+ </ReleaseNotice>+{meta ? (<p className="-mt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{meta.last_indexed_atdiff --git a/tests/unit/cli/test_update_history_refresh_wiring.py b/tests/unit/cli/test_update_history_refresh_wiring.pynew file mode 100644index 000000000..844ee7137--- /dev/null+++ b/tests/unit/cli/test_update_history_refresh_wiring.py@@ -0,0 +1,33 @@+"""The update's health writer must carry ``repo_path`` through to core.++``persist_partial_health`` re-scores the git-derived markers on files the run+did not walk, and it only does that when it is given a repo path. The CLI+update called it without one, so on that path every history marker kept+whatever the last full index said: a file could sit at "bug-fixed 9 times+recently" long after the fixes stopped, and a scoring change would not reach+any file the update happened not to touch.+"""++from __future__ import annotations++from typing import Any++import pytest++from repowise.cli.commands.update_cmd.persistence import _persist_partial_health+++async def test_partial_health_persist_forwards_repo_path(monkeypatch) -> None:+ seen: dict[str, Any] = {}++ async def _fake(session, repo_id, report, repo_path=None):+ seen["repo_path"] = repo_path++ import repowise.core.pipeline.incremental as incremental++ monkeypatch.setattr(incremental, "persist_partial_health", _fake)++ await _persist_partial_health(object(), "repo-1", object(), "/tmp/some-repo")++ assert seen["repo_path"] == "/tmp/some-repo"diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.pyindex 9ca22030c..9ff13e4bd 100644--- a/tests/unit/health/test_organizational_biomarkers.py+++ b/tests/unit/health/test_organizational_biomarkers.py@@ -25,6 +25,7 @@ from repowise.core.analysis.health.biomarkers.ownership_risk import (from repowise.core.analysis.health.biomarkers.prior_defect import (PriorDefectDetector,)+from repowise.core.analysis.health.complexity import FunctionComplexitydef _authors(*pairs: tuple[str, int]) -> str:@@ -385,57 +386,110 @@ def test_change_entropy_silent_without_signal():def _partners(*pairs: tuple[str, float]) -> str:- # The scatter count reads shared commits, so the record needs one.return json.dumps([{"file_path": p, "co_change_count": c, "frequency": int(c)} for p, c in pairs])-def test_co_change_scatter_fires_on_broad_coupling():+def _scatter_meta(**over) -> dict:meta = {- "co_change_partners_json": _partners(*[(f"m{i}.py", 3.0) for i in range(9)]),+ "co_change_scatter_pct": 0.85,+ "co_change_partner_count": 41,+ "co_change_mass": 12.5,+ "co_change_partners_json": _partners(*[(f"m{i}.py", 3.0) for i in range(25)]),"commit_count_90d": 5,}- out = CoChangeScatterDetector().detect(_ctx(meta))- assert len(out) == 1- assert out[0].severity == "medium" # 8 <= scatter < 15- assert out[0].details["scatter"] == 9+ meta.update(over)+ return meta-def test_co_change_scatter_high_severity_on_heavy_coupling():- meta = {- "co_change_partners_json": _partners(*[(f"m{i}.py", 2.5) for i in range(16)]),- "commit_count_90d": 7,- }- out = CoChangeScatterDetector().detect(_ctx(meta))- assert out- assert out[0].severity == "high" # scatter >= 15+def test_co_change_scatter_fires_in_the_top_fifth():+ (finding,) = CoChangeScatterDetector().detect(_ctx(_scatter_meta()))+ assert finding.severity == "medium" # 0.80 <= pct < 0.95+ assert finding.details["co_change_scatter_pct"] == 85.0-def test_co_change_scatter_counts_every_recorded_partner():- """The indexer already dropped pairs sharing too few commits, so a second- cutoff here would only disagree with it."""- meta = {- "co_change_partners_json": _partners(*[(f"m{i}.py", 0.04) for i in range(12)]),- "commit_count_90d": 5,- }- (finding,) = CoChangeScatterDetector().detect(_ctx(meta))- assert finding.details["scatter"] == 12+def test_co_change_scatter_high_severity_in_the_top_twentieth():+ out = CoChangeScatterDetector().detect(_ctx(_scatter_meta(co_change_scatter_pct=0.97)))+ assert out[0].severity == "high"+++def test_co_change_scatter_reports_the_true_partner_count_not_the_stored_list():+ """The stored list is capped, so counting it saturates. The finding quotes+ the count measured before truncation and carries the capped one beside it,+ so a reader can see the stored list is a truncation."""+ (finding,) = CoChangeScatterDetector().detect(_ctx(_scatter_meta()))+ assert finding.details["scatter"] == 41+ assert finding.details["recorded_partners"] == 25+ assert "41 distinct files" in finding.reason+++def test_co_change_scatter_falls_below_the_gate():+ assert CoChangeScatterDetector().detect(_ctx(_scatter_meta(co_change_scatter_pct=0.79))) == []def test_co_change_scatter_skips_low_activity():- meta = {- "co_change_partners_json": _partners(*[(f"m{i}.py", 3.0) for i in range(10)]),- "commit_count_90d": 1,- }- assert CoChangeScatterDetector().detect(_ctx(meta)) == []+ assert CoChangeScatterDetector().detect(_ctx(_scatter_meta(commit_count_90d=1))) == []def test_co_change_scatter_silent_on_essential_tier():- # Empty partner list (ESSENTIAL git tier) → no signal.+ # No breadth columns (ESSENTIAL git tier, or an index written before they+ # existed) -> no signal, rather than a guess off the truncated list.assert CoChangeScatterDetector().detect(_ctx({"commit_count_90d": 8})) == []+def test_co_change_scatter_exempts_test_files():+ """A test co-changes with its subject by definition, so breadth says+ nothing about it -- the same exemption hidden_coupling makes."""+ ctx = FileContext(+ file_path="tests/unit/test_payments.py",+ language="python",+ nloc=120,+ has_test_file=False,+ module=None,+ git_meta=_scatter_meta(co_change_scatter_pct=0.99),+ )+ assert CoChangeScatterDetector().detect(ctx) == []+++def test_co_change_scatter_exempts_a_barrel_that_defines_nothing():+ ctx = FileContext(+ file_path="packages/ui/src/zoom/index.ts",+ language="typescript",+ nloc=20,+ has_test_file=False,+ module=None,+ git_meta=_scatter_meta(co_change_scatter_pct=0.99),+ )+ assert CoChangeScatterDetector().detect(ctx) == []+++def test_co_change_scatter_exempts_a_barrel_named_file_even_with_logic():+ """The exemption is the filename alone, on purpose: history_refresh+ re-scores from git metadata without a parse, so a structural corroboration+ would answer differently depending on which pass ran."""+ ctx = FileContext(+ file_path="packages/ui/src/zoom/index.ts",+ language="typescript",+ nloc=400,+ has_test_file=False,+ module=None,+ git_meta=_scatter_meta(co_change_scatter_pct=0.99),+ all_functions=(+ FunctionComplexity(+ name="render",+ start_line=1,+ end_line=40,+ ccn=6,+ max_nesting=2,+ cognitive=8,+ nloc=35,+ ),+ ),+ )+ assert CoChangeScatterDetector().detect(ctx) == []++# ---- prior_defect --------------------------------------------------------diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pyindex 874cad7cb..6495c86f6 100644--- a/tests/unit/test_git_indexer.py+++ b/tests/unit/test_git_indexer.py@@ -173,30 +173,30 @@ class TestCoChangeDetection:)mock_repo.git.log.return_value = raw_log- result, _entropy = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=500)+ result = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=500)# a.py <-> b.py should appear (co-changed 4 times)- assert "a.py" in result- partner_paths = [p["file_path"] for p in result["a.py"]]+ assert "a.py" in result.partners+ partner_paths = [p["file_path"] for p in result.partners["a.py"]]assert "b.py" in partner_paths- assert "b.py" in result- partner_paths_b = [p["file_path"] for p in result["b.py"]]+ assert "b.py" in result.partners+ partner_paths_b = [p["file_path"] for p in result.partners["b.py"]]assert "a.py" in partner_paths_b# Three of the four commits are the pair alone, so each contributes its# full weight; the three-file commit contributes half.- co_count = next(p["co_change_count"] for p in result["a.py"] if p["file_path"] == "b.py")+ co_count = next(p["co_change_count"] for p in result.partners["a.py"] if p["file_path"] == "b.py")assert 3.4 <= co_count <= 3.6# The plain count is undecayed and unsplit.- entry_b = next(p for p in result["a.py"] if p["file_path"] == "b.py")+ entry_b = next(p for p in result.partners["a.py"] if p["file_path"] == "b.py")assert entry_b["frequency"] == 4assert entry_b["self_commits"] == 4assert entry_b["partner_commits"] == 4# Verify last_co_change date is present- entry = next(p for p in result["a.py"] if p["file_path"] == "b.py")+ entry = next(p for p in result.partners["a.py"] if p["file_path"] == "b.py")assert "last_co_change" in entryassert entry["last_co_change"] is not None@@ -964,8 +964,35 @@ class TestCoChangeBelowThresholdSkipped:"""A pair is kept on shared commits, not on the decayed weight."""def test_an_old_pair_survives_where_a_weight_cutoff_would_drop_it(self) -> None:- """Three co-changes two years ago decay to a weight under any useful- cutoff, but they are still three co-changes and the pair is real."""+ """Three co-changes buried deep in the history decay to a weight under+ any useful cutoff, but they are still three co-changes and the pair is+ real. Deep in COMMITS, not in days: the pair weight decays on the walk+ position, which is the only clock this measure uses."""+ mock_repo = MagicMock()+ import time++ now = int(time.time())+ # 2,000 unrelated commits ahead of the pair, so it sits four+ # commit-tau deep in the walk.+ blocks = [f"\x00{now - i}\nnoise_a.py\nnoise_b.py\n" for i in range(2000)]+ blocks += [f"\x00{now - 2000 - i}\np.py\nq.py\n" for i in range(3)]+ mock_repo.git.log.return_value = "".join(blocks)++ result = compute_co_changes_and_entropy(+ mock_repo,+ {"p.py", "q.py", "noise_a.py", "noise_b.py"},+ commit_limit=5000,+ )++ (partner,) = result.partners["p.py"]+ assert partner["frequency"] == 3+ assert partner["co_change_count"] < 0.1++ def test_calendar_age_alone_does_not_decay_a_pair(self) -> None:+ """The regression the commit clock exists to stop. A repo whose whole+ indexed history is old is not a repo whose coupling is stale: under the+ calendar decay these three two-year-old commits weighed ~0.01, and+ under the commit clock they are the newest commits there are."""mock_repo = MagicMock()import time@@ -974,13 +1001,48 @@ class TestCoChangeBelowThresholdSkipped:f"\x00{old - i * 86400}\np.py\nq.py\n" for i in range(3))- result, _entropy = compute_co_changes_and_entropy(+ result = compute_co_changes_and_entropy(mock_repo, {"p.py", "q.py"}, commit_limit=500)- (partner,) = result["p.py"]- assert partner["frequency"] == 3- assert partner["co_change_count"] < 0.1+ (partner,) = result.partners["p.py"]+ assert partner["co_change_count"] > 2.9+ # Breadth is measured over every partner, not the truncated list.+ assert result.partner_count["p.py"] == 1+ # Same quantity, stored to one more decimal place than the record.+ assert result.partner_mass["p.py"] == pytest.approx(+ partner["co_change_count"], abs=1e-4+ )+++class TestCoChangeBreadth:+ """partner_count / partner_mass are measured before the storage cap."""++ def test_breadth_counts_past_the_partner_cap(self) -> None:+ import time++ from repowise.core.co_change import MAX_PARTNERS_PER_FILE++ peers = [f"peer_{i}.py" for i in range(MAX_PARTNERS_PER_FILE + 20)]+ all_files = {"hub.py", *peers}+ mock_repo = MagicMock()++ now = int(time.time())+ # Two commits per pair, so every pair clears MIN_CO_CHANGE_SUPPORT.+ blocks = []+ for i, peer in enumerate(peers):+ for rep in range(2):+ blocks.append(f"\x00{now - (i * 2 + rep)}\nhub.py\n{peer}\n")+ mock_repo.git.log.return_value = "".join(blocks)++ result = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=5000)++ # The stored list saturates at the cap; the count does not.+ assert len(result.partners["hub.py"]) == MAX_PARTNERS_PER_FILE+ assert result.partner_count["hub.py"] == len(peers)+ assert result.partner_mass["hub.py"] > sum(+ p["co_change_count"] for p in result.partners["hub.py"]+ )# ---------------------------------------------------------------------------@@ -1021,18 +1083,18 @@ class TestChangeEntropy:mock_repo = MagicMock()mock_repo.git.log.return_value = "".join(blocks)- _co, entropy = compute_co_changes_and_entropy(+ entropy = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=2000)# Focused file changed alone → no entropy entry.- assert entropy.get("focused.py", 0.0) == 0.0+ assert entropy.entropy.get("focused.py", 0.0) == 0.0# Scattered file accrued positive entropy.- assert entropy.get("scattered.py", 0.0) > 0.0+ assert entropy.entropy.get("scattered.py", 0.0) > 0.0# Mass-edit commit excluded → bigcommit.py gets nothing from it.- assert entropy.get("bigcommit.py", 0.0) == 0.0+ assert entropy.entropy.get("bigcommit.py", 0.0) == 0.0# Scattered clearly dominates focused.- assert entropy["scattered.py"] > entropy.get("focused.py", 0.0)+ assert entropy.entropy["scattered.py"] > entropy.entropy.get("focused.py", 0.0)def test_change_entropy_percentile_silent_when_all_zero(self) -> None:"""ESSENTIAL-tier shape (no entropy on any file) → all pct stay 0.0."""@@ -1146,12 +1208,12 @@ class TestCoChangeCommitWidth:wide,)- result, _entropy = compute_co_changes_and_entropy(+ result = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=500)- narrow = next(p for p in result["a.py"] if p["file_path"] == "b.py")- broad = next(p for p in result["w0.py"] if p["file_path"] == "w1.py")+ narrow = next(p for p in result.partners["a.py"] if p["file_path"] == "b.py")+ broad = next(p for p in result.partners["w0.py"] if p["file_path"] == "w1.py")assert narrow["frequency"] == broad["frequency"] == 2assert narrow["co_change_count"] > broad["co_change_count"] * 10@@ -1170,11 +1232,11 @@ class TestCoChangeCommitWidth:now, ("hub.py", *others), ("hub.py", *others))- result, _entropy = compute_co_changes_and_entropy(+ result = compute_co_changes_and_entropy(mock_repo, all_files, commit_limit=500)- assert len(result["hub.py"]) == MAX_PARTNERS_PER_FILE+ assert len(result.partners["hub.py"]) == MAX_PARTNERS_PER_FILEdef test_partner_records_carry_each_side_own_commit_total(self) -> None:"""The two totals differ, which is what makes confidence directional."""@@ -1190,11 +1252,11 @@ class TestCoChangeCommitWidth:("readme.md", "other.md"),)- result, _entropy = compute_co_changes_and_entropy(+ result = compute_co_changes_and_entropy(mock_repo, {"readme.md", "bench.md", "other.md"}, commit_limit=500)- bench = next(p for p in result["readme.md"] if p["file_path"] == "bench.md")+ bench = next(p for p in result.partners["readme.md"] if p["file_path"] == "bench.md")assert bench["self_commits"] == 4assert bench["partner_commits"] == 2@@ -1210,11 +1272,11 @@ class TestCoChangeCommitWidth:mock_repo = MagicMock()mock_repo.git.log.return_value = self._log(now, shared, shared, *([alone] * 9))- result, _entropy = compute_co_changes_and_entropy(+ result = compute_co_changes_and_entropy(mock_repo, {"config.py", "loader.py"}, commit_limit=500)- (partner,) = result["config.py"]+ (partner,) = result.partners["config.py"]assert partner["frequency"] == 2assert partner["self_commits"] == 11 # 2 shared + 9 aloneassert partner["partner_commits"] == 2