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(health): count only bug fixes that change production code (#931)

Raghav Chamadiya29d7ada71637
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 8a1d324da..70451895a 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -683,6 +683,7 @@ def _git_metadata_to_dict(gm: Any) -> dict[str, Any]:
"merge_commit_count_90d": gm.merge_commit_count_90d,
"temporal_hotspot_score": gm.temporal_hotspot_score,
"prior_defect_count": gm.prior_defect_count,
+ "prior_defect_raw_count": gm.prior_defect_raw_count,
"change_entropy": gm.change_entropy,
"change_entropy_pct": gm.change_entropy_pct,
}
diff --git a/packages/core/alembic/versions/0039_prior_defect_raw_count.py b/packages/core/alembic/versions/0039_prior_defect_raw_count.py
new file mode 100644
index 000000000..4180122e4
--- /dev/null
+++ b/packages/core/alembic/versions/0039_prior_defect_raw_count.py
@@ -0,0 +1,39 @@
+"""Unfiltered prior-defect count alongside the shape-filtered one.
+
+``prior_defect_count`` now counts only bug-fix commits whose diff actually
+changes production code (doc-only, test-only, config-only and comment-only
+fixes are dropped — see ``ingestion.git_indexer.fix_shape``). The pre-filter
+total moves into ``prior_defect_raw_count`` so the noise a repo carries stays
+visible and the two can be compared per file.
+
+Defaulted and back-populated on the next index, like every other git_metadata
+column: existing indexes read 0 until then.
+
+Revision ID: 0039
+Revises: 0038
+Create Date: 2026-07-19
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0039"
+down_revision: str | None = "0038"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "git_metadata",
+ sa.Column("prior_defect_raw_count", sa.Integer, nullable=False, server_default="0"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("git_metadata", "prior_defect_raw_count")
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index 6bd84c05d..6ed20aebb 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -3,8 +3,16 @@
``repowise risk`` reads a change as aggregate counts (``--numstat``); the
test-impact query needs the actual changed *line numbers* so it can intersect
them with per-test coverage. This module parses a ``--unified=0`` diff into
-``{file: {line, ...}}`` over the *new* side of the change - the lines that
-exist in the head/index/working tree, which is the space coverage is keyed in.
+per-file records covering **both** sides of the change:
+
+* the *new* side (``new_lines``) - the lines that exist in the head/index/
+ working tree, which is the space coverage is keyed in;
+* the *old* side (``old_ranges``) plus the removed/added line text, which is
+ what the fix-shape classifier and (later) SZZ blame read at ``fix^``.
+
+One parser, two consumers: :func:`changed_lines` keeps its new-side-only
+contract, and the git indexer's prior-defect pass reuses
+:func:`parse_unified_diff` directly rather than growing a second implementation.
Pure ``git`` subprocess walking, reusing the wrapper from the change-risk
feature extractor (no new dependency, deterministic).
@@ -13,43 +21,100 @@ feature extractor (no new dependency, deterministic).
from __future__ import annotations
import re
+from dataclasses import dataclass, field
from .change_risk.features import _git
-# New-side hunk header: ``@@ -a,b +c,d @@`` -> we only care about ``+c,d``
-# (the lines present after the change). ``d`` defaults to 1 when omitted.
-_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
+# ``@@ -a,b +c,d @@`` - both sides. ``b``/``d`` default to 1 when omitted; a
+# count of 0 means "nothing on that side" (pure insertion / pure deletion).
+_HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
+
+
+@dataclass
+class FileDiff:
+ """One file's slice of a ``--unified=0`` diff.
+
+ *path* is the new-side path, falling back to the old-side one for a
+ deletion. *old_ranges* are inclusive ``(start, end)`` line spans on the
+ pre-change file - the space ``git blame <sha>^`` is keyed in. A hunk with
+ an old count of 0 is a pure insertion and contributes no range (there is
+ nothing to blame).
+ """
+
+ path: str
+ new_lines: set[int] = field(default_factory=set)
+ old_ranges: list[tuple[int, int]] = field(default_factory=list)
+ removed: list[str] = field(default_factory=list)
+ added: list[str] = field(default_factory=list)
+
+
+def _header_path(raw: str) -> str | None:
+ """Normalize a ``--- a/x`` / ``+++ b/x`` header path. ``None`` for /dev/null."""
+ path = raw.strip()
+ # git quotes paths with special chars ("b/pa\tth"); strip the quotes so the
+ # common (unquoted) key still resolves. Rare enough to accept the imperfect
+ # unescaping.
+ if len(path) >= 2 and path[0] == '"' and path[-1] == '"':
+ path = path[1:-1]
+ if path == "/dev/null":
+ return None
+ return path[2:] if path[:2] in ("a/", "b/") else path
+
+
+def parse_unified_diff(diff: str) -> dict[str, FileDiff]:
+ """Parse a ``--unified=0`` diff into per-file, two-sided records.
+
+ A ``--- x`` line only counts as a file header when the next line is its
+ ``+++ y`` partner: inside a hunk, a *removed* line whose own text starts
+ with ``--`` renders as ``--- ...`` and would otherwise be misread as the
+ start of a new file (same hazard for ``+++`` on the added side).
+ """
+ result: dict[str, FileDiff] = {}
+ current: FileDiff | None = None
+ lines = diff.splitlines()
+
+ def _record(path: str) -> FileDiff:
+ entry = result.get(path)
+ if entry is None:
+ entry = result[path] = FileDiff(path=path)
+ return entry
+
+ i = 0
+ while i < len(lines):
+ line = lines[i]
+ if line.startswith("--- ") and i + 1 < len(lines) and lines[i + 1].startswith("+++ "):
+ # A deletion has no new-side path; key it by the old one so the
+ # file still shows up for shape classification.
+ path = _header_path(lines[i + 1][4:]) or _header_path(line[4:])
+ current = _record(path) if path else None
+ i += 2
+ continue
+ if line.startswith("@@") and current is not None:
+ if (m := _HUNK_RE.match(line)) is not None:
+ old_start = int(m.group(1))
+ old_count = int(m.group(2)) if m.group(2) is not None else 1
+ new_start = int(m.group(3))
+ new_count = int(m.group(4)) if m.group(4) is not None else 1
+ if old_count > 0:
+ current.old_ranges.append((old_start, old_start + old_count - 1))
+ if new_count > 0:
+ current.new_lines.update(range(new_start, new_start + new_count))
+ elif current is not None:
+ if line.startswith("-"):
+ current.removed.append(line[1:])
+ elif line.startswith("+"):
+ current.added.append(line[1:])
+ i += 1
+ return result
def _parse_unified_diff(diff: str) -> dict[str, set[int]]:
- """Parse ``git diff --unified=0`` into new-side changed lines per file."""
- result: dict[str, set[int]] = {}
- current: str | None = None
- for line in diff.splitlines():
- if line.startswith("+++ "):
- path = line[4:].strip()
- # git quotes paths with special chars ("b/pa\tth"); strip the quotes
- # so the common (unquoted) key still resolves. Rare enough to accept
- # the imperfect unescaping.
- if len(path) >= 2 and path[0] == '"' and path[-1] == '"':
- path = path[1:-1]
- if path == "/dev/null": # file deleted - nothing on the new side
- current = None
- continue
- if path.startswith("b/"):
- path = path[2:]
- current = path
- result.setdefault(current, set())
- elif current is not None and line.startswith("@@"):
- m = _HUNK_RE.match(line)
- if not m:
- continue
- start = int(m.group(1))
- count = int(m.group(2)) if m.group(2) is not None else 1
- result[current].update(range(start, start + count))
- # Drop files whose only change was a deletion (no new-side lines): they
- # cannot intersect coverage, and would otherwise read as "touched".
- return {path: lines for path, lines in result.items() if lines}
+ """New-side changed lines per file - the coverage-intersection view.
+
+ Files whose only change was a deletion (no new-side lines) are dropped:
+ they cannot intersect coverage, and would otherwise read as "touched".
+ """
+ return {path: f.new_lines for path, f in parse_unified_diff(diff).items() if f.new_lines}
def _verify_ref(repo_path: str, ref: str) -> None:
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 9456ec986..ec02d0d6f 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py
@@ -36,9 +36,10 @@ from .enrich import (
meets_hotspot_floors,
)
from .file_history import index_file
+from .fix_shape import SHAPE_KINDS, classify_fix_shape
from .identity import build_identity_resolver, canonicalize_author_email
from .indexer import GitIndexer
-from .prior_defects import compute_prior_defects
+from .prior_defects import PriorDefects, compute_prior_defects
from .records import (
_FIELD_SEP,
_LOG_FORMAT,
@@ -54,6 +55,7 @@ from .tiers import GitIndexTier
__all__ = [
"BACKFILL_PHASE",
"HOTSPOT_HALFLIFE_DAYS",
+ "SHAPE_KINDS",
# Re-exported for ``git_commit_index`` which builds the shared commit index.
"_FIELD_SEP",
"_LOG_FORMAT",
@@ -63,6 +65,7 @@ __all__ = [
"GitIndexSummary",
"GitIndexTier",
"GitIndexer",
+ "PriorDefects",
"_CommitRec",
"_extract_rename_paths",
"_parse_commit_record",
@@ -71,6 +74,7 @@ __all__ = [
"build_identity_resolver",
"canonicalize_author_email",
"classifier_from_repo_config",
+ "classify_fix_shape",
"compute_co_changes",
"compute_co_changes_and_entropy",
"compute_percentiles",
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
index d38e9ccb6..bfffa145c 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
@@ -113,8 +113,10 @@ def new_meta(file_path: str) -> dict[str, Any]:
# the trailing PRIOR_DEFECT_WINDOW_DAYS window (anchored to as_of_ts when
# set, so T0 benchmark scoring stays leakage-free). Consumed by the
# ``prior_defect`` health biomarker; mirrors the benchmark's
- # prior-defects baseline definition (product == benchmark).
+ # prior-defects baseline definition (product == benchmark). The raw
+ # variant is the same walk before fix-shape filtering (fix_shape.py).
"prior_defect_count": 0,
+ "prior_defect_raw_count": 0,
# Agent provenance rollup: how much of this file's indexed history is
# agent-attributed (local channels only — see agent_provenance module).
# agent_authored_pct stays None when the file has no commits at all.
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/fix_shape.py b/packages/core/src/repowise/core/ingestion/git_indexer/fix_shape.py
new file mode 100644
index 000000000..813a662e0
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/fix_shape.py
@@ -0,0 +1,285 @@
+"""What a bug-fix commit's diff actually touches.
+
+``is_fix_commit`` reads the commit *subject*; it cannot tell a one-line null
+guard from a docstring typo sweep. On doc-heavy upstream repos that gap is
+large: on flask, 53.5% of the commits the subject rule counts as fixes change
+no production code at all, which is pure noise in the ``prior_defect``
+biomarker (measured in ``local-stash/fix-diff-intelligence``).
+
+So the prior-defect pass opens each matched fix commit's ``-U0`` diff and
+buckets it:
+
+``code_fix``
+ Touches production code in a way that changes what the code does. The only
+ kind that increments ``prior_defect_count``.
+``test_only`` / ``doc_only`` / ``config_other``
+ Touches only tests, only docs, or only non-code files (build config, CI,
+ lockfiles, assets).
+``comment_only``
+ Touches code files, but the executable content is byte-identical on both
+ sides - a typo sweep through docstrings, or a dropped ``# type: ignore``.
+``empty``
+ No file-level changes at all (an empty commit, or one whose whole diff is
+ a mode change).
+
+``is_fix_commit`` itself stays untouched: it is contractually byte-identical
+to the defect benchmark's ``lib/defect_counter``, so filtering happens *after*
+it and the unfiltered total is kept alongside as ``prior_defect_raw_count``.
+
+Zero LLM, pure path rules + line comparison, deterministic. Ported from the
+evaluation harness (``local-stash/fix-diff-intelligence/evallib.py``), whose
+frozen 240-commit label set is what the path and comment rules below are tuned
+against.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Mapping
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING
+
+from ._constants import _CODE_EXTENSIONS
+
+if TYPE_CHECKING:
+ # Type-only: ``analysis.change_risk`` imports back into this package, so a
+ # runtime import here would close an import cycle.
+ from ...analysis.changed_lines import FileDiff
+
+__all__ = ["SHAPE_KINDS", "classify_fix_shape", "is_code_path", "is_test_path"]
+
+SHAPE_KINDS: tuple[str, ...] = (
+ "code_fix",
+ "test_only",
+ "doc_only",
+ "config_other",
+ "comment_only",
+ "empty",
+)
+
+# ---------------------------------------------------------------------------
+# Path rules
+# ---------------------------------------------------------------------------
+
+_DOC_EXT = frozenset({".md", ".mdx", ".rst", ".txt", ".adoc"})
+_DOC_DIRS = frozenset({"docs", "doc", "documentation"})
+
+# Directory components that mean "this is somebody's test suite". Deliberately
+# NOT bare ``test``: ``django/test/`` and ``src/flask/testing.py`` are shipped
+# test-*framework* library code that every downstream suite imports, and the
+# old ``"test" in path`` substring rule silently dropped every fix to them from
+# the defect count. The plural/underscored forms below are the ones repos
+# actually use for their own suites.
+_TEST_DIRS = frozenset({"tests", "__tests__", "testsuite", "test_suite", "spec", "specs"})
+
+# ``test_x.py`` / ``x_test.go`` / ``x.test.ts`` / ``x.spec.tsx`` / ``XTest.java``
+# / ``conftest.py``. Anchored to the basename, so ``vitest.config.ts`` and
+# ``testing.py`` stay production code.
+_TEST_FILE_RE = re.compile(
+ r"^(?:test_.+|.+_test|conftest|.+\.(?:test|spec)|.+Tests?|.+TestCase)\.[^.]+$"
+)
+
+# Build/tool configuration that happens to carry a code extension
+# (``vitest.config.ts``, ``webpack.config.js``, ``.eslintrc.js``). Fixing one
+# is a toolchain fix, not a defect in the product's code.
+_CONFIG_FILE_RE = re.compile(r"^(?:\..+rc|.+\.(?:config|conf)|.+\.d)\.[^.]+$")
+
+
+def _parts(path: str) -> tuple[str, ...]:
+ return tuple(p.lower() for p in PurePosixPath(path.replace("\\", "/")).parts)
+
+
+def is_doc_path(path: str) -> bool:
+ p = PurePosixPath(path.replace("\\", "/"))
+ return p.suffix.lower() in _DOC_EXT or bool(_DOC_DIRS.intersection(_parts(path)[:-1]))
+
+
+def is_test_path(path: str) -> bool:
+ name = PurePosixPath(path.replace("\\", "/")).name
+ if _CONFIG_FILE_RE.match(name):
+ return False
+ return bool(_TEST_DIRS.intersection(_parts(path)[:-1])) or bool(_TEST_FILE_RE.match(name))
+
+
+def is_code_path(path: str) -> bool:
+ """Production code: a known code extension that is neither test nor config."""
+ p = PurePosixPath(path.replace("\\", "/"))
+ if p.suffix.lower() not in _CODE_EXTENSIONS:
+ return False
+ return not _CONFIG_FILE_RE.match(p.name) and not is_test_path(path)
+
+
+# ---------------------------------------------------------------------------
+# Line rules
+# ---------------------------------------------------------------------------
+
+# Leading markers that make a whole line a comment or a docstring delimiter.
+_COMMENT_PREFIXES = ("#", "//", "/*", "*/", "*", "--", "'''", '"""', "<!--", ";")
+
+# Punctuation that no natural-language sentence carries but almost every line
+# of code does. Used to tell reflowed docstring prose from real statements.
+_CODE_PUNCT = frozenset("(){}[]=;<>|&\\%@")
+
+# Statement keywords that can open a punctuation-free line of real code
+# (``return a or b``, ``import os, sys``, ``del first second``).
+_CODE_LEAD_WORDS = frozenset(
+ {
+ "return",
+ "import",
+ "from",
+ "del",
+ "global",
+ "nonlocal",
+ "raise",
+ "assert",
+ "yield",
+ "pass",
+ "break",
+ "continue",
+ "export",
+ "var",
+ "let",
+ "const",
+ "public",
+ "private",
+ "protected",
+ "static",
+ "func",
+ "fn",
+ "package",
+ "use",
+ "require",
+ "module",
+ "end",
+ "then",
+ "do",
+ "elif",
+ "else",
+ "case",
+ "default",
+ "type",
+ "struct",
+ "interface",
+ "impl",
+ "match",
+ "with",
+ }
+)
+
+
+def _strip_trailing_comment(line: str) -> str:
+ """Drop a trailing ``#``/``//`` comment, ignoring tokens inside quotes."""
+ quote: str | None = None
+ i = 0
+ while i < len(line):
+ ch = line[i]
+ if quote:
+ if ch == "\\":
+ i += 2
+ continue
+ if ch == quote:
+ quote = None
+ elif ch in ("'", '"', "`"):
+ quote = ch
+ elif ch == "#" or (ch == "/" and line[i + 1 : i + 2] == "/"):
+ return line[:i]
+ i += 1
+ return line
+
+
+def _is_prose(text: str) -> bool:
+ """Whether a punctuation-free, multi-word line reads as documentation.
+
+ Docstring bodies are the one kind of "code line" that carries no comment
+ marker of its own (``some very advanced use cases for which ...``), so a
+ prefix test alone reads a reflowed docstring as a code change. Kept
+ deliberately strict - any code punctuation, a trailing ``:``, a ``:=``, or
+ a leading statement keyword disqualifies the line - because the shape only
+ changes when *every* changed line in the commit passes.
+ """
+ if ":=" in text or text.endswith(":"):
+ return False
+ if any(c in _CODE_PUNCT for c in text):
+ return False
+ words = text.split()
+ if len(words) < 3:
+ return False
+ return words[0].strip(":.,").lower() not in _CODE_LEAD_WORDS
+
+
+def _code_part(raw: str) -> str:
+ """A changed line with its trailing comment removed, indentation preserved.
+
+ Indentation is load-bearing: it is what separates "the same statement, now
+ nested one level deeper" (a real change) from "the same statement, minus a
+ ``# type: ignore``".
+ """
+ return _strip_trailing_comment(raw).rstrip()
+
+
+def _is_inert(raw: str) -> bool:
+ """Whether a changed line carries no executable content of its own."""
+ text = _code_part(raw).strip()
+ return not text or text.startswith(_COMMENT_PREFIXES) or _is_prose(text)
+
+
+def _is_comment_only_change(removed: list[str], added: list[str]) -> bool:
+ """Whether a diff's code files changed nothing but comments.
+
+ Two mechanisms count, and nothing else:
+
+ * every changed line is inert - a comment, a blank, or docstring prose;
+ * the executable lines pair up one-for-one and differ *only* in their
+ trailing comment (``foo(x) # type: ignore`` -> ``foo(x)``).
+
+ The second clause is why the comparison is ordered and requires the raw
+ lines to differ. Sorting the two sides instead would read a swap of two
+ adjacent statements as "no change", and dropping the ``raw != raw`` test
+ would do the same for a statement moved between hunks - both are real
+ behaviour changes that must stay ``code_fix``.
+ """
+ code_removed = [line for line in removed if not _is_inert(line)]
+ code_added = [line for line in added if not _is_inert(line)]
+ if not code_removed and not code_added:
+ return True
+ if len(code_removed) != len(code_added):
+ return False
+ return all(
+ r != a and _code_part(r) == _code_part(a)
+ for r, a in zip(code_removed, code_added, strict=True)
+ )
+
+
+# ---------------------------------------------------------------------------
+# Classification
+# ---------------------------------------------------------------------------
+
+
+def classify_fix_shape(files: Mapping[str, FileDiff]) -> str:
+ """Bucket a parsed fix diff into one of :data:`SHAPE_KINDS`.
+
+ Order matters. ``doc_only`` needs *every* file to be documentation, so a
+ docs-plus-tests commit falls through to ``test_only``; ``comment_only`` is
+ only reachable once production-code files are in play. All four non-code
+ kinds are excluded from the count either way, so the ordering decides how
+ the noise is labelled, not how much of it there is.
+ """
+ if not files:
+ return "empty"
+
+ paths = list(files)
+ if all(is_doc_path(p) for p in paths):
+ return "doc_only"
+ if all(is_test_path(p) or is_doc_path(p) for p in paths):
+ return "test_only"
+
+ code_files = [f for p, f in files.items() if is_code_path(p)]
+ if not code_files:
+ return "config_other"
+
+ removed = [line for f in code_files for line in f.removed]
+ added = [line for f in code_files for line in f.added]
+ if not removed and not added:
+ # Code files present but no changed lines: a pure rename or mode change.
+ return "config_other"
+ return "comment_only" if _is_comment_only_change(removed, added) else "code_fix"
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 f1e731302..57d5034af 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -31,7 +31,7 @@ from ._constants import (
from .co_change import compute_co_changes, compute_co_changes_and_entropy
from .enrich import compute_percentiles
from .file_history import index_file
-from .prior_defects import compute_prior_defects
+from .prior_defects import PriorDefects, compute_prior_defects
from .records import GitIndexSummary, _CommitRec, _should_skip_index, capture_repo_totals
from .tiers import GitIndexTier
@@ -259,7 +259,7 @@ class GitIndexer:
# depth-capped commit index, which under-counts the busiest files —
# exactly the ones this signal flags). Bounded to the trailing window,
# so it's cheap regardless of total repo age and leakage-free at T0.
- prior_defects: dict[str, int] = {}
+ prior_defects = PriorDefects()
try:
prior_defects = compute_prior_defects(repo, set(indexable_files), as_of_ts=as_of_ts)
except Exception as exc:
@@ -278,8 +278,10 @@ class GitIndexer:
meta["co_change_partners_json"] = json.dumps(co_changes[fp])
if fp in change_entropy:
meta["change_entropy"] = change_entropy[fp]
- if fp in prior_defects:
- meta["prior_defect_count"] = prior_defects[fp]
+ if fp in prior_defects.counts:
+ meta["prior_defect_count"] = prior_defects.counts[fp]
+ if fp in prior_defects.raw_counts:
+ meta["prior_defect_raw_count"] = prior_defects.raw_counts[fp]
share = trace_line_shares.get(fp)
if share:
meta["agent_line_count"] = share[0]
@@ -429,8 +431,11 @@ class GitIndexer:
repo, {m["file_path"] for m in results}, as_of_ts=as_of_ts
)
for meta in results:
- if meta["file_path"] in prior_defects:
- meta["prior_defect_count"] = prior_defects[meta["file_path"]]
+ fp = meta["file_path"]
+ if fp in prior_defects.counts:
+ meta["prior_defect_count"] = prior_defects.counts[fp]
+ if fp in prior_defects.raw_counts:
+ meta["prior_defect_raw_count"] = prior_defects.raw_counts[fp]
except Exception as exc:
logger.debug("prior_defect_pass_failed", error=str(exc))
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 585b75f56..d4b101702 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,10 +9,10 @@ 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.
-It mirrors the defect benchmark's prior-defects baseline
+The walk mirrors the defect benchmark's prior-defects baseline
(``lib/baselines._prior_defect_count`` → ``defect_counter.find_fix_commits`` +
-``_attribute``) so the product counts exactly the commits the benchmark labels as
-fixes (product == benchmark):
+``_attribute``) so the product identifies exactly the commits the benchmark
+labels as fixes (product == benchmark):
* resolve the window-start commit = the last commit on/before ``as_of - window``;
* walk the **topological range** ``prior_sha..head`` (every non-merge commit
@@ -22,27 +22,61 @@ fixes (product == benchmark):
* attribute a fix to every indexable file it touched.
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.
"""
from __future__ import annotations
+from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from ._constants import PRIOR_DEFECT_WINDOW_DAYS, is_fix_commit
+from .fix_shape import classify_fix_shape
from .records import _RECORD_SEP, _extract_rename_paths
logger = structlog.get_logger(__name__)
-__all__ = ["compute_prior_defects"]
+__all__ = ["PriorDefects", "compute_prior_defects"]
# sha <US> subject, one record per commit (NUL-separated); --name-only then
# emits the touched paths on the lines that follow.
_PRIOR_LOG_FORMAT = "%x00%H%x1f%s"
_FIELD_SEP = "\x1f"
+# Fix commits per ``git log --no-walk`` batch in the diff pass. One subprocess
+# per batch, so bigger is cheaper — but each sha costs 41 characters of command
+# line and Windows caps that at 32 KB, so this stays well clear of the ceiling.
+_SHAPE_BATCH_SIZE = 300
+
+
+@dataclass(frozen=True)
+class PriorDefects:
+ """Per-file bug-fix counts over the trailing window, before and after filtering.
+
+ *counts* keeps only commits whose diff changes production code and is what
+ the ``prior_defect`` biomarker scores. *raw_counts* is every subject-matched
+ fix, i.e. what the count was before shape filtering — persisted alongside so
+ the noise a repo carries stays visible instead of silently disappearing.
+ """
+
+ counts: dict[str, int] = field(default_factory=dict)
+ raw_counts: dict[str, int] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class _FixCommit:
+ """A subject-matched fix commit and the indexable files it touched."""
+
+ sha: str
+ paths: list[str]
+
def compute_prior_defects(
repo: Any,
@@ -50,38 +84,81 @@ def compute_prior_defects(
*,
as_of_ts: float | None,
window_days: int = PRIOR_DEFECT_WINDOW_DAYS,
-) -> dict[str, int]:
- """Return ``{file_path: bug-fix-commit count}`` over the trailing window.
+) -> PriorDefects:
+ """Return per-file bug-fix counts over the trailing window.
*as_of_ts* anchors the window's end (the repo's HEAD-commit timestamp under
``REPOWISE_GIT_WINDOW_ANCHOR``, else wall-clock now). Only commits reachable
from HEAD are walked, so a historical T0 checkout never sees post-T0 fixes.
Files outside *indexable_files* are ignored.
"""
+ rev_range = _resolve_rev_range(repo, as_of_ts=as_of_ts, window_days=window_days)
+ if rev_range is None:
+ return PriorDefects()
+
+ fixes = _walk_fix_commits(repo, rev_range, indexable_files)
+ if not fixes:
+ return PriorDefects()
+
+ raw_counts: dict[str, int] = {}
+ for fix in fixes:
+ for path in fix.paths:
+ raw_counts[path] = raw_counts.get(path, 0) + 1
+
+ shapes = _classify_shapes(repo, [f.sha for f in fixes])
+ counts: dict[str, int] = {}
+ for fix in fixes:
+ # Unknown shape (the diff pass failed) counts as a fix: falling back to
+ # the raw behaviour is the safe direction for a defect signal.
+ if shapes.get(fix.sha, "code_fix") != "code_fix":
+ continue
+ for path in fix.paths:
+ counts[path] = counts.get(path, 0) + 1
+
+ return PriorDefects(counts=counts, raw_counts=raw_counts)
+
+
+# ---------------------------------------------------------------------------
+# Pass 1: which commits are fixes, and what did they touch
+# ---------------------------------------------------------------------------
+
+
+def _resolve_rev_range(repo: Any, *, as_of_ts: float | None, window_days: int) -> str | None:
+ """``prior_sha..head`` for the trailing window, or ``None`` when HEAD is unreadable.
+
+ Falls back to plain ``head`` (every reachable commit) when the repo is
+ younger than the window and no boundary commit exists.
+ """
now = datetime.fromtimestamp(as_of_ts, tz=UTC) if as_of_ts is not None else datetime.now(UTC)
window_start = (now - timedelta(days=window_days)).strftime("%Y-%m-%d")
try:
- head_sha = repo.head.commit.hexsha # type: ignore[attr-defined]
+ head_sha = repo.head.commit.hexsha
except Exception as exc:
logger.debug("prior_defect_head_failed", error=str(exc))
- return {}
+ return None
# Window-start boundary: the last commit on/before (as_of - window),
# reachable from HEAD. Mirrors the benchmark's ``resolve_t0_sha``.
prior_sha = ""
try:
- prior_sha = repo.git.log( # type: ignore[attr-defined]
+ prior_sha = repo.git.log(
head_sha, f"--before={window_start}T23:59:59", "-1", "--format=%H"
).strip()
except Exception as exc:
logger.debug("prior_defect_window_resolve_failed", error=str(exc))
- # Range: prior_sha..head (window) when the boundary resolves; otherwise the
- # repo is younger than the window → count all fixes reachable from HEAD.
- rev_range = f"{prior_sha}..{head_sha}" if prior_sha else head_sha
+ 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]:
+ """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.
+ """
try:
- raw = repo.git.log( # type: ignore[attr-defined]
+ raw = repo.git.log(
rev_range,
"--no-merges",
"--name-only",
@@ -89,27 +166,86 @@ def compute_prior_defects(
)
except Exception as exc:
logger.debug("prior_defect_log_failed", error=str(exc))
- return {}
+ return []
if not raw:
- return {}
+ return []
- counts: dict[str, int] = {}
+ fixes: list[_FixCommit] = []
for record in raw.split(_RECORD_SEP):
record = record.strip("\n")
if not record:
continue
- head, _, rest = record.partition("\n")
- _sha, _, subject = head.partition(_FIELD_SEP)
+ header, _, body = record.partition("\n")
+ sha, _, subject = header.partition(_FIELD_SEP)
if not is_fix_commit(subject):
continue
- for line in rest.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
- if path in indexable_files:
- counts[path] = counts.get(path, 0) + 1
- return counts
+ paths = [p for p in _record_paths(body) if p in indexable_files]
+ if paths:
+ fixes.append(_FixCommit(sha=sha, paths=paths))
+ return fixes
+
+
+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
+
+
+# ---------------------------------------------------------------------------
+# Pass 2: what each fix commit's diff actually changes
+# ---------------------------------------------------------------------------
+
+
+def _classify_shapes(repo: Any, shas: list[str]) -> dict[str, str]:
+ """Map each fix sha to its :mod:`fix_shape` kind.
+
+ Batched: one ``git log --no-walk -p`` subprocess per :data:`_SHAPE_BATCH_SIZE`
+ commits rather than a ``git show`` spawn each, which is what keeps the pass
+ affordable on Windows (where process spawn dominates git's own cost).
+ Failures degrade to an empty map, and the caller then counts the commit.
+ """
+ shapes: dict[str, str] = {}
+ for start in range(0, len(shas), _SHAPE_BATCH_SIZE):
+ batch = shas[start : start + _SHAPE_BATCH_SIZE]
+ try:
+ raw = repo.git.log(
+ "--no-walk",
+ "--patch",
+ "--unified=0",
+ "--no-color",
+ "--format=%x00%H",
+ *batch,
+ )
+ except Exception as exc:
+ logger.debug("prior_defect_shape_batch_failed", error=str(exc), commits=len(batch))
+ continue
+ shapes.update(_parse_shape_batch(raw))
+ return shapes
+
+
+def _parse_shape_batch(raw: str) -> dict[str, str]:
+ """Split a batched ``--format=%x00%H --patch`` log into per-sha shape kinds."""
+ # Imported here, not at module scope: ``analysis.change_risk`` imports back
+ # into this package, so a top-level import would close an import cycle.
+ from ...analysis.changed_lines import parse_unified_diff
+
+ shapes: dict[str, str] = {}
+ for record in raw.split(_RECORD_SEP):
+ record = record.strip("\n")
+ if not record:
+ continue
+ sha, _, diff = record.partition("\n")
+ sha = sha.strip()
+ if len(sha) != 40:
+ continue
+ shapes[sha] = classify_fix_shape(parse_unified_diff(diff))
+ return shapes
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 950392e23..b9f254f8a 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -445,7 +445,13 @@ class GitMetadata(Base):
# Prior-defect history: bug-fix commits touching this file in the trailing
# ~6-month defect window (anchored to the index's as_of reference). Consumed
# by the ``prior_defect`` health biomarker — a leakage-aware process signal.
+ #
+ # ``prior_defect_count`` keeps only fixes whose diff changes production code
+ # (see ingestion.git_indexer.fix_shape); ``prior_defect_raw_count`` is every
+ # subject-matched fix, kept alongside so the filtered-out noise stays
+ # inspectable instead of silently vanishing from the count.
prior_defect_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ prior_defect_raw_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
# Temporal hotspot score: exponentially time-decayed churn signal
temporal_hotspot_score: Mapped[float | None] = mapped_column(Float, nullable=True, default=0.0)
diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.py
index 616a171f4..f7c048872 100644
--- a/tests/unit/cli/test_commands.py
+++ b/tests/unit/cli/test_commands.py
@@ -355,6 +355,7 @@ class TestGitMetadataToDict:
merge_commit_count_90d=1,
temporal_hotspot_score=0.8,
prior_defect_count=5,
+ prior_defect_raw_count=9,
change_entropy=0.42,
change_entropy_pct=0.6,
)
@@ -366,6 +367,7 @@ class TestGitMetadataToDict:
assert d["bus_factor"] == 2
# Columns added by the newer health biomarkers must flow through too.
assert d["prior_defect_count"] == 5
+ assert d["prior_defect_raw_count"] == 9
assert d["change_entropy"] == 0.42
assert d["change_entropy_pct"] == 0.6
diff --git a/tests/unit/ingestion/test_fix_shape.py b/tests/unit/ingestion/test_fix_shape.py
new file mode 100644
index 000000000..cb899db63
--- /dev/null
+++ b/tests/unit/ingestion/test_fix_shape.py
@@ -0,0 +1,240 @@
+"""Fix-shape classification: which bug-fix diffs actually change production code.
+
+The shape kind gates ``prior_defect_count``, so every rule here is a rule about
+whether a commit gets counted as a defect. Cases are drawn from the frozen
+240-commit label set in ``local-stash/fix-diff-intelligence/labels`` — each
+class of miss that set exposed has a test below.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.changed_lines import parse_unified_diff
+from repowise.core.ingestion.git_indexer.fix_shape import (
+ classify_fix_shape,
+ is_code_path,
+ is_test_path,
+)
+
+
+def shape(diff: str) -> str:
+ return classify_fix_shape(parse_unified_diff(diff))
+
+
+def one_file(path: str, *, removed: list[str], added: list[str]) -> str:
+ """A minimal single-hunk ``-U0`` diff for *path*."""
+ old_count, new_count = len(removed), len(added)
+ body = "".join(f"-{line}\n" for line in removed) + "".join(f"+{line}\n" for line in added)
+ return (
+ f"diff --git a/{path} b/{path}\n"
+ f"--- a/{path}\n+++ b/{path}\n"
+ f"@@ -10,{old_count} +10,{new_count} @@\n{body}"
+ )
+
+
+# --- path rules ------------------------------------------------------------
+
+
+ "path",
+ [
+ "tests/test_app.py",
+ "src/pkg/test_helpers.py",
+ "packages/ui/__tests__/panel.test.tsx",
+ "internal/server_test.go",
+ "spec/models/user_spec.rb",
+ "flask/testsuite/basic.py",
+ "conftest.py",
+ ],
+)
+def test_test_paths_recognised(path: str) -> None:
+ assert is_test_path(path)
+
+
+ "path",
+ [
+ # Shipped test-*framework* library code, not somebody's test suite. The
+ # old ``"test" in path`` substring rule dropped every fix to these from
+ # the defect count.
+ "django/test/client.py",
+ "src/flask/testing.py",
+ "packages/core/src/repowise/core/analysis/latest.py",
+ # Tooling config that happens to carry a code extension.
+ "vitest.config.ts",
+ ],
+)
+def test_production_paths_not_mistaken_for_tests(path: str) -> None:
+ assert not is_test_path(path)
+
+
+def test_config_files_are_not_production_code() -> None:
+ assert not is_code_path("vitest.config.ts")
+ assert not is_code_path("packages/app/webpack.config.js")
+ assert is_code_path("packages/app/src/index.ts")
+
+
+# --- shape classification --------------------------------------------------
+
+
+def test_empty_diff() -> None:
+ assert shape("") == "empty"
+
+
+def test_doc_only_includes_mdx() -> None:
+ diff = one_file("docs/api.mdx", removed=["old text here"], added=["new text here"])
+ assert shape(diff) == "doc_only"
+
+
+def test_test_only() -> None:
+ diff = one_file("tests/test_app.py", removed=["assert a == 1"], added=["assert a == 2"])
+ assert shape(diff) == "test_only"
+
+
+def test_config_other() -> None:
+ diff = one_file(".github/workflows/ci.yml", removed=[" node: 18"], added=[" node: 20"])
+ assert shape(diff) == "config_other"
+
+
+def test_code_fix() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[" return items[0]"],
+ added=[" return items[0] if items else None"],
+ )
+ assert shape(diff) == "code_fix"
+
+
+def test_fix_to_shipped_test_framework_counts_as_code() -> None:
+ diff = one_file(
+ "django/test/client.py",
+ removed=[" return self.response.template"],
+ added=[" return self.response.templates[0]"],
+ )
+ assert shape(diff) == "code_fix"
+
+
+# --- comment_only ----------------------------------------------------------
+
+
+def test_comment_only_full_line_comments() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[" # exception ocurrs and reloads", " # fidling with dicts"],
+ added=[" # exception occurs and reloads", " # fiddling with dicts"],
+ )
+ assert shape(diff) == "comment_only"
+
+
+def test_comment_only_docstring_prose() -> None:
+ """Reflowed docstring bodies carry no comment marker of their own."""
+ diff = one_file(
+ "src/cli.py",
+ removed=[" some very advanced usecases for which it makes sense to"],
+ added=[" some very advanced use cases for which it makes sense to"],
+ )
+ assert shape(diff) == "comment_only"
+
+
+def test_comment_only_trailing_type_ignore_removed() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[" rv.headers.update(headers) # type: ignore[arg-type]"],
+ added=[" rv.headers.update(headers)"],
+ )
+ assert shape(diff) == "comment_only"
+
+
+def test_added_docstring_block_is_comment_only() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[],
+ added=[
+ "",
+ " .. admonition:: Debug Note",
+ "",
+ " In debug mode Flask will not tear down a request",
+ ],
+ )
+ assert shape(diff) == "comment_only"
+
+
+def test_swapped_statements_are_a_code_fix() -> None:
+ """Identical line multisets in a different order change behaviour."""
+ diff = one_file(
+ "src/ctx.py",
+ removed=[
+ " return _cv_app.get(None) is not None",
+ " return _cv_req.get(None) is not None",
+ ],
+ added=[
+ " return _cv_req.get(None) is not None",
+ " return _cv_app.get(None) is not None",
+ ],
+ )
+ assert shape(diff) == "code_fix"
+
+
+def test_statement_moved_deeper_is_a_code_fix() -> None:
+ """Same statement, new indentation: a real change, not a comment edit."""
+ diff = one_file(
+ "src/app.py",
+ removed=[" ctx.push()"],
+ added=[" ctx.push()"],
+ )
+ assert shape(diff) == "code_fix"
+
+
+def test_comment_marker_inside_a_string_is_not_stripped() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[' url = "http://old.example"'],
+ added=[' url = "http://new.example"'],
+ )
+ assert shape(diff) == "code_fix"
+
+
+def test_docs_plus_tests_reads_as_test_only() -> None:
+ """``doc_only`` needs every file to be docs; either way it is not counted."""
+ diff = one_file("README.md", removed=["a b c"], added=["a b d"]) + one_file(
+ "tests/test_app.py", removed=["assert x"], added=["assert y"]
+ )
+ assert shape(diff) == "test_only"
+
+
+def test_comment_edit_plus_real_change_is_a_code_fix() -> None:
+ diff = one_file(
+ "src/app.py",
+ removed=[" # a typo heer", " return None"],
+ added=[" # a typo here", " return default"],
+ )
+ assert shape(diff) == "code_fix"
+
+
+# --- two-sided diff parsing ------------------------------------------------
+
+
+def test_parser_returns_old_ranges_and_line_text() -> None:
+ diff = one_file("src/app.py", removed=["old"], added=["new"])
+ parsed = parse_unified_diff(diff)
+ entry = parsed["src/app.py"]
+ assert entry.old_ranges == [(10, 10)]
+ assert entry.new_lines == {10}
+ assert entry.removed == ["old"]
+ assert entry.added == ["new"]
+
+
+def test_parser_keeps_deleted_files_under_their_old_path() -> None:
+ diff = "diff --git a/gone.py b/gone.py\n--- a/gone.py\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\n"
+ parsed = parse_unified_diff(diff)
+ assert parsed["gone.py"].old_ranges == [(1, 2)]
+ assert parsed["gone.py"].new_lines == set()
+
+
+def test_parser_does_not_mistake_removed_dashes_for_a_header() -> None:
+ """A removed line whose text starts with ``--`` renders as ``--- ...``."""
+ diff = one_file("src/app.py", removed=["-- a sql comment", "code()"], added=["code2()"])
+ parsed = parse_unified_diff(diff)
+ assert list(parsed) == ["src/app.py"]
+ assert parsed["src/app.py"].removed == ["-- a sql comment", "code()"]
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index a74dea505..f1065d6ff 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -510,22 +510,47 @@ class TestPriorDefectCount:
shared keyword rule, and attributes each fix to every indexable file it
touched — mirroring the defect benchmark's prior-defects baseline."""
- def _mock_repo(self, records: list[tuple[str, list[str]]]) -> MagicMock:
- """records: list of (subject, [touched paths]). Builds the --name-only
- log output and routes prior_sha resolution vs the windowed walk."""
+ @staticmethod
+ def _code_diff(paths: list[str]) -> str:
+ """A ``-U0`` patch that changes real code in each of *paths*."""
+ return "".join(
+ f"diff --git a/{p} b/{p}\n--- a/{p}\n+++ b/{p}\n"
+ f"@@ -10 +10 @@\n- return None\n+ return value\n"
+ for p in paths
+ )
+
+ def _mock_repo(
+ self,
+ records: list[tuple[str, list[str]]],
+ diffs: dict[int, str] | None = None,
+ ) -> MagicMock:
+ """records: list of (subject, [touched paths]).
+
+ Builds the ``--name-only`` log output and routes the three ``git log``
+ shapes the pass issues: prior_sha resolution, the windowed walk, and the
+ batched ``--no-walk --patch`` shape pass. *diffs* overrides the patch for
+ a record by index; the default is a plain code change, so a commit that
+ the subject rule matches also classifies as ``code_fix``.
+ """
mock_repo = MagicMock()
mock_repo.head.commit.hexsha = "HEADSHA"
chunks = []
+ patches = {}
for i, (subject, paths) in enumerate(records):
+ sha = f"{i:040d}"
body = "\n".join(paths)
- chunks.append(f"\x00sha{i:04d}\x1f{subject}\n{body}")
+ chunks.append(f"\x00{sha}\x1f{subject}\n{body}")
+ patches[sha] = (diffs or {}).get(i, self._code_diff(paths))
log_out = "\n".join(chunks)
def _log(*args, **kwargs):
- # prior_sha resolution carries --before / -1; the walk carries
- # --name-only. Route on that.
+ # prior_sha resolution carries --before / -1; the shape pass carries
+ # --no-walk; the windowed walk carries --name-only. Route on that.
if any(str(a).startswith("--before") for a in args):
return "PRIORSHA"
+ if "--no-walk" in args:
+ shas = [a for a in args if len(str(a)) == 40]
+ return "\n".join(f"\x00{sha}\n{patches[sha]}" for sha in shas)
return log_out
mock_repo.git.log.side_effect = _log
@@ -544,10 +569,11 @@ class TestPriorDefectCount:
("fix lint", ["src/app.py"]), # excluded keyword
]
)
- counts = compute_prior_defects(
+ result = compute_prior_defects(
repo, {"src/app.py", "src/util.py"}, as_of_ts=1_700_000_000.0
)
- assert counts == {"src/app.py": 2, "src/util.py": 1}
+ assert result.counts == {"src/app.py": 2, "src/util.py": 1}
+ assert result.raw_counts == {"src/app.py": 2, "src/util.py": 1}
def test_ignores_non_indexable_paths(self) -> None:
from repowise.core.ingestion.git_indexer.prior_defects import (
@@ -559,8 +585,8 @@ class TestPriorDefectCount:
("fix: bug", ["src/app.py", "docs/readme.md"]),
]
)
- counts = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
- assert counts == {"src/app.py": 1}
+ result = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
+ assert result.counts == {"src/app.py": 1}
def test_zero_when_no_fixes(self) -> None:
from repowise.core.ingestion.git_indexer.prior_defects import (
@@ -573,8 +599,57 @@ class TestPriorDefectCount:
("docs: update readme", ["src/app.py"]),
]
)
- counts = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
- assert counts == {}
+ result = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
+ assert result.counts == {}
+ assert result.raw_counts == {}
+
+ def test_non_code_fixes_are_filtered_but_still_counted_raw(self) -> None:
+ """A docstring-only "fix" stops incrementing the biomarker's count.
+
+ The raw total keeps it, so the noise a repo carries stays inspectable
+ instead of silently disappearing from the signal.
+ """
+ from repowise.core.ingestion.git_indexer.prior_defects import (
+ compute_prior_defects,
+ )
+
+ repo = self._mock_repo(
+ [
+ ("fix: real crash", ["src/app.py"]),
+ ("fix: wording in the module docstring", ["src/app.py"]),
+ ],
+ diffs={
+ 1: (
+ "diff --git a/src/app.py b/src/app.py\n"
+ "--- a/src/app.py\n+++ b/src/app.py\n"
+ "@@ -3 +3 @@\n"
+ "- # returns the parsed thing\n"
+ "+ # returns the parsed value\n"
+ )
+ },
+ )
+ result = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
+ assert result.counts == {"src/app.py": 1}
+ assert result.raw_counts == {"src/app.py": 2}
+
+ def test_unreadable_diff_counts_the_fix(self) -> None:
+ """A failed shape pass falls back to the raw behaviour, never to zero."""
+ from repowise.core.ingestion.git_indexer.prior_defects import (
+ compute_prior_defects,
+ )
+
+ repo = self._mock_repo([("fix: crash", ["src/app.py"])])
+
+ def _log(*args, **kwargs):
+ if any(str(a).startswith("--before") for a in args):
+ return "PRIORSHA"
+ if "--no-walk" in args:
+ raise RuntimeError("git exploded")
+ return "\x00" + "0" * 40 + "\x1ffix: crash\nsrc/app.py"
+
+ repo.git.log.side_effect = _log
+ result = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)
+ assert result.counts == {"src/app.py": 1}
# ---------------------------------------------------------------------------