Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

perf: batched git log + C# member reads + extension scan ungate (#184)

Raghav Chamadiya84233a41e86b
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 3dd6cf714..906e9952c 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -52,7 +52,7 @@ All eight languages support:
- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)
- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)
- Per-language dynamic-hint extractors (Django/Pytest/Node for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)
-- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection
+- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, and local `var x = new T()` property reads bound to the defining file
### Good
@@ -279,6 +279,21 @@ No changes are needed to `traverser.py`, `dead_code.py`,
`page_generator.py`, `cost_estimator.py`, or any other consumer file ---
they all derive their language sets from the registry automatically.
+### Optional language-specific passes
+
+Three pluggable hooks let a language opt into deeper resolution
+without touching the shared pipeline files:
+
+- `graph_warmups.py` --- register a one-time pre-import warmup (e.g.
+ building a project index) so its cost shows up as its own phase
+ instead of inflating `graph.imports`.
+- `type_ref_resolution._STRATEGIES` --- register a strategy that
+ resolves parameter-type captures (`@param.type` in the language's
+ `.scm`) to file-level type-use edges. Drives DI-aware analysis.
+- `languages/<lang>_member_reads.py` --- emit `reads` edges for
+ property / member access. Used today for C# `var x = new T()`
+ locals; the same shape applies to any statically-typed language.
+
---
## Architecture
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
index 7c4db5827..0268884e3 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
@@ -67,6 +67,16 @@ _INTERNALS_VISIBLE_RE = re.compile(
r"\[\s*assembly\s*:\s*InternalsVisibleTo\s*\(\s*[\"']([^\"']+)[\"']"
)
+# ``nameof(TypeName)`` — used heavily for DI key strings (e.g.
+# ``services.Configure<T>(nameof(T))``), options binding, and route /
+# policy names that never appear as a `using` import. We only match
+# arguments that look like a *type* (PascalCase identifier) so we
+# don't bind to property / method names — those produce noise and
+# resolve to internal members that the analyser already credits via
+# the parent class file. The dotted form (``nameof(NS.Type)``) also
+# resolves: ``_files_for`` strips the namespace.
+_NAMEOF_TYPE_RE = re.compile(r"\bnameof\s*\(\s*([A-Z][\w.]*)\s*\)")
+
class DotNetDynamicHints(DynamicHintExtractor):
"""Discover DI registrations, reflection, and assembly-level hints in .NET."""
@@ -250,6 +260,19 @@ class DotNetDynamicHints(DynamicHintExtractor):
)
)
+ # ---- nameof(TypeName) — DI keys, options, policies ----
+ for match in _NAMEOF_TYPE_RE.finditer(text):
+ for target in _files_for(match.group(1)):
+ if target != rel:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:nameof",
+ )
+ )
+
# ---- [assembly: InternalsVisibleTo("Other.Tests")] ----
for match in _INTERNALS_VISIBLE_RE.finditer(text):
friend = match.group(1)
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.py
index b754cbbdf..adb0cfb35 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py
@@ -55,6 +55,14 @@ def add_framework_edges(
if aspnet_in_stack or _has_aspnet_imports(parsed_files):
count += _add_aspnet_edges(graph, parsed_files, path_set)
+ # Host-builder extension-method calls (``app.MapCatalogApi()`` etc.)
+ # run on ANY C# repo — desktop .NET (WPF/WinUI) defines its own
+ # extension methods on ``IServiceCollection`` / module hosts even
+ # when ASP.NET Core is absent. The host-type allowlist inside
+ # ``aspnet_extensions`` keeps this safe to run unconditionally.
+ if _has_csharp_files(parsed_files):
+ count += _add_csharp_extension_edges(graph, parsed_files, path_set)
+
if "rails" in stack_lower or "config/application.rb" in path_set:
count += _add_rails_edges(graph, parsed_files, ctx, path_set)
@@ -374,19 +382,35 @@ def _add_aspnet_edges(
if target and target in path_set and _add_edge_if_new(graph, db_path, target):
count += 1
- # ---- 6. Host-builder extension-method calls ----
- # ``app.MapCatalogApi()`` / ``services.AddCatalogServices()`` bind to
- # extension methods declared on ``IEndpointRouteBuilder`` /
- # ``IServiceCollection`` / etc. Without this pass the defining file
- # has no static importer and reads as orphaned. Lives in its own
- # module so the regex set and host-type allowlist stay testable in
- # isolation.
+ # NOTE: host-builder extension-method scanning (``app.MapCatalogApi()``)
+ # moved to ``_add_csharp_extension_edges`` so it fires on desktop .NET
+ # (WPF/WinUI) too, not just ASP.NET — see audit item #28.
+
+ return count
+
+
+def _has_csharp_files(parsed_files: dict[str, Any]) -> bool:
+ return any(p.file_info.language == "csharp" for p in parsed_files.values())
+
+
+def _add_csharp_extension_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ """Run the host-builder extension-method scan on any C# repo.
+
+ Lifted out of ``_add_aspnet_edges`` so it also fires on desktop .NET
+ (WPF / WinUI / WinForms) where ``Microsoft.AspNetCore.*`` is never
+ imported but ``IServiceCollection`` / ``IModuleHost`` extension
+ methods are still common. The host-type allowlist inside
+ ``aspnet_extensions`` keeps false positives from generic ``Map(...)``
+ LINQ calls at bay.
+ """
from .aspnet_extensions import add_extension_method_edges, collect_csharp_texts
cs_texts = collect_csharp_texts(parsed_files, path_set)
- count += add_extension_method_edges(graph, cs_texts, path_set)
-
- return count
+ return add_extension_method_edges(graph, cs_texts, path_set)
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
new file mode 100644
index 000000000..60af47518
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -0,0 +1,149 @@
+"""Single-pass repo-wide commit index for git_indexer.
+
+The original per-file path in ``git_indexer._index_file`` spawned one
+``git log --numstat`` subprocess per tracked file. On a 5,000-file repo
+that meant 5,000 process spawns — ~50–100 ms each on Windows — which
+made the git phase dominate the total ``repowise init`` wall-clock.
+
+This module replaces the fan-out with one repo-wide ``git log`` pass
+and an in-memory bucketing step. The shape mirrors what
+``_compute_co_changes`` already does — one subprocess, fan-out via
+Python dicts — so any future debugging only has one log format to
+understand.
+
+The batched path is only used when ``follow_renames=False`` (the
+default). Rename-tracking still falls back to the per-file ``--follow``
+path because git's rename heuristics are evaluated against a single
+input file, not retro-fittable from a repo-wide log.
+"""
+
+from __future__ import annotations
+
+import structlog
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .git_indexer import _CommitRec
+
+logger = structlog.get_logger(__name__)
+
+# Git log record separator (NUL byte) and field separator (US, 0x1f) —
+# chosen so they can't appear in any commit metadata. Subjects can
+# legally contain anything else, so we cannot use printable separators.
+_RECORD_SEP = "\x00"
+_FIELD_SEP = "\x1f"
+
+_LOG_FORMAT = f"{_RECORD_SEP}%H{_FIELD_SEP}%an{_FIELD_SEP}%ae{_FIELD_SEP}%ct{_FIELD_SEP}%P{_FIELD_SEP}%s"
+
+
+def load_commit_index(
+ repo: object,
+ commit_limit: int,
+ indexable_files: set[str],
+) -> dict[str, list["_CommitRec"]]:
+ """Bucket every commit in the recent history by the files it touched.
+
+ *commit_limit* caps the depth (newest first); *indexable_files* is
+ the allowlist of paths the caller will later read. Files outside
+ this set are silently dropped — they are still seen by co-change
+ detection upstream, but per-file metadata is only produced for the
+ indexable set so there is no benefit to retaining their commits
+ here.
+
+ Returns a dict mapping ``file_path → [commit records, newest first]``.
+ Files with no commits in the window simply aren't present in the
+ dict; callers should treat ``KeyError`` / ``get(file, [])`` as
+ "no recorded history" rather than an error.
+
+ Failures (git unavailable, corrupt log output, etc.) return an
+ empty dict so the caller can fall back to per-file indexing.
+ """
+ # Imported here to avoid a circular import — _CommitRec lives in
+ # git_indexer and this module is imported from there.
+ from .git_indexer import _CommitRec, _extract_rename_paths
+
+ try:
+ raw = repo.git.log( # type: ignore[attr-defined]
+ f"-{commit_limit}",
+ "--numstat",
+ "--no-merges",
+ f"--format={_LOG_FORMAT}",
+ )
+ except Exception as exc:
+ logger.warning("repo_commit_index_failed", error=str(exc))
+ return {}
+
+ if not raw:
+ return {}
+
+ bucket: dict[str, list[_CommitRec]] = {}
+ current_meta: tuple[str, str, str, int, bool, str] | None = None
+
+ for line in raw.splitlines():
+ if line.startswith(_RECORD_SEP):
+ parts = line.lstrip(_RECORD_SEP).split(_FIELD_SEP)
+ if len(parts) < 6:
+ current_meta = None
+ continue
+ sha, an, ae, ct, parents, subj = parts[:6]
+ try:
+ ts = int(ct)
+ except ValueError:
+ ts = 0
+ is_merge = len(parents.split()) > 1
+ current_meta = (sha, an or "unknown", ae, ts, is_merge, subj)
+ continue
+
+ if current_meta is None or not line.strip():
+ continue
+
+ # numstat line: added\tdeleted\tpath
+ cols = line.split("\t")
+ if len(cols) < 3:
+ continue
+
+ stat_path = cols[2]
+ # Handle rename markers — ``{old => new}`` resolves to a new
+ # path. Without ``--follow`` git still emits these for moves
+ # detected via the rename heuristic; we add both names but
+ # attribute the churn to the new path.
+ if "=>" in stat_path:
+ seen: set[str] = set()
+ old_path, new_path = _extract_rename_paths(stat_path, seen)
+ target = new_path or stat_path
+ else:
+ target = stat_path
+
+ if target not in indexable_files:
+ continue
+
+ try:
+ added = int(cols[0]) if cols[0] != "-" else 0
+ deleted = int(cols[1]) if cols[1] != "-" else 0
+ except ValueError:
+ added = 0
+ deleted = 0
+
+ sha, an, ae, ts, is_merge, subj = current_meta
+ # Each commit becomes one record per file it touched — the
+ # per-file analyzer treats this list as the file's own history.
+ bucket.setdefault(target, []).append(
+ _CommitRec(
+ sha=sha,
+ author_name=an,
+ author_email=ae,
+ ts=ts,
+ is_merge=is_merge,
+ subject=subj,
+ added=added,
+ deleted=deleted,
+ )
+ )
+
+ logger.debug(
+ "repo_commit_index_built",
+ commits_parsed=raw.count(_RECORD_SEP),
+ files_with_history=len(bucket),
+ indexable_files=len(indexable_files),
+ )
+ return bucket
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer.py
index 19061e99c..a2021d2a2 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer.py
@@ -94,6 +94,16 @@ _DEFAULT_CO_CHANGE_COMMIT_LIMIT: int = 2000
# already sorts partners by weight so the ranking is unaffected.
_DEFAULT_CO_CHANGE_MIN_COUNT: int = 2
+# Commits that touch a very large number of files (mass renames,
+# copyright header sweeps, code-mod runs) produce O(N^2) pairs and
+# contribute no useful co-change signal. Skip pair generation for any
+# commit above this threshold. The decay-weighted score already
+# de-prioritises mass-edit commits, but the pairs are materialised
+# first — for a worst-case 500 files/commit × 2000 commits run that's
+# 250M pairs ≈ 16 GB RAM. The cap is a memory safeguard, not a
+# correctness change: typical commits sit well under 20 files.
+_MAX_FILES_PER_COMMIT_FOR_COCHANGE: int = 200
+
# Commit message classification regexes (Phase 2.2).
_COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {
"feature": re.compile(
@@ -229,6 +239,7 @@ class GitIndexer:
on_file_done: Callable[[], None] | None = None,
on_commit_done: Callable[[], None] | None = None,
on_co_change_start: Callable[[int], None] | None = None,
+ on_co_change_done: Callable[[], None] | None = None,
) -> tuple[GitIndexSummary, list[dict]]:
"""Full index of all tracked files. Returns summary + list of metadata dicts
ready for bulk upsert.
@@ -241,6 +252,11 @@ class GitIndexer:
co-change analysis
on_commit_done() — fired after each commit is processed during
co-change analysis
+ on_co_change_done() — fired the moment co-change accumulation
+ completes (BEFORE per-file git indexing
+ finishes). Lets callers stop a co_change
+ phase timer without including the wallclock
+ cost of the still-running per-file walk.
"""
start = time.monotonic()
repo = self._get_repo()
@@ -267,6 +283,19 @@ class GitIndexer:
semaphore = asyncio.Semaphore(20)
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) on large repos.
+ commit_index: dict[str, list[_CommitRec]] = {}
+ if not self.follow_renames:
+ from .git_commit_index import load_commit_index
+
+ commit_index = load_commit_index(
+ repo, self.commit_limit, set(indexable_files)
+ )
+
def _index_one_sync(file_path: str) -> dict:
"""Use a per-thread Repo to avoid shared-handle issues on Windows."""
try:
@@ -277,7 +306,12 @@ class GitIndexer:
search_parent_directories=True,
)
try:
- return self._index_file(file_path, thread_repo)
+ precomputed = (
+ commit_index.get(file_path) if commit_index else None
+ )
+ return self._index_file(
+ file_path, thread_repo, precomputed_commits=precomputed
+ )
finally:
thread_repo.close()
except Exception:
@@ -318,7 +352,7 @@ class GitIndexer:
# any pairs at all. Defaults live in module constants so
# tests and re-index paths can override without touching
# this call site.
- return await loop.run_in_executor(
+ result = await loop.run_in_executor(
executor,
self._compute_co_changes,
repo,
@@ -328,6 +362,16 @@ class GitIndexer:
on_commit_done,
on_co_change_start,
)
+ # Fire the done callback the instant accumulation finishes so
+ # any co_change phase timer stops here, NOT after the parallel
+ # per-file git walk also completes (it can run for many more
+ # minutes on large repos).
+ if on_co_change_done is not None:
+ try:
+ on_co_change_done()
+ except Exception:
+ pass
+ return result
metadata_list, co_changes = await asyncio.gather(
asyncio.gather(*file_tasks, return_exceptions=True),
@@ -459,13 +503,23 @@ class GitIndexer:
logger.warning("Failed to list tracked files", error=str(exc))
return []
- def _index_file(self, file_path: str, repo: Any) -> dict:
+ def _index_file(
+ self,
+ file_path: str,
+ repo: Any,
+ precomputed_commits: list[_CommitRec] | None = None,
+ ) -> dict:
"""Index a single file's git history. Runs in executor.
Uses a single ``git log --numstat`` call to collect commit metadata,
line-churn stats, and merge-commit flag in one subprocess instead of
the previous three separate calls (_get_commits, _get_line_stats,
_get_merge_commit_count).
+
+ When *precomputed_commits* is provided (the default when called
+ from the batched full-repo path), the per-file ``git log``
+ subprocess is skipped entirely — eliminating the dominant
+ process-spawn cost on large repos.
"""
now = datetime.now(UTC)
ninety_days_ago = now - timedelta(days=90)
@@ -507,90 +561,93 @@ class GitIndexer:
"temporal_hotspot_score": 0.0,
}
- try:
- # Single git log call: header line + optional numstat lines per commit.
- # Format: NUL-delimited record per commit so we can split reliably.
- # Fields: sha, author name, author email, unix timestamp, parent SHAs, subject
- log_args: list[str] = []
- if self.follow_renames:
- log_args.append("--follow")
- log_args += [
- f"-{self.commit_limit}",
- "--numstat",
- "--format=%x00%H%x1f%an%x1f%ae%x1f%ct%x1f%P%x1f%s",
- "--",
- file_path,
- ]
- raw = repo.git.log(*log_args)
- except Exception:
- return meta
-
- if not raw.strip():
- return meta
-
- # Parse records — each starts with a \x00 marker line followed by
- # zero-or-more numstat lines (added\tdeleted\tpath).
- # When --follow is active, older commits may reference previous file
- # names so we track all names seen via rename markers ("{old => new}").
- known_paths: set[str] = {file_path}
- # When --follow is active, seed known_paths with the original path
- # so that numstat lines referencing the old name (without a rename
- # marker in the log window) are still counted.
orig_path: str | None = None
- if self.follow_renames:
- orig_path = self._detect_original_path(file_path, repo)
- if orig_path:
- known_paths.add(orig_path)
- commits: list[_CommitRec] = []
- current: _CommitRec | None = None
-
- for line in raw.splitlines():
- if line.startswith("\x00"):
- parts = line.lstrip("\x00").split("\x1f")
- if len(parts) >= 6:
- sha, an, ae, ct, parents, subj = (
- parts[0],
- parts[1],
- parts[2],
- parts[3],
- parts[4],
- parts[5],
- )
- try:
- ts = int(ct)
- except ValueError:
- ts = 0
- current = _CommitRec(
- sha=sha,
- author_name=an or "unknown",
- author_email=ae,
- ts=ts,
- is_merge=len(parents.split()) > 1,
- subject=subj,
- )
- commits.append(current)
- elif current is not None and line.strip():
- # numstat line: added\tdeleted\tpath — only count the target file.
- # With --follow, git may emit rename lines like
- # "10\t5\t{old_dir => new_dir}/file.py" or just the old path.
- numstat_parts = line.split("\t")
- if len(numstat_parts) >= 3:
- stat_path = numstat_parts[2]
- # Track renamed paths so we can match them in older commits.
- # For rename lines the raw stat_path (with {old => new}) won't
- # match known_paths directly — check the expanded new path instead.
- match_path = stat_path
- if "=>" in stat_path:
- _old, _new = _extract_rename_paths(stat_path, known_paths)
- match_path = _new or stat_path
- if match_path in known_paths or match_path == file_path:
+ if precomputed_commits is not None:
+ commits: list[_CommitRec] = precomputed_commits
+ else:
+ try:
+ # Single git log call: header line + optional numstat lines per commit.
+ # Format: NUL-delimited record per commit so we can split reliably.
+ # Fields: sha, author name, author email, unix timestamp, parent SHAs, subject
+ log_args: list[str] = []
+ if self.follow_renames:
+ log_args.append("--follow")
+ log_args += [
+ f"-{self.commit_limit}",
+ "--numstat",
+ "--format=%x00%H%x1f%an%x1f%ae%x1f%ct%x1f%P%x1f%s",
+ "--",
+ file_path,
+ ]
+ raw = repo.git.log(*log_args)
+ except Exception:
+ return meta
+
+ if not raw.strip():
+ return meta
+
+ # Parse records — each starts with a \x00 marker line followed by
+ # zero-or-more numstat lines (added\tdeleted\tpath).
+ # When --follow is active, older commits may reference previous file
+ # names so we track all names seen via rename markers ("{old => new}").
+ known_paths: set[str] = {file_path}
+ # When --follow is active, seed known_paths with the original path
+ # so that numstat lines referencing the old name (without a rename
+ # marker in the log window) are still counted.
+ if self.follow_renames:
+ orig_path = self._detect_original_path(file_path, repo)
+ if orig_path:
+ known_paths.add(orig_path)
+ commits = []
+ current: _CommitRec | None = None
+
+ for line in raw.splitlines():
+ if line.startswith("\x00"):
+ parts = line.lstrip("\x00").split("\x1f")
+ if len(parts) >= 6:
+ sha, an, ae, ct, parents, subj = (
+ parts[0],
+ parts[1],
+ parts[2],
+ parts[3],
+ parts[4],
+ parts[5],
+ )
try:
- current.added += int(numstat_parts[0]) if numstat_parts[0] != "-" else 0
- current.deleted += (
- int(numstat_parts[1]) if numstat_parts[1] != "-" else 0
- )
+ ts = int(ct)
except ValueError:
- pass
+ ts = 0
+ current = _CommitRec(
+ sha=sha,
+ author_name=an or "unknown",
+ author_email=ae,
+ ts=ts,
+ is_merge=len(parents.split()) > 1,
+ subject=subj,
+ )
+ commits.append(current)
+ elif current is not None and line.strip():
+ # numstat line: added\tdeleted\tpath — only count the target file.
+ # With --follow, git may emit rename lines like
+ # "10\t5\t{old_dir => new_dir}/file.py" or just the old path.
+ numstat_parts = line.split("\t")
+ if len(numstat_parts) >= 3:
+ stat_path = numstat_parts[2]
+ # Track renamed paths so we can match them in older commits.
+ # For rename lines the raw stat_path (with {old => new}) won't
+ # match known_paths directly — check the expanded new path instead.
+ match_path = stat_path
+ if "=>" in stat_path:
+ _old, _new = _extract_rename_paths(stat_path, known_paths)
+ match_path = _new or stat_path
+ if match_path in known_paths or match_path == file_path:
+ try:
+ current.added += int(numstat_parts[0]) if numstat_parts[0] != "-" else 0
+ current.deleted += (
+ int(numstat_parts[1]) if numstat_parts[1] != "-" else 0
+ )
+ except ValueError:
+ pass
if not commits:
return meta
@@ -872,6 +929,15 @@ class GitIndexer:
def _flush_commit() -> None:
if len(current) < 2:
return
+ if len(current) > _MAX_FILES_PER_COMMIT_FOR_COCHANGE:
+ # Mass-edit commit — skip pair generation entirely (see
+ # constant docstring). Logged at debug for traceability.
+ logger.debug(
+ "co_change_skip_oversized_commit",
+ files_in_commit=len(current),
+ threshold=_MAX_FILES_PER_COMMIT_FOR_COCHANGE,
+ )
+ return
age_days = max((now_ts - current_ts) / 86400.0, 0.0)
weight = math.exp(-age_days / _CO_CHANGE_DECAY_TAU)
sorted_files = sorted(current)
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index a4021b109..eb5070b4f 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -235,12 +235,29 @@ class GraphBuilder:
parsed_files=self._parsed_files,
)
+ # --- Phase 1 prelude: language-specific warmups ---
+ # Some languages need an expensive one-time index built before any
+ # per-file import resolution can run. Doing it here, under a dedicated
+ # phase event, keeps the cost out of ``graph.imports`` and surfaces
+ # a meaningful progress label instead of a stuck per-file bar.
+ from .graph_warmups import run_warmups
+
+ run_warmups(self._parsed_files, ctx, progress=progress)
+
# --- Phase 1: Resolve file-level imports ---
import_targets: dict[str, set[str]] = {} # file → set of imported files
+ # Per-language import-resolution timing — surfaces which language is
+ # actually dominating the import loop on multi-language repos
+ # (audit #30). Persisted to state.json for after-the-fact analysis.
+ import time as _t
+ lang_import_time: dict[str, float] = {}
+
if progress:
progress.on_phase_start("graph.imports", len(self._parsed_files))
for path, parsed in self._parsed_files.items():
+ _lang = parsed.file_info.language
+ _t0 = _t.monotonic()
file_imports: set[str] = set()
for imp in parsed.imports:
target = resolve_import(imp.module_path, path, parsed.file_info.language, ctx)
@@ -260,12 +277,18 @@ class GraphBuilder:
imported_names=list(imp.imported_names),
)
import_targets[path] = file_imports
+ lang_import_time[_lang] = lang_import_time.get(_lang, 0.0) + (_t.monotonic() - _t0)
if progress:
progress.on_item_done("graph.imports")
if progress:
_phase_done = getattr(progress, "on_phase_done", None)
if _phase_done is not None:
_phase_done("graph.imports")
+ if lang_import_time:
+ log.info(
+ "import_resolution_per_language",
+ seconds={k: round(v, 2) for k, v in lang_import_time.items()},
+ )
# --- Phase 1b: Resolve non-import type references (e.g. C# ctor params) ---
# Lives between import resolution and heritage so the type-use
@@ -291,6 +314,12 @@ class GraphBuilder:
_phase_done("graph.type_refs")
del type_use_counts # used only for logging inside resolve_type_refs
+ # --- Phase 1c: Resolve C# member-access reads ---
+ # Bind `var x = new T(...); ... x.Prop` style property reads
+ # to T's defining file. Cuts the largest single bucket of C#
+ # unused_export false positives (audit #23).
+ self._resolve_member_reads(progress=progress)
+
# --- Phase 2: Resolve heritage (extends/implements) ---
self._resolve_heritage(import_targets, progress=progress)
@@ -362,6 +391,42 @@ class GraphBuilder:
_phase_done("graph.heritage")
log.info("Heritage edges resolved", total=total_resolved)
+ def _resolve_member_reads(self, progress: Any | None = None) -> None:
+ """Phase 1c: emit ``reads`` edges for C# property / member access.
+
+ Runs after type-use resolution so the dead-code analyser sees
+ member access as evidence of reachability. The pass is C#-only
+ today (the lever is largest there); the helper module is set
+ up to receive other languages via additional strategies.
+ """
+ from .languages.csharp_member_reads import (
+ build_csharp_type_to_file,
+ collect_csharp_source_texts,
+ resolve_csharp_member_reads,
+ )
+
+ has_csharp = any(
+ pf.file_info.language == "csharp" for pf in self._parsed_files.values()
+ )
+ if not has_csharp:
+ return
+
+ phase = "graph.member_reads"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ cs_texts = collect_csharp_source_texts(self._parsed_files)
+ type_to_file = build_csharp_type_to_file(self._parsed_files)
+ added = resolve_csharp_member_reads(self._graph, cs_texts, type_to_file)
+ log.info("member_read_edges", language="csharp", added=added)
+ except Exception as exc:
+ log.warning("member_reads_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
def _resolve_calls(
self,
import_targets: dict[str, set[str]],
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
new file mode 100644
index 000000000..6b1f12234
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -0,0 +1,74 @@
+"""Per-language warmup hooks that run before the graph-import phase.
+
+Some languages (notably C# / .NET) need an expensive one-time index
+built before any per-file import can be resolved. When that build runs
+lazily on first import resolution, the progress bar appears frozen for
+many minutes mid-phase and the cost is silently absorbed into
+``graph.imports`` timing — making it indistinguishable from real
+import-resolution work.
+
+This module gives each language a place to declare a *warmup* function
+that runs in its own phase event (``graph.<lang>_index``), before the
+``graph.imports`` loop starts. Warmups are gated on whether any
+parsed file actually uses the language, so a Python-only repo never
+pays a Java index cost.
+
+Adding a new language's warmup is one entry in :data:`_WARMUPS`.
+Implementations live in the language's resolver subpackage so this
+module stays language-agnostic.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from .models import ParsedFile
+ from .resolvers import ResolverContext
+
+
+# A warmup receives the resolver context and returns nothing. It may
+# cache its result on ``ctx`` (the resolvers already use a per-context
+# attribute cache); the dispatcher does not inspect the return value.
+Warmup = Callable[["ResolverContext"], None]
+
+
+def _warmup_dotnet(ctx: "ResolverContext") -> None:
+ from .resolvers.dotnet import get_or_build_index
+
+ get_or_build_index(ctx)
+
+
+# Map language tag → (phase-event name, warmup function). The phase
+# name shows up in the CLI progress bar and in ``state.json`` timings.
+_WARMUPS: dict[str, tuple[str, Warmup]] = {
+ "csharp": ("graph.dotnet_index", _warmup_dotnet),
+}
+
+
+def run_warmups(
+ parsed_files: dict[str, "ParsedFile"],
+ ctx: "ResolverContext",
+ progress: Any | None = None,
+) -> None:
+ """Run every registered warmup whose language appears in ``parsed_files``.
+
+ Each warmup runs under its own ``on_phase_start`` / ``on_phase_done``
+ pair so phase timings attribute the cost to the language rather
+ than dropping it into ``graph.imports``.
+ """
+ present_langs: set[str] = {pf.file_info.language for pf in parsed_files.values()}
+ for lang, (phase_name, warmup) in _WARMUPS.items():
+ if lang not in present_langs:
+ continue
+ if progress is not None:
+ progress.on_phase_start(phase_name, None)
+ try:
+ warmup(ctx)
+ except Exception: # warmup failures must not abort the build
+ pass
+ if progress is not None:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase_name)
diff --git a/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py b/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py
new file mode 100644
index 000000000..b08eb7750
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py
@@ -0,0 +1,195 @@
+"""C# member-access read resolution.
+
+Background
+----------
+Property reads in C# never appear as calls — ``var x = new Order();``
+followed by ``return x.Total;`` produces a ``member_access_expression``
+but no invocation. The existing static-call resolver and ``using``
+import resolver both miss this entirely, which makes any class whose
+only consumers READ its properties read as orphaned.
+
+This pass closes the biggest sub-case without touching the brittle
+tree-sitter grammar:
+
+1. **Local-typed receivers** — ``var x = new Foo(...);`` plus
+ ``Foo x = new(...);`` plus ``Foo x = ...;`` declare a local whose
+ type we know syntactically. Subsequent ``x.SomeMember`` reads in
+ the same file resolve to the file that declares ``Foo``.
+
+2. **``this.PropName``** — the receiver is the enclosing class.
+ When the file declares exactly one named type (the dominant case
+ for C#), ``this.Prop`` reads resolve to that file. Cross-file
+ resolution would require partial-class awareness; we skip it for
+ safety.
+
+The resolved file becomes a low-confidence ``reads`` edge. Dead-code
+treats every incoming edge as evidence of life, so this directly
+reduces unused_export false positives without affecting other
+analyses. ``reads`` is a new edge type — ``calls`` / ``imports`` /
+``type_use`` remain unchanged so semantics-aware consumers can tell
+them apart.
+
+The module is **self-contained**: it reads source text directly,
+runs a few regexes, and emits dicts. It does not depend on the parser
+or the call resolver, which keeps the pass isolated and easy to gate
+behind a feature flag if it ever proves noisy.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+# ``var foo = new Bar(`` / ``var foo = new Bar<...>(`` / ``Bar foo = new(``
+# / ``Bar foo = new Bar(``. We capture the LOCAL name + the type name
+# in a single match. Generic / qualified type names are stripped to the
+# last identifier so we resolve through ``DotNetProjectIndex.type_map``.
+_LOCAL_DECL_RE = re.compile(
+ r"\b(?:var|(?P<type1>[A-Z][\w\.]*(?:<[^>]+>)?))\s+"
+ r"(?P<name>[a-z_]\w*)\s*=\s*"
+ r"new(?:\s+(?P<type2>[A-Z][\w\.]*(?:<[^>]+>)?))?\s*\("
+)
+
+# ``receiver.Member`` — only PascalCase member names (properties /
+# methods, never lowercase locals or keywords). The receiver may be
+# any identifier; we resolve through the local-decl map.
+_MEMBER_ACCESS_RE = re.compile(r"\b(?P<recv>[a-z_]\w*)\.(?P<name>[A-Z]\w*)\b")
+
+# ``this.PropName`` — receiver is the enclosing type.
+_THIS_MEMBER_RE = re.compile(r"\bthis\.(?P<name>[A-Z]\w*)\b")
+
+# First class-like declaration in a file. Used to resolve ``this.X``
+# back to "the type declared here". Multiple-type files punt (see
+# module docstring).
+_PRIMARY_TYPE_RE = re.compile(
+ r"\b(?:public|internal|private|protected|sealed|abstract|static|partial|\s)*"
+ r"\s+(?:class|struct|record|interface)\s+(?P<name>[A-Z]\w*)"
+)
+
+
+_READS_CONFIDENCE = 0.6
+
+
+def _head_type(raw: str) -> str:
+ """Strip generic parameters / namespace prefix to a bare identifier."""
+ head = raw.split("<", 1)[0]
+ return head.rsplit(".", 1)[-1]
+
+
+def resolve_csharp_member_reads(
+ graph: "nx.DiGraph",
+ cs_texts: dict[str, str],
+ type_to_file: dict[str, str],
+) -> int:
+ """Emit ``reads`` edges for property / member access in C# files.
+
+ *cs_texts* maps repo-relative path → source text.
+ *type_to_file* maps short type name → defining file path. Caller
+ is responsible for building it (e.g. from
+ ``DotNetProjectIndex.type_map`` or by scanning AST symbols).
+
+ Returns the number of edges added.
+ """
+ if not cs_texts or not type_to_file:
+ return 0
+
+ count = 0
+ for path, text in cs_texts.items():
+ # Local-typed receiver map for this file only. Re-scanning per
+ # file is fine — regex is fast and the alternative (cross-file
+ # state) would create false matches when the same local name
+ # is reused across files.
+ local_type: dict[str, str] = {}
+ for m in _LOCAL_DECL_RE.finditer(text):
+ type_name = m.group("type2") or m.group("type1")
+ if not type_name:
+ continue
+ local_type[m.group("name")] = _head_type(type_name)
+
+ primary_match = _PRIMARY_TYPE_RE.search(text)
+ primary_type = primary_match.group("name") if primary_match else None
+
+ # Resolve each receiver-member pair we recognise.
+ emitted_targets: set[str] = set()
+ for m in _MEMBER_ACCESS_RE.finditer(text):
+ recv = m.group("recv")
+ type_name = local_type.get(recv)
+ if not type_name:
+ continue
+ target = type_to_file.get(type_name)
+ if not target or target == path or target in emitted_targets:
+ continue
+ if _add_reads_edge(graph, path, target):
+ emitted_targets.add(target)
+ count += 1
+
+ if primary_type is not None:
+ target = type_to_file.get(primary_type)
+ if target and target != path and _THIS_MEMBER_RE.search(text):
+ # ``this.X`` reads in a same-file class are redundant
+ # (same node); we already skip target == path above.
+ # Cross-file ``this.X`` only happens for partial
+ # classes — keep this branch for completeness.
+ if _add_reads_edge(graph, path, target):
+ count += 1
+
+ return count
+
+
+def _add_reads_edge(graph: "nx.DiGraph", source: str, target: str) -> bool:
+ """Add a ``reads`` edge if no edge already connects source → target.
+
+ A stronger pre-existing edge (``imports``, ``calls``, ``type_use``,
+ etc.) wins — we don't overwrite. ``reads`` is purely additive
+ evidence for dead-code's "incoming edge" check.
+ """
+ if source == target:
+ return False
+ if not graph.has_node(source) or not graph.has_node(target):
+ return False
+ if graph.has_edge(source, target):
+ return False
+ graph.add_edge(
+ source,
+ target,
+ edge_type="reads",
+ confidence=_READS_CONFIDENCE,
+ imported_names=[],
+ )
+ return True
+
+
+def build_csharp_type_to_file(parsed_files: dict[str, Any]) -> dict[str, str]:
+ """Build a short-name → defining-file map across all parsed C# files.
+
+ Used as a lightweight alternative to ``DotNetProjectIndex.type_map``
+ in contexts where the full resolver is not available (tests,
+ standalone pipelines). Last-wins on duplicates.
+ """
+ result: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "csharp":
+ continue
+ for sym in parsed.symbols:
+ if sym.kind in ("class", "struct", "record", "interface"):
+ result[sym.name] = path
+ return result
+
+
+def collect_csharp_source_texts(parsed_files: dict[str, Any]) -> dict[str, str]:
+ """Read each parsed C# file's source from disk, keyed by repo path."""
+ out: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "csharp":
+ continue
+ try:
+ out[path] = Path(parsed.file_info.abs_path).read_text(
+ encoding="utf-8-sig", errors="ignore"
+ )
+ except OSError:
+ continue
+ return out
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index cb42dc4d6..b10e394e8 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -703,15 +703,26 @@ async def _run_git_indexing(
if progress:
progress.on_item_done("co_change")
+ def _on_co_change_done() -> None:
+ # Stop the co_change timer the moment accumulation finishes;
+ # otherwise the recorded duration also includes the parallel
+ # per-file git walk that keeps running afterwards (audit #29).
+ _phase_done(progress, "co_change")
+
git_summary, git_metadata_list = await git_indexer.index_repo(
"",
on_start=_on_start,
on_file_done=_on_file_done,
on_co_change_start=_on_co_change_start,
on_commit_done=_on_commit_done,
+ on_co_change_done=_on_co_change_done,
)
git_meta_map = {m["file_path"]: m for m in git_metadata_list}
_phase_done(progress, "git")
+ # co_change phase already closed inside the done-callback above;
+ # call again only as a safety-net in case the callback was never
+ # invoked (e.g. co-change skipped early). PhaseTimingRecorder
+ # ignores done-without-start so this is a no-op in the happy path.
_phase_done(progress, "co_change")
return git_summary, git_metadata_list, git_meta_map
except Exception as exc:
diff --git a/tests/unit/ingestion/test_csharp_framework_edges.py b/tests/unit/ingestion/test_csharp_framework_edges.py
index 1516c5986..a13c0cbbd 100644
--- a/tests/unit/ingestion/test_csharp_framework_edges.py
+++ b/tests/unit/ingestion/test_csharp_framework_edges.py
@@ -185,6 +185,42 @@ public static class Helpers {
# ``List<int>`` is not in the host allowlist → no edge.
assert not graph.has_edge("Program.cs", "Other.cs")
+ def test_extension_scan_fires_on_desktop_dotnet(self, tmp_path: Path) -> None:
+ """Map/Add/Use extension scan must run on any C# repo, including
+ desktop .NET projects with no ASP.NET imports (audit item #28).
+ """
+ (tmp_path / "App.xaml.cs").write_text(
+ """namespace Acme;
+public partial class App {
+ public App() {
+ var services = new ServiceCollection();
+ services.AddCatalogServices();
+ }
+}
+"""
+ )
+ (tmp_path / "Catalog.cs").write_text(
+ """using Microsoft.Extensions.DependencyInjection;
+namespace Acme;
+public static class CatalogExtensions {
+ public static IServiceCollection AddCatalogServices(this IServiceCollection services)
+ {
+ return services;
+ }
+}
+"""
+ )
+ parsed = _build_parsed_files(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+
+ # No ASP.NET signal at all — empty tech_stack, no AspNetCore imports.
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge("App.xaml.cs", "Catalog.cs")
+ assert graph["App.xaml.cs"]["Catalog.cs"]["edge_type"] == "framework"
+
def test_no_edges_when_no_aspnet_signal(self, tmp_path: Path) -> None:
(tmp_path / "Plain.cs").write_text(
"namespace Plain;\npublic class Foo {}\n"
@@ -246,6 +282,40 @@ builder.Services.AddScoped<IUserService, UserService>();
edges = DotNetDynamicHints().extract(tmp_path)
assert any(e.source == "Boot.cs" and e.target == "Worker.cs" for e in edges)
+ def test_nameof_type_emits_dynamic_uses(self, tmp_path: Path) -> None:
+ """``nameof(MySettings)`` must surface as a dynamic edge to the
+ defining file (audit item #26).
+ """
+ (tmp_path / "MySettings.cs").write_text(
+ "namespace Acme;\npublic class MySettings { }\n"
+ )
+ (tmp_path / "Program.cs").write_text(
+ """namespace Acme;
+public class Bootstrap {
+ void Configure() {
+ services.Configure<MySettings>(nameof(MySettings));
+ }
+}
+"""
+ )
+ edges = DotNetDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Program.cs"
+ and e.target == "MySettings.cs"
+ and e.hint_source.endswith(":nameof")
+ for e in edges
+ )
+
+ def test_nameof_lowercase_member_ignored(self, tmp_path: Path) -> None:
+ """``nameof(someLocal)`` must NOT bind — only type-looking
+ identifiers are scanned to keep noise out.
+ """
+ (tmp_path / "Foo.cs").write_text(
+ 'namespace Acme;\npublic class Foo { void Go(int someLocal) { var n = nameof(someLocal); } }\n'
+ )
+ edges = DotNetDynamicHints().extract(tmp_path)
+ assert not any(e.hint_source.endswith(":nameof") for e in edges)
+
def test_internals_visible_to_emits_friend_edge(self, tmp_path: Path) -> None:
(tmp_path / "AssemblyInfo.cs").write_text(
'[assembly: InternalsVisibleTo("Acme.Tests")]\n'
diff --git a/tests/unit/ingestion/test_csharp_member_reads.py b/tests/unit/ingestion/test_csharp_member_reads.py
new file mode 100644
index 000000000..6f3abda2d
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_member_reads.py
@@ -0,0 +1,101 @@
+"""Unit tests for C# member-access read resolution."""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.ingestion.languages.csharp_member_reads import (
+ resolve_csharp_member_reads,
+)
+
+
+def _seed_graph(*paths: str) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in paths:
+ g.add_node(p)
+ return g
+
+
+def test_var_new_local_binds_member_read() -> None:
+ """``var x = new Order(); ... x.Total`` resolves to Order.cs."""
+ graph = _seed_graph("Caller.cs", "Order.cs")
+ cs_texts = {
+ "Caller.cs": (
+ "namespace Acme;\npublic class Caller {\n"
+ " decimal Sum() { var order = new Order(); return order.Total; }\n}"
+ ),
+ "Order.cs": "namespace Acme;\npublic class Order { public decimal Total { get; } }",
+ }
+ type_to_file = {"Order": "Order.cs", "Caller": "Caller.cs"}
+
+ added = resolve_csharp_member_reads(graph, cs_texts, type_to_file)
+
+ assert added == 1
+ assert graph.has_edge("Caller.cs", "Order.cs")
+ edge = graph["Caller.cs"]["Order.cs"]
+ assert edge["edge_type"] == "reads"
+
+
+def test_typed_local_binds_member_read() -> None:
+ """``Order o = new(...);`` (target-typed new) also binds."""
+ graph = _seed_graph("Caller.cs", "Order.cs")
+ cs_texts = {
+ "Caller.cs": (
+ "namespace Acme;\npublic class Caller {\n"
+ " decimal Sum() { Order o = new(); return o.Total; }\n}"
+ ),
+ "Order.cs": "namespace Acme;\npublic class Order { public decimal Total { get; } }",
+ }
+ type_to_file = {"Order": "Order.cs", "Caller": "Caller.cs"}
+
+ resolve_csharp_member_reads(graph, cs_texts, type_to_file)
+
+ assert graph.has_edge("Caller.cs", "Order.cs")
+
+
+def test_unknown_receiver_no_edge() -> None:
+ """An untyped receiver must not produce an edge — would be a guess."""
+ graph = _seed_graph("Caller.cs", "Order.cs")
+ cs_texts = {
+ "Caller.cs": (
+ "namespace Acme;\npublic class Caller {\n"
+ " void F(object x) { var y = x; var n = y.SomeProp; }\n}"
+ ),
+ "Order.cs": "namespace Acme;\npublic class Order { public int SomeProp { get; } }",
+ }
+ type_to_file = {"Order": "Order.cs"}
+
+ resolve_csharp_member_reads(graph, cs_texts, type_to_file)
+
+ assert not graph.has_edge("Caller.cs", "Order.cs")
+
+
+def test_existing_edge_preserved() -> None:
+ """A pre-existing `imports` edge wins over `reads` (no overwrite)."""
+ graph = _seed_graph("Caller.cs", "Order.cs")
+ graph.add_edge("Caller.cs", "Order.cs", edge_type="imports", imported_names=["Order"])
+ cs_texts = {
+ "Caller.cs": (
+ "namespace Acme;\npublic class Caller {\n"
+ " decimal Sum() { var o = new Order(); return o.Total; }\n}"
+ ),
+ "Order.cs": "namespace Acme;\npublic class Order { public decimal Total { get; } }",
+ }
+ resolve_csharp_member_reads(graph, cs_texts, {"Order": "Order.cs"})
+
+ assert graph["Caller.cs"]["Order.cs"]["edge_type"] == "imports"
+
+
+def test_self_reads_skipped() -> None:
+ """``this.Prop`` on a same-file class doesn't add a self-loop."""
+ graph = _seed_graph("Order.cs")
+ cs_texts = {
+ "Order.cs": (
+ "namespace Acme;\npublic class Order {\n"
+ " public decimal Total { get; }\n"
+ " decimal Half() { return this.Total / 2; }\n}"
+ ),
+ }
+ resolve_csharp_member_reads(graph, cs_texts, {"Order": "Order.cs"})
+
+ assert not graph.has_edge("Order.cs", "Order.cs")
diff --git a/tests/unit/test_git_commit_index.py b/tests/unit/test_git_commit_index.py
new file mode 100644
index 000000000..1d2c12e1f
--- /dev/null
+++ b/tests/unit/test_git_commit_index.py
@@ -0,0 +1,123 @@
+"""Unit tests for the batched repo-wide commit index loader."""
+
+from __future__ import annotations
+
+import time
+from unittest.mock import MagicMock
+
+from repowise.core.ingestion.git_commit_index import load_commit_index
+
+
+def _build_log(commits: list[dict]) -> str:
+ """Render an in-memory list of commit dicts into the raw `git log` format.
+
+ Each dict shape: {sha, an, ae, ct, parents, subj, files: [(added, deleted, path), ...]}.
+ """
+ lines: list[str] = []
+ for c in commits:
+ header = (
+ "\x00"
+ + c["sha"]
+ + "\x1f"
+ + c["an"]
+ + "\x1f"
+ + c["ae"]
+ + "\x1f"
+ + str(c["ct"])
+ + "\x1f"
+ + c.get("parents", "")
+ + "\x1f"
+ + c["subj"]
+ )
+ lines.append(header)
+ for added, deleted, path in c["files"]:
+ lines.append(f"{added}\t{deleted}\t{path}")
+ return "\n".join(lines)
+
+
+def test_load_commit_index_buckets_per_file() -> None:
+ now = int(time.time())
+ raw = _build_log(
+ [
+ {
+ "sha": "aaa",
+ "an": "Alice",
+ "ct": now,
+ "subj": "feat: thing",
+ "files": [(5, 1, "src/a.py"), (3, 0, "src/b.py")],
+ },
+ {
+ "sha": "bbb",
+ "an": "Bob",
+ "ct": now - 3600,
+ "subj": "fix: stuff",
+ "files": [(2, 4, "src/a.py")],
+ },
+ ]
+ )
+ repo = MagicMock()
+ repo.git.log.return_value = raw
+
+ index = load_commit_index(repo, 100, {"src/a.py", "src/b.py"})
+
+ assert set(index.keys()) == {"src/a.py", "src/b.py"}
+ assert len(index["src/a.py"]) == 2
+ assert index["src/a.py"][0].sha == "aaa"
+ assert index["src/a.py"][0].added == 5
+ assert index["src/a.py"][1].added == 2
+ assert len(index["src/b.py"]) == 1
+
+
+def test_load_commit_index_drops_non_indexable_files() -> None:
+ raw = _build_log(
+ [
+ {
+ "sha": "aaa",
+ "an": "Alice",
+ "ct": int(time.time()),
+ "subj": "mix",
+ "files": [(5, 1, "src/a.py"), (1, 0, "docs/skip.md")],
+ },
+ ]
+ )
+ repo = MagicMock()
+ repo.git.log.return_value = raw
+
+ # docs/skip.md is not in the indexable set — it must be dropped.
+ index = load_commit_index(repo, 100, {"src/a.py"})
+
+ assert "docs/skip.md" not in index
+ assert "src/a.py" in index
+
+
+def test_load_commit_index_returns_empty_on_failure() -> None:
+ repo = MagicMock()
+ repo.git.log.side_effect = RuntimeError("git not available")
+
+ assert load_commit_index(repo, 100, {"a.py"}) == {}
+
+
+def test_load_commit_index_handles_renames() -> None:
+ """Rename markers ``{old => new}`` must be attributed to the new path."""
+ raw = _build_log(
+ [
+ {
+ "sha": "aaa",
+ "an": "Alice",
+ "ct": int(time.time()),
+ "subj": "rename",
+ "files": [(10, 5, "src/{old.py => new.py}")],
+ }
+ ]
+ )
+ repo = MagicMock()
+ repo.git.log.return_value = raw
+
+ index = load_commit_index(repo, 100, {"src/new.py", "src/old.py"})
+ # Churn attributed to the new path
+ assert "src/new.py" in index
+ assert index["src/new.py"][0].added == 10