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.

fix(git): keep a file's history across renames (#2569)

Raghav Chamadiya405140e2ffba
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index 9fe1ccb05..88a9752c6 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -12,9 +12,10 @@ 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.
+default). It still keeps a file's history across a rename: the walk reads
+git's rename rows newest first and files older commits under the current
+name (see :class:`~.git_indexer.records.RenameTrail`). ``follow_renames``
+switches to the per-file ``--follow`` path instead.
"""
from __future__ import annotations
@@ -26,7 +27,7 @@ from typing import TYPE_CHECKING
import structlog
if TYPE_CHECKING:
- from .git_indexer import _CommitRec
+ from .git_indexer import RenameTrail, _CommitRec
logger = structlog.get_logger(__name__)
@@ -219,6 +220,7 @@ def load_commit_index(
trace_index: object | None = None,
cache_dir: Path | None = None,
stats_sink: dict[str, int | bool] | None = None,
+ renames: RenameTrail | None = None,
) -> dict[str, list[_CommitRec]]:
"""Bucket every commit in the recent history by the files it touched.
@@ -261,6 +263,10 @@ def load_commit_index(
:func:`_window_records`). Ignored with *since_ts*, whose own bound already
keeps that walk short.
+ *renames*, when given, files each commit under the path its file has at
+ HEAD and learns the window's renames, so a deeper walk can continue it.
+ The commit sink keeps the paths as the commit wrote them.
+
Failures (git unavailable, corrupt log output, etc.) return an
empty dict so the caller can fall back to per-file indexing.
"""
@@ -358,6 +364,7 @@ def load_commit_index(
# agent-trace channel needs the changed-path set for its file-overlap
# check; the same list feeds the commit sink.
commit_changes: list[tuple[str, int, int]] = []
+ moved: list[tuple[str, str]] = []
for line in numstat_lines:
cols = line.split("\t")
@@ -371,8 +378,10 @@ def load_commit_index(
# 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)
+ old_path, new_path = _extract_rename_paths(stat_path, seen)
target = new_path or stat_path
+ if old_path and new_path:
+ moved.append((old_path, new_path))
else:
target = stat_path
@@ -404,6 +413,8 @@ def load_commit_index(
)
for target, added, deleted in commit_changes:
+ if renames is not None:
+ target = renames.resolve(target)
if target not in indexable_files:
continue
@@ -447,6 +458,9 @@ def load_commit_index(
),
}
)
+ if renames is not None:
+ for old_path, new_path in moved:
+ renames.record(old_path, new_path)
logger.debug(
"repo_commit_index_built",
@@ -469,6 +483,7 @@ def load_deep_commit_index(
provenance_classifier: object | None = None,
trace_index: object | None = None,
stats_sink: dict[str, int | bool] | None = None,
+ renames: RenameTrail | None = None,
) -> dict[str, list[_CommitRec]]:
"""Bucket commits OLDER than the recent window for *wanted_files* only.
@@ -490,9 +505,10 @@ def load_deep_commit_index(
shows a rename as a whole-file addition). All three rename-free lanes use
``--no-merges`` so changing lanes cannot change the retained commit set.
That makes deep-bucketed files CONSISTENT with window-indexed files,
- which always had repo-walk semantics. Files absent from this bucket
- (pre-rename names the marker parser cannot resolve, or history deeper
- than *deep_limit*) keep the per-file fallback path.
+ which always had repo-walk semantics. *renames* continues the newer
+ walks' rename trail, so a pre-rename commit here lands under the current
+ name. Files absent from this bucket (history deeper than *deep_limit*)
+ keep the per-file fallback path.
Failures return an empty dict; every missed file then falls back to
the per-file path exactly as before.
@@ -555,6 +571,7 @@ def load_deep_commit_index(
# provenance work (the window walk classifies every commit because
# the commit sink needs the labels).
changes: list[tuple[str, int, int]] = []
+ moved: list[tuple[str, str]] = []
touches_wanted = False
for line in numstat_lines:
@@ -564,10 +581,14 @@ def load_deep_commit_index(
stat_path = cols[2]
if "=>" in stat_path:
seen: set[str] = set()
- _old_path, new_path = _extract_rename_paths(stat_path, seen)
+ old_path, new_path = _extract_rename_paths(stat_path, seen)
target = new_path or stat_path
+ if old_path and new_path:
+ moved.append((old_path, new_path))
else:
target = stat_path
+ if renames is not None:
+ target = renames.resolve(target)
try:
added = int(cols[0]) if cols[0] != "-" else 0
@@ -580,6 +601,9 @@ def load_deep_commit_index(
if target in wanted_files:
touches_wanted = True
+ if renames is not None:
+ for old_path, new_path in moved:
+ renames.record(old_path, new_path)
if not touches_wanted:
continue
@@ -653,6 +677,11 @@ def load_sampled_commit_index(
tops it up, and a per-file walk remains required when the shared walks
neither fill the cap nor reach the repository root.
"""
+ from .git_indexer import RenameTrail
+
+ # One trail across the recent and deep walks: they partition one
+ # newest-first history, so a rename seen in the window applies below it.
+ renames = RenameTrail()
recent_stats: dict[str, int | bool] = {}
recent = load_commit_index(
repo,
@@ -663,6 +692,7 @@ def load_sampled_commit_index(
trace_index=trace_index,
cache_dir=cache_dir,
stats_sink=recent_stats,
+ renames=renames,
)
sample = HistorySample(
commits={path: list(records[:per_file_limit]) for path, records in recent.items()},
@@ -696,6 +726,7 @@ def load_sampled_commit_index(
provenance_classifier=provenance_classifier,
trace_index=trace_index,
stats_sink=deep_stats,
+ renames=renames,
)
for path, records in deep.items():
remaining = per_file_limit - len(sample.commits.get(path, ()))
@@ -733,6 +764,9 @@ def load_sampled_commit_index(
path for path in indexable_files if len(sample.commits.get(path, ())) < per_file_limit
}
if not shared_walk_complete:
+ # Ceiling: the per-file fallback log does not follow renames, so a
+ # fallback file's history still starts at its last rename. Passing the
+ # trail's old names as extra pathspecs, cut at the rename time, lifts it.
sample.fallback_files = underfilled
sample.deep_files.difference_update(sample.fallback_files)
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
index bb737b703..881f777c8 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
@@ -74,10 +74,16 @@ builds a single repo-wide commit index once (`git_commit_index.load_commit_index
from that dict. This caps depth at `_DEFAULT_COMMIT_LIMIT` (the newest N commits)
to keep `init` inside its time/memory budget.
+**Renames keep history.** Every shared walk (commit index, co-change, prior
+defects) reads git's rename rows newest first and files older commits under the
+path the file has at HEAD (`records.RenameTrail`), so churn, age, authorship,
+co-change partners and fix counts carry across a rename. A path reused by a
+different file after the move keeps only its own commits.
+
**Caveat the prior-defect pass works around:** that cap bounds the index by
*commit count*, so on a hyperactive repo a hot file's slice under-represents a
wide window. `compute_prior_defects` therefore does NOT read the index — it runs
-its own date-bounded `git log prior_sha..HEAD --name-only` pass, which reaches
+its own date-bounded `git log prior_sha..HEAD --name-status` pass, which reaches
the full window at a fraction of the cost of lifting the global cap (it scales
with window activity, not total repo age). Windowed-but-decayed signals
(90d counts, entropy) tolerate the cap because old commits contribute ~nothing.
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
index cf7e5ff2f..f32b8a9b6 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
@@ -52,6 +52,7 @@ from .records import (
_LOG_FORMAT,
_RECORD_SEP,
GitIndexSummary,
+ RenameTrail,
_CommitRec,
_extract_rename_paths,
_parse_commit_record,
@@ -76,6 +77,7 @@ __all__ = [
"GitIndexTier",
"GitIndexer",
"PriorDefects",
+ "RenameTrail",
"_CommitRec",
"_extract_rename_paths",
"_parse_commit_record",
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.py
index 38869a953..c476c3563 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
@@ -1,6 +1,6 @@
"""Repo-wide co-change accumulation + change entropy (FULL-tier signals).
-A single ``git log --name-only`` walk feeds two history signals at once:
+A single ``git log --name-status`` walk feeds two history signals at once:
* **Co-change** — decay-weighted co-occurrence pairs across tracked files,
each carrying its raw shared-commit count and both files' commit totals.
@@ -35,6 +35,7 @@ from ._constants import (
_MAX_PARTNERS_PER_FILE,
_MIN_CO_CHANGE_SUPPORT,
)
+from .records import RenameTrail, name_status_path
logger = structlog.get_logger(__name__)
@@ -43,7 +44,7 @@ __all__ = ["CoChangeWalk", "compute_co_changes_and_entropy"]
@dataclass
class CoChangeWalk:
- """Everything one ``git log --name-only`` walk yields, keyed by file path.
+ """Everything one ``git log --name-status`` walk yields, keyed by file path.
A record rather than a tuple, like ``PriorDefects`` and ``FixWalk`` in the
orchestrator that consumes this, because the walk keeps acquiring signals.
@@ -109,8 +110,10 @@ def compute_co_changes_and_entropy(
) -> CoChangeWalk:
"""Walk recent commits once, returning every history signal it yields.
- Uses a single ``git log --name-only`` call instead of spawning one
+ 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
@@ -164,7 +167,7 @@ def compute_co_changes_and_entropy(
# %x00 = commit separator, %ct = committer timestamp (Unix epoch).
raw = repo.git.log(
f"-{commit_limit}",
- "--name-only",
+ "--name-status",
"--no-merges",
"--format=%x00%ct",
)
@@ -176,6 +179,8 @@ def compute_co_changes_and_entropy(
on_co_change_start(actual_commits)
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
@@ -231,7 +236,10 @@ def compute_co_changes_and_entropy(
if line == "\x00" or line.startswith("\x00"):
# Commit boundary — flush previous, parse timestamp.
_flush_commit()
+ for old_path, new_path in moved:
+ renames.record(old_path, new_path)
current = set()
+ moved = []
ts_part = line.lstrip("\x00").strip()
try:
current_ts = int(ts_part)
@@ -241,9 +249,12 @@ def compute_co_changes_and_entropy(
commits_seen += 1
if on_commit_done is not None:
on_commit_done()
- else:
- path = line.strip()
- if path and path in all_files:
+ elif line.strip():
+ path, renamed_from = name_status_path(line)
+ if renamed_from:
+ moved.append((renamed_from, path))
+ path = renames.resolve(path)
+ if path in all_files:
current.add(path)
_flush_commit() # final commit
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.py
index 5fa634ac4..032de3cb9 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
@@ -19,7 +19,8 @@ labels as fixes (product == benchmark):
merged into HEAD since then — so feature-branch fixes count, matching the
benchmark's ``prior_sha..t0_sha`` range, not a date-pruned ``--since`` walk);
* classify each commit subject with the shared ``is_fix_commit`` keyword rule;
-* attribute a fix to every indexable file it touched.
+* attribute a fix to every indexable file it touched, under the path that file
+ has at HEAD, so a rename inside the window does not reset the count.
Reachable-from-HEAD means a T0 worktree never sees post-T0 fixes → leakage-free.
@@ -39,7 +40,7 @@ import structlog
from ._constants import PRIOR_DEFECT_WINDOW_DAYS, _truncate_body, is_fix_commit
from .fix_shape import classify_fix_shape
-from .records import _RECORD_SEP, _extract_rename_paths
+from .records import _RECORD_SEP, RenameTrail, name_status_path
if TYPE_CHECKING:
# Type-only: ``analysis.change_risk`` imports back into this package, so a
@@ -51,10 +52,10 @@ logger = structlog.get_logger(__name__)
__all__ = ["FixCommit", "FixWalk", "PriorDefects", "collect_fix_commits", "compute_prior_defects"]
# sha <US> committer-time <US> subject <US> body <STX>, one record per commit
-# (NUL-separated); --name-only then emits the touched paths on the lines that
+# (NUL-separated); --name-status then emits the touched paths on the lines that
# follow. The body (``%b``) is the only multi-line field, so it is captured last
# and terminated explicitly: unlike the numstat block ``records.py`` disentangles
-# by shape, a ``--name-only`` path line is indistinguishable from a line of prose,
+# by shape, a ``--name-status`` path line is indistinguishable from a line of prose,
# so the boundary has to be a byte git will never emit inside a message.
_PRIOR_LOG_FORMAT = "%x00%H%x1f%ct%x1f%s%x1f%b%x02"
_FIELD_SEP = "\x1f"
@@ -94,6 +95,10 @@ class FixCommit:
consumers read neither: they exist for consumers that quote a change rather
than count it, and they cost no extra git work because the walk already
parses the subject to classify the commit.
+
+ *history_paths* is what the counts are keyed by: each touched file under the
+ path it has at HEAD. ``None`` means the same as *paths*. *paths* stays as the
+ commit wrote it, because *files* and the SZZ blame are keyed that way.
"""
sha: str
@@ -103,6 +108,7 @@ class FixCommit:
files: dict[str, FileDiff] = field(default_factory=dict)
subject: str = ""
body: str = ""
+ history_paths: list[str] | None = None
@dataclass(frozen=True)
@@ -180,6 +186,7 @@ def collect_fix_commits(
files=diffs.get(fix.sha, {}),
subject=fix.subject,
body=fix.body,
+ history_paths=fix.history_paths,
)
for fix in fixes
]
@@ -214,11 +221,12 @@ def compute_prior_defects(
raw_counts: dict[str, int] = {}
counts: dict[str, int] = {}
for fix in walk.fixes:
- for path in fix.paths:
+ paths = fix.paths if fix.history_paths is None else fix.history_paths
+ for path in paths:
raw_counts[path] = raw_counts.get(path, 0) + 1
if fix.shape_kind != "code_fix":
continue
- for path in fix.paths:
+ for path in paths:
counts[path] = counts.get(path, 0) + 1
return PriorDefects(counts=counts, raw_counts=raw_counts)
@@ -267,7 +275,7 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> l
raw = repo.git.log(
rev_range,
"--no-merges",
- "--name-only",
+ "--name-status",
f"--format={_PRIOR_LOG_FORMAT}",
)
except Exception as exc:
@@ -278,25 +286,32 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> l
return []
fixes: list[FixCommit] = []
+ renames = RenameTrail()
for record in raw.split(_RECORD_SEP):
record = record.strip("\n")
if not record:
continue
fields, path_block = _split_record(record)
sha, committed, subject, body = fields
- if not is_fix_commit(subject):
- continue
- paths = [p for p in _record_paths(path_block) if p in indexable_files]
- if paths:
- fixes.append(
- FixCommit(
- sha=sha,
- ts=_as_ts(committed),
- paths=paths,
- subject=_truncate_body(subject.strip()),
- body=_truncate_body(body.strip()),
+ entries = _record_paths(path_block)
+ if is_fix_commit(subject):
+ paths = [p for p, _ in entries if p in indexable_files]
+ history = [renames.resolve(p) for p, _ in entries]
+ history = [p for p in dict.fromkeys(history) if p in indexable_files]
+ if history:
+ fixes.append(
+ FixCommit(
+ sha=sha,
+ ts=_as_ts(committed),
+ paths=paths,
+ subject=_truncate_body(subject.strip()),
+ body=_truncate_body(body.strip()),
+ history_paths=history,
+ )
)
- )
+ for path, renamed_from in entries:
+ if renamed_from:
+ renames.record(renamed_from, path)
return fixes
@@ -333,18 +348,9 @@ def _as_ts(raw: str) -> int:
return 0
-def _record_paths(body: str) -> list[str]:
- """The ``--name-only`` path lines of one log record, renames resolved."""
- paths: list[str] = []
- for line in body.split("\n"):
- path = line.strip()
- if not path:
- continue
- if "=>" in path: # rename marker {old => new}
- _old, new = _extract_rename_paths(path, set())
- path = new or path
- paths.append(path)
- return paths
+def _record_paths(body: str) -> list[tuple[str, str | None]]:
+ """``(path, renamed_from)`` for each ``--name-status`` line of one log record."""
+ return [name_status_path(line) for line in body.split("\n") if line.strip()]
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
index bd906ade1..01dffb0de 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -17,12 +17,14 @@ __all__ = [
"_RECORD_SEP",
"GitHistoryCoverage",
"GitIndexSummary",
+ "RenameTrail",
"RepoTotals",
"_CommitRec",
"_extract_rename_paths",
"_parse_commit_record",
"_should_skip_index",
"capture_repo_totals",
+ "name_status_path",
]
# Git log record/field separators (NUL byte + US 0x1f) — chosen so they can't
@@ -246,6 +248,7 @@ def _extract_rename_paths(stat_path: str, known_paths: set[str]) -> tuple[str |
10\t5\t{old => new}/shared_suffix
10\t5\told_dir/{old_name => new_name}.py
10\t5\tsrc/{ => newdir}/shared_suffix
+ 10\t5\told.py => pkg/new.py
The third form has an EMPTY side: a directory inserted into (or removed
from) the middle of a path. Expanding the empty side leaves a doubled
@@ -264,9 +267,53 @@ def _extract_rename_paths(stat_path: str, known_paths: set[str]) -> tuple[str |
known_paths.add(old_path)
known_paths.add(new_path)
return old_path, new_path
+ # Paths sharing no leading or trailing component get no braces: ``a.py => src/b.py``.
+ old_path, sep, new_path = stat_path.partition(" => ")
+ if sep and old_path and new_path:
+ known_paths.add(old_path)
+ known_paths.add(new_path)
+ return old_path, new_path
return None, None
+class RenameTrail:
+ """Maps a path as it was at some commit to the path that file has at HEAD.
+
+ Every history walk runs newest first, so a rename is seen before any commit
+ older than it. Resolving each path through the renames seen so far carries
+ a file's pre-rename commits over to its current name, and a path reused by
+ a different file after the rename keeps its own history, because commits
+ to the reused path are all newer than the rename.
+
+ Record a commit's renames only after resolving that commit's own paths: a
+ commit that moves ``a`` to ``b`` and creates a new ``a`` must not hand the
+ new ``a`` to ``b``.
+ """
+
+ __slots__ = ("_current",)
+
+ def __init__(self) -> None:
+ self._current: dict[str, str] = {}
+
+ def resolve(self, path: str) -> str:
+ return self._current.get(path, path)
+
+ def record(self, old_path: str, new_path: str) -> None:
+ current = self.resolve(new_path)
+ if old_path == current:
+ self._current.pop(old_path, None)
+ else:
+ self._current[old_path] = current
+
+
+def name_status_path(line: str) -> tuple[str, str | None]:
+ """``(path, renamed_from)`` for one ``--name-status`` (or ``--name-only``) line."""
+ parts = line.strip().split("\t")
+ if len(parts) >= 3 and parts[0].startswith("R"):
+ return parts[2], parts[1]
+ return parts[-1], None
+
+
@dataclass
class RepoTotals:
"""Whole-history git facts, captured independently of ``commit_limit``.
diff --git a/tests/unit/ingestion/test_git_history_renames.py b/tests/unit/ingestion/test_git_history_renames.py
new file mode 100644
index 000000000..05a82b297
--- /dev/null
+++ b/tests/unit/ingestion/test_git_history_renames.py
@@ -0,0 +1,126 @@
+"""A rename keeps a file's history: commits made under its old path count for it."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from repowise.core.ingestion.git_commit_index import load_sampled_commit_index
+from repowise.core.ingestion.git_indexer import GitIndexer, RenameTrail
+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+_BODY = "".join(f"def f{i}(x):\n return x + {i}\n\n" for i in range(12))
+
+
+def _repo(root):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(root)
+ with repo.config_writer() as cw:
+ cw.set_value("user", "name", "Alice")
+ cw.set_value("user", "email", "[email protected]")
+ return repo
+
+
+def _commit(repo, root, files: dict[str, str], msg: str, date: str, author: str = "Alice"):
+ # The git CLI rather than gitpython's index, which would not see a staged ``git mv``.
+ for name, content in files.items():
+ path = root / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ repo.git.add("--", *files)
+ email = f"{author.lower()}@example.com"
+ env = {
+ "GIT_AUTHOR_NAME": author,
+ "GIT_AUTHOR_EMAIL": email,
+ "GIT_COMMITTER_NAME": author,
+ "GIT_COMMITTER_EMAIL": email,
+ "GIT_AUTHOR_DATE": date,
+ "GIT_COMMITTER_DATE": date,
+ }
+ repo.git.commit("-q", "-m", msg, env=env)
+ return repo.head.commit
+
+
+def _rename(repo, root, old: str, new: str, msg: str, date: str):
+ (root / new).parent.mkdir(parents=True, exist_ok=True)
+ repo.git.mv(old, new)
+ text = (root / new).read_text() + "# moved\n"
+ return _commit(repo, root, {new: text}, msg, date)
+
+
+def _build(root):
+ """a.py and c.py change together as Bob, then a.py moves to src/b.py."""
+ repo = _repo(root)
+ for i in range(3):
+ _commit(
+ repo,
+ root,
+ {"a.py": _BODY + f"# rev {i}\n", "c.py": f"y = {i}\n"},
+ "fix: null check in a" if i == 1 else f"feat: extend a {i}",
+ f"2024-01-0{i + 1}T12:00:00",
+ author="Bob",
+ )
+ _rename(repo, root, "a.py", "src/b.py", "refactor: move a into src", "2024-02-01T12:00:00")
+ _commit(repo, root, {"src/b.py": _BODY + "# after\n"}, "feat: tune b", "2024-02-02T12:00:00")
+ # A new, unrelated a.py after the move keeps only its own history.
+ _commit(repo, root, {"a.py": "z = 1\n"}, "feat: new a", "2024-02-03T12:00:00")
+ repo.close()
+
+
+async def test_renamed_file_keeps_its_pre_rename_history(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")
+ _build(tmp_path)
+
+ _s, rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")
+ meta = {row["file_path"]: row for row in rows}
+
+ moved = meta["src/b.py"]
+ assert moved["commit_count_total"] == 5
+ assert moved["first_commit_at"].date().isoformat() == "2024-01-01"
+ authors = {a["name"]: a["commit_count"] for a in json.loads(moved["top_authors_json"])}
+ assert authors == {"Bob": 3, "Alice": 2}
+ assert moved["prior_defect_raw_count"] == 1
+ partners = {p["file_path"] for p in json.loads(moved["co_change_partners_json"])}
+ assert "c.py" in partners
+
+ assert meta["a.py"]["commit_count_total"] == 1
+ assert meta["a.py"]["prior_defect_raw_count"] == 0
+
+
+def test_deep_walk_continues_the_window_rename_trail(tmp_path) -> None:
+ import git as gitpython
+
+ repo = _repo(tmp_path)
+ old = _commit(repo, tmp_path, {"a.py": _BODY}, "feat: add a", "2024-01-01T12:00:00")
+ moved = _rename(repo, tmp_path, "a.py", "b.py", "refactor: a to b", "2024-01-02T12:00:00")
+ _commit(repo, tmp_path, {"x.py": "x = 1\n"}, "feat: x", "2024-01-03T12:00:00")
+ repo.close()
+
+ repo = gitpython.Repo(tmp_path)
+ try:
+ # A two-commit window holds the rename; the deep walk reaches the add.
+ sample = load_sampled_commit_index(
+ repo, 2, {"b.py", "x.py"}, deep_limit=10, deep_threshold=1
+ )
+ finally:
+ repo.close()
+
+ assert [c.sha for c in sample.commits["b.py"]] == [moved.hexsha, old.hexsha]
+ assert "b.py" not in sample.fallback_files
+
+
+ ("renames", "path", "want"),
+ [
+ ([("b", "c"), ("a", "b")], "a", "c"), # a -> b -> c, seen newest first
+ ([("a", "b")], "b", "b"),
+ ([("b", "a"), ("a", "b")], "a", "a"), # moved away and back
+ ],
+)
+def test_rename_trail_resolves_chains(renames, path, want) -> None:
+ trail = RenameTrail()
+ for old, new in renames:
+ trail.record(old, new)
+ assert trail.resolve(path) == want
diff --git a/tests/unit/ingestion/test_git_rename_markers.py b/tests/unit/ingestion/test_git_rename_markers.py
index b6a2b8c95..6c13b16fb 100644
--- a/tests/unit/ingestion/test_git_rename_markers.py
+++ b/tests/unit/ingestion/test_git_rename_markers.py
@@ -30,6 +30,8 @@ from repowise.core.ingestion.git_indexer.records import _extract_rename_paths
),
# Mid-path segment rename.
("a/{b => c}/d.py", "a/b/d.py", "a/c/d.py"),
+ # No shared leading or trailing component: git prints no braces.
+ ("a.py => src/b.py", "a.py", "src/b.py"),
],
)
def test_rename_marker_forms(stat_path: str, want_old: str, want_new: str) -> None: