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(git): commit history for non-code files, explicit rename detection, and one fix rule (#2690)
Swati Ahuja03ab2e001718
diff --git a/packages/core/alembic/versions/0089_git_history_only.py b/packages/core/alembic/versions/0089_git_history_only.pynew file mode 100644index 000000000..e8a206eec--- /dev/null+++ b/packages/core/alembic/versions/0089_git_history_only.py@@ -0,0 +1,35 @@+"""git_metadata: history-tier rows for non-code files.++Non-code tracked files (docs, config, data) now get their commit counts, first+and last commit and authors from the repo-wide walk. ``history_only`` marks+those rows so the churn, hotspot, entropy, scatter and prior-defect rankings+stay over code files. Existing rows are all code rows, hence ``false``.++Revision ID: 0089+Revises: 0088+Create Date: 2026-09-29+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0089"+down_revision: str | None = "0088"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "git_metadata",+ sa.Column("history_only", sa.Boolean(), nullable=False, server_default=sa.false()),+ )+++def downgrade() -> None:+ op.drop_column("git_metadata", "history_only")diff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.pyindex 16530c5a1..c144d9645 100644--- a/packages/core/src/repowise/core/analysis/change_risk/model.py+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py@@ -120,6 +120,18 @@ class ChangeRisk:key=lambda d: -abs(d.contribution),)+ @property+ def top_driver(self) -> RiskDriver | None:+ """The shown driver that raised the score most; ``None`` when none raised it.++ "Shown" is what a breakdown renders: reportable drivers with a known+ value. The strongest by absolute size can be one that *lowered* the+ score, which is no answer to "what drove this risk".+ """+ shown = [d for d in self.top_drivers if d.value is not None]+ best = max(shown, key=lambda d: d.contribution, default=None)+ return best if best is not None and best.contribution > 0 else None+def _sigmoid(z: float) -> float:if z >= 0:diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.pyindex bbab32a57..b8cf5a906 100644--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py@@ -98,7 +98,7 @@ def _git_ai_notes_log(repo: object, commit_limit: int | None) -> str:#: shape version it carries. Bump the version when ``_LOG_FORMAT`` or the#: record layout changes, so an older cache is re-walked rather than misread._WINDOW_CACHE_NAME = "commit_window_cache.json"-_WINDOW_CACHE_VERSION = 1+_WINDOW_CACHE_VERSION = 2 # v2: records carry rename rows (explicit -M)def _record_ts(record: str) -> int:@@ -170,8 +170,10 @@ def _log_records(repo: object, revisions: str) -> list[str]:"""The non-empty raw ``--numstat`` log records git returns for *revisions*."""from .git_indexer import _LOG_FORMAT, _RECORD_SEP+ # ``-M`` explicitly: the rename trail needs rename rows whatever the+ # repository's ``diff.renames`` says.raw = repo.git.log( # type: ignore[attr-defined]- revisions, "--numstat", "--no-merges", f"--format={_LOG_FORMAT}"+ revisions, "-M", "--numstat", "--no-merges", f"--format={_LOG_FORMAT}")return [rec for rec in raw.split(_RECORD_SEP) if rec.strip()]@@ -282,6 +284,20 @@ def _resolved(return [(renames.resolve(target), added, deleted) for target, added, deleted in changes]+def _pure_moves(+ changes: list[tuple[str, int, int]],+ moved: list[tuple[str, str]],+ renames: RenameTrail | None,+) -> set[str]:+ """Paths (at HEAD) this commit only moved: a rename row with no lines changed."""+ moved_to = {new_path for _old, new_path in moved}+ return {+ renames.resolve(target) if renames is not None else target+ for target, added, deleted in changes+ if target in moved_to and added == 0 and deleted == 0+ }++def _record_moves(renames: RenameTrail | None, moved: list[tuple[str, str]]) -> None:# Only after the commit's own paths are resolved (see RenameTrail).if renames is not None:@@ -376,7 +392,11 @@ class _FileBuckets:self.records: dict[str, list[_CommitRec]] = {}def add(- self, header: dict, prov: AgentProvenance, changes: list[tuple[str, int, int]]+ self,+ header: dict,+ prov: AgentProvenance,+ changes: list[tuple[str, int, int]],+ pure_moves: set[str],) -> None:"""File one commit under each of its changed paths that is tracked here."""from .git_indexer import _CommitRec@@ -399,6 +419,7 @@ class _FileBuckets:deleted=deleted,agent=prov.agent,agent_tier=prov.autonomy_tier,+ pure_move=target in pure_moves,))@@ -503,7 +524,12 @@ def load_commit_index(# agent-trace overlap check and the commit sink both need it.commit_changes, moved = _parse_numstat(numstat_lines)prov = labeler.label(header, commit_changes)- buckets.add(header, prov, _resolved(commit_changes, renames))+ buckets.add(+ header,+ prov,+ _resolved(commit_changes, renames),+ _pure_moves(commit_changes, moved, renames),+ )_record_moves(renames, moved)logger.debug(@@ -579,6 +605,7 @@ def load_deep_commit_index(raw = repo.git.log( # type: ignore[attr-defined]f"--skip={skip}",f"-{deep_limit}",+ "-M","--numstat","--no-merges",f"--format={_LOG_FORMAT}",@@ -597,13 +624,14 @@ def load_deep_commit_index(records = [record for record in raw.split(_RECORD_SEP) if record.strip()]for header, numstat_lines in _commits_after(records, None):commits_parsed += 1- changes, moved = _parse_numstat(numstat_lines)- changes = _resolved(changes, renames)+ raw_changes, moved = _parse_numstat(numstat_lines)+ changes = _resolved(raw_changes, renames)+ pure_moves = _pure_moves(raw_changes, moved, renames)_record_moves(renames, moved)# Only commits touching a wanted file pay for provenance (the window# walk classifies every commit because the commit sink needs labels).if any(target in wanted_files for target, _, _ in changes):- buckets.add(header, labeler.label(header, changes), changes)+ buckets.add(header, labeler.label(header, changes), changes, pure_moves)logger.debug("deep_commit_index_built",diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.pyindex eedb23a93..52a7db940 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py@@ -167,7 +167,8 @@ _MAX_FILES_PER_COMMIT_FOR_COCHANGE: int = 200# above it are dropped from the entropy accumulation entirely._MAX_FILES_PER_COMMIT_FOR_ENTROPY: int = 30-# Commit message classification regexes (Phase 2.2).+# Commit message classification regexes. "fix" is not here: a+# commit is a fix exactly when ``is_fix_commit`` says so, on every surface._COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {"feature": re.compile(r"\b(add|implement|introduce|create|new|feat)\b",@@ -177,10 +178,6 @@ _COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {r"\b(refactor|restructure|cleanup|clean.up|rename|reorganize|extract|simplify|move)\b",re.IGNORECASE,),- "fix": re.compile(- r"\b(fix|bug|patch|hotfix|revert|regression|broken|crash|error)\b",- re.IGNORECASE,- ),"dependency": re.compile(r"\b(upgrade|bump|update.dep|migrate.to|switch.to|dependency|dependencies)\b",re.IGNORECASE,@@ -194,10 +191,9 @@ _COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {# INCLUDE pattern and NO EXCLUDE pattern; merge commits are excluded upstream# (the per-file walk skips ``is_merge``), mirroring the bench's ``--no-merges``.#-# Deliberately NOT reusing ``_COMMIT_CATEGORIES["fix"]`` — that is a broader-# classifier tuned for commit-category *ratios* (it catches "refactor to fix-# crash", "error handling"), whereas the defect label wants high-precision-# fix-only matches and must stay byte-identical to the benchmark's regex set.+# The one fix definition: the per-file category counts and the evolution+# timeline both label a commit "fix" exactly when this rule does, so every+# fix count the product shows counts the same commits._FIX_COMMIT_INCLUDE: tuple[re.Pattern[str], ...] = (re.compile(r"\bfix\b", re.IGNORECASE),re.compile(r"\bbug\b", re.IGNORECASE),@@ -269,9 +265,6 @@ _CONVENTIONAL_PREFIX = re.compile(_CONVENTIONAL_MAP: dict[str, str] = {"feat": "feature","feature": "feature",- "fix": "fix",- "bugfix": "fix",- "hotfix": "fix","perf": "refactor","refactor": "refactor","style": "refactor",@@ -283,7 +276,6 @@ _CONVENTIONAL_MAP: dict[str, str] = {"deps": "deps","ci": "chore","chore": "chore",- "revert": "fix",}# Keyword fallback, tried in this exact order; first hit wins.@@ -298,7 +290,6 @@ _EVOLUTION_KEYWORDS: tuple[tuple[str, re.Pattern[str]], ...] = (re.IGNORECASE,),),- ("fix", re.compile(r"\b(fix|fixes|fixed|bug|patch|hotfix|regression|crash|revert)\b", re.IGNORECASE)),("refactor",re.compile(@@ -324,11 +315,15 @@ _EVOLUTION_KEYWORDS: tuple[tuple[str, re.Pattern[str]], ...] = (def classify_commit_category(subject: str) -> str:"""Assign a commit *subject* exactly one :data:`EVOLUTION_CATEGORIES` label.- A leading conventional-commit prefix is authoritative; otherwise the first+ "fix" is exactly :func:`is_fix_commit`, checked first, so the timeline's+ fix band counts the same commits as every other fix count. Otherwise a+ leading conventional-commit prefix is authoritative, then the firstmatching keyword pattern (in priority order) wins. Unmatched -> ``"other"``."""if not subject:return "other"+ if is_fix_commit(subject):+ return "fix"m = _CONVENTIONAL_PREFIX.match(subject)if m:mapped = _CONVENTIONAL_MAP.get(m.group("type").lower())diff --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 c476c3563..a9a53f543 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@@ -165,8 +165,10 @@ def compute_co_changes_and_entropy(try:# %x00 = commit separator, %ct = committer timestamp (Unix epoch).+ # ``-M`` explicitly, so the rename rows survive ``diff.renames=false``.raw = repo.git.log(f"-{commit_limit}",+ "-M","--name-status","--no-merges","--format=%x00%ct",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 17fc00233..aac5ec845 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@@ -27,6 +27,7 @@ from ._constants import (_PR_NUMBER_RE,HOTSPOT_HALFLIFE_DAYS,_truncate_body,+ is_fix_commit,)from .enrich import detect_original_path, is_significant_commitfrom .function_blame import (@@ -89,6 +90,9 @@ def new_meta(file_path: str) -> dict[str, Any]:"""Return the default metadata dict for *file_path* (all fields zeroed)."""return {"file_path": file_path,+ # A non-code file: history tier only (counts, span, authors). No blame,+ # no churn signals, and kept out of the repo-relative rankings.+ "history_only": False,"commit_count_total": 0,"commit_count_90d": 0,"commit_count_30d": 0,@@ -212,6 +216,7 @@ def _per_file_log_args(file_path: str, commit_limit: int, follow_renames: bool)walk = ["--no-merges",f"-{commit_limit}",+ "-M","--numstat",f"--format={_LOG_FORMAT}","--",@@ -250,12 +255,17 @@ def _add_own_churn(if len(numstat_parts) < 3:continuematch_path = numstat_parts[2]- if "=>" in match_path:+ renamed = "=>" in match_path+ if renamed:_old, _new = _extract_rename_paths(match_path, known_paths)match_path = _new or match_pathchanged_paths.add(match_path)if match_path in known_paths:_add_row_churn(current, numstat_parts)+ # Accumulate: a later row for the file must not clear the rename.+ current.pure_move |= renamed and numstat_parts[:2] == ["0", "0"]+ # Still a pure move only if no row for the file changed a line.+ current.pure_move = current.pure_move and not (current.added or current.deleted)return changed_paths@@ -308,6 +318,7 @@ def index_file(provenance_classifier: Any | None = None,note_agents: dict[str, str] | None = None,trace_index: Any | None = None,+ history_only: bool = False,) -> dict:"""Index a single file's git history. Runs in executor.@@ -319,12 +330,17 @@ def index_file(repo's newest commit, so re-indexing the same commit yields the samewindows and a historical checkout measures the 90 days before it. Fallsback to ``now()``.++ *history_only* (a non-code file) keeps the history tier: commit counts and+ windows, first and last commit, and authorship. Blame, the decayed churn+ score, agent provenance and commit-message mining stay code-only."""now = _window_anchor(as_of_ts)ninety_days_ago_ts = (now - timedelta(days=90)).timestamp()thirty_days_ago_ts = (now - timedelta(days=30)).timestamp()meta = new_meta(file_path)+ meta["history_only"] = history_onlyorig_path: str | None = Noneif precomputed_commits is not None:@@ -354,16 +370,18 @@ def index_file(_add_span(meta, commits, now)authors = _Authors.tally(commits, ninety_days_ago_ts)_add_windows(meta, commits, ninety_days_ago_ts, thirty_days_ago_ts)+ _add_ownership(meta, authors)+ meta["is_stable"] = _is_stable(meta)+ if history_only:+ return meta_add_agent_rollup(meta, commits)meta["temporal_hotspot_score"] = _temporal_hotspot_score(commits, now)- _add_ownership(meta, authors)if include_blame:_add_blame_ownership(meta, repo, repo_path, now, authors)_add_commit_messages(meta, commits)# Only the per-file ``--follow`` walk reports an original path.if orig_path:meta["original_path"] = orig_path- meta["is_stable"] = _is_stable(meta)except Exception:logger.debug("git_indexer_partial_failure", file_path=file_path, exc_info=True)@@ -427,6 +445,8 @@ class _Authors:def tally(cls, commits: list[_CommitRec], recent_since_ts: float) -> _Authors:authors = cls()for c in commits:+ if c.pure_move:+ continue # moving a file is not authoring itname = c.author_nameauthors.counts[name] += 1if c.ts >= recent_since_ts:@@ -599,6 +619,8 @@ def _significant_entry(c: _CommitRec, msg: str) -> dict[str, Any]:def _commit_category(msg: str) -> str | None:+ if is_fix_commit(msg):+ return "fix"for cat, pattern in _COMMIT_CATEGORIES.items():if pattern.search(msg):return catdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex 9aa506832..18eb54a11 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -36,6 +36,7 @@ from .records import (GitHistoryCoverage,GitIndexSummary,_CommitRec,+ _history_tier_files,_should_skip_index,_tz_offset_minutes,capture_repo_totals,@@ -215,11 +216,12 @@ class GitIndexer:if not tracked_files:return GitIndexSummary(0, 0, 0, 0.0), []- # Only run expensive per-file indexing (git log + blame) on code files.+ # Two tiers. Code files get the full per-file pass (blame, churn+ # signals, the per-file fallback walk). Every other tracked file that+ # is not vendored, a lockfile or binary gets its history tier (counts,+ # span, authors) from the shared repo-wide walk only.indexable_files = [fp for fp in tracked_files if not _should_skip_index(fp)]-- if on_start is not None:- on_start(len(indexable_files))+ history_files = _history_tier_files(self.repo_path, tracked_files)from concurrent.futures import ThreadPoolExecutor@@ -233,7 +235,7 @@ class GitIndexer:commit_index: dict[str, list[_CommitRec]] = {}commit_sink: list[dict] = []prov_clf = self._provenance_classifier()- fallback_files = set(indexable_files)+ fallback_files = set(indexable_files) | history_filesrecent_files: set[str] = set()deep_files: set[str] = set()global_commits = deep_commits = complete_through_depth = 0@@ -243,15 +245,20 @@ class GitIndexer:# line-share merge — which is why it loads even in follow_renames mode,# where neither commit-index walk runs.trace_index = self._load_trace_index(repo)+ # Known limit: follow_renames skips this walk, so non-code files get no+ # history rows in that mode (the history tier never walks per file).if not self.follow_renames:from ..git_commit_index import load_sampled_commit_indexsample = load_sampled_commit_index(repo,self.commit_limit,- set(indexable_files),+ set(indexable_files) | history_files,deep_limit=_DEEP_WALK_COMMIT_LIMIT,- deep_threshold=_DEEP_WALK_MIN_FALLBACK,+ # A history-tier file the shared walks leave short has no+ # per-file walk to fall back on, so any one of them is worth a+ # deep walk.+ deep_threshold=1 if history_files else _DEEP_WALK_MIN_FALLBACK,commit_sink=commit_sink,provenance_classifier=prov_clf,trace_index=trace_index,@@ -265,8 +272,14 @@ class GitIndexer:deep_commits = sample.deep_commitscomplete_through_depth = sample.history_complete_through_depth+ # A non-code file the shared walks could not prove complete gets no row+ # (its count stays unknown) rather than a per-file walk of its own.+ history_files -= fallback_files+ if on_start is not None:+ on_start(len(indexable_files) + len(history_files))+fallback_note_agents: dict[str, str] = {}- if fallback_files:+ if fallback_files.intersection(indexable_files):from ..git_commit_index import load_git_ai_note_agentsfallback_note_agents = load_git_ai_note_agents(repo, None)@@ -302,6 +315,7 @@ class GitIndexer:provenance_classifier=prov_clf,note_agents=fallback_note_agents,trace_index=trace_index,+ history_only=file_path in history_files,)except Exception:return {"file_path": file_path}@@ -327,7 +341,7 @@ class GitIndexer:on_file_done()return result- file_tasks = [index_one(fp) for fp in indexable_files]+ file_tasks = [index_one(fp) for fp in [*indexable_files, *sorted(history_files)]]async def _co_change_task() -> CoChangeWalk:# ESSENTIAL tier defers co-change entirely (the expensive repo-wide@@ -404,7 +418,9 @@ class GitIndexer:# Merge co-change partners + change entropy + prior defects + AI line# share into metadata.- for meta in results:+ # History-tier rows take none of these; they are code signals.+ code_results = [meta for meta in results if meta["file_path"] not in history_files]+ for meta in code_results:fp = meta["file_path"]if fp in walk.partners:meta["co_change_partners_json"] = json.dumps(walk.partners[fp])@@ -422,7 +438,7 @@ class GitIndexer:meta["agent_line_count"] = share[0]meta["agent_line_model_json"] = json.dumps(share[1])- compute_percentiles(results)+ compute_percentiles(code_results)# Per-commit rows + just-in-time change-risk, built in-memory from the# commit-index walk's already-parsed diffs (no extra git pass). Empty@@ -464,18 +480,17 @@ class GitIndexer:history_coverage=GitHistoryCoverage(eligible_files=len(indexable_files),files_with_history=sum(- 1 for row in results if int(row.get("commit_count_total", 0)) > 0- ),- unavailable_files=sum(1 for row in results if "commit_count_total" not in row),- retained_commits=sum(- int(row.get("commit_count_total", 0)) for row in results+ 1 for row in code_results if int(row.get("commit_count_total", 0)) > 0),+ unavailable_files=sum(1 for row in code_results if "commit_count_total" not in row),+ retained_commits=sum(int(row.get("commit_count_total", 0)) for row in code_results),per_file_limit=self.commit_limit,global_commits=global_commits,deep_commits=deep_commits,- recent_files=len(recent_files),- deep_files=len(deep_files),- fallback_files=len(fallback_files),+ # Coverage describes the code tier the per-file fallback serves.+ recent_files=len(recent_files.intersection(indexable_files)),+ deep_files=len(deep_files.intersection(indexable_files)),+ fallback_files=len(fallback_files.intersection(indexable_files)),complete_through_depth=complete_through_depth,workers=workers,),@@ -553,6 +568,9 @@ class GitIndexer:# idle refresh minted rows for every tracked config and markup file,# which the health pass then scored: a store grew rows a fresh index# never has.+ # Non-code files get the same history tier the full index gives them.+ history_files = _history_tier_files(self.repo_path, all_files or changed_file_paths)+ history_changed = history_files.intersection(changed_file_paths)changed_file_paths = [fp for fp in changed_file_paths if not _should_skip_index(fp)]if all_files:all_files = {fp for fp in all_files if not _should_skip_index(fp)}@@ -577,7 +595,11 @@ class GitIndexer:and not self.follow_renamesand self.tier.includes_co_change)- target_files = set(all_files) if refresh_idle else set(changed_file_paths)+ target_files = (+ set(all_files) | history_files+ if refresh_idle+ else set(changed_file_paths) | history_changed+ )workers = git_worker_count(len(changed_file_paths), requested=self.max_workers)from concurrent.futures import ThreadPoolExecutor@@ -598,15 +620,19 @@ class GitIndexer:self.commit_limit,target_files,deep_limit=_DEEP_WALK_COMMIT_LIMIT,- deep_threshold=(1 if refresh_idle else _DEEP_WALK_MIN_FALLBACK),+ deep_threshold=(+ 1 if refresh_idle or history_changed else _DEEP_WALK_MIN_FALLBACK+ ),provenance_classifier=prov_clf,trace_index=trace_index,cache_dir=self._window_cache_dir(),)commit_index = sample.commitsfallback_files = sample.fallback_files+ history_files -= fallback_files+ history_changed -= fallback_filesfallback_note_agents: dict[str, str] = {}- if fallback_files:+ if fallback_files.intersection(changed_file_paths):from ..git_commit_index import load_git_ai_note_agentsfallback_note_agents = load_git_ai_note_agents(repo, None)@@ -646,6 +672,7 @@ class GitIndexer:provenance_classifier=prov_clf,note_agents=fallback_note_agents,trace_index=trace_index,+ history_only=file_path in history_changed,)except Exception:return {"file_path": file_path}@@ -665,7 +692,7 @@ class GitIndexer:)return {"file_path": file_path}- tasks = [index_one(fp) for fp in changed_file_paths]+ tasks = [index_one(fp) for fp in [*changed_file_paths, *sorted(history_changed)]]try:with timed(timings, "rebuild.git.changed_files"):results_raw = await asyncio.gather(*tasks, return_exceptions=True)@@ -688,7 +715,7 @@ class GitIndexer:# Idle files (window commits, but not in this change set) whose decay# fields we will refresh — computed here so the prior-defect pass below# covers them in its single windowed walk.- changed_set = set(changed_file_paths)+ changed_set = set(changed_file_paths) | history_changedidle_paths = ([fp@@ -698,6 +725,8 @@ class GitIndexer:if refresh_idleelse [])+ # The code signals below (prior defects, co-change) skip history-tier rows.+ code_results = [m for m in results if m["file_path"] not in history_changed]# Recompute prior-defect counts (same dedicated windowed pass as the# full index — the per-file commit list can't carry this signal@@ -707,9 +736,12 @@ class GitIndexer:try:with timed(timings, "rebuild.git.prior_defects"):prior_defects = compute_prior_defects(- repo, {m["file_path"] for m in results} | set(idle_paths), as_of_ts=as_of_ts+ repo,+ {m["file_path"] for m in code_results}+ | set(idle_paths).difference(history_files),+ as_of_ts=as_of_ts,)- for meta in results:+ for meta in code_results:fp = meta["file_path"]if fp in prior_defects.counts:meta["prior_defect_count"] = prior_defects.counts[fp]@@ -739,7 +771,7 @@ class GitIndexer:None,as_of_ts,)- for meta in results:+ for meta in code_results:fp = meta["file_path"]if fp in walk.partners:meta["co_change_partners_json"] = json.dumps(walk.partners[fp])@@ -770,6 +802,7 @@ class GitIndexer:prov_clf,walk,prior_defects,+ history_files,))except Exception as exc:@@ -795,6 +828,7 @@ class GitIndexer:prov_clf: Any,walk: CoChangeWalk,prior_defects: PriorDefects,+ history_files: set[str],) -> dict[str, dict]:"""Decay-only partial rows for *idle_paths* (see ``index_changed_files``).@@ -818,6 +852,7 @@ class GitIndexer:precomputed_commits=commit_index.get(fp),as_of_ts=as_of_ts,provenance_classifier=prov_clf,+ history_only=fp in history_files,)meta["change_entropy"] = walk.entropy.get(fp, 0.0)meta["co_change_partners_json"] = json.dumps(walk.partners.get(fp, []))diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.pyindex 140557071..d50ba0f82 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py@@ -275,6 +275,7 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> lraw = repo.git.log(rev_range,"--no-merges",+ "-M","--name-status",f"--format={_PRIOR_LOG_FORMAT}",)diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.pyindex c39ac01ba..4917244dd 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport contextlibimport re+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom pathlib import Path@@ -21,6 +22,7 @@ __all__ = ["RepoTotals","_CommitRec","_extract_rename_paths",+ "_history_tier_files","_parse_commit_record","_should_skip_index","capture_repo_totals",@@ -82,6 +84,9 @@ class _CommitRec:# the record so per-file rollups don't re-run the regex per touched file).agent: str | None = Noneagent_tier: int | None = None+ # The commit only moved this file (a rename row with 0/0 lines). It counts+ # as one of the file's commits but credits nobody with ownership.+ pure_move: bool = Falsedef _tz_offset_minutes(iso: str) -> int | None:@@ -623,3 +628,30 @@ def _should_skip_index(file_path: str) -> bool:Everything else (data, config, markup, dotfiles, binaries) is skipped."""return Path(file_path).suffix.lower() not in _CODE_EXTENSIONS+++def _history_tier_files(repo_path: Path, paths: Iterable[str]) -> set[str]:+ """The non-code files among *paths* that still get their commit history recorded.++ The history tier (counts, first and last commit, authors) covers every+ tracked file except vendored and generated directories, lockfiles and+ binaries: the traverser's own blocklists, plus a sniff for NUL bytes.+ """+ from ..traverser import (+ _BLOCKED_DIRS,+ _BLOCKED_EXTENSIONS,+ _BLOCKED_FILENAME_SPEC,+ _is_binary,+ )++ def _keep(file_path: str) -> bool:+ parts = file_path.split("/")+ if any(part in _BLOCKED_DIRS for part in parts[:-1]):+ return False+ if Path(file_path).suffix.lower() in _BLOCKED_EXTENSIONS:+ return False+ if _BLOCKED_FILENAME_SPEC.match_file(parts[-1]):+ return False+ return not _is_binary(repo_path / file_path)++ return {fp for fp in paths if _should_skip_index(fp) and _keep(fp)}diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex c87c2dece..36cae9f02 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -10,7 +10,7 @@ import jsonfrom collections.abc import Sequencefrom datetime import UTC, datetime-from sqlalchemy import delete, func, or_, select, text+from sqlalchemy import ColumnElement, and_, delete, func, or_, select, textfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import AsyncSession@@ -39,6 +39,16 @@ from ._shared import (# ---------------------------------------------------------------------------+def code_file_rows(repository_id: str) -> ColumnElement[bool]:+ """``where`` clause for a repository's code-file git rows.++ Repo-wide ownership, bus-factor and module rollups count only these: a+ ``history_only`` row (a doc or config file) carries commit counts, not+ ownership signal.+ """+ return and_(GitMetadata.repository_id == repository_id, GitMetadata.history_only.is_(False))++async def upsert_git_metadata(session: AsyncSession,*,@@ -321,6 +331,9 @@ async def recompute_git_percentiles(Python path gives it, and a gate at 0.80 turns that into findings thatappear and disappear on an unchanged tree.+ Every ranking is over code rows: ``history_only`` rows (non-code files)+ carry counts and authors but no rank, and read 0 / not-a-hotspot.+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.@@ -348,33 +361,37 @@ WITH ranked AS (ORDER BY COALESCE(temporal_hotspot_score, 0.0), commit_count_90d) AS prankFROM git_metadata- WHERE repository_id = :repo_id+ WHERE repository_id = :repo_id AND NOT history_only),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+ WHERE repository_id = :repo_id AND NOT history_only+ AND COALESCE(change_entropy, 0.0) > 0.0) AS erankFROM git_metadata- WHERE repository_id = :repo_id AND COALESCE(change_entropy, 0.0) > 0.0+ WHERE repository_id = :repo_id AND NOT history_only 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+ WHERE repository_id = :repo_id AND NOT history_only+ AND COALESCE(co_change_mass, 0.0) > 0.0) AS crankFROM git_metadata- WHERE repository_id = :repo_id AND COALESCE(co_change_mass, 0.0) > 0.0+ WHERE repository_id = :repo_id AND NOT history_only AND COALESCE(co_change_mass, 0.0) > 0.0),defect_ranked AS (SELECT id,PERCENT_RANK() OVER (ORDER BY COALESCE(prior_defect_count, 0)) AS drankFROM git_metadata- WHERE repository_id = :repo_id+ WHERE repository_id = :repo_id AND NOT history_only)UPDATE git_metadata-SET churn_percentile = (SELECT prank FROM ranked WHERE ranked.id = git_metadata.id),- is_hotspot = ((SELECT prank FROM ranked WHERE ranked.id = git_metadata.id) >= 0.75+SET churn_percentile = COALESCE(+ (SELECT prank FROM ranked WHERE ranked.id = git_metadata.id), 0.0),+ is_hotspot = (COALESCE((SELECT prank FROM ranked WHERE ranked.id = git_metadata.id), 0.0)+ >= 0.75AND git_metadata.commit_count_90d >= :min_commits_90dAND (git_metadata.commit_count_90d >= :high_commits_90dOR COALESCE(git_metadata.temporal_hotspot_score, 0.0)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 4613a9095..0b5ecedb8 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -27,6 +27,7 @@ from sqlalchemy import (String,Text,UniqueConstraint,+ false,)from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column@@ -597,6 +598,9 @@ class GitMetadata(Base):churn_percentile: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)age_days: Mapped[int] = mapped_column(Integer, nullable=False, default=0)commit_count_capped: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ # A non-code file: history tier only (counts, span, authors), no blame or+ # churn signals, and left out of the repo-relative rankings.+ history_only: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=false())# Diff size (Phase 2)lines_added_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.pyindex ef2da2587..95e65e300 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py@@ -6,6 +6,7 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GitMetadatafrom repowise.core.registry import mcp_tool_registry as mcp@@ -193,9 +194,7 @@ _READING_ORDER_HINT = (async def _load_git_rows(session: Any, repository: Any, exclude_spec: Any) -> list[Any]:"""Git metadata rows outside the exclude rules, the source of git health and ownership."""git_res = await session.execute(- select(GitMetadata).where(- GitMetadata.repository_id == repository.id,- )+ select(GitMetadata).where(code_file_rows(repository.id)))return filter_rows_by_attr(list(git_res.scalars().all()), "file_path", exclude_spec)diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 708a50ef3..e16d99c70 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -160,7 +160,7 @@ def _commit_fields() -> dict:"""Shared CommitResponse field map (raw row + repo-relative normalization)."""risk = _commit_risk(r)- top_driver = risk.top_drivers[0].label if risk and risk.top_drivers else None+ top_driver = risk.top_driver.label if risk and risk.top_driver else Nonereturn {"sha": r.sha,"short_sha": r.sha[:8],@@ -629,7 +629,7 @@ async def get_ownership(one entry per tracked file."""- result = await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id))+ result = await session.execute(select(GitMetadata).where(crud.code_file_rows(repo_id)))all_meta = result.scalars().all()if granularity == "file":@@ -835,7 +835,7 @@ async def get_git_summary(10) so an engineering leader can see the broader contributor surface."""- result = await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id))+ result = await session.execute(select(GitMetadata).where(crud.code_file_rows(repo_id)))all_meta = list(result.scalars().all())hotspot_count = sum(1 for m in all_meta if m.is_hotspot)diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 6a8f4a665..9cecf2c6f 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -286,7 +286,7 @@ async def overview_summary(# /ownership?granularity=module aggregation the page used to fetch).owner_rows = await session.execute(select(GitMetadata.file_path, GitMetadata.primary_owner_name).where(- GitMetadata.repository_id == repo_id+ crud.code_file_rows(repo_id)))module_owner_files: dict[str, dict[str, int]] = {}diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.pyindex 7e9d580f9..b363b4fd3 100644--- a/packages/server/src/repowise/server/routers/stats.py+++ b/packages/server/src/repowise/server/routers/stats.py@@ -202,7 +202,7 @@ async def stats_highlights(GitMetadata.commit_count_capped,GitMetadata.first_commit_at,GitMetadata.last_commit_at,- ).where(GitMetadata.repository_id == repo_id),+ ).where(crud.code_file_rows(repo_id)),)commits = await _rows(session,diff --git a/packages/server/src/repowise/server/services/c4_builder/__init__.py b/packages/server/src/repowise/server/services/c4_builder/__init__.pyindex 068d58441..748317861 100644--- a/packages/server/src/repowise/server/services/c4_builder/__init__.py+++ b/packages/server/src/repowise/server/services/c4_builder/__init__.py@@ -25,6 +25,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.ids import ExternalSystemId, SystemId, file_path_of, parse, renderfrom repowise.core.persistence import ExternalSystem, Repositoryfrom repowise.core.persistence.crud import (+ code_file_rows,get_kg_layers,get_kg_project_meta,get_kg_tour_steps,@@ -352,7 +353,7 @@ async def _per_file_signals(session: AsyncSession, repo_id: str) -> dict[str, diGitMetadata.is_hotspot,GitMetadata.primary_owner_name,GitMetadata.bus_factor,- ).where(GitMetadata.repository_id == repo_id)+ ).where(code_file_rows(repo_id)))).all()hotspot_paths = [row[0] for row in git_rows if row[1]]diff --git a/packages/server/src/repowise/server/services/knowledge_map.py b/packages/server/src/repowise/server/services/knowledge_map.pyindex 64588ee15..c935d0127 100644--- a/packages/server/src/repowise/server/services/knowledge_map.py+++ b/packages/server/src/repowise/server/services/knowledge_map.py@@ -13,6 +13,7 @@ from repowise.core.analysis.knowledge_map import (onboarding_targets,rank_silos,)+from repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.models import GitMetadata, GraphNode, Page@@ -35,7 +36,7 @@ async def compute_knowledge_silos(session: AsyncSession, repo_id: str) -> list[dGitMetadata.commit_count_90d,GitMetadata.is_hotspot,).where(- GitMetadata.repository_id == repo_id,+ code_file_rows(repo_id),GitMetadata.primary_owner_commit_pct > SILO_OWNER_PCT,))@@ -116,7 +117,7 @@ async def compute_knowledge_map(session: AsyncSession, repo_id: str) -> dict[strGitMetadata.primary_owner_email,GitMetadata.primary_owner_name,GitMetadata.primary_owner_commit_pct,- ).where(GitMetadata.repository_id == repo_id)+ ).where(code_file_rows(repo_id)))all_git = git_res.all()diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.pyindex 08bad915f..90673af22 100644--- a/packages/server/src/repowise/server/services/module_health.py+++ b/packages/server/src/repowise/server/services/module_health.py@@ -24,6 +24,7 @@ from repowise.core.analysis.module_health import (module_health_score,summarize,)+from repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.models import (DeadCodeFinding,DecisionRecord,@@ -47,7 +48,7 @@ async def aggregate_modules(session: AsyncSession, repo_id: str) -> dict[str, Mo"""Fetch the four inputs for *repo_id* and fold them by top-level module."""files = (- (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))+ (await session.execute(select(GitMetadata).where(code_file_rows(repo_id)))).scalars().all())diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.pyindex 3bdee0f8b..1dafc48b9 100644--- a/packages/server/src/repowise/server/services/owner_profile.py+++ b/packages/server/src/repowise/server/services/owner_profile.py@@ -17,6 +17,7 @@ from repowise.core.analysis.owners import (owner_key,silo_modules,)+from repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.models import (DeadCodeFinding,GitCommit,@@ -36,7 +37,7 @@ async def aggregate_owners("""git_rows = (- (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))+ (await session.execute(select(GitMetadata).where(code_file_rows(repo_id)))).scalars().all())diff --git a/packages/ui/__tests__/symbols/symbol-detail-body.test.tsx b/packages/ui/__tests__/symbols/symbol-detail-body.test.tsxnew file mode 100644index 000000000..3301b2a93--- /dev/null+++ b/packages/ui/__tests__/symbols/symbol-detail-body.test.tsx@@ -0,0 +1,23 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { SymbolDetailBody } from "../../src/symbols/symbol-detail-body.js";++describe("SymbolDetailBody", () => {+ it("labels the blame count as commits in current code and says what it counts", () => {+ render(+ <SymbolDetailBody+ data={{+ identity: { name: "run", kind: "function", file_path: "src/app.py", start_line: 3 },+ blame_mod_count: 4,+ blame_recent_mod_count: 1,+ }}+ />,+ );++ expect(screen.queryByText("Modifications")).toBeNull();+ const label = screen.getByText("Commits in current code");+ const tile = label.parentElement as HTMLElement;+ expect(tile.textContent).toContain("4");+ expect(tile.getAttribute("title")).toMatch(/current lines, by git blame/);+ });+});diff --git a/packages/ui/src/shared/stat-grid.tsx b/packages/ui/src/shared/stat-grid.tsxindex 20a9f523b..34e4e056f 100644--- a/packages/ui/src/shared/stat-grid.tsx+++ b/packages/ui/src/shared/stat-grid.tsx@@ -27,15 +27,19 @@ export interface StatTileProps {label: string;value: React.ReactNode;hint?: string;+ /** Tooltip saying what the number counts, when the label alone cannot. */+ title?: string;className?: string;}/** Compact label/value/hint cell — the consolidated inline-stat helper. */-export function StatTile({ label, value, hint, className }: StatTileProps) {+export function StatTile({ label, value, hint, title, className }: StatTileProps) {return (<div+ title={title}className={cn("rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3",+ title && "cursor-help",className,)}>diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsxindex daffc851f..72c8b52c0 100644--- a/packages/ui/src/symbols/symbol-detail-body.tsx+++ b/packages/ui/src/symbols/symbol-detail-body.tsx@@ -119,7 +119,8 @@ export function SymbolDetailBody({value={data.complexity_estimate != null ? String(data.complexity_estimate) : "—"}/><StatTile- label="Modifications"+ label="Commits in current code"+ title="Distinct commits that wrote this symbol's current lines, by git blame. A commit whose lines were all rewritten since is not counted."value={data.blame_mod_count != null ? String(data.blame_mod_count) : "—"}{...(data.blame_recent_mod_count != null? { hint: `${data.blame_recent_mod_count} recent` }@@ -127,7 +128,7 @@ export function SymbolDetailBody({/><StatTile label="Median age" value={age != null ? `${age}d` : "—"} />{data.fix_count != null && data.fix_count > 0 && (- // "How often changed" (Modifications) beside "how often broken" is+ // "How often changed" (commits in current code) beside "how often broken" is// the contrast that earns this tile. It appears only for a positive// count, since a symbol nobody has had to fix says nothing worth a cell,// and the hint hedges, because fixes are matched to symbols by linediff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex d5a68b922..ffc6090cd 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -612,3 +612,26 @@ def test_payload_offers_the_absolute_band_only_as_a_fallback(git_repo: Path) ->assert unranked["fallback_band"] in {"low", "moderate", "high"}assert unranked["score_unit"] == "per-commit"assert "probability" not in ranked and "level" not in ranked+++ "features",+ [+ ChangeFeatures(la=la, ld=ld, nf=nf, nd=nd, ns=ns, entropy=ent, exp=exp)+ for la in (0, 3, 40, 900)+ for ld in (0, 25, 400)+ for nf, nd, ns, ent in ((1, 1, 1, 0.0), (6, 3, 2, 2.1), (80, 20, 6, 5.5))+ for exp in (None, 0, 12, 4000)+ ],+)+def test_top_driver_is_the_argmax_of_the_shown_contributions(features) -> None:+ """The list's "top driver" is the biggest score-raising row the breakdown shows."""+ risk = score_change(features)+ shown = [d for d in risk.top_drivers if d.value is not None]+ raising = [d for d in shown if d.contribution > 0]+ if not raising:+ assert risk.top_driver is None+ return+ assert risk.top_driver is not None+ assert risk.top_driver.contribution == max(d.contribution for d in shown)+ assert risk.top_driver in showndiff --git a/tests/unit/ingestion/test_co_change_differential.py b/tests/unit/ingestion/test_co_change_differential.pynew file mode 100644index 000000000..e323933b0--- /dev/null+++ b/tests/unit/ingestion/test_co_change_differential.py@@ -0,0 +1,136 @@+"""The co-change walk against brute-force pair counting, commit by commit.++The brute force asks git about one commit at a time (``git show --name-status+-M``), files each path under its name at HEAD, and counts every pair and every+file's commits by hand. The walk must agree on every pair's support, both+files' commit totals and the last shared date, with and without the repo's+``diff.renames`` turned off.+"""++from __future__ import annotations++import os+import random+import subprocess+from collections import Counter+from datetime import UTC, datetime+from itertools import combinations+from pathlib import Path++import pytest++from repowise.core.ingestion.git_indexer._constants import _MIN_CO_CHANGE_SUPPORT+from repowise.core.ingestion.git_indexer.co_change import compute_co_changes_and_entropy++_FILES = [f"pkg/m{i}.py" for i in range(7)]+++def _git(root: Path, *args: str, date: str | None = None) -> str:+ env = {+ **os.environ,+ "GIT_AUTHOR_NAME": "A",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "A",+ "GIT_COMMITTER_EMAIL": "[email protected]",+ "HOME": str(root),+ "GIT_CONFIG_GLOBAL": os.devnull,+ }+ if date:+ env |= {"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date}+ return subprocess.run(+ ["git", "-C", str(root), *args], env=env, check=True, capture_output=True, text=True+ ).stdout+++def _build(root: Path, renames_off: bool) -> None:+ rng = random.Random(7)+ _git(root, "init", "-q")+ if renames_off:+ _git(root, "config", "diff.renames", "false")+ live = list(_FILES)+ body = {p: "".join(f"line {p} {k}\n" for k in range(30)) for p in live}+ for n in range(40):+ if n == 25:+ # A pure move of one file, and a move-with-edit of another.+ (root / "lib").mkdir(exist_ok=True)+ _git(root, "mv", "pkg/m0.py", "lib/m0.py")+ _git(root, "mv", "pkg/m1.py", "lib/m1.py")+ body["lib/m0.py"] = body.pop("pkg/m0.py")+ body["lib/m1.py"] = body.pop("pkg/m1.py") + "edited\n"+ (root / "lib/m1.py").write_text(body["lib/m1.py"])+ live = sorted(body)+ touched = ["lib/m0.py", "lib/m1.py"]+ else:+ touched = rng.sample(live, rng.choice([1, 2, 2, 3, 4]))+ for path in touched:+ body[path] += f"rev {n}\n"+ (root / path).parent.mkdir(parents=True, exist_ok=True)+ (root / path).write_text(body[path])+ _git(root, "add", "-A")+ _git(+ root, "commit", "-q", "-m", f"c{n}", date=f"2024-01-{1 + n % 28:02d}T{n % 24:02d}:00:00"+ )+++def _brute(root: Path, limit: int) -> tuple[Counter, Counter, dict]:+ shas = _git(root, "rev-list", "--no-merges", f"-{limit}", "HEAD").split()+ trail: dict[str, str] = {}+ file_commits: Counter = Counter()+ support: Counter = Counter()+ last: dict = {}+ tracked = set(_git(root, "ls-files").split())+ for sha in shas:+ ts = int(_git(root, "show", "-s", "--format=%ct", sha).strip())+ rows = _git(root, "show", "-M", "--name-status", "--format=", sha).splitlines()+ paths, moves = set(), []+ for row in rows:+ cols = row.split("\t")+ if not row.strip():+ continue+ path = cols[-1]+ if cols[0].startswith("R"):+ moves.append((cols[1], cols[2]))+ head = trail.get(path, path)+ if head in tracked:+ paths.add(head)+ for old, new in moves:+ trail[old] = trail.get(new, new)+ for path in paths:+ file_commits[path] += 1+ for a, b in combinations(sorted(paths), 2):+ support[(a, b)] += 1+ last[(a, b)] = max(last.get((a, b), 0), ts)+ return file_commits, support, last++[email protected]("renames_off", [False, True])+def test_walk_matches_brute_force_pair_counts(tmp_path, renames_off) -> None:+ import git as gitpython++ _build(tmp_path, renames_off)+ tracked = set(_git(tmp_path, "ls-files").split())+ limit = 30 # shorter than the history, so the depth cap is exercised too++ repo = gitpython.Repo(tmp_path)+ try:+ walk = compute_co_changes_and_entropy(repo, tracked, limit, max_partners=100)+ finally:+ repo.close()+ file_commits, support, last = _brute(tmp_path, limit)++ expected = {pair for pair, n in support.items() if n >= _MIN_CO_CHANGE_SUPPORT}+ got: dict[tuple[str, str], dict] = {}+ for owner, records in walk.partners.items():+ for rec in records:+ got[tuple(sorted((owner, rec["file_path"])))] = rec | {"owner": owner}+ assert set(got) == expected+ assert expected, "fixture should produce pairs above support"+ for pair, rec in got.items():+ assert rec["frequency"] == support[pair]+ other = rec["file_path"]+ assert rec["self_commits"] == file_commits[rec["owner"]]+ assert rec["partner_commits"] == file_commits[other]+ day = datetime.fromtimestamp(last[pair], tz=UTC).strftime("%Y-%m-%d")+ assert rec["last_co_change"] == day+ # The moved files kept their pre-move history.+ assert file_commits["lib/m0.py"] > 1diff --git a/tests/unit/ingestion/test_git_history_renames.py b/tests/unit/ingestion/test_git_history_renames.pyindex 05a82b297..e91c9d446 100644--- a/tests/unit/ingestion/test_git_history_renames.py+++ b/tests/unit/ingestion/test_git_history_renames.py@@ -124,3 +124,93 @@ def test_rename_trail_resolves_chains(renames, path, want) -> None:for old, new in renames:trail.record(old, new)assert trail.resolve(path) == want+++def _bulk_move_repo(root, *, renames_off: bool = False):+ """Bob writes three files; Carol moves them all into src/ without editing a line."""+ repo = _repo(root)+ if renames_off:+ with repo.config_writer() as cw:+ cw.set_value("diff", "renames", "false")+ files = {"a.py": _BODY, "b.py": _BODY.replace("x +", "x -"), "notes.md": "# notes\n" * 20}+ for i in range(3):+ _commit(+ repo,+ root,+ {name: body + f"# rev {i}\n" for name, body in files.items()},+ f"feat: round {i}",+ f"2024-01-0{i + 1}T12:00:00",+ author="Bob",+ )+ (root / "src").mkdir()+ for name in files:+ repo.git.mv(name, f"src/{name}")+ env = {+ "GIT_AUTHOR_NAME": "Carol",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Carol",+ "GIT_COMMITTER_EMAIL": "[email protected]",+ "GIT_AUTHOR_DATE": "2024-02-01T12:00:00",+ "GIT_COMMITTER_DATE": "2024-02-01T12:00:00",+ }+ repo.git.commit("-q", "-m", "refactor: move everything into src", env=env)+ repo.close()++[email protected]("renames_off", [False, True])+async def test_bulk_pure_move_counts_for_the_file_but_credits_nobody(+ tmp_path, monkeypatch, renames_off+) -> None:+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")+ _bulk_move_repo(tmp_path, renames_off=renames_off)++ _s, rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")+ meta = {row["file_path"]: row for row in rows}++ for path in ("src/a.py", "src/b.py", "src/notes.md"):+ row = meta[path]+ # Three edits plus the move: the move is one of the file's commits,+ # even with the repository's own rename detection switched off.+ assert row["commit_count_total"] == 4+ authors = {a["name"]: a["commit_count"] for a in json.loads(row["top_authors_json"])}+ assert authors == {"Bob": 3}+ assert row["contributor_count"] == 1+ assert row["primary_owner_commit_pct"] == 1.0+ assert row["last_commit_at"].date().isoformat() == "2024-02-01"+ assert meta["src/a.py"]["primary_owner_name"] == "Bob"+++async def test_per_file_fallback_lane_also_skips_a_pure_move(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")+ _bulk_move_repo(tmp_path)++ # --follow runs the per-file lane for every file.+ _s, rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL, follow_renames=True).index_repo(+ "r"+ )+ row = {r["file_path"]: r for r in rows}["src/a.py"]+ assert row["commit_count_total"] == 4+ authors = {a["name"]: a["commit_count"] for a in json.loads(row["top_authors_json"])}+ assert authors == {"Bob": 3}+++ ("rows", "want"),+ [+ (["0 0 {old => new}/a.py", "0 0 other.py"], True),+ (["0 0 {old => new}/a.py", "0 0 new/a.py"], True),+ (["0 0 {old => new}/a.py", "3 1 new/a.py"], False),+ (["2 0 {old => new}/a.py"], False),+ (["0 0 new/a.py"], False),+ ],+)+def test_per_file_lane_pure_move_is_accumulated_across_rows(rows, want) -> None:+ """A later row naming the file cannot clear an earlier pure-move rename."""+ from repowise.core.ingestion.git_indexer.file_history import _add_own_churn+ from repowise.core.ingestion.git_indexer.records import _CommitRec++ rec = _CommitRec(+ sha="s", author_name="C", author_email="c@x", ts=0, is_merge=False, subject="m"+ )+ _add_own_churn(rec, rows, {"new/a.py"})+ assert rec.pure_move is wantdiff --git a/tests/unit/ingestion/test_git_history_tier.py b/tests/unit/ingestion/test_git_history_tier.pynew file mode 100644index 000000000..50e2c8021--- /dev/null+++ b/tests/unit/ingestion/test_git_history_tier.py@@ -0,0 +1,159 @@+"""Non-code files get a history tier: counts, span and authors from the repo-wide walk.++Code files keep the full pass (blame, churn signals). Binary, vendored and lock+files get no row. History-tier rows stay out of the repo-relative rankings+(the SQL recompute is covered in ``tests/unit/persistence``).+"""++from __future__ import annotations++import json+import os+import subprocess+from pathlib import Path++from repowise.core.ingestion.git_indexer import GitIndexer+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier++_PY = "".join(f"def f{i}(x):\n return x + {i}\n\n" for i in range(12))+++def _git(root: Path, *args: str, date: str | None = None, author: str = "Alice") -> str:+ env = {+ **os.environ,+ "GIT_AUTHOR_NAME": author,+ "GIT_AUTHOR_EMAIL": f"{author.lower()}@example.com",+ "GIT_COMMITTER_NAME": author,+ "GIT_COMMITTER_EMAIL": f"{author.lower()}@example.com",+ "HOME": str(root),+ "GIT_CONFIG_GLOBAL": os.devnull,+ }+ if date:+ env |= {"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date}+ out = subprocess.run(+ ["git", "-C", str(root), *args], env=env, check=True, capture_output=True, text=True+ )+ return out.stdout+++def _commit(root: Path, files: dict[str, str | bytes], msg: str, day: int, author: str) -> None:+ for name, content in files.items():+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ if isinstance(content, bytes):+ path.write_bytes(content)+ else:+ path.write_text(content)+ _git(root, "add", "--", *files)+ _git(root, "commit", "-q", "-m", msg, date=f"2024-03-{day:02d}T12:00:00", author=author)+++def _build(root: Path) -> None:+ _git(root, "init", "-q")+ _commit(+ root,+ {+ "a.py": _PY,+ "b.py": "y = 1\n",+ "README.md": "# r\n",+ ".github/workflows/ci.yml": "on: push\n",+ "config.json": "{}\n",+ "logo.png": b"\x89PNG\r\n\x1a\n\x00\x00\x00binary",+ "yarn.lock": "# lock\n",+ "vendor/lib/notes.md": "vendored\n",+ },+ "feat: initial",+ 1,+ "Alice",+ )+ for i in range(2, 6):+ _commit(+ root,+ {"a.py": _PY + f"# {i}\n", "README.md": f"# r {i}\n", "logo.png": b"\x00" * i},+ f"feat: round {i}",+ i,+ "Bob" if i % 2 else "Alice",+ )+ _commit(root, {"config.json": '{"k": 1}\n'}, "chore: config", 7, "Carol")+ _commit(root, {".github/workflows/ci.yml": "on: [push]\n"}, "ci: tweak", 8, "Bob")+++def _git_log_count(root: Path, path: str) -> int:+ return len(_git(root, "log", "--no-merges", "--format=%H", "--", path).split())+++async def test_non_code_files_get_history_from_the_shared_walk(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")+ _build(tmp_path)++ _summary, rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")+ meta = {row["file_path"]: row for row in rows}++ # Binary, lock and vendored files get no row at all.+ assert set(meta) == {"a.py", "b.py", "README.md", ".github/workflows/ci.yml", "config.json"}++ for path in ("README.md", ".github/workflows/ci.yml", "config.json"):+ row = meta[path]+ assert row["history_only"] is True+ # The count git itself reports for the path, exactly.+ assert row["commit_count_total"] == _git_log_count(tmp_path, path)+ assert row["first_commit_at"] is not None and row["last_commit_at"] is not None+ # Blame and the code signals stay code-only.+ assert row["primary_owner_line_pct"] is None+ assert "blame_index" not in row+ assert row["temporal_hotspot_score"] == 0.0+ assert row["churn_percentile"] == 0.0 and row["is_hotspot"] is False+ assert json.loads(row["co_change_partners_json"]) == []++ readme = meta["README.md"]+ assert readme["commit_count_total"] == 5+ authors = {a["name"]: a["commit_count"] for a in json.loads(readme["top_authors_json"])}+ assert authors == {"Alice": 3, "Bob": 2}+ assert readme["contributor_count"] == 2+ assert meta["config.json"]["last_commit_at"].date().isoformat() == "2024-03-07"++ # Code rows keep the full pass and rank among code files only.+ assert meta["a.py"]["history_only"] is False+ assert meta["a.py"]["commit_count_total"] == _git_log_count(tmp_path, "a.py")+ assert meta["a.py"]["primary_owner_line_pct"] is not None+ assert {meta["a.py"]["churn_percentile"], meta["b.py"]["churn_percentile"]} <= {0.0, 0.5}+++async def test_update_writes_the_same_history_rows_as_a_full_index(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")+ _build(tmp_path)+ tracked = set(_git(tmp_path, "ls-files").split())++ sink: dict[str, dict] = {}+ rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_changed_files(+ ["README.md", "logo.png", "yarn.lock", "a.py"],+ all_files=tracked,+ co_change_sink={},+ idle_decay_sink=sink,+ )+ _summary, full_rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")+ full = {row["file_path"]: row for row in full_rows}++ changed = {row["file_path"]: row for row in rows}+ assert set(changed) == {"a.py", "README.md"}+ for key in ("history_only", "commit_count_total", "top_authors_json", "last_commit_at"):+ assert changed["README.md"][key] == full["README.md"][key]+ assert set(sink) <= set(full)+ # Idle history-tier rows refresh their windows but carry no code signal.+ for path in ("config.json", ".github/workflows/ci.yml"):+ assert sink[path]["temporal_hotspot_score"] == 0.0+ assert sink[path]["prior_defect_count"] == 0+++async def test_follow_renames_mode_gives_non_code_files_no_rows(tmp_path, monkeypatch) -> None:+ """Pins a known limit: --follow skips the shared walk the history tier fills from."""+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")+ _build(tmp_path)++ _s, rows = await GitIndexer(+ tmp_path, tier=GitIndexTier.FULL, follow_renames=True+ ).index_repo("r")+ paths = {row["file_path"] for row in rows}++ assert "a.py" in paths+ assert not {"README.md", ".github/workflows/ci.yml", "config.json"} & pathsdiff --git a/tests/unit/ingestion/test_git_index_changed_files_allowlist.py b/tests/unit/ingestion/test_git_index_changed_files_allowlist.pyindex c8fa94323..fa753d7cf 100644--- a/tests/unit/ingestion/test_git_index_changed_files_allowlist.py+++ b/tests/unit/ingestion/test_git_index_changed_files_allowlist.py@@ -1,10 +1,9 @@"""An update's git index covers the same files a full index does.-``index_repo`` skips every path outside the source-extension allowlist.-``index_changed_files`` did not, so a changed workflow file got a row, and the-idle-decay refresh minted a row for every tracked config and markup file; the-health pass then scored them. A store that had taken updates held rows a fresh-index never writes.+``index_repo`` gives code files the full pass and other tracked files only the+history tier. ``index_changed_files`` once applied no allowlist, so a store that+had taken updates held rows a fresh index never writes. Both now split the+tiers the same way: a non-code row is ``history_only`` on either path."""from __future__ import annotations@@ -49,9 +48,14 @@ async def test_changed_files_and_idle_refresh_follow_the_full_index_allowlist(tmidle_decay_sink=sink,)- assert {r["file_path"] for r in rows} == {"a.py"}- assert not {p for p in sink if p.endswith((".yaml", ".md"))}+ by_path = {r["file_path"]: r for r in rows}+ assert set(by_path) == {"a.py", ".github/workflows/ci.yaml"}+ assert by_path[".github/workflows/ci.yaml"]["history_only"] is True+ assert by_path["a.py"]["history_only"] is False_summary, full_rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")- full_paths = {r["file_path"] for r in full_rows}- assert {r["file_path"] for r in rows} | set(sink) <= full_paths+ full = {r["file_path"]: r for r in full_rows}+ assert set(by_path) | set(sink) <= set(full)+ for path, row in by_path.items():+ assert row["history_only"] == full[path]["history_only"]+ assert row["commit_count_total"] == full[path]["commit_count_total"]diff --git a/tests/unit/ingestion/test_one_fix_definition.py b/tests/unit/ingestion/test_one_fix_definition.pynew file mode 100644index 000000000..451ab3981--- /dev/null+++ b/tests/unit/ingestion/test_one_fix_definition.py@@ -0,0 +1,44 @@+"""Every fix count counts the same commits: the ``is_fix_commit`` rule.++The per-file commit categories and the evolution timeline once each carried a+broader "fix" regex of their own, so a file page, the commits page and the+bug-fix history disagreed about how many fixes there were.+"""++from __future__ import annotations++import pytest++from repowise.core.ingestion.git_indexer._constants import (+ classify_commit_category,+ is_fix_commit,+)+from repowise.core.ingestion.git_indexer.file_history import _commit_category++SUBJECTS = [+ "fix: null check in parser",+ "fix(api): handle empty body",+ "Fix typo in README",+ "fix: bump deps",+ "chore: fix lint",+ 'Revert "feat: add cache"',+ "revert: drop flaky retry",+ "handle crash on startup",+ "error handling for uploads",+ "feat: add retry, fixes #12",+ "refactor: move helpers, closes #40",+ "hotfix: restore login",+ "bugfix: off-by-one in pager",+ "Resolve race in scheduler",+ "docs: explain the bug in the FAQ",+ "patch the vendored parser",+ "feat: add export",+ "",+]++[email protected]("subject", SUBJECTS)+def test_every_surface_labels_fix_exactly_as_is_fix_commit(subject) -> None:+ want = is_fix_commit(subject)+ assert (classify_commit_category(subject) == "fix") == want+ assert (_commit_category(subject) == "fix") == wantdiff --git a/tests/unit/persistence/test_git_history_only_ranking.py b/tests/unit/persistence/test_git_history_only_ranking.pynew file mode 100644index 000000000..e784d03f5--- /dev/null+++ b/tests/unit/persistence/test_git_history_only_ranking.py@@ -0,0 +1,40 @@+"""The SQL percentile recompute ranks code rows only; history-tier rows read 0."""++from __future__ import annotations++from sqlalchemy import select++from repowise.core.persistence.crud import recompute_git_percentiles, upsert_git_metadata_bulk+from repowise.core.persistence.models import GitMetadata+from tests.unit.persistence.helpers import insert_repo+++async def test_sql_recompute_ranks_code_rows_only(async_session) -> None:+ repo = await insert_repo(async_session)+ code = [+ {"file_path": f"m{i}.py", "temporal_hotspot_score": float(i), "commit_count_90d": 9}+ for i in range(4)+ ]+ docs = [+ {"file_path": f"d{i}.md", "history_only": True, "commit_count_90d": 50} for i in range(8)+ ]+ await upsert_git_metadata_bulk(async_session, repo.id, code + docs)+ await recompute_git_percentiles(async_session, repo.id)++ rows = (+ (+ await async_session.execute(+ select(GitMetadata).where(GitMetadata.repository_id == repo.id)+ )+ )+ .scalars()+ .all()+ )+ pct = {r.file_path: r.churn_percentile for r in rows}+ # Ranked among the four code rows alone: 0, 1/3, 2/3, 1.+ assert [round(pct[f"m{i}.py"], 3) for i in range(4)] == [0.0, 0.333, 0.667, 1.0]+ for r in rows:+ if r.history_only:+ assert r.churn_percentile == 0.0+ assert r.is_hotspot is False+ assert r.prior_defect_pct == 0.0diff --git a/tests/unit/server/test_history_only_rollups.py b/tests/unit/server/test_history_only_rollups.pynew file mode 100644index 000000000..5d6be8bb5--- /dev/null+++ b/tests/unit/server/test_history_only_rollups.py@@ -0,0 +1,76 @@+"""History-only git rows (docs, config) carry counts but no ownership signal.++A README written by one person must not make them a file owner, a silo or a+bus-factor risk, nor pull a module's bus factor or hotspot share down.+"""++from __future__ import annotations++import json++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.server.services.knowledge_map import compute_knowledge_map+from tests.unit.server.conftest import create_test_repo+from tests.unit.server.test_modules_health import _seed+++async def _add_doc(session_factory, repo_id: str) -> None:+ async with get_session(session_factory) as session:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path="src/README.md",+ history_only=True,+ commit_count_total=3,+ primary_owner_name="Carol",+ primary_owner_email="[email protected]",+ primary_owner_commit_pct=1.0,+ top_authors_json=json.dumps(+ [{"name": "Carol", "email": "[email protected]", "commit_count": 3}]+ ),+ bus_factor=1,+ churn_percentile=0.0,+ )+++async def _snapshot(client: AsyncClient, session_factory, repo_id: str) -> dict:+ base = f"/api/repos/{repo_id}"+ out = {}+ for key, path in {+ "owners": "/owners",+ "modules": "/modules/health",+ "ownership": "/ownership?granularity=module",+ "summary": "/git-summary",+ }.items():+ resp = await client.get(base + path)+ assert resp.status_code == 200, (path, resp.text)+ out[key] = resp.json()+ async with get_session(session_factory) as session:+ out["knowledge"] = await compute_knowledge_map(session, repo_id)+ return out+++async def test_doc_rows_leave_ownership_and_module_rollups_unchanged(+ client: AsyncClient, app+) -> None:+ plain = await create_test_repo(client)+ await _seed(app.state.session_factory, plain["id"])+ with_doc = await create_test_repo(client)+ await _seed(app.state.session_factory, with_doc["id"])+ await _add_doc(app.state.session_factory, with_doc["id"])++ want = await _snapshot(client, app.state.session_factory, plain["id"])+ got = await _snapshot(client, app.state.session_factory, with_doc["id"])++ assert {o["name"] for o in got["owners"]["items"]} == {"Alice"}+ assert got["owners"]["items"] == want["owners"]["items"]+ assert got["modules"]["items"] == want["modules"]["items"]+ assert got["ownership"]["items"] == want["ownership"]["items"]+ assert got["summary"] == want["summary"]+ for key in ("top_owners", "knowledge_silos"):+ assert got["knowledge"][key] == want["knowledge"][key]