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.

feat(git): count prior defects by conventional commit type (#4126)

Raghav Chamadiyab303ee81ce97
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index 1a8ff85f9..9e5d7aa71 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -20,7 +20,7 @@ import math
from collections.abc import Callable, Iterable
from dataclasses import dataclass
-from ...ingestion.git_indexer._constants import is_fix_commit
+from ...ingestion.git_indexer.fix_rule import is_typed_fix_commit
from ..changed_lines import untracked_diffs
# All but path_filter are re-exported: callers across the package import them from here.
@@ -302,7 +302,7 @@ def extract_commit_features(
ns=len(subs),
entropy=_entropy(per_file),
exp=exp,
- is_fix=is_fix_commit(subject),
+ is_fix=is_typed_fix_commit(subject),
author=author,
subject=subject,
ref=sha,
@@ -334,7 +334,7 @@ def extract_range_features(
author, _, subject = meta.partition("\x00")
# Any fix commit in the range marks the change as a fix (informational).
range_subjects = _git(["log", "--format=%s", f"{base}..{head}"], repo_path)
- is_fix = any(is_fix_commit(s) for s in range_subjects.split("\n") if s)
+ is_fix = any(is_typed_fix_commit(s) for s in range_subjects.split("\n") if s)
exp = _author_experience(repo_path, author, base)
return ChangeFeatures(
la=la,
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/prior_defect.py b/packages/core/src/repowise/core/analysis/health/biomarkers/prior_defect.py
index c836e5e90..92d3b8384 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/prior_defect.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/prior_defect.py
@@ -7,9 +7,9 @@ cost-effective signal (highest Popt) — it flags only files that already proved
fragile, so inspecting them per line of code catches defects efficiently.
The git indexer counts, per file, the bug-fix commits touching it in the
-trailing ~6-month window (``git_meta["prior_defect_count"]``), classified by the
-same keyword rule the benchmark labels fixes with, and anchored to the index's
-``as_of`` reference so a historical/T0 checkout measures the window *before* that
+trailing ~6-month window (``git_meta["prior_defect_count"]``), classified by
+the conventional-commit-aware fix rule (``git_indexer/fix_rule.py``), and
+anchored to the index's ``as_of`` reference so a historical/T0 checkout measures the window *before* that
commit — no leakage from future fixes. This biomarker is the consumer.
Fires when the file's fix count is in the top fifth *for this repository*
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
index 65009ec83..b3c698067 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/_constants.py
@@ -150,19 +150,15 @@ _COMMIT_CATEGORIES: dict[str, re.Pattern[str]] = {
),
}
-# Bug-fix commit classifier — mirrors the defect benchmark's
-# ``lib/defect_counter.find_fix_commits`` (keyword strategy) so the product's
-# ``prior_defect`` signal counts exactly the commits the benchmark labels as
-# fixes (product == benchmark). A commit subject is a fix iff it matches an
-# INCLUDE pattern and NO EXCLUDE pattern; merge commits are excluded upstream
-# (the per-file walk skips ``is_merge``), mirroring the bench's ``--no-merges``.
+# Bug-fix commit classifier: the defect benchmark's
+# ``lib/defect_counter.find_fix_commits`` keyword strategy, byte for byte. A
+# subject is a fix iff it matches an INCLUDE pattern and NO EXCLUDE pattern;
+# merge commits are excluded upstream, mirroring the bench's ``--no-merges``.
+# Accepts verb forms, compounds ("hotfix") and issue references ("fixes #12").
#
-# Accepts the verb forms ("fix", "fixed", "fixes", "fixing"), compounds
-# ("hotfix", "bugfix"), and issue reference forms ("fixes #12", "fixed #12").
-#
-# The one fix definition: the per-file category counts and the evolution
-# timeline both label a commit "fix" exactly when this rule does, so every
-# fix count the product shows counts the same commits.
+# Commit rows, the per-file category counts and the evolution timeline label a
+# commit "fix" exactly when this rule does. ``prior_defect`` and the change-risk
+# ``is_fix`` flag read the type first instead (``fix_rule.py``).
_FIX_COMMIT_INCLUDE: tuple[re.Pattern[str], ...] = (
re.compile(r"\b(?:hot|bug)?fix(?:e[sd]|ing)?\b", re.IGNORECASE),
re.compile(r"\bbug\b", re.IGNORECASE),
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/fix_rule.py b/packages/core/src/repowise/core/ingestion/git_indexer/fix_rule.py
new file mode 100644
index 000000000..b97579d96
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/fix_rule.py
@@ -0,0 +1,34 @@
+"""The fix rule that reads a conventional-commit type before the subject's words.
+
+``is_fix_commit`` is the defect benchmark's keyword rule and stays byte-identical
+for parity. On a repository that writes conventional commits it miscounts in both
+directions: "refactor(...): split the Fix-first builder" matches the word "fix", and
+"fix(deps): patch advisories" is dropped by the word "deps" in its scope.
+
+This rule decides by the declared type first. A non-fix type (the types the
+evolution timeline maps to a category) is never a fix, and a fix type always is:
+the diff-shape filter downstream drops a fix that touches no production code. A
+subject without a known type is a fix when its type word or the text after the
+prefix passes the keyword rule, so a scope never excludes it. It counts
+``prior_defect`` and its fix events and sets the change-risk ``is_fix`` flag;
+every other fix count keeps ``is_fix_commit``.
+"""
+
+from __future__ import annotations
+
+from ._constants import _CONVENTIONAL_MAP, _CONVENTIONAL_PREFIX, is_fix_commit
+
+_FIX_TYPES = frozenset({"fix", "hotfix", "bugfix"})
+
+
+def is_typed_fix_commit(subject: str) -> bool:
+ """Whether *subject* is a fix, judged by its conventional type when it declares one."""
+ match = _CONVENTIONAL_PREFIX.match(subject or "")
+ if match is None:
+ return is_fix_commit(subject)
+ kind = match.group("type").lower()
+ if kind in _FIX_TYPES:
+ return True
+ if kind in _CONVENTIONAL_MAP:
+ return False
+ return is_fix_commit(kind) or is_fix_commit(subject[match.end() :])
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index a28528d73..b29af7e06 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -1038,7 +1038,7 @@ class GitIndexer:
def capture_new_fix_events(
self, *, known_shas: set[str] | None = None
- ) -> tuple[list[dict], int, set[str]]:
+ ) -> tuple[list[dict], int, set[str], set[str]]:
"""Build ``fix_events`` rows for fix commits not already persisted.
The incremental counterpart to the tracing ``index_repo`` runs inline,
@@ -1047,16 +1047,16 @@ class GitIndexer:
the rest. An update with no new fix commits does the walk and stops,
which is why it stays inside the +1s budget.
- Returns ``(rows, oldest_fix_ts, tracked_paths)``. Both trailing values
- come back even when there are no new rows, because the caller still has
- two prunes to do: events that aged out of the window, and events for
- files that no longer exist. A fresh index never produces the latter, so
- without that second prune an update accumulates rows for deleted files
- and drifts away from what a re-index would hold.
+ Returns ``(rows, oldest_fix_ts, tracked_paths, retracted_shas)``. The
+ trailing values come back even when there are no new rows, because the
+ caller still has three prunes to do: events that aged out of the window,
+ events for files that no longer exist, and *known_shas* the fix rule no
+ longer names. A fresh index produces none of them, so without the prunes
+ an update drifts away from what a re-index would hold.
"""
repo = self._get_repo()
if repo is None:
- return [], 0, set()
+ return [], 0, set(), set()
try:
tracked = {fp for fp in self._get_tracked_files(repo) if not _should_skip_index(fp)}
walk = collect_fix_commits(
@@ -1067,10 +1067,13 @@ class GitIndexer:
)
rows, ok = self._build_fix_events(walk)
self._record_git_episodes(walk)
- return rows, (walk.oldest_fix_ts if ok else 0), tracked
+ retracted = set()
+ if ok and walk.shas is not None:
+ retracted = set(known_shas or ()) - walk.shas
+ return rows, (walk.oldest_fix_ts if ok else 0), tracked, retracted
except Exception as exc:
logger.debug("incremental_fix_events_failed", error=str(exc))
- return [], 0, set()
+ return [], 0, set(), set()
finally:
with contextlib.suppress(Exception):
repo.close()
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 d50ba0f82..1ab77ca80 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
@@ -9,25 +9,23 @@ index, deliberately: that index is depth-capped (``_DEFAULT_COMMIT_LIMIT`` newes
commits repo-wide) and buckets by file, so on a busy repo a hot file's slice of
those commits silently under-counts — exactly the files this signal cares about.
-The walk mirrors the defect benchmark's prior-defects baseline
+The walk follows the defect benchmark's prior-defects baseline
(``lib/baselines._prior_defect_count`` → ``defect_counter.find_fix_commits`` +
-``_attribute``) so the product identifies exactly the commits the benchmark
-labels as fixes (product == benchmark):
+``_attribute``) except in how it names a fix:
* resolve the window-start commit = the last commit on/before ``as_of - window``;
* walk the **topological range** ``prior_sha..head`` (every non-merge commit
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;
+* classify each commit subject with :func:`.fix_rule.is_typed_fix_commit`;
* 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.
A second pass then opens each matched fix commit's ``-U0`` diff and keeps only
-the ones that actually change production code (:mod:`fix_shape`). ``is_fix_commit``
-stays byte-identical to the benchmark's regex set; the filter sits after it, and
-both totals are returned so the delta is inspectable.
+the ones that actually change production code (:mod:`fix_shape`); both totals are
+returned so the delta is inspectable.
"""
from __future__ import annotations
@@ -38,7 +36,8 @@ from typing import TYPE_CHECKING, Any
import structlog
-from ._constants import PRIOR_DEFECT_WINDOW_DAYS, _truncate_body, is_fix_commit
+from ._constants import PRIOR_DEFECT_WINDOW_DAYS, _truncate_body
+from .fix_rule import is_typed_fix_commit
from .fix_shape import classify_fix_shape
from .records import _RECORD_SEP, RenameTrail, name_status_path
@@ -132,6 +131,9 @@ class FixWalk:
fixes: list[FixCommit] = field(default_factory=list)
oldest_fix_ts: int = 0
+ #: Every fix commit's sha, taken before ``skip_shas`` narrows *fixes*;
+ #: ``None`` when the walk did not run, so no stored fix can be judged gone.
+ shas: frozenset[str] | None = None
def collect_fix_commits(
@@ -168,13 +170,16 @@ def collect_fix_commits(
return FixWalk()
fixes = _walk_fix_commits(repo, rev_range, indexable_files)
+ if fixes is None:
+ return FixWalk()
# Taken before the skip, so an update and a full index at the same HEAD agree
# on the trailing edge even though they trace different commits.
oldest = min((f.ts for f in fixes if f.ts > 0), default=0)
+ shas = frozenset(f.sha for f in fixes)
if skip_shas:
fixes = [f for f in fixes if f.sha not in skip_shas]
if not fixes:
- return FixWalk(oldest_fix_ts=oldest)
+ return FixWalk(oldest_fix_ts=oldest, shas=shas)
diffs = _parse_fix_diffs(repo, [f.sha for f in fixes])
resolved_fixes = [
@@ -190,7 +195,7 @@ def collect_fix_commits(
)
for fix in fixes
]
- return FixWalk(fixes=resolved_fixes, oldest_fix_ts=oldest)
+ return FixWalk(fixes=resolved_fixes, oldest_fix_ts=oldest, shas=shas)
def compute_prior_defects(
@@ -265,11 +270,13 @@ def _resolve_rev_range(repo: Any, *, as_of_ts: float | None, window_days: int) -
return f"{prior_sha}..{head_sha}" if prior_sha else head_sha
-def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> list[FixCommit]:
+def _walk_fix_commits(
+ repo: Any, rev_range: str, indexable_files: set[str]
+) -> list[FixCommit] | None:
"""Subject-matched fix commits in *rev_range*, each with its indexable paths.
Commits that touched nothing indexable are dropped here so the diff pass
- never pays for them.
+ never pays for them. ``None`` when the log itself failed.
"""
try:
raw = repo.git.log(
@@ -281,7 +288,7 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> l
)
except Exception as exc:
logger.debug("prior_defect_log_failed", error=str(exc))
- return []
+ return None
if not raw:
return []
@@ -295,7 +302,7 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> l
fields, path_block = _split_record(record)
sha, committed, subject, body = fields
entries = _record_paths(path_block)
- if is_fix_commit(subject):
+ if is_typed_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]
@@ -325,7 +332,7 @@ def _split_record(record: str) -> tuple[tuple[str, str, str, str], str]:
therefore the real one, and a commit message that somehow carried one keeps
its paths and its subject intact. Taking the subject boundary from the left
instead would truncate a subject at an embedded separator and change which
- commits ``is_fix_commit`` matches, which is a defect count rather than a
+ commits the fix rule matches, which is a defect count rather than a
cosmetic loss.
The terminator is not optional and there is no fallback for its absence:
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 65e0f19c5..9a890814f 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -1147,6 +1147,22 @@ async def prune_fix_events_for_missing_paths(
return int(deleted.rowcount or 0)
+async def prune_fix_events_for_shas(
+ session: AsyncSession, repository_id: str, shas: set[str]
+) -> int:
+ """Drop the fix events of commits the fix rule no longer names a fix."""
+ if not shas:
+ return 0
+ deleted = await session.execute(
+ delete(FixEvent).where(
+ FixEvent.repository_id == repository_id,
+ FixEvent.fix_sha.in_(sorted(shas)),
+ )
+ )
+ await session.flush()
+ return int(deleted.rowcount or 0)
+
+
async def get_fix_event_shas(session: AsyncSession, repository_id: str) -> set[str]:
"""Every fix sha already persisted for a repo.
diff --git a/packages/core/src/repowise/core/pipeline/incremental/commits.py b/packages/core/src/repowise/core/pipeline/incremental/commits.py
index 62c95786d..d35527d37 100644
--- a/packages/core/src/repowise/core/pipeline/incremental/commits.py
+++ b/packages/core/src/repowise/core/pipeline/incremental/commits.py
@@ -318,22 +318,22 @@ def _recompute_commit_experience(stored: list[dict]) -> list[dict]:
async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Any) -> None:
"""Trace + upsert ``fix_events`` for fix commits this index has not seen.
- Two halves, and both are needed for an update to converge on what a fresh
- index would produce: append the fix commits missing from the table, then drop
- the ones that have aged out of the trailing defect window. Without the prune
- the stored set only ever grows past the window's trailing edge; without the
- append it goes stale. Failure-isolated, like every other git-phase refresh.
+ Both halves are needed for an update to converge on what a fresh index would
+ produce: append the fix commits missing from the table, then drop the ones that
+ aged out of the window, lost their file, or the fix rule no longer names.
+ Failure-isolated, like every other git-phase refresh.
"""
from repowise.core.persistence.crud import (
get_fix_event_shas,
prune_fix_events_before,
prune_fix_events_for_missing_paths,
+ prune_fix_events_for_shas,
upsert_fix_events_bulk,
)
try:
known = await get_fix_event_shas(session, repo_id)
- rows, oldest_ts, tracked = await asyncio.to_thread(
+ rows, oldest_ts, tracked, retracted = await asyncio.to_thread(
indexer.capture_new_fix_events, known_shas=known
)
except Exception as exc:
@@ -350,6 +350,7 @@ async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: An
await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))
if tracked:
await prune_fix_events_for_missing_paths(session, repo_id, tracked)
+ await prune_fix_events_for_shas(session, repo_id, retracted)
# Recompute over the whole stored window, not just the rows this update
# appended: decay ages every file's mass whether or not the file changed.
diff --git a/tests/unit/ingestion/test_fix_events.py b/tests/unit/ingestion/test_fix_events.py
index 9ce68adf5..046aec351 100644
--- a/tests/unit/ingestion/test_fix_events.py
+++ b/tests/unit/ingestion/test_fix_events.py
@@ -146,12 +146,12 @@ async def test_capture_new_fix_events_skips_known_commits(tmp_path) -> None:
indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
- everything, oldest, tracked = indexer.capture_new_fix_events()
+ everything, oldest, tracked, _ = indexer.capture_new_fix_events()
assert {r["fix_sha"] for r in everything} == {first, second}
assert oldest > 0
assert tracked == {"a.py"}
- new_only, oldest_again, _ = indexer.capture_new_fix_events(known_shas={first})
+ new_only, oldest_again, _, _ = indexer.capture_new_fix_events(known_shas={first})
assert {r["fix_sha"] for r in new_only} == {second}
# The cutoff is taken before the skip, so narrowing the trace must not move it.
assert oldest_again == oldest
@@ -168,10 +168,10 @@ async def test_update_capture_matches_a_full_index(tmp_path) -> None:
_write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")
_write(repo, tmp_path, "a.py", "x = 2\n", "fix: first")
indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
- seeded, _, _ = indexer.capture_new_fix_events()
+ seeded, _, _, _ = indexer.capture_new_fix_events()
_write(repo, tmp_path, "a.py", "x = 3\n", "fix: second")
- incremental, _, _ = indexer.capture_new_fix_events(known_shas={r["fix_sha"] for r in seeded})
+ incremental, _, _, _ = indexer.capture_new_fix_events(known_shas={r["fix_sha"] for r in seeded})
merged = sorted(seeded + incremental, key=lambda r: (r["fix_sha"], r["file_path"]))
summary, _ = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("repo1")
diff --git a/tests/unit/ingestion/test_typed_fix_rule.py b/tests/unit/ingestion/test_typed_fix_rule.py
new file mode 100644
index 000000000..134dbd6be
--- /dev/null
+++ b/tests/unit/ingestion/test_typed_fix_rule.py
@@ -0,0 +1,101 @@
+"""prior_defect counts fixes by the commit's conventional type before its words.
+
+Subjects are taken from this repository's own history.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.git_indexer._constants import is_fix_commit
+from repowise.core.ingestion.git_indexer.fix_rule import is_typed_fix_commit
+from repowise.core.ingestion.git_indexer.prior_defects import compute_prior_defects
+
+NOT_FIXES = [
+ "refactor(health): split the Fix-first builder into unit modules (#4071)",
+ "refactor(context): resolve get_context targets through an ordered resolver list (#3988)",
+ "feat(health): order Fix first by the function's own change history (#3565)",
+ "test(web): align fix-first-section scope and exclusions assertions (#3339)",
+ "perf(walker): resolve names once per file",
+ "docs: explain the bug in the FAQ",
+ "chore: fix lint",
+ "ci: patch the release workflow",
+ "build(deps): bump vite",
+ "style: fix import order",
+ "feat: add retry, fixes #12",
+ "handle crash on startup",
+]
+FIXES = [
+ "fix(deps): patch fsspec, Mako, multidict, source-map-js, postcss-selector-parser and KaTeX advisories (#3887)",
+ "fix(update): write the repair marker after a docs-mode update (#4026)",
+ "fix(ui): portal the docs Export menu so the header doesn't clip it (#3778)",
+ "fix: null check in parser",
+ "hotfix: restore login",
+ "bugfix: off-by-one in pager",
+ "Fix crash when the index is empty",
+ "Resolve race in scheduler",
+ "revert(api): fix the retry loop",
+ "Fixes: crash on an empty index",
+ "Bug: pager skips the last row",
+ "Resolves: race in scheduler",
+ "fix!: drop the broken retry",
+ 'Revert "fix: x"',
+]
+
+
[email protected]("subject", NOT_FIXES)
+def test_a_non_fix_type_or_wording_is_not_a_fix(subject: str) -> None:
+ assert not is_typed_fix_commit(subject)
+
+
[email protected]("subject", FIXES)
+def test_a_fix_type_or_untyped_fix_wording_is_a_fix(subject: str) -> None:
+ assert is_typed_fix_commit(subject)
+
+
+def test_the_benchmark_rule_is_unchanged() -> None:
+ assert is_fix_commit(NOT_FIXES[0])
+ assert not is_fix_commit(FIXES[0])
+
+
+def _repo(tmp_path):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ repo.config_writer().set_value("user", "email", "[email protected]").release()
+ repo.config_writer().set_value("user", "name", "T").release()
+ return repo
+
+
+def test_prior_defect_counts_by_the_typed_rule(tmp_path) -> None:
+ import git as gitpython
+
+ repo = _repo(tmp_path)
+ subjects = ["feat: add a", NOT_FIXES[0], NOT_FIXES[1], FIXES[0], FIXES[1]]
+ for i, subject in enumerate(subjects):
+ (tmp_path / "a.py").write_text(f"def f():\n return {i}\n", encoding="utf-8")
+ repo.index.add(["a.py"])
+ repo.index.commit(subject)
+
+ counts = compute_prior_defects(gitpython.Repo(tmp_path), {"a.py"}, as_of_ts=None)
+
+ assert counts.counts == {"a.py": 2}
+ assert counts.raw_counts == {"a.py": 2}
+
+
+def test_change_risk_flags_a_commit_by_the_typed_rule(tmp_path) -> None:
+ from repowise.core.analysis.change_risk.features import (
+ extract_commit_features,
+ extract_range_features,
+ )
+
+ repo = _repo(tmp_path)
+ shas = []
+ for i, subject in enumerate(["feat: add a", NOT_FIXES[1], FIXES[0]]):
+ (tmp_path / "a.py").write_text(f"x = {i}\n", encoding="utf-8")
+ repo.index.add(["a.py"])
+ shas.append(repo.index.commit(subject).hexsha)
+
+ assert not extract_commit_features(str(tmp_path), shas[1]).is_fix
+ assert extract_commit_features(str(tmp_path), shas[2]).is_fix
+ assert not extract_range_features(str(tmp_path), shas[0], shas[1]).is_fix
diff --git a/tests/unit/ingestion/test_typed_fix_rule_convergence.py b/tests/unit/ingestion/test_typed_fix_rule_convergence.py
new file mode 100644
index 000000000..7d868af0a
--- /dev/null
+++ b/tests/unit/ingestion/test_typed_fix_rule_convergence.py
@@ -0,0 +1,66 @@
+"""An index written under the keyword fix rule converges on the typed rule at the next update."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+from repowise.core.ingestion.git_indexer import prior_defects as prior_defects_module
+from repowise.core.ingestion.git_indexer._constants import is_fix_commit
+
+_REFACTOR = "refactor(context): resolve get_context targets through an ordered resolver list"
+
+
+def _repo(tmp_path):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ repo.config_writer().set_value("user", "email", "[email protected]").release()
+ repo.config_writer().set_value("user", "name", "T").release()
+ return repo
+
+
+def _write(repo, tmp_path, name: str, body: str, message: str) -> str:
+ (tmp_path / name).write_text(body, encoding="utf-8")
+ repo.index.add([name])
+ return repo.index.commit(message).hexsha
+
+
+def _history(tmp_path) -> str:
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "a.py", "def f():\n return 1\n", "feat: add a")
+ _write(repo, tmp_path, "b.py", "y = 0\n", "feat: add b")
+ return _write(repo, tmp_path, "a.py", "def f():\n return 2\n", _REFACTOR)
+
+
+async def test_an_untouched_files_prior_defect_count_converges(tmp_path, monkeypatch) -> None:
+ _history(tmp_path)
+ with monkeypatch.context() as old_rule:
+ old_rule.setattr(prior_defects_module, "is_typed_fix_commit", is_fix_commit)
+ _summary, meta = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")
+ assert {m["file_path"]: m["prior_defect_count"] for m in meta}["a.py"] == 1
+
+ repo = _repo(tmp_path)
+ _write(repo, tmp_path, "b.py", "y = 1\n", "feat: touch b")
+ sink: dict[str, dict] = {}
+ await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_changed_files(
+ ["b.py"], all_files={"a.py", "b.py"}, idle_decay_sink=sink
+ )
+
+ assert sink["a.py"]["prior_defect_count"] == 0
+
+
+async def test_a_fix_event_the_rule_no_longer_names_is_retracted(tmp_path, monkeypatch) -> None:
+ refactor_sha = _history(tmp_path)
+ indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
+ with monkeypatch.context() as old_rule:
+ old_rule.setattr(prior_defects_module, "is_typed_fix_commit", is_fix_commit)
+ seeded, _, _, _ = indexer.capture_new_fix_events()
+ assert {r["fix_sha"] for r in seeded} == {refactor_sha}
+
+ rows, _, _, retracted = indexer.capture_new_fix_events(known_shas={refactor_sha})
+
+ assert rows == []
+ assert retracted == {refactor_sha}
diff --git a/tests/unit/persistence/test_fix_event_retraction.py b/tests/unit/persistence/test_fix_event_retraction.py
new file mode 100644
index 000000000..93bbf48f3
--- /dev/null
+++ b/tests/unit/persistence/test_fix_event_retraction.py
@@ -0,0 +1,39 @@
+"""An update drops the stored fix events of commits the fix rule no longer names."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.persistence.models import FixEvent
+from repowise.core.pipeline.incremental.commits import persist_incremental_fix_events
+from tests.unit.persistence.helpers import insert_repo
+
+_AT = datetime(2026, 7, 1, tzinfo=UTC)
+_PATH = "src/store.py"
+_REFACTOR, _FIX = "a" * 40, "b" * 40
+
+
+class _Indexer:
+ def capture_new_fix_events(self, *, known_shas=None):
+ return [], int(_AT.timestamp()) - 1, {_PATH}, {_REFACTOR} & set(known_shas or ())
+
+
+async def test_a_retracted_fix_commit_leaves_the_table(async_session) -> None:
+ repo = await insert_repo(async_session)
+ for sha in (_REFACTOR, _FIX):
+ async_session.add(
+ FixEvent(
+ repository_id=repo.id, fix_sha=sha, file_path=_PATH,
+ shape_kind="code_fix", old_ranges_json="[]", committed_at=_AT,
+ )
+ )
+ await async_session.flush()
+
+ await persist_incremental_fix_events(async_session, repo.id, _Indexer())
+
+ stored = (await async_session.execute(select(FixEvent.fix_sha))).scalars().all()
+ assert stored == [_FIX]