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(refactoring): give split_file the same commit sets on a re-score as on a full index (#2856)

Raghav Chamadiya19b818498628
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index a7468417b..10f074728 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -127,13 +127,14 @@ page cost the whole repository.
`performance_fix` plans are excluded by construction: the performance layer
composes, ranks and owns the lifecycle of its own opportunities.
-**Known limit: Split File ids across `init` and `update`.** A `split_file` plan
-id can differ between a full index and an incremental update of the same
-commit. The partition behind it comes from community detection over the file's
-symbol graph, and modularity is sensitive to edge density, which the two paths
-do not always build identically. The id is stable from one update to the next,
-but not guaranteed equal between an `init` and an `update` at one commit, and
-the opportunity id over it moves with it.
+**Split File ids across `init` and `update`.** A full index, an incremental
+update and a re-score from stored git metadata now build the same symbol graph
+for a file at one commit, so its `split_file` plan id is the same on every path:
+the co-change edge reads each function's commit set (its 50 most recent
+distinct commits) from `git_function_blame` when no blame index is at hand.
+A re-score blames, once, the candidate files whose rows predate that column.
+This moved Split File groups, so refactoring model 4 re-mints every plan id
+once on upgrade; a held `refac3_` id reports `stale_model`.
### Ordering, and `refactoring_view`
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 2b94e6a22..4c50ec74f 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -18,7 +18,14 @@ from typing import Any
import structlog
-from repowise.cli.helpers import console, head_commit_ts, load_config, run_async, save_state
+from repowise.cli.helpers import (
+ console,
+ head_commit_ts,
+ load_config,
+ load_state,
+ run_async,
+ save_state,
+)
from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
from repowise.core.pipeline import PhaseTimings, timed
@@ -1417,12 +1424,19 @@ async def _rescore_health_from_db(
init_db,
upsert_repository,
)
- from repowise.core.persistence.crud import save_coverage_files
+ from repowise.core.persistence.crud import (
+ save_coverage_files,
+ upsert_git_function_blame_bulk,
+ )
from repowise.core.persistence.models import GitMetadata, HealthFinding
from repowise.core.pipeline.persist import (
persist_graph_nodes,
save_full_health_report,
)
+ from repowise.core.pipeline.resume.rehydrate import (
+ attach_commit_set_blame,
+ attach_stored_commit_shas,
+ )
from repowise.core.workspace.update import get_head_commit
url = get_db_url_for_repo(repo_path)
@@ -1459,6 +1473,15 @@ async def _rescore_health_from_db(
for gm in git_rows
if exclude_spec is None or not exclude_spec.match_file(gm.file_path)
)
+ # No blame index here, so Split File reads the stored commit sets,
+ # and blames once the candidates stored before the sets existed.
+ await attach_stored_commit_shas(session, repo_id, git_meta_map)
+ attach_commit_set_blame(
+ repo_path,
+ git_meta_map,
+ parsed_files,
+ git_tier=load_state(Path(repo_path)).get("git_tier"),
+ )
stored_blame_findings: dict[str, list[HealthFinding]] = {}
for finding in (
await session.execute(
@@ -1508,6 +1531,9 @@ async def _rescore_health_from_db(
await save_full_health_report(
session, repo_id, report, analyzed_commit=get_head_commit(Path(repo_path))
)
+ # Rows for the files blamed above, so the next re-score reads them.
+ if report.function_blame_rows:
+ await upsert_git_function_blame_bulk(session, repo_id, report.function_blame_rows)
if coverage.authoritative:
# Stamp the live HEAD from disk, not the stored
# ``repo.head_commit`` column. The column names the last
diff --git a/packages/core/alembic/versions/0093_function_blame_commit_shas.py b/packages/core/alembic/versions/0093_function_blame_commit_shas.py
new file mode 100644
index 000000000..a5fb9d400
--- /dev/null
+++ b/packages/core/alembic/versions/0093_function_blame_commit_shas.py
@@ -0,0 +1,38 @@
+"""git_function_blame: keep each function's bounded commit set.
+
+Split File's co-change edge needs the commits behind each function, which only
+the transient blame index carried, so a re-score built a different partition
+than the full index did. Nullable with no backfill: the next full index or
+update writes it.
+
+Local SQLite stores get the column from ``init_db``'s additive reconciler; this
+migration covers managed Postgres.
+
+Revision ID: 0093
+Revises: 0092
+Create Date: 2026-10-01
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0093"
+down_revision: str | None = "0092"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "git_function_blame",
+ sa.Column("commit_shas_json", sa.Text, nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("git_function_blame", "commit_shas_json")
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index b6b5902dd..ffd65a82d 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -51,6 +51,7 @@ from .dataflow import FileDataflowCache
from .duplication import ClonePair, DuplicationReport
from .duplication.isolation import detect_clones_with_isolation as detect_clones
from .finding_identity import SYMBOL_INDEX_KEY, SYMBOL_KEY, SYMBOL_LINE_KEY
+from .function_blame_rollup import blame_commit_entries, commit_spans
from .history_refresh import BLAME_MARKERS, as_biomarker_result
from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity
from .perf import (
@@ -108,7 +109,15 @@ log = structlog.get_logger(__name__)
# Not a licence to move a calibrated scoring weight — those are frozen
# independently of this stamp.
#
-# Current stamp (v37): schema migrations are ``tooling`` in the performance
+# Current stamp (v38): Split File's co-change edge reads per-function commit
+# sets (the 50 newest distinct commits of each function, stored on
+# ``git_function_blame``), and a class takes the union of its methods' sets
+# instead of blame over its whole span. Group membership is a kernel input to
+# the ``split_file`` id, so ``REFACTORING_MODEL_VERSION`` moved 3 -> 4 with it:
+# every refactoring id now carries the ``refac4_`` prefix, and a held ``refac3_``
+# id reports ``stale_model``.
+#
+# v37: schema migrations are ``tooling`` in the performance
# ``execution_context`` (any ``migrations/`` directory, Rails ``db/migrate``,
# Alembic ``alembic/versions``). The context is stored on every performance
# opportunity and is a kernel input to its id, so ``PERFORMANCE_MODEL_VERSION``
@@ -370,7 +379,7 @@ log = structlog.get_logger(__name__)
# forms. Files that were counted untested and are not become tested, which
# moves untested-hotspot findings and the scores that carry them, on every
# language with a prefix or spec convention rather than Ruby alone.
-HEALTH_ANALYZER_VERSION = 37
+HEALTH_ANALYZER_VERSION = 38
def _mark_deprecated(
@@ -506,6 +515,15 @@ def _log_duplication_diagnostics(report: DuplicationReport) -> None:
log.debug("health_duplication_limits", **diag)
+def _commit_entries(fcx: FileComplexity, git_meta: dict) -> list:
+ """Split File's per-function commit sets: from the blame index, the stored
+ rows, or the blame a re-score took for a file stored without them."""
+ idx = git_meta.get("blame_index") or git_meta.get("commit_set_blame")
+ if isinstance(idx, BlameIndex):
+ return blame_commit_entries(fcx.functions, idx)
+ return list(git_meta.get("function_commit_shas") or ())
+
+
def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] | None:
"""Read a file's source as 1-indexed lines for the Extract Helper snippet.
@@ -1625,7 +1643,8 @@ class HealthAnalyzer:
methods_by_file.get(file_path, ()) if methods_by_file is not None else None
),
function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),
- blame_index=blame_index,
+ # Stored sets when no blame index, so a re-score matches the index.
+ commit_spans=commit_spans(fcx.functions, _commit_entries(fcx, file_git_meta)),
# The Extract Helper snippet; ``None`` unless the file carries clones.
source_lines=source_lines,
)
diff --git a/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py b/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py
index 940a0f14e..8875d2a15 100644
--- a/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py
+++ b/packages/core/src/repowise/core/analysis/health/function_blame_rollup.py
@@ -15,6 +15,8 @@ churned functions (the "no signal" convention used by the biomarkers).
from __future__ import annotations
+import json
+from collections.abc import Iterable
from typing import Any
from ...ingestion.git_indexer.function_blame import (
@@ -24,6 +26,7 @@ from ...ingestion.git_indexer.function_blame import (
median_author_time_in_range,
owner_in_range,
recent_commits_in_range,
+ recent_distinct_commits_in_range,
)
# Recent-modification window for the rollup. Broader than the 30-day window
@@ -31,6 +34,17 @@ from ...ingestion.git_indexer.function_blame import (
# general-purpose signal, so a 90-day window matches the rest of the git data.
_RECENT_WINDOW_DAYS = 90
+# Commits kept per function for Split File's co-change edge. Blame credits each
+# line to one commit, so a function's set is already bounded by its length; on
+# this repository 99.96% of modified functions have 50 or fewer, and the cap
+# keeps the persisted column small for the rest.
+COMMIT_SET_LIMIT = 50
+
+# One function's bounded commit set: ``(name, start_line, end_line, shas)``.
+CommitEntry = tuple[str, int, int, list[str]]
+# What Split File reads: ``(start_line, end_line, shas)`` per function.
+CommitSpan = tuple[int, int, frozenset[str]]
+
def build_function_blame_rows(
walked: list[tuple[Any, Any]],
@@ -51,7 +65,8 @@ def build_function_blame_rows(
for pf, fcx in walked:
path = pf.file_info.path
meta = git_meta_map.get(path) or {}
- idx = meta.get("blame_index")
+ # ``commit_set_blame``: a re-score's blame for a file stored without sets.
+ idx = meta.get("blame_index") or meta.get("commit_set_blame")
if not isinstance(idx, BlameIndex) or not idx.lines:
continue
since = (now_ts if now_ts is not None else blame_as_of(idx)) - recent_window_days * 86400
@@ -64,6 +79,7 @@ def build_function_blame_rows(
recent_mod = len(recent_commits_in_range(idx, start, end, since_unix_ts=since))
median_ts = median_author_time_in_range(idx, start, end)
owner_name, owner_email, owner_pct = owner_in_range(idx, start, end)
+ shas = recent_distinct_commits_in_range(idx, start, end, limit=COMMIT_SET_LIMIT)
rows.append(
{
"symbol_id": f"{path}::{fc.name}",
@@ -78,6 +94,44 @@ def build_function_blame_rows(
"owner_name": owner_name,
"owner_email": owner_email,
"owner_line_pct": owner_pct,
+ "commit_shas_json": json.dumps(shas),
}
)
return rows
+
+
+def blame_commit_entries(functions: Iterable[Any], idx: Any) -> list[CommitEntry]:
+ """Each modified function's bounded commit set, read off a live blame index.
+
+ The same projection ``build_function_blame_rows`` persists, so a re-score
+ reading the stored rows sees what a full index saw.
+ """
+ if not isinstance(idx, BlameIndex) or not idx.lines:
+ return []
+ entries: list[CommitEntry] = []
+ for fc in functions:
+ shas = recent_distinct_commits_in_range(
+ idx, fc.start_line, fc.end_line, limit=COMMIT_SET_LIMIT
+ )
+ if shas:
+ entries.append((fc.name, fc.start_line, fc.end_line, shas))
+ return entries
+
+
+def commit_spans(functions: Iterable[Any], entries: Iterable[CommitEntry]) -> list[CommitSpan]:
+ """The commit sets of *functions*, from live or stored *entries*.
+
+ Rows are keyed by ``path::name``, so of two same-named functions only the
+ last one is stored; the live path keeps the last one too. An entry whose
+ span no longer matches a walked function is a stale row and is dropped.
+ """
+ by_name: dict[str, CommitEntry] = {}
+ for entry in entries:
+ by_name[entry[0]] = entry
+ walked = {(fc.name, fc.start_line, fc.end_line) for fc in functions}
+ spans = [
+ (start, end, frozenset(shas))
+ for name, start, end, shas in by_name.values()
+ if shas and (name, start, end) in walked
+ ]
+ return sorted(spans, key=lambda span: (span[0], span[1]))
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py
index e785a002f..be75caf86 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py
@@ -24,7 +24,7 @@ from typing import Any
from ..rows import field
-REFACTORING_MODEL_VERSION = 3
+REFACTORING_MODEL_VERSION = 4
"""Version of the identity semantics. v1 was the fresh-UUID-per-index era.
The version is the id prefix rather than a hash input, so a stale id is
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 580f7b767..155a8ab0c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -182,14 +182,13 @@ class RefactoringContext:
# a re-parse of its own. Empty for files with no such finding -- the
# detector then yields nothing.
function_analyses: list[Any] = field(default_factory=list)
- # This file's per-line blame index (``git_indexer.function_blame.BlameIndex``,
- # typed ``Any`` to avoid importing the ingestion layer into the model). A
- # shared read-only reference the engine already materialised for the
- # function-level biomarkers; Split File projects each top-level symbol's line
- # range through it for a co-change "keep-together" edge. ``None`` (or an empty
- # index) is the documented "no signal" outcome — the detector degrades to its
+ # Each modified function's ``(start_line, end_line, commit shas)``, from the
+ # live blame index on a full index and from ``git_function_blame`` on a
+ # re-score, through the same projection so both see the same sets. Split
+ # File unions the spans inside each top-level symbol for its co-change
+ # edge. Empty is the "no signal" outcome: the detector falls back to its
# call/import signals only.
- blame_index: Any = None
+ commit_spans: list[tuple[int, int, frozenset[str]]] = field(default_factory=list)
# This file's source as 1-indexed lines (``source_lines[0]`` is line 1). The
# engine reads it only for files that carry clone pairs, so the cost stays
# proportional to clone-bearing files rather than the whole repo. The Extract
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
index 121c74581..959e0379c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
@@ -19,8 +19,8 @@ Algorithm (all signals from ``ctx.graph``):
1. direct intra-file call (A calls B) -> ``w = 3`` — they belong together;
2. co-change affinity (A and B's line ranges are touched by overlapping
commits) -> ``w = 2 x Jaccard(commits_a, commits_b)`` — "these always
- change together, keep them together". Read from the file's blame index
- at zero index cost; absent when no ``blame_index`` is threaded in.
+ change together, keep them together". Read from the per-function
+ commit sets in ``ctx.commit_spans``; absent when there are none.
3. shared local helper (A and B both call a third local symbol) ->
``w = 2`` per shared helper — cohesion without a direct A<->B edge;
4. shared external-import surface (A and B lean on the same *imported
@@ -134,6 +134,16 @@ def _is_skippable_path(path: str, language: str | None = None) -> bool:
return is_test_related_path(path, language) or _is_generated_path(path)
+def may_split(path: str, language: str | None, line_count: int, top_level_symbols: int) -> bool:
+ """A necessary condition for a plan, from what a parse knows: lets a caller
+ skip work only a candidate file needs."""
+ return (
+ not _is_skippable_path(path, language)
+ and line_count >= _MIN_FILE_NLOC
+ and top_level_symbols >= _MIN_SYMBOLS
+ )
+
+
def _line_range(data: dict) -> tuple[int, int] | None:
start = data.get("start_line")
end = data.get("end_line")
@@ -689,23 +699,21 @@ class SplitFileDetector(RefactoringDetector):
defined: dict[str, dict],
cluster_nodes: list[str],
) -> dict[str, set[str]]:
- """Project each node's ``(start_line, end_line)`` through the file's
- blame index to its set of touching commits — the raw material for the
- co-change edge. Empty (the documented "no signal" outcome) when no
- ``blame_index`` was threaded in or the index has no coverage."""
- idx = ctx.blame_index
- if idx is None or not getattr(idx, "lines", None):
- return {}
- try:
- from repowise.core.ingestion.git_indexer.function_blame import (
- distinct_commits_in_range,
- )
- except Exception:
+ """Each node's commits: the union of the function commit sets whose
+ span overlaps the node's, so a class collects its methods. The raw
+ material for the co-change edge; empty (the "no signal" outcome) when
+ the context carries no commit spans."""
+ if not ctx.commit_spans:
return {}
out: dict[str, set[str]] = {}
for nid in cluster_nodes:
span = _line_range(defined.get(nid, {}))
- commits = distinct_commits_in_range(idx, *span) if span else None
+ if span is None:
+ continue
+ commits: set[str] = set()
+ for start, end, shas in ctx.commit_spans:
+ if start <= span[1] and end >= span[0]:
+ commits |= shas
if commits:
out[nid] = commits
return out
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
index ec597a97f..27d78a2a5 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py
@@ -39,6 +39,7 @@ __all__ = [
"median_author_time_in_range",
"owner_in_range",
"recent_commits_in_range",
+ "recent_distinct_commits_in_range",
]
# Files with fewer than this many total commits have no useful signal — the
@@ -260,6 +261,24 @@ def distinct_commits_in_range(idx: BlameIndex, start_line: int, end_line: int) -
return out
+def recent_distinct_commits_in_range(
+ idx: BlameIndex, start_line: int, end_line: int, *, limit: int
+) -> list[str]:
+ """The *limit* most recent distinct shas touching the range, newest first.
+
+ Recency is the blame author time; ties break on the sha so the cut is
+ deterministic. Empty when the range has no blame coverage.
+ """
+ if not idx.lines or start_line > end_line or limit <= 0:
+ return []
+ times: dict[str, int] = {}
+ for ln in range(start_line, end_line + 1):
+ entry = idx.lines.get(ln)
+ if entry is not None:
+ times[entry[0]] = max(entry[1], times.get(entry[0], 0))
+ return sorted(times, key=lambda sha: (-times[sha], sha))[:limit]
+
+
def median_author_time_in_range(idx: BlameIndex, start_line: int, end_line: int) -> int | None:
"""Median ``author_time`` (unix seconds) over the given line range.
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 b4852d009..48fb74464 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -30,7 +30,8 @@ from ._constants import (
)
from .co_change import CoChangeWalk, compute_co_changes_and_entropy
from .enrich import compute_percentiles
-from .file_history import DECAY_REFRESH_KEYS, index_file
+from .file_history import DECAY_REFRESH_KEYS, _window_anchor, index_file
+from .function_blame import build_blame_index
from .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defects
from .records import (
GitHistoryCoverage,
@@ -1149,6 +1150,28 @@ class GitIndexer:
except Exception:
return None
+ def blame_indexes(self, file_paths: Sequence[str]) -> dict[str, Any]:
+ """Per-line ``BlameIndex`` for *file_paths*, anchored as an index run
+ anchors it. For a re-score that must recover what only an index built;
+ files the size cap or a git error skips are left out."""
+ if not file_paths:
+ return {}
+ repo = self._get_repo()
+ if repo is None:
+ return {}
+ try:
+ anchor = int(_window_anchor(self._resolve_as_of_ts(repo)).timestamp())
+ out: dict[str, Any] = {}
+ for path in file_paths:
+ idx = build_blame_index(repo, path, repo_path=self.repo_path)
+ if idx.lines:
+ idx.as_of_ts = anchor
+ out[path] = idx
+ return out
+ finally:
+ with contextlib.suppress(Exception):
+ repo.close()
+
def _thread_repo_pool(self) -> tuple[Callable[[], Any], Callable[[], None]]:
"""Return ``(get_thread_repo, close_all)`` for per-thread Repo reuse.
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 36cae9f02..71995e123 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -910,6 +910,37 @@ async def get_git_function_mod_counts(session: AsyncSession, repository_id: str)
return [int(mod_count) for (mod_count,) in result.all()]
+async def get_function_commit_shas(
+ session: AsyncSession, repository_id: str
+) -> dict[str, list[tuple[str, int, int, list[str]]]]:
+ """Each file's stored ``(name, start_line, end_line, shas)`` commit sets.
+
+ One query for the repository. Rows written before the column existed carry
+ no set and are left out.
+ """
+ result = await session.execute(
+ select(
+ GitFunctionBlame.file_path,
+ GitFunctionBlame.function_name,
+ GitFunctionBlame.start_line,
+ GitFunctionBlame.end_line,
+ GitFunctionBlame.commit_shas_json,
+ ).where(
+ GitFunctionBlame.repository_id == repository_id,
+ GitFunctionBlame.commit_shas_json.isnot(None),
+ )
+ )
+ out: dict[str, list[tuple[str, int, int, list[str]]]] = {}
+ for path, name, start, end, raw in result.all():
+ try:
+ shas = json.loads(raw)
+ except (TypeError, ValueError):
+ continue
+ if isinstance(shas, list) and shas:
+ out.setdefault(path, []).append((name, start, end, [str(s) for s in shas]))
+ return out
+
+
async def get_git_function_blame(
session: AsyncSession, repository_id: str, symbol_id: str
) -> GitFunctionBlame | None:
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 93e61fe12..986e1911e 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1044,6 +1044,10 @@ class GitFunctionBlame(Base):
owner_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
owner_line_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
+ # JSON list of the most recent distinct commits over the range, capped at
+ # ``function_blame_rollup.COMMIT_SET_LIMIT``. Split File's co-change edge
+ # reads it when a re-score has no blame index. NULL on rows written before.
+ commit_shas_json: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
diff --git a/packages/core/src/repowise/core/pipeline/resume/controller.py b/packages/core/src/repowise/core/pipeline/resume/controller.py
index 8749b39fe..969591518 100644
--- a/packages/core/src/repowise/core/pipeline/resume/controller.py
+++ b/packages/core/src/repowise/core/pipeline/resume/controller.py
@@ -30,6 +30,7 @@ from ..progress import emit_warning
from .ledger import ResumeLedger
from .phases import RESUME_PHASE_ORDER, ResumePhase
from .rehydrate import (
+ attach_stored_commit_shas,
rehydrate_dead_code_report,
rehydrate_decision_report,
rehydrate_git_meta_map,
@@ -104,6 +105,8 @@ class ResumeController:
async with get_session(self._sf) as session:
graph_builder = await rehydrate_graph_builder(session, self._repo_id, repo_path)
git_meta_map = await rehydrate_git_meta_map(session, self._repo_id)
+ # The analysis phase re-scores without a blame index.
+ await attach_stored_commit_shas(session, self._repo_id, git_meta_map)
# The index is, by definition, already persisted (we just read it).
self._index_persisted = True
return graph_builder, git_meta_map
diff --git a/packages/core/src/repowise/core/pipeline/resume/rehydrate.py b/packages/core/src/repowise/core/pipeline/resume/rehydrate.py
index 4aff3123a..1e54f0012 100644
--- a/packages/core/src/repowise/core/pipeline/resume/rehydrate.py
+++ b/packages/core/src/repowise/core/pipeline/resume/rehydrate.py
@@ -10,12 +10,14 @@ persisted (see ``phases/git.py: drop_transient_git_signals``), so a
rehydrated ``git_meta_map`` carries every durable signal but no
``blame_index``. Blame-dependent biomarkers treat its absence as "no
signal" — which is exactly the case for FAST/ESSENTIAL-tier runs that
-never computed blame in the first place.
+never computed blame in the first place. Split File's per-function commit sets
+are the exception: :func:`attach_stored_commit_shas` puts the stored ones back.
"""
from __future__ import annotations
import json
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -26,6 +28,8 @@ from ..upgrade import rehydrate_graph_builder
logger = structlog.get_logger(__name__)
__all__ = [
+ "attach_commit_set_blame",
+ "attach_stored_commit_shas",
"rehydrate_dead_code_report",
"rehydrate_decision_report",
"rehydrate_git_meta_map",
@@ -67,6 +71,85 @@ async def rehydrate_git_meta_map(session: Any, repo_id: str) -> dict[str, dict[s
return {path: _git_metadata_to_dict(row) for path, row in rows.items()}
+async def attach_stored_commit_shas(
+ session: Any, repo_id: str, git_meta_map: dict[str, dict[str, Any]]
+) -> None:
+ """Put each file's stored per-function commit sets under
+ ``"function_commit_shas"``, where a score without a blame index reads them.
+
+ Only files already in *git_meta_map* get them. Best effort: a failed read
+ leaves the map as it was.
+ """
+ from repowise.core.persistence.crud import get_function_commit_shas
+
+ try:
+ stored = await get_function_commit_shas(session, repo_id)
+ except Exception as exc:
+ logger.debug("stored_commit_shas_failed", error=str(exc))
+ return
+ for path, entries in stored.items():
+ meta = git_meta_map.get(path)
+ if meta is not None:
+ meta["function_commit_shas"] = entries
+
+
+def attach_commit_set_blame(
+ repo_path: Any,
+ git_meta_map: dict[str, dict[str, Any]],
+ parsed_files: list[Any],
+ *,
+ git_tier: str | None,
+) -> int:
+ """Blame the Split File candidates that have no stored commit sets, under
+ ``"commit_set_blame"``, so a re-score mints their plans as a full index
+ would. Returns the number of files blamed.
+
+ Rows written before the sets existed carry none, so without this the first
+ re-score after an upgrade mints ids that move again at the next index. Only
+ what an index would have blamed qualifies: a FULL-tier repo, a file with
+ enough commits to keep its blame index, and one Split File could act on.
+ Once the rows are written back the files are skipped, so the cost is paid
+ once.
+ """
+ from repowise.core.analysis.health.refactoring.split_file import may_split
+ from repowise.core.ingestion.git_indexer import GitIndexer
+ from repowise.core.ingestion.git_indexer.function_blame import _MIN_COMMITS_FOR_BLAME
+ from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+ try:
+ if git_tier and not GitIndexTier(git_tier).includes_blame:
+ return 0
+ except ValueError:
+ pass
+ paths: list[str] = []
+ for pf in parsed_files:
+ path = pf.file_info.path
+ meta = git_meta_map.get(path)
+ if (
+ meta is None
+ or "function_commit_shas" in meta
+ or (meta.get("commit_count_total") or 0) < _MIN_COMMITS_FOR_BLAME
+ ):
+ continue
+ top_level = sum(
+ 1 for s in pf.symbols if s.kind in ("class", "function") and not s.parent_name
+ )
+ try:
+ line_count = Path(pf.file_info.abs_path).read_bytes().count(b"\n") + 1
+ except OSError:
+ continue
+ if may_split(path, pf.file_info.language, line_count, top_level):
+ paths.append(path)
+ try:
+ blamed = GitIndexer(repo_path).blame_indexes(paths)
+ except Exception as exc:
+ logger.debug("commit_set_blame_failed", error=str(exc))
+ return 0
+ for path, idx in blamed.items():
+ git_meta_map[path]["commit_set_blame"] = idx
+ return len(blamed)
+
+
# ---------------------------------------------------------------------------
# Analysis reports (generation INPUT only — never re-persisted)
# ---------------------------------------------------------------------------
diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.json
index 0e2aa3d43..1dceb2177 100644
--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json
+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json
@@ -13,7 +13,7 @@
"lead_biomarker": null,
"lead_refactoring_type": "split_file",
"mechanical_steps": 0,
- "opportunity_id": "refop3_f99fabfc0113b941a05f",
+ "opportunity_id": "refop4_5a97fa33cd4c4ffc9740",
"rank_factors": {
"benefit": 1.6931,
"cost": 3.0,
@@ -23,7 +23,7 @@
},
"rank_score": 0.4233,
"recoverable_health": 0.0,
- "refactoring_model_version": 3,
+ "refactoring_model_version": 4,
"step_count": 1,
"steps": [
{
@@ -50,7 +50,7 @@
"effort_bucket": "L",
"file_path": "inventory.go",
"impact_delta": 0.0,
- "plan_id": "refac3_396717806264bd16aab8",
+ "plan_id": "refac4_396717806264bd16aab8",
"refactoring_type": "split_file",
"relocated_by": null,
"source_biomarker": "",
@@ -84,7 +84,7 @@
"lead_biomarker": "complex_method",
"lead_refactoring_type": "extract_method",
"mechanical_steps": 1,
- "opportunity_id": "refop3_6e81e602a1892b6fa13d",
+ "opportunity_id": "refop4_b09c227ff6aff8d07dda",
"rank_factors": {
"benefit": 0.256,
"cost": 1.0,
@@ -94,7 +94,7 @@
},
"rank_score": 0.256,
"recoverable_health": 0.256,
- "refactoring_model_version": 3,
+ "refactoring_model_version": 4,
"step_count": 1,
"steps": [
{
@@ -116,7 +116,7 @@
"effort_bucket": "S",
"file_path": "account.ts",
"impact_delta": 0.256,
- "plan_id": "refac3_a5f94bcfa0d5e0e24f37",
+ "plan_id": "refac4_a5f94bcfa0d5e0e24f37",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -151,7 +151,7 @@
"lead_biomarker": "complex_method",
"lead_refactoring_type": "extract_method",
"mechanical_steps": 1,
- "opportunity_id": "refop3_508583d74573db062900",
+ "opportunity_id": "refop4_b4793adb29a0d1200787",
"rank_factors": {
"benefit": 0.256,
"cost": 1.0,
@@ -161,7 +161,7 @@
},
"rank_score": 0.256,
"recoverable_health": 0.256,
- "refactoring_model_version": 3,
+ "refactoring_model_version": 4,
"step_count": 1,
"steps": [
{
@@ -183,7 +183,7 @@
"effort_bucket": "S",
"file_path": "workspace.ts",
"impact_delta": 0.256,
- "plan_id": "refac3_b21dea1501a82eec255a",
+ "plan_id": "refac4_b21dea1501a82eec255a",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -216,7 +216,7 @@
"effort_bucket": "S",
"evidence": [
{
- "plan_id": "refac3_aa609dc289a6e9572306",
+ "plan_id": "refac4_aa609dc289a6e9572306",
"refactoring_type": "extract_helper",
"source_biomarker": "dry_violation",
"summary": {
@@ -229,7 +229,7 @@
"target_symbol": "handlers.py:25-45"
},
{
- "plan_id": "refac3_8ea65569516929f43f5b",
+ "plan_id": "refac4_8ea65569516929f43f5b",
"refactoring_type": "extract_helper",
"source_biomarker": "dry_violation",
"summary": {
@@ -247,7 +247,7 @@
"lead_biomarker": "dry_violation",
"lead_refactoring_type": "extract_method",
"mechanical_steps": 3,
- "opportunity_id": "refop3_a0a4fa71a224c520f90b",
+ "opportunity_id": "refop4_2b1f7e87189e7adb819c",
"rank_factors": {
"benefit": 0.249,
"cost": 3.0,
@@ -257,7 +257,7 @@
},
"rank_score": 0.0934,
"recoverable_health": 0.249,
- "refactoring_model_version": 3,
+ "refactoring_model_version": 4,
"step_count": 3,
"steps": [
{
@@ -279,7 +279,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac3_cdc5177783ea57d763e5",
+ "plan_id": "refac4_cdc5177783ea57d763e5",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -304,7 +304,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac3_48c888afc5af0d975522",
+ "plan_id": "refac4_48c888afc5af0d975522",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -329,7 +329,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac3_4ecbf32a9c6419829a56",
+ "plan_id": "refac4_4ecbf32a9c6419829a56",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
diff --git a/tests/integration/test_split_file_path_parity.py b/tests/integration/test_split_file_path_parity.py
index 2e9967abb..d89fbd1ea 100644
--- a/tests/integration/test_split_file_path_parity.py
+++ b/tests/integration/test_split_file_path_parity.py
@@ -5,10 +5,15 @@ community label. A path that hands the analyzer no labels keys by raw file path
instead, so the same file on the same commit gets a sparser graph, a different
partition and a different plan id depending on whether ``init`` or ``update``
wrote it.
+
+The co-change signal has the same hazard: its commit sets came from a blame
+index only a full index builds, so a re-score from stored git metadata dropped
+the edges.
"""
from __future__ import annotations
+import json
import os
import sqlite3
import subprocess
@@ -21,6 +26,7 @@ from click.testing import CliRunner
from repowise.cli.helpers import release_update_lock
from repowise.cli.main import cli
from repowise.core.analysis.change_health.analyzer import RevisionHealthAnalyzer
+from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
from repowise.core.analysis.health.refactoring import split_file
_GROUPS = ("ledger", "mailer")
@@ -84,6 +90,21 @@ def _make_repo(path: Path) -> None:
_git(path, "commit", "-q", "-m", "initial")
+def _commit_group_history(path: Path, revisions: int = 5) -> None:
+ # Each revision touches one line in every function of one group, so a
+ # group's functions share their commits and the co-change edge forms.
+ big = path / "big.py"
+ for rev in range(1, revisions + 1):
+ group = _GROUPS[rev % 2]
+ lines = big.read_text(encoding="utf-8").split("\n")
+ for n, line in enumerate(lines):
+ if line.startswith(f" y = {group}_step_"):
+ lines[n] = f"{line.split(')')[0]}) + {rev}"
+ big.write_text("\n".join(lines), encoding="utf-8")
+ _git(path, "add", "big.py")
+ _git(path, "commit", "-q", "-m", f"touch {group} ({rev})")
+
+
def _invoke(runner: CliRunner, repo: Path, *args: str) -> None:
try:
result = runner.invoke(cli, [*args, str(repo)], catch_exceptions=False)
@@ -100,9 +121,7 @@ def _split_plans(repo: Path) -> list[tuple[str, str]]:
).fetchall()
-def test_split_file_graph_and_plan_match_across_init_and_update(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
+def _record_graphs(monkeypatch: pytest.MonkeyPatch) -> list[tuple[tuple[str, str, float], ...]]:
graphs: list[tuple[tuple[str, str, float], ...]] = []
original = split_file._weighted_graph
original_revision = RevisionHealthAnalyzer.analyze
@@ -125,30 +144,58 @@ def test_split_file_graph_and_plan_match_across_init_and_update(
monkeypatch.setattr(split_file, "_weighted_graph", _recording)
monkeypatch.setattr(RevisionHealthAnalyzer, "analyze", _revision)
- init_args = (
- "init",
- "--no-prose",
- "--embedder",
- "mock",
- "--no-editor-setup",
- "--no-hook",
- "--no-onboarding",
- "--no-seed",
- "--no-agents",
- "--no-codex",
- "--no-claude-md",
- "--no-cost-tracking",
- "--no-workspace",
- "-y",
- )
+ return graphs
+
+
+_INIT_ARGS = (
+ "init",
+ "--no-prose",
+ "--embedder",
+ "mock",
+ "--no-editor-setup",
+ "--no-hook",
+ "--no-onboarding",
+ "--no-seed",
+ "--no-agents",
+ "--no-codex",
+ "--no-claude-md",
+ "--no-cost-tracking",
+ "--no-workspace",
+ "-y",
+)
+
+
+def _use_store(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:
+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")
+
+
+def _init_clone(
+ runner: CliRunner, source: Path, full: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ subprocess.run(["git", "clone", "-q", str(source), str(full)], check=True)
+ _use_store(monkeypatch, full)
+ _invoke(runner, full, *_INIT_ARGS)
+
+
+def _cochange_edges(repo: Path) -> list[int]:
+ with closing(sqlite3.connect(repo / ".repowise" / "wiki.db")) as connection:
+ rows = connection.execute(
+ "SELECT evidence_json FROM refactoring_suggestions "
+ "WHERE refactoring_type = 'split_file' AND status = 'open'"
+ ).fetchall()
+ return [json.loads(raw).get("cochange_edges", 0) for (raw,) in rows]
+
+
+def test_split_file_graph_and_plan_match_across_init_and_update(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ graphs = _record_graphs(monkeypatch)
runner = CliRunner()
incremental = tmp_path / "incremental" / "repo"
_make_repo(incremental)
- monkeypatch.setenv(
- "REPOWISE_DB_URL", f"sqlite+aiosqlite:///{incremental / '.repowise' / 'wiki.db'}"
- )
- _invoke(runner, incremental, *init_args)
+ _use_store(monkeypatch, incremental)
+ _invoke(runner, incremental, *_INIT_ARGS)
with (incremental / "big.py").open("a", encoding="utf-8") as source:
source.write("\n# harmless incremental edit\n")
_git(incremental, "add", "big.py")
@@ -158,10 +205,8 @@ def test_split_file_graph_and_plan_match_across_init_and_update(
update_graphs = list(graphs)
full = tmp_path / "full" / "repo"
- subprocess.run(["git", "clone", "-q", str(incremental), str(full)], check=True)
- monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{full / '.repowise' / 'wiki.db'}")
graphs.clear()
- _invoke(runner, full, *init_args)
+ _init_clone(runner, incremental, full, monkeypatch)
full_graphs = list(graphs)
assert update_graphs, "the update never rebuilt big.py's split graph"
@@ -170,3 +215,58 @@ def test_split_file_graph_and_plan_match_across_init_and_update(
full_plans = _split_plans(full)
assert full_plans
assert _split_plans(incremental) == full_plans
+
+
[email protected]("stored_before_sets", [False, True], ids=["current", "upgraded"])
+def test_split_file_cochange_matches_across_init_and_stored_rescore(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stored_before_sets: bool
+) -> None:
+ graphs = _record_graphs(monkeypatch)
+ runner = CliRunner()
+
+ repo = tmp_path / "rescore" / "repo"
+ _make_repo(repo)
+ _commit_group_history(repo)
+ _use_store(monkeypatch, repo)
+ _invoke(runner, repo, *_INIT_ARGS)
+ if stored_before_sets:
+ # A store written before the commit sets existed: the re-score has to
+ # blame the candidate itself, or it mints ids that move again later.
+ with closing(sqlite3.connect(repo / ".repowise" / "wiki.db")) as connection:
+ connection.execute("UPDATE git_function_blame SET commit_shas_json = NULL")
+ connection.commit()
+ # An analyzer change forces the full re-score, which reads git metadata
+ # from the store and so has no blame index. big.py itself is untouched.
+ state_path = repo / ".repowise" / "state.json"
+ state = json.loads(state_path.read_text(encoding="utf-8"))
+ state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION - 1
+ state_path.write_text(json.dumps(state), encoding="utf-8")
+ (repo / "NOTES.md").write_text("notes\n", encoding="utf-8")
+ _git(repo, "add", "NOTES.md")
+ _git(repo, "commit", "-q", "-m", "notes")
+ graphs.clear()
+ _invoke(runner, repo, "update", "--no-workspace", "--no-agents")
+ rescore_graphs = list(graphs)
+
+ full = tmp_path / "full" / "repo"
+ graphs.clear()
+ _init_clone(runner, repo, full, monkeypatch)
+ full_graphs = list(graphs)
+
+ assert rescore_graphs, "the re-score never rebuilt big.py's split graph"
+ assert full_graphs
+ # The fixture's shared history must reach the graph, or this proves nothing.
+ assert all(count > 0 for count in _cochange_edges(full))
+ assert set(rescore_graphs) == set(full_graphs)
+ full_plans = _split_plans(full)
+ assert full_plans
+ assert _split_plans(repo) == full_plans
+ assert _cochange_edges(repo) == _cochange_edges(full)
+ if stored_before_sets:
+ # Written back, so the next re-score reads them instead of blaming again.
+ with closing(sqlite3.connect(repo / ".repowise" / "wiki.db")) as connection:
+ filled = connection.execute(
+ "SELECT COUNT(*) FROM git_function_blame "
+ "WHERE file_path = 'big.py' AND commit_shas_json IS NOT NULL"
+ ).fetchone()[0]
+ assert filled > 0
diff --git a/tests/unit/health/test_function_blame.py b/tests/unit/health/test_function_blame.py
index 0933e2f4c..b2cbf9e44 100644
--- a/tests/unit/health/test_function_blame.py
+++ b/tests/unit/health/test_function_blame.py
@@ -12,6 +12,7 @@ from repowise.core.ingestion.git_indexer.function_blame import (
distinct_commits_in_range,
median_author_time_in_range,
recent_commits_in_range,
+ recent_distinct_commits_in_range,
)
_PORCELAIN = (
@@ -86,6 +87,19 @@ def test_recent_commits_in_range():
}
+def test_recent_distinct_commits_in_range_keeps_the_newest():
+ idx = BlameIndex(lines=_parse_porcelain(_PORCELAIN)[0])
+ assert recent_distinct_commits_in_range(idx, 1, 4, limit=10) == ["c" * 40, "b" * 40, "a" * 40]
+ assert recent_distinct_commits_in_range(idx, 1, 4, limit=2) == ["c" * 40, "b" * 40]
+ assert recent_distinct_commits_in_range(BlameIndex(), 1, 4, limit=2) == []
+ assert recent_distinct_commits_in_range(idx, 4, 1, limit=2) == []
+
+
+def test_recent_distinct_commits_in_range_breaks_ties_on_sha():
+ idx = BlameIndex(lines={1: ("b", 5), 2: ("a", 5), 3: ("c", 1)})
+ assert recent_distinct_commits_in_range(idx, 1, 3, limit=2) == ["a", "b"]
+
+
def test_build_blame_index_skips_low_commit_count():
repo = SimpleNamespace(git=SimpleNamespace(blame=lambda *a, **kw: _PORCELAIN))
idx = build_blame_index(repo, "foo.py", commit_count_total=2)
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index 6e198958a..32cde161c 100644
--- a/tests/unit/health/test_model_version_coupling.py
+++ b/tests/unit/health/test_model_version_coupling.py
@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (
# The three stamps as they stand together. Moving either identity model means
# moving the analyzer with it, and updating this tuple in the same commit.
-_STAMPS = (37, 3, 3)
+_STAMPS = (38, 3, 4)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:
diff --git a/tests/unit/health/test_refactoring_identity_contract.py b/tests/unit/health/test_refactoring_identity_contract.py
index d08003d15..598eab3d5 100644
--- a/tests/unit/health/test_refactoring_identity_contract.py
+++ b/tests/unit/health/test_refactoring_identity_contract.py
@@ -21,8 +21,8 @@ from repowise.core.analysis.health.refactoring.identity import (
refactoring_public_id,
)
-EXTRACT_METHOD_ID = "refac3_f98f466eecc2dd332485"
-CLONE_ID = "refac3_e0d9feee45201e014bc3"
+EXTRACT_METHOD_ID = "refac4_f98f466eecc2dd332485"
+CLONE_ID = "refac4_e0d9feee45201e014bc3"
def _extract_method(**overrides):
@@ -86,7 +86,7 @@ def _clone(**overrides):
def test_the_model_version_is_pinned_and_is_carried_by_the_id_prefix() -> None:
- assert REFACTORING_MODEL_VERSION == 3
+ assert REFACTORING_MODEL_VERSION == 4
assert refactoring_public_id(_extract_method()) == EXTRACT_METHOD_ID
assert refactoring_public_id(_clone()) == CLONE_ID
assert EXTRACT_METHOD_ID.startswith(f"refac{REFACTORING_MODEL_VERSION}_")
@@ -100,6 +100,7 @@ def test_the_model_version_is_pinned_and_is_carried_by_the_id_prefix() -> None:
("refac_" + "0" * 20, "stale_model"),
("refac1_" + "0" * 20, "stale_model"),
("refac2_f98f466eecc2dd332485", "stale_model"),
+ ("refac3_f98f466eecc2dd332485", "stale_model"),
("plan_" + "0" * 20, "unrecognized"),
("", "unrecognized"),
],
diff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.py
index 5efc11bf6..ef248d5b8 100644
--- a/tests/unit/health/test_refactoring_opportunity.py
+++ b/tests/unit/health/test_refactoring_opportunity.py
@@ -321,7 +321,7 @@ def test_the_id_is_built_over_the_member_plan_ids() -> None:
assert opportunity.opportunity_id == opportunity_public_id(
[step.plan_id for step in opportunity.steps], "svc/orders.py"
)
- assert opportunity.opportunity_id.startswith("refop3_")
+ assert opportunity.opportunity_id.startswith("refop4_")
def test_the_id_survives_a_uniform_line_shift() -> None:
diff --git a/tests/unit/health/test_refactoring_split_file.py b/tests/unit/health/test_refactoring_split_file.py
index 73fe0e4b8..ee4a14757 100644
--- a/tests/unit/health/test_refactoring_split_file.py
+++ b/tests/unit/health/test_refactoring_split_file.py
@@ -10,8 +10,14 @@ partition — are explicit.
from __future__ import annotations
+from types import SimpleNamespace
+
import networkx as nx
+from repowise.core.analysis.health.function_blame_rollup import (
+ blame_commit_entries,
+ commit_spans,
+)
from repowise.core.analysis.health.refactoring import (
RefactoringContext,
detect_refactorings,
@@ -73,12 +79,19 @@ def _ctx(
blame_index: BlameIndex | None = None,
community_label_map: dict[str, str] | None = None,
) -> RefactoringContext:
+ # The file's symbols stand in for the walker's functions, and the spans go
+ # through the projection the engine uses on a full index.
+ functions = [
+ SimpleNamespace(name=d["name"], start_line=d["start_line"], end_line=d["end_line"])
+ for _n, d in g.nodes(data=True)
+ if d.get("file_path") == file_path and d.get("start_line") is not None
+ ]
return RefactoringContext(
file_path=file_path,
language=language,
nloc=nloc,
graph=g,
- blame_index=blame_index,
+ commit_spans=commit_spans(functions, blame_commit_entries(functions, blame_index)),
community_label_map=community_label_map or {},
)
@@ -410,6 +423,61 @@ def test_signals_are_deterministic():
assert first[0].evidence == second[0].evidence
+def test_cochange_unions_a_classes_methods():
+ # Each class collects the commit sets of the methods inside its span, so
+ # the co-change edge sees the class even though no row is keyed by it.
+ g = nx.DiGraph()
+ for i in range(8):
+ _add_class(g, "big.py", f"Cls{i}", start=10 * i + 1, end=10 * i + 10)
+ functions = [
+ SimpleNamespace(name=f"m{i}", start_line=10 * i + 2, end_line=10 * i + 5) for i in range(8)
+ ]
+ ctx = RefactoringContext(
+ file_path="big.py",
+ language="python",
+ nloc=600,
+ graph=g,
+ commit_spans=commit_spans(
+ functions,
+ [(f"m{i}", 10 * i + 2, 10 * i + 5, ["ca" if i < 4 else "cb"]) for i in range(8)],
+ ),
+ )
+ detector = SplitFileDetector()
+ nodes = [f"big.py::Cls{i}" for i in range(8)]
+ sets = detector._commit_sets(ctx, detector._defined_symbols(g, "big.py"), nodes)
+ assert sets["big.py::Cls0"] == {"ca"}
+ assert sets["big.py::Cls7"] == {"cb"}
+
+
+def test_stored_commit_sets_split_like_the_blame_index():
+ # A re-score reads the stored rows instead of a blame index; the plan must
+ # be the one the full index produced.
+ g = _disconnected_blocks()
+ blame = _blame_index(
+ [(10 * i + 1, 10 * i + 10, "ca" if i < 4 else "cb") for i in range(8)]
+ )
+ live = _detect(g, "big.py", blame_index=blame)
+ stored = [
+ s
+ for s in detect_refactorings(
+ RefactoringContext(
+ file_path="big.py",
+ language="python",
+ nloc=600,
+ graph=g,
+ commit_spans=[
+ (10 * i + 1, 10 * i + 10, frozenset({"ca" if i < 4 else "cb"}))
+ for i in range(8)
+ ],
+ )
+ )
+ if s.refactoring_type == "split_file"
+ ]
+ assert live and stored
+ assert stored[0].plan == live[0].plan
+ assert stored[0].evidence == live[0].evidence
+
+
def test_empty_blame_index_is_silent():
# An empty index (the documented "no signal" outcome) must not raise and
# must not invent co-change edges.
diff --git a/tests/unit/persistence/test_function_blame_commit_shas_migration.py b/tests/unit/persistence/test_function_blame_commit_shas_migration.py
new file mode 100644
index 000000000..9eb7387b6
--- /dev/null
+++ b/tests/unit/persistence/test_function_blame_commit_shas_migration.py
@@ -0,0 +1,54 @@
+"""Migration 0093: the per-function commit set column on git_function_blame."""
+
+from __future__ import annotations
+
+import asyncio
+import sqlite3
+from pathlib import Path
+
+
+def _columns(db_path: Path) -> set[str]:
+ conn = sqlite3.connect(db_path)
+ try:
+ return {row[1] for row in conn.execute('PRAGMA table_info("git_function_blame")')}
+ finally:
+ conn.close()
+
+
+def _alembic_config(db_path: Path):
+ from alembic.config import Config
+
+ root = Path(__file__).resolve().parents[3] / "packages" / "core"
+ config = Config()
+ config.set_main_option("script_location", str(root / "alembic"))
+ config.set_main_option("sqlalchemy.url", f"sqlite+aiosqlite:///{db_path}")
+ return config
+
+
+def test_the_migration_adds_and_drops_the_column(tmp_path: Path) -> None:
+ from alembic import command
+
+ db_path = tmp_path / "wiki.db"
+ config = _alembic_config(db_path)
+ command.upgrade(config, "0093")
+ assert "commit_shas_json" in _columns(db_path)
+ command.downgrade(config, "0092")
+ assert "commit_shas_json" not in _columns(db_path)
+
+
+def test_the_migration_and_the_model_agree(tmp_path: Path) -> None:
+ from alembic import command
+
+ from repowise.core.persistence.database import create_engine, init_db
+
+ migrated = tmp_path / "migrated.db"
+ command.upgrade(_alembic_config(migrated), "head")
+ declared = tmp_path / "declared.db"
+
+ async def _build() -> None:
+ engine = create_engine(f"sqlite+aiosqlite:///{declared}")
+ await init_db(engine)
+ await engine.dispose()
+
+ asyncio.run(_build())
+ assert _columns(migrated) == _columns(declared)
diff --git a/tests/unit/persistence/test_git_function_blame_crud.py b/tests/unit/persistence/test_git_function_blame_crud.py
index 8226ed8fb..35d70c9ff 100644
--- a/tests/unit/persistence/test_git_function_blame_crud.py
+++ b/tests/unit/persistence/test_git_function_blame_crud.py
@@ -7,6 +7,7 @@ import pytest
from repowise.core.persistence.crud import (
count_git_function_blame,
delete_git_function_blame,
+ get_function_commit_shas,
get_git_function_blame,
get_git_function_blames,
get_git_function_mod_counts,
@@ -118,3 +119,24 @@ async def test_get_git_function_mod_counts_excludes_zero(async_session) -> None:
# loader that computes the repo-wide p80 from these must not let a zero
# row into the distribution (matches the in-memory computation).
assert sorted(counts) == [1, 4, 4, 5]
+
+
+async def test_function_commit_shas_by_file(async_session) -> None:
+ repo = await insert_repo(async_session)
+ await upsert_git_function_blame_bulk(
+ async_session,
+ repo.id,
+ [
+ _row("a.py::foo", mods=2, commit_shas_json='["s2", "s1"]'),
+ _row("b.py::bar", mods=1, commit_shas_json='["s3"]', start_line=4, end_line=8),
+ # Written before the column existed: no set, so not a co-change source.
+ _row("c.py::old", mods=3),
+ ],
+ )
+ await async_session.commit()
+
+ assert await get_function_commit_shas(async_session, repo.id) == {
+ "a.py": [("foo", 1, 10, ["s2", "s1"])],
+ "b.py": [("bar", 4, 8, ["s3"])],
+ }
diff --git a/tests/unit/persistence/test_refactoring_lifecycle.py b/tests/unit/persistence/test_refactoring_lifecycle.py
index 14ba4c9d0..dcfe064c0 100644
--- a/tests/unit/persistence/test_refactoring_lifecycle.py
+++ b/tests/unit/persistence/test_refactoring_lifecycle.py
@@ -69,7 +69,7 @@ async def test_an_unchanged_plan_keeps_its_row_and_its_public_id(async_session):
assert len(before) == 2
assert after == before, "a second analysis of unchanged source must not mint new rows"
- assert all(key.startswith("refac3_") for key in after)
+ assert all(key.startswith("refac4_") for key in after)
@pytest.mark.asyncio
diff --git a/tests/unit/pipeline/test_commit_set_blame.py b/tests/unit/pipeline/test_commit_set_blame.py
new file mode 100644
index 000000000..c0a7aef58
--- /dev/null
+++ b/tests/unit/pipeline/test_commit_set_blame.py
@@ -0,0 +1,61 @@
+"""A re-score blames only the Split File candidates stored without commit sets."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.function_blame import BlameIndex
+from repowise.core.pipeline.resume.rehydrate import attach_commit_set_blame
+
+
+def _parsed(tmp_path: Path, path: str, *, lines: int, symbols: int):
+ abs_path = tmp_path / path
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_text("x = 1\n" * lines, encoding="utf-8")
+ return SimpleNamespace(
+ file_info=SimpleNamespace(path=path, abs_path=str(abs_path), language="python"),
+ symbols=[SimpleNamespace(kind="function", parent_name=None) for _ in range(symbols)],
+ )
+
+
+def blamed(monkeypatch: pytest.MonkeyPatch) -> list[list[str]]:
+ calls: list[list[str]] = []
+
+ def _blame(self: GitIndexer, paths):
+ calls.append(list(paths))
+ return {p: BlameIndex(lines={1: ("a", 1)}) for p in paths}
+
+ monkeypatch.setattr(GitIndexer, "blame_indexes", _blame)
+ return calls
+
+
+def test_only_candidates_without_stored_sets_are_blamed(tmp_path: Path, blamed) -> None:
+ parsed = [
+ _parsed(tmp_path, "big.py", lines=400, symbols=10),
+ _parsed(tmp_path, "stored.py", lines=400, symbols=10),
+ _parsed(tmp_path, "small.py", lines=100, symbols=10),
+ _parsed(tmp_path, "few.py", lines=400, symbols=3),
+ _parsed(tmp_path, "young.py", lines=400, symbols=10),
+ _parsed(tmp_path, "tests/test_big.py", lines=400, symbols=10),
+ ]
+ meta = {pf.file_info.path: {"commit_count_total": 9} for pf in parsed}
+ meta["stored.py"]["function_commit_shas"] = [("f", 1, 2, ["a"])]
+ meta["young.py"]["commit_count_total"] = 2
+
+ assert attach_commit_set_blame(tmp_path, meta, parsed, git_tier="full") == 1
+ assert blamed == [["big.py"]]
+ assert isinstance(meta["big.py"]["commit_set_blame"], BlameIndex)
+ assert "commit_set_blame" not in meta["stored.py"]
+
+
+def test_a_tier_without_blame_blames_nothing(tmp_path: Path, blamed) -> None:
+ parsed = [_parsed(tmp_path, "big.py", lines=400, symbols=10)]
+ meta = {"big.py": {"commit_count_total": 9}}
+ assert attach_commit_set_blame(tmp_path, meta, parsed, git_tier="essential") == 0
+ assert blamed == []
+ assert "commit_set_blame" not in meta["big.py"]
diff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.py
index b055abb68..6b57b839a 100644
--- a/tests/unit/server/mcp/test_performance_levels.py
+++ b/tests/unit/server/mcp/test_performance_levels.py
@@ -268,7 +268,7 @@ async def test_one_id_returns_the_cause_its_plan_and_its_rank_rationale(
assert result["intervention_symbol"] == "src/shared.py::load"
assert result["plan_status"] == "available"
# The plan address space is the refactoring layer's content identity.
- assert result["plan_reference"].startswith("refac3_")
+ assert result["plan_reference"].startswith("refac4_")
assert result["confidence"] == "high"
assert result["fix"]["safety"] == "advisory"
assert [step["order"] for step in result["plan_steps"]] == [1, 2, 3, 4, 5]
@@ -399,7 +399,7 @@ async def test_the_lead_links_the_exact_plan_for_the_exact_lead(setup_mcp, mater
page = await get_health(include=["performance"], only=["performance_opportunities"], limit=1)
lead = page["performance_opportunities"][0]
- assert lead["plan_reference"].startswith("refac3_")
+ assert lead["plan_reference"].startswith("refac4_")
plan = await get_health(plan_id=lead["plan_reference"])
assert plan["resolved"] is True
diff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.py
index 7c35d34d0..4bd29b889 100644
--- a/tests/unit/server/mcp/test_refactoring.py
+++ b/tests/unit/server/mcp/test_refactoring.py
@@ -107,7 +107,7 @@ async def test_generate_code_disabled(factory, _mcp_globals) -> None:
result = await generate_refactoring_code(sid)
assert result["resolved"] is True
# The content-derived plan identity, versioned by its prefix.
- assert result["suggestion_id"].startswith("refac3_")
+ assert result["suggestion_id"].startswith("refac4_")
assert result["generation"]["available"] is False
assert result["generation"]["reason"] == "disabled"
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 1252b463c..2168cc24e 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -694,7 +694,7 @@ async def test_plan_status_round_trips_and_hides_the_row(client: AsyncClient, ap
assert body["status"] == "acknowledged"
assert body["status_reason"] == "user"
assert body["status_changed_at"] is not None
- assert body["public_id"].startswith("refac3_")
+ assert body["public_id"].startswith("refac4_")
resp = await client.patch(
f"/api/repos/{repo_id}/refactoring/{target['id']}/status",
diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.py
index c81038a90..b858b1a29 100644
--- a/tests/unit/server/test_refactoring_opportunities.py
+++ b/tests/unit/server/test_refactoring_opportunities.py
@@ -128,7 +128,7 @@ async def test_finalizer_composes_one_opportunity_per_file(client, app):
assert body["total"] == 5
assert len({item["file_path"] for item in body["items"]}) == 5
for item in body["items"]:
- assert item["opportunity_id"].startswith("refop3_")
+ assert item["opportunity_id"].startswith("refop4_")
assert item["step_count"] == 1
# The lead was supplied, so this is a real answer rather than unknown.
assert item["addresses_primary_problem"] is True
@@ -472,7 +472,7 @@ async def test_bare_get_health_leads_with_fix_first_and_links_the_opportunity(cl
lead = result["fix_first"]["lead"]
assert lead["kind"] == "refactor"
opportunity_id = lead["next_call"]["arguments"]["opportunity_id"]
- assert opportunity_id.startswith("refop3_")
+ assert opportunity_id.startswith("refop4_")
# Level 0 is a lead, not a queue: it must stay small enough to survive.
assert len(str(result["fix_first"])) < 6000
@@ -607,7 +607,7 @@ async def test_a_plan_id_resolves_to_the_opportunity_that_owns_it(client, app):
async def test_an_unknown_opportunity_id_says_which_kind_of_unknown(client, app):
await _seed(client, app, files=2)
get_health = await _mcp(app)
- missing = await get_health(opportunity_id="refop3_" + "0" * 20)
+ missing = await get_health(opportunity_id="refop4_" + "0" * 20)
assert missing["found"] is False
assert missing["model_state"]["state"] == "current"
stale = await get_health(opportunity_id="refop1_" + "0" * 20)
diff --git a/tests/unit/test_function_blame_rollup.py b/tests/unit/test_function_blame_rollup.py
index 3536975ac..dd2f2f34e 100644
--- a/tests/unit/test_function_blame_rollup.py
+++ b/tests/unit/test_function_blame_rollup.py
@@ -2,9 +2,14 @@
from __future__ import annotations
+import json
from dataclasses import dataclass
-from repowise.core.analysis.health.function_blame_rollup import build_function_blame_rows
+from repowise.core.analysis.health.function_blame_rollup import (
+ blame_commit_entries,
+ build_function_blame_rows,
+ commit_spans,
+)
from repowise.core.ingestion.git_indexer.function_blame import BlameIndex
@@ -97,3 +102,36 @@ def test_rollup_empty_when_no_blame() -> None:
)
== []
)
+
+
+def test_rollup_persists_the_commit_set_newest_first() -> None:
+ walked, meta = _walked_and_meta()
+ rows = {r["function_name"]: r for r in build_function_blame_rows(walked, meta, now_ts=_NOW)}
+ assert json.loads(rows["foo"]["commit_shas_json"]) == ["s2", "s1"]
+ assert json.loads(rows["bar"]["commit_shas_json"]) == ["s3"]
+
+
+def test_stored_rows_give_the_same_spans_as_the_blame_index() -> None:
+ walked, meta = _walked_and_meta()
+ functions = walked[0][1].functions
+ live = commit_spans(functions, blame_commit_entries(functions, meta["a.py"]["blame_index"]))
+ stored = [
+ (r["function_name"], r["start_line"], r["end_line"], json.loads(r["commit_shas_json"]))
+ for r in build_function_blame_rows(walked, meta, now_ts=_NOW)
+ ]
+ assert live == commit_spans(functions, stored)
+ assert live == [(1, 3, frozenset({"s1", "s2"})), (5, 6, frozenset({"s3"}))]
+
+
+def test_commit_spans_keep_the_last_same_named_function_like_the_store() -> None:
+ # Rows are keyed path::name, so the store holds only the last __init__.
+ functions = [_Fn("__init__", 1, 3), _Fn("__init__", 10, 12)]
+ entries = [("__init__", 1, 3, ["a"]), ("__init__", 10, 12, ["b"])]
+ assert commit_spans(functions, entries) == [(10, 12, frozenset({"b"}))]
+
+
+def test_commit_spans_drop_stale_rows() -> None:
+ # A stored row whose function moved or vanished no longer describes the file.
+ functions = [_Fn("foo", 5, 9)]
+ entries = [("foo", 1, 3, ["a"]), ("gone", 20, 30, ["b"])]
+ assert commit_spans(functions, entries) == []