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
refactor(git): stage index_repo and the co-change walk (#4057)
Raghav Chamadiya4ba74f1e22c6
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_full_index.py b/packages/core/src/repowise/core/ingestion/git_indexer/_full_index.pynew file mode 100644index 000000000..a0dc7f2a4--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_full_index.py@@ -0,0 +1,99 @@+"""Stages of :meth:`GitIndexer.index_repo` that run after the parallel walks."""++from __future__ import annotations++import json+from typing import Any, NamedTuple++import structlog++from ._incremental import apply_co_change, apply_prior_defects+from .co_change import CoChangeWalk+from .enrich import compute_percentiles+from .prior_defects import PriorDefects+from .records import GitHistoryCoverage, _CommitRec++# Logged under the indexer module's name.+logger = structlog.get_logger("repowise.core.ingestion.git_indexer.indexer")+++class CommitSample(NamedTuple):+ """The repo-wide commit-index walk of a full index, or its rename-tracking stand-in."""++ commits: dict[str, list[_CommitRec]]+ fallback_files: set[str]+ recent_files: set[str]+ deep_files: set[str]+ global_commits: int+ deep_commits: int+ complete_through_depth: int+++def merge_code_signals(+ code_results: list[dict],+ walk: CoChangeWalk,+ prior_defects: PriorDefects,+ trace_index: Any,+) -> None:+ """Overlay co-change, entropy, prior defects and AI line share, then percentiles.++ The line share is keyed by path, so it merges whichever commit-index walk+ (if any) ran.+ """+ trace_line_shares = trace_index.line_shares() if trace_index else {}+ apply_co_change(code_results, walk)+ apply_prior_defects(code_results, prior_defects)+ for meta in code_results:+ share = trace_line_shares.get(meta["file_path"])+ if share:+ meta["agent_line_count"] = share[0]+ meta["agent_line_model_json"] = json.dumps(share[1])++ compute_percentiles(code_results)+++def build_commit_tables(commit_sink: list[dict]) -> tuple[list[dict], list[dict]]:+ """Per-commit rows and their file detail from the commit-index walk's parsed diffs.++ Empty in rename-tracking mode (no batched commit index). Failure-isolated+ so a change_risk hiccup never breaks file-level git metadata.+ """+ if not commit_sink:+ return [], []+ try:+ from .commit_rows import build_commit_file_rows, build_commit_rows++ built = build_commit_rows(commit_sink)+ built_files = build_commit_file_rows(commit_sink)+ except Exception as exc:+ logger.debug("commit_rows_build_failed", error=str(exc))+ return [], []+ # Returned together: a half-built pair would write commits whose file+ # detail describes a different set.+ return built, built_files+++def history_coverage(+ indexable_files: list[str],+ code_results: list[dict],+ sample: CommitSample,+ per_file_limit: int,+ workers: int,+) -> GitHistoryCoverage:+ """How much history the full index saw; it describes the code tier."""+ return GitHistoryCoverage(+ eligible_files=len(indexable_files),+ files_with_history=sum(+ 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=per_file_limit,+ global_commits=sample.global_commits,+ deep_commits=sample.deep_commits,+ recent_files=len(sample.recent_files.intersection(indexable_files)),+ deep_files=len(sample.deep_files.intersection(indexable_files)),+ fallback_files=len(sample.fallback_files.intersection(indexable_files)),+ complete_through_depth=sample.complete_through_depth,+ workers=workers,+ )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 15c79bcaf..ab9ae1480 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@@ -103,107 +103,35 @@ def _partner_records(return out-def compute_co_changes_and_entropy(- repo: Any,- all_files: set[str],- commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,- max_partners: int = _MAX_PARTNERS_PER_FILE,- on_commit_done: Callable[[], None] | None = None,- on_co_change_start: Callable[[int], None] | None = None,- as_of_ts: float | None = None,-) -> CoChangeWalk:- """Walk recent commits once, returning every history signal it yields.-- Uses a single ``git log --name-status`` call instead of spawning one- ``git diff`` subprocess per commit — O(1) processes vs O(commit_limit).- Its rename rows file each older commit under the path at HEAD, so a file- keeps its co-change partners and entropy across a rename, like its churn.-- **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 hundred- other files. Without that, a commit contributes ``O(n^2)`` pairs at full- weight 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 both- files' commit totals from this same walk, so a caller can state a- directional confidence without borrowing a denominator computed over a- different window. Pairs below ``_MIN_CO_CHANGE_SUPPORT`` shared commits are- dropped, then each file keeps its ``max_partners`` strongest — both- scale-free, unlike a cutoff on the weight, which shifts whenever the- weighting does.-- ``on_co_change_start(total)`` is called once with the actual number of- commits found; ``on_commit_done()`` after each commit block. Both run from a- thread-pool thread; callers must ensure thread safety.-- **Change entropy** adapts Hassan's History Complexity Metric: each commit is- a one-period window whose entropy is ``log2(|F|)`` (``|F|`` = tracked files- it touched), distributed uniformly (``1/|F|`` each) across those files with- the same temporal decay. A file only ever changed alone (``|F| == 1``, so- ``log2(1) == 0``) accrues no entropy; a file repeatedly caught in wide,- scattered commits accrues a lot. Commits touching more than- ``_MAX_FILES_PER_COMMIT_FOR_ENTROPY`` files are dropped as noise. The return- 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_focused: defaultdict[tuple[str, str], int] = defaultdict(int)- pair_last_date: dict[tuple[str, str], int] = {} # pair → latest Unix ts- file_commits: defaultdict[str, int] = defaultdict(int)- entropy_scores: defaultdict[str, float] = defaultdict(float)- # Anchor the decay reference to the repo's most recent commit (passed by the- # orchestrator) rather than wall-clock time, so the decay is deterministic- # and historical-checkout-correct (mirrors file_history's as_of_ts). Falls- # back to wall clock when not supplied.- now_ts = as_of_ts if as_of_ts is not None else time.time()-- 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",- )- except Exception:- return CoChangeWalk()-- actual_commits = raw.count("\x00")- if on_co_change_start is not None:- on_co_change_start(actual_commits)+@dataclass+class _WalkTally:+ """Per-pair and per-file accumulators of one ``git log`` walk."""- current: set[str] = set()- moved: list[tuple[str, str]] = []- renames = RenameTrail()- 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 = 0+ now_ts: float+ pair_scores: defaultdict[tuple[str, str], float] = field(+ default_factory=lambda: defaultdict(float)+ )+ pair_support: defaultdict[tuple[str, str], int] = field(+ default_factory=lambda: defaultdict(int)+ )+ pair_focused: defaultdict[tuple[str, str], int] = field(+ default_factory=lambda: defaultdict(int)+ )+ pair_last_date: dict[tuple[str, str], int] = field(default_factory=dict) # latest Unix ts+ file_commits: defaultdict[str, int] = field(default_factory=lambda: defaultdict(int))+ entropy_scores: defaultdict[str, float] = field(default_factory=lambda: defaultdict(float))- def _flush_commit() -> None:- nonlocal current_ts+ def add_commit(self, current: set[str], current_ts: int, current_ordinal: int) -> None:+ """Fold one commit's tracked files into the tallies."""n = len(current)# Counted before the pair guard: a commit where a file changed alone is# still one of its commits, and it is the denominator that decides# whether the file ever changes without its partner.for path in current:- file_commits[path] += 1+ self.file_commits[path] += 1if n < 2:return- age_days = max((now_ts - current_ts) / 86400.0, 0.0)+ age_days = max((self.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.@@ -216,11 +144,10 @@ def compute_co_changes_and_entropy(if n <= _MAX_FILES_PER_COMMIT_FOR_ENTROPY:contribution = weight * math.log2(n) / nfor path in current:- entropy_scores[path] += contribution+ self.entropy_scores[path] += contributionif n > _MAX_FILES_PER_COMMIT_FOR_COCHANGE:- # Mass-edit commit — skip pair generation entirely (see constant- # docstring). Logged at debug for traceability.+ # Mass-edit commit: no pairs (see the constant's docstring).logger.debug("co_change_skip_oversized_commit",files_in_commit=n,@@ -229,23 +156,46 @@ 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 = pair_decay / (n - 1)- focused = n <= _MAX_FILES_PER_COMMIT_FOR_ENTROPY- sorted_files = sorted(current)+ self._add_pairs(+ sorted(current),+ current_ts,+ pair_decay / (n - 1),+ n <= _MAX_FILES_PER_COMMIT_FOR_ENTROPY,+ )++ def _add_pairs(+ self, sorted_files: list[str], current_ts: int, pair_weight: float, focused: bool+ ) -> None:for i in range(len(sorted_files)):for j in range(i + 1, len(sorted_files)):pair = (sorted_files[i], sorted_files[j])- pair_scores[pair] += pair_weight- pair_support[pair] += 1+ self.pair_scores[pair] += pair_weight+ self.pair_support[pair] += 1if focused:- pair_focused[pair] += 1- if pair not in pair_last_date or current_ts > pair_last_date[pair]:- pair_last_date[pair] = current_ts+ self.pair_focused[pair] += 1+ if pair not in self.pair_last_date or current_ts > self.pair_last_date[pair]:+ self.pair_last_date[pair] = current_ts+++def _walk_commits(+ raw: str,+ all_files: set[str],+ tally: _WalkTally,+ on_commit_done: Callable[[], None] | None,+) -> None:+ """Feed every commit block of *raw* to *tally*, filing renamed paths under HEAD's name."""+ current: set[str] = set()+ moved: list[tuple[str, str]] = []+ renames = RenameTrail()+ 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 = 0for line in raw.splitlines():if line == "\x00" or line.startswith("\x00"):# Commit boundary — flush previous, parse timestamp.- _flush_commit()+ tally.add_commit(current, current_ts, current_ordinal)for old_path, new_path in moved:renames.record(old_path, new_path)current = set()@@ -267,11 +217,20 @@ def compute_co_changes_and_entropy(if path in all_files:current.add(path)- _flush_commit() # final commit+ tally.add_commit(current, current_ts, current_ordinal) # final commit+- # Keep each file's strongest partners, via a bounded min-heap per file so- # the persisted column stays linear in the file count.+def _strongest_partners(+ tally: _WalkTally, max_partners: int+) -> tuple[dict[str, list[tuple[float, str]]], dict[str, int], dict[str, float]]:+ """Each file's ``max_partners`` strongest partners, plus breadth over every partner.++ A bounded min-heap per file keeps the persisted column linear in the file+ count. Returns ``(kept, partner_count, partner_mass)``.+ """kept: defaultdict[str, list[tuple[float, str]]] = defaultdict(list)+ partner_count: defaultdict[str, int] = defaultdict(int)+ partner_mass: defaultdict[str, float] = defaultdict(float)def _offer(owner: str, other: str, score: float) -> None:heap = kept[owner]@@ -280,8 +239,8 @@ def compute_co_changes_and_entropy(elif score > heap[0][0]:heapq.heapreplace(heap, (score, other))- for pair, score in pair_scores.items():- if pair_support[pair] < _MIN_CO_CHANGE_SUPPORT:+ for pair, score in tally.pair_scores.items():+ if tally.pair_support[pair] < _MIN_CO_CHANGE_SUPPORT:continuea, b = pair# Past the support filter, before the heap: breadth over every partner.@@ -291,17 +250,98 @@ def compute_co_changes_and_entropy(partner_mass[b] += score_offer(a, b, score)_offer(b, a, score)+ return kept, partner_count, partner_mass+- result = _partner_records(kept, pair_support, pair_focused, pair_last_date, file_commits)+def compute_co_changes_and_entropy(+ repo: Any,+ all_files: set[str],+ commit_limit: int = _DEFAULT_CO_CHANGE_COMMIT_LIMIT,+ max_partners: int = _MAX_PARTNERS_PER_FILE,+ on_commit_done: Callable[[], None] | None = None,+ on_co_change_start: Callable[[int], None] | None = None,+ as_of_ts: float | None = None,+) -> CoChangeWalk:+ """Walk recent commits once, returning every history signal it yields.++ Uses a single ``git log --name-status`` call instead of spawning one+ ``git diff`` subprocess per commit — O(1) processes vs O(commit_limit).+ Its rename rows file each older commit under the path at HEAD, so a file+ keeps its co-change partners and entropy across a rename, like its churn.++ **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 hundred+ other files. Without that, a commit contributes ``O(n^2)`` pairs at full+ weight 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 both+ files' commit totals from this same walk, so a caller can state a+ directional confidence without borrowing a denominator computed over a+ different window. Pairs below ``_MIN_CO_CHANGE_SUPPORT`` shared commits are+ dropped, then each file keeps its ``max_partners`` strongest — both+ scale-free, unlike a cutoff on the weight, which shifts whenever the+ weighting does.++ ``on_co_change_start(total)`` is called once with the actual number of+ commits found; ``on_commit_done()`` after each commit block. Both run from a+ thread-pool thread; callers must ensure thread safety.++ **Change entropy** adapts Hassan's History Complexity Metric: each commit is+ a one-period window whose entropy is ``log2(|F|)`` (``|F|`` = tracked files+ it touched), distributed uniformly (``1/|F|`` each) across those files with+ the same temporal decay. A file only ever changed alone (``|F| == 1``, so+ ``log2(1) == 0``) accrues no entropy; a file repeatedly caught in wide,+ scattered commits accrues a lot. Commits touching more than+ ``_MAX_FILES_PER_COMMIT_FOR_ENTROPY`` files are dropped as noise. The return+ value maps ``file_path → decayed HCM sum`` (only files with a positive sum).+ """+ # Decay is anchored to the repo's newest commit when the orchestrator passes+ # it, so it is deterministic and correct on a historical checkout.+ tally = _WalkTally(now_ts=as_of_ts if as_of_ts is not None else time.time())++ 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",+ )+ except Exception:+ return CoChangeWalk()++ actual_commits = raw.count("\x00")+ if on_co_change_start is not None:+ on_co_change_start(actual_commits)++ _walk_commits(raw, all_files, tally, on_commit_done)+ kept, partner_count, partner_mass = _strongest_partners(tally, max_partners)++ result = _partner_records(+ kept, tally.pair_support, tally.pair_focused, tally.pair_last_date, tally.file_commits+ )- entropy = {fp: round(score, 6) for fp, score in entropy_scores.items() if score > 0.0}+ entropy = {fp: round(score, 6) for fp, score in tally.entropy_scores.items() if score > 0.0}logger.debug("co_change_computed",commits=actual_commits,tracked_files=len(all_files),- pairs_considered=len(pair_scores),- pairs_above_support=sum(1 for c in pair_support.values() if c >= _MIN_CO_CHANGE_SUPPORT),+ pairs_considered=len(tally.pair_scores),+ pairs_above_support=sum(+ 1 for c in tally.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.diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex 81b148dd9..a28528d73 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -31,6 +31,12 @@ from ._constants import (_FILE_INDEX_TIMEOUT_SECS,_MAX_PARTNERS_PER_FILE,)+from ._full_index import (+ CommitSample,+ build_commit_tables,+ history_coverage,+ merge_code_signals,+)from ._incremental import (IdleRefresh,SignalPass,@@ -39,15 +45,12 @@ from ._incremental import (idle_refresh_paths,prior_defect_stage,)-from ._incremental import apply_co_change as _apply_co_change-from ._incremental import apply_prior_defects as _apply_prior_defectsfrom .co_change import CoChangeWalk, compute_co_changes_and_entropyfrom .enrich import compute_percentilesfrom .file_history import DECAY_REFRESH_KEYS, _window_anchor, index_filefrom .function_blame import build_blame_indexfrom .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defectsfrom .records import (- GitHistoryCoverage,GitIndexSummary,RepoTotals,_CommitRec,@@ -327,51 +330,15 @@ class GitIndexer:workers = git_worker_count(len(indexable_files), requested=self.max_workers)loop = asyncio.get_event_loop()- # Build a repo-wide commit index in ONE git log subprocess when- # rename-tracking is off (the default). Each per-file worker then reads- # its commits from this shared dict instead of spawning its own- # ``git log -- <file>`` — turning O(files) process spawns into O(1).- commit_index: dict[str, list[_CommitRec]] = {}commit_sink: list[dict] = []prov_clf = self._provenance_classifier()- fallback_files = set(indexable_files) | history_files- recent_files: set[str] = set()- deep_files: set[str] = set()- global_commits = deep_commits = complete_through_depth = 0- # Agent-trace records read ONCE per index (one stat call for repos- # without a .agent-trace/ dir). Shared with both commit-index walks so- # the file isn't re-read per walk, and reused below for the per-file- # line-share merge — which is why it loads even in follow_renames mode,- # where neither commit-index walk runs.+ # Agent-trace records, read once and shared with both commit-index walks+ # and the line-share merge, so they load even when no 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_index-- with timed(timings, "git.commit_index"):- sample = load_sampled_commit_index(- repo,- self.commit_limit,- set(indexable_files) | history_files,- deep_limit=_DEEP_WALK_COMMIT_LIMIT,- # 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,- cache_dir=self._window_cache_dir(),- cache_writable=not self.read_only,- )- commit_index = sample.commits- fallback_files = sample.fallback_files- recent_files = sample.recent_files- deep_files = sample.deep_files- global_commits = sample.global_commits- deep_commits = sample.deep_commits- complete_through_depth = sample.history_complete_through_depth+ sample = self._full_commit_index(+ repo, indexable_files, history_files, commit_sink, prov_clf, trace_index, timings+ )+ commit_index, fallback_files = sample.commits, sample.fallback_files# 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.@@ -465,43 +432,10 @@ class GitIndexer:with timed(timings, "git.episodes"):await asyncio.to_thread(self._record_git_episodes, fix_walk)- # Per-file AI line share from the agent-trace records. Keyed by path- # like the aggregates below, so it merges in the same pass and- # works regardless of which commit-index walk (if any) ran.- trace_line_shares = trace_index.line_shares() if trace_index else {}-- # Merge co-change partners + change entropy + prior defects + AI line- # share into metadata.- # History-tier rows take none of these; they are code signals.+ # History-tier rows take none of the code signals.code_results = [meta for meta in results if meta["file_path"] not in history_files]- _apply_co_change(code_results, walk)- _apply_prior_defects(code_results, prior_defects)- for meta in code_results:- share = trace_line_shares.get(meta["file_path"])- if share:- meta["agent_line_count"] = share[0]- meta["agent_line_model_json"] = json.dumps(share[1])-- 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- # in rename-tracking mode (no batched commit index) and failure-isolated- # so a change_risk hiccup never breaks file-level git metadata.- commit_rows: list[dict] = []- commit_file_rows: list[dict] = []- if commit_sink:- try:- from .commit_rows import build_commit_file_rows, build_commit_rows-- built = build_commit_rows(commit_sink)- built_files = build_commit_file_rows(commit_sink)- except Exception as exc:- logger.debug("commit_rows_build_failed", error=str(exc))- else:- # Assigned together: a half-built pair would write commits- # whose file detail describes a different set.- commit_rows, commit_file_rows = built, built_files+ merge_code_signals(code_results, walk, prior_defects, trace_index)+ commit_rows, commit_file_rows = build_commit_tables(commit_sink)duration = time.monotonic() - starthotspots = sum(1 for m in results if m.get("is_hotspot", False))@@ -517,26 +451,10 @@ class GitIndexer:fix_event_rows=fix_event_rows,fix_oldest_ts=fix_walk.oldest_fix_ts,fix_events_built=built_ok,- # Whole-history totals: true project age / commit / contributor- # counts for the stats page, which must not read them off the- # depth-capped sample (issue #730).+ # Whole-history totals, never read off the depth-capped sample.repo_totals=repo_totals,- history_coverage=GitHistoryCoverage(- eligible_files=len(indexable_files),- files_with_history=sum(- 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,- # 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,+ history_coverage=history_coverage(+ indexable_files, code_results, sample, self.commit_limit, workers),)_release_repo(repo)@@ -552,6 +470,52 @@ class GitIndexer:)return summary, results+ def _full_commit_index(+ self,+ repo: Any,+ indexable_files: list[str],+ history_files: set[str],+ commit_sink: list[dict],+ prov_clf: Any,+ trace_index: Any,+ timings: Any,+ ) -> CommitSample:+ """One repo-wide ``git log`` that every per-file worker reads its commits from.++ Turns O(files) process spawns into O(1). Rename tracking skips it, so+ every file walks its own history and non-code files get no history rows.+ """+ if self.follow_renames:+ return CommitSample({}, set(indexable_files) | history_files, set(), set(), 0, 0, 0)+ from repowise.core.pipeline.phase_timing import timed++ from ..git_commit_index import load_sampled_commit_index++ with timed(timings, "git.commit_index"):+ sample = load_sampled_commit_index(+ repo,+ self.commit_limit,+ set(indexable_files) | history_files,+ deep_limit=_DEEP_WALK_COMMIT_LIMIT,+ # A short history-tier file 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,+ cache_dir=self._window_cache_dir(),+ cache_writable=not self.read_only,+ )+ return CommitSample(+ sample.commits,+ sample.fallback_files,+ sample.recent_files,+ sample.deep_files,+ sample.global_commits,+ sample.deep_commits,+ sample.history_complete_through_depth,+ )+def _window_cache_dir(self) -> Path | None:"""Where the commit-window cache lives: the index directory, once it exists.@@ -719,7 +683,12 @@ class GitIndexer:code_results,co_change_sink,IdleRefresh(- idle_decay_sink, idle_paths, commit_index, prov_clf, prior_defects, history_files+ idle_decay_sink,+ idle_paths,+ commit_index,+ prov_clf,+ prior_defects,+ history_files,),)