Skip to content

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

fix(git): measure history windows from the indexed commit, not the wall clock (#2568)

Raghav Chamadiya11a9e896798c
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 845c44174..72fe2fe3d 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -364,7 +364,7 @@ file in the trailing ~6-month window, read from `prior_defect_count`. The
git indexer classifies a commit as a fix with the **same keyword rule the
defect benchmark labels fixes with** (`_constants.is_fix_commit`), counts only
non-merge commits inside the window, and anchors the window to the index's
-`as_of` reference (`REPOWISE_GIT_WINDOW_ANCHOR`): so scoring a historical T0
+`as_of` reference (the indexed commit's committer date): so scoring a historical T0
checkout measures the fixes *before* T0, never leaking the post-T0 fixes that
form the benchmark's labels. It carries a **neutral (1.0) weight by design**:
on the calibration corpus prior-defect history is largely redundant with the
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 1ce14e019..ebfa2ffc5 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -988,7 +988,7 @@ Anonymous usage telemetry is **enabled by default** (opt-out).
| Variable | Description |
|----------|-------------|
-| `REPOWISE_GIT_WINDOW_ANCHOR` | Set to `head` to anchor git "now" to the latest commit instead of wall-clock time |
+| `REPOWISE_GIT_WINDOW_ANCHOR` | Git history windows (90-day churn, prior defects, decay, blame age) are measured from the indexed commit's committer date by default. Set to `now` to measure them from wall-clock time instead |
| `REPOWISE_SKIP_EDITOR_SETUP` | Truthy value stops `init` writing to your machine-wide editor config: the Claude Code / Claude Desktop MCP entry, the Claude Code hooks, and the distill rewrite-hook offer. Same switch as `init --no-editor-setup` ([CLI_REFERENCE.md](CLI_REFERENCE.md#repowise-init-path)); the env var is the one to use for CI, sandboxes, and benchmark runs that index many repos. Project-local files (`.repowise/mcp.json`, `CLAUDE.md`, Codex config) are written either way |
| `REPOWISE_CHANGELOG` | Override the changelog source used by the "what's new" check |
| `REPOWISE_PARSE_WORKERS` | How many processes parse files during indexing. Defaults to your CPU count capped at 8, and never exceeds the number of files to parse. Each worker is a separate interpreter holding roughly 50 MB, so lower it on a memory-constrained machine; raising it above 8 is not measurably faster |
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 ddb58ca93..4b81cfd73 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1613,8 +1613,8 @@ def _run_full_health_rescore(
# decay refresh runs every update, but the health *findings* for idle files only
# recover when the analyzer re-scores them. Those biomarkers have a ~125-180d
# half-life, so weekly is ample. The interval is anchored to the repo's
-# newest-commit timestamp (not wall clock) so it stays deterministic under
-# REPOWISE_GIT_WINDOW_ANCHOR / historical checkouts; override for tests.
+# HEAD commit timestamp (not wall clock), like the git history windows, so it
+# stays deterministic on historical checkouts; override for tests.
_FULL_RESCORE_INTERVAL_DAYS = 7.0
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 55bd28ddc..dcb07a25f 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -630,8 +630,8 @@ def head_commit_ts(repo_path: Path) -> float | None:
"""Committer timestamp of the repo's HEAD, or None when git is unavailable.
Anchors the periodic idle-file health re-score gate (#728) to repo time
- rather than wall clock, so the cadence is deterministic under
- ``REPOWISE_GIT_WINDOW_ANCHOR`` and correct for historical checkouts.
+ rather than wall clock, the same anchor the git history windows use, so
+ the cadence is deterministic and correct for historical checkouts.
Shared with ``init`` so a fresh index can stamp ``last_full_rescore_at`` in
the same units the gate reads it back in.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
index 95b5ac58c..e92c34afc 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
@@ -14,6 +14,9 @@ by the FULL git tier:
* ``recent_mod_count`` — distinct shas touching the range whose
``author_time`` falls inside the last 30 days.
+"now" is the index's anchor (the indexed commit), not wall-clock time, so
+the marker reads the same at the benchmark's T0 as in the product.
+
Tier-aware: when ``ctx.blame_index`` is ``None`` (ESSENTIAL git tier),
or empty, the detector emits zero findings. Function-level no-op is the
documented "no signal" outcome until the FULL-tier backfill
@@ -29,9 +32,8 @@ Severity (calibrated against the 1-year / 2-year age boundaries):
from __future__ import annotations
-import time
-
from ....ingestion.git_indexer.function_blame import (
+ blame_as_of,
median_author_time_in_range,
recent_commits_in_range,
)
@@ -62,7 +64,7 @@ class CodeAgeVolatilityDetector:
if idx is None or not idx.lines:
return []
- now = int(time.time())
+ now = blame_as_of(idx)
since = now - _RECENT_WINDOW_SECS
findings: list[BiomarkerResult] = []
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index c42e46211..6ebee40b3 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -19,7 +19,6 @@ from __future__ import annotations
import asyncio
import os
-import time
from datetime import UTC, datetime
from typing import Any
@@ -112,6 +111,12 @@ log = structlog.get_logger(__name__)
# and a declining call's arguments are not scanned, so an assertion passed as an
# argument still does not stand in for the header's oracle.
#
+# v33: git history windows are measured from the indexed commit's committer
+# date instead of wall-clock time, by default. ``code_age_volatility`` and the
+# per-function blame rollup read line ages from the same anchor, so a store
+# scored against wall-clock time holds different windowed findings for any repo
+# whose last commit is not today.
+#
# v32: the history (organizational) cap follows the file's structure half,
# ``history_cap(structure)`` in scoring.py, so every stored score that carries
# a history deduction, and the refactoring impact figures, move.
@@ -307,7 +312,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 = 32
+HEALTH_ANALYZER_VERSION = 33
def walked_functions(
@@ -1173,9 +1178,7 @@ class HealthAnalyzer:
try:
from .function_blame_rollup import build_function_blame_rows
- return build_function_blame_rows(
- list(walked), self.git_meta_map, now_ts=int(time.time())
- )
+ return build_function_blame_rows(list(walked), self.git_meta_map)
except Exception as exc:
log.debug("function_blame_rollup_failed", error=str(exc))
return []
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 9213e27d2..940a0f14e 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
@@ -19,6 +19,7 @@ from typing import Any
from ...ingestion.git_indexer.function_blame import (
BlameIndex,
+ blame_as_of,
distinct_commits_in_range,
median_author_time_in_range,
owner_in_range,
@@ -35,7 +36,7 @@ def build_function_blame_rows(
walked: list[tuple[Any, Any]],
git_meta_map: dict[str, dict],
*,
- now_ts: int,
+ now_ts: int | None = None,
recent_window_days: int = _RECENT_WINDOW_DAYS,
) -> list[dict]:
"""Build ``git_function_blame`` row dicts from walked files + blame indexes.
@@ -43,9 +44,8 @@ def build_function_blame_rows(
*walked* is the engine's ``[(parsed_file, FileComplexity)]`` list; each
file's blame index is looked up in *git_meta_map* under ``"blame_index"``
(the FULL-tier git tier attaches it there). *now_ts* anchors the recent
- window (unix seconds) — pass the index-time clock.
+ window (unix seconds); ``None`` uses each blame index's own anchor.
"""
- since = now_ts - recent_window_days * 86400
rows: list[dict] = []
for pf, fcx in walked:
@@ -54,6 +54,7 @@ def build_function_blame_rows(
idx = meta.get("blame_index")
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
for fc in fcx.functions:
start, end = fc.start_line, fc.end_line
mod_count = len(distinct_commits_in_range(idx, start, end))
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
index 881f777c8..0dac4dcb1 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
@@ -26,14 +26,15 @@ layers consume:
Every recency window (90d/30d, age, temporal decay, co-change/entropy decay, the
prior-defect window) is measured relative to a single reference "now":
-- **default (env unset)** → wall-clock `now()`, so "churned lately" means
- relative to today — the live-product meaning.
-- **`REPOWISE_GIT_WINDOW_ANCHOR=head`** → the repo's most-recent commit
- timestamp. This makes indexing **deterministic** (re-indexing the same commit
- yields identical windows) and **correct for historical checkouts**: scoring a
- worktree detached at an old commit then measures the window *before that
- commit*, not an empty window in its future. Used by the defect benchmark to
- score repos at a past T0 without leaking future history into the signals.
+- **default** → the committer date of the indexed commit (HEAD). Indexing is
+ **deterministic** (re-indexing the same commit later yields identical windows)
+ and **correct for historical checkouts**: scoring a worktree detached at an
+ old commit measures the window *before that commit*, not an empty window in
+ its future. This is the anchor the defect benchmark calibrates on, and the
+ blame-based markers (`code_age_volatility`, the per-function blame rollup)
+ read line ages from it too.
+- **`REPOWISE_GIT_WINDOW_ANCHOR=now`** → wall-clock `now()`, so "churned
+ lately" means relative to today even when the checkout has not moved.
`REPOWISE_SKIP_EDITOR_SETUP=1` is the companion guard that lets `init` index a
transient worktree without touching the developer's global editor config.
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 412a34d04..7469229e6 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
@@ -475,6 +475,7 @@ def index_file(
repo_path=repo_path,
)
if blame_idx.lines:
+ blame_idx.as_of_ts = int(now.timestamp())
if meta["commit_count_total"] >= _MIN_COMMITS_FOR_BLAME:
meta["blame_index"] = blame_idx
blame_name, blame_email, blame_pct = ownership_from_blame(blame_idx)
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 e0589eaad..ec597a97f 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
@@ -20,6 +20,7 @@ engine can pick it up when building each ``FileContext``.
from __future__ import annotations
+import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -32,6 +33,7 @@ logger = structlog.get_logger(__name__)
__all__ = [
"BlameIndex",
+ "blame_as_of",
"build_blame_index",
"distinct_commits_in_range",
"median_author_time_in_range",
@@ -59,6 +61,14 @@ class BlameIndex:
lines: dict[int, tuple[str, int]] = field(default_factory=dict)
authors: dict[str, tuple[str, str]] = field(default_factory=dict)
+ # The indexer's history anchor (unix seconds), so line ages are measured
+ # from the indexed commit like every other git window.
+ as_of_ts: int | None = None
+
+
+def blame_as_of(idx: BlameIndex) -> int:
+ """Reference 'now' for *idx*: its anchor, or wall clock when built without one."""
+ return idx.as_of_ts if idx.as_of_ts is not None else int(time.time())
def ownership_from_blame(idx: BlameIndex) -> tuple[str | None, str | None, float | None]:
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 eda01013e..9aa506832 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -51,6 +51,10 @@ __all__ = ["GitIndexer", "git_worker_count"]
# 200 leaves generous headroom while keeping the subprocess count low.
_OFFSET_LOOKUP_CHUNK = 200
+# ``REPOWISE_GIT_WINDOW_ANCHOR`` values that measure windows from wall-clock
+# time instead of the indexed commit. Unset, or any other value, anchors to HEAD.
+_WALL_CLOCK_ANCHORS = frozenset({"now", "0", "false", "no", "off"})
+
_GIT_WORKERS_ENV = "REPOWISE_GIT_WORKERS"
_MAX_GIT_WORKERS = 8
_GIT_WORKER_MEMORY_BYTES = 384 * 1024 * 1024
@@ -268,7 +272,7 @@ class GitIndexer:
fallback_note_agents = load_git_ai_note_agents(repo, None)
include_blame = self.tier.includes_blame
- as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ as_of_ts = self._resolve_as_of_ts(repo)
executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="git-idx")
semaphore = asyncio.Semaphore(workers)
get_thread_repo, close_thread_repos = self._thread_repo_pool()
@@ -606,7 +610,7 @@ class GitIndexer:
from ..git_commit_index import load_git_ai_note_agents
fallback_note_agents = load_git_ai_note_agents(repo, None)
- as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ as_of_ts = self._resolve_as_of_ts(repo)
executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="git-idx")
semaphore = asyncio.Semaphore(workers)
get_thread_repo, close_thread_repos = self._thread_repo_pool()
@@ -1077,33 +1081,22 @@ class GitIndexer:
return AgentTraceIndex()
- def _resolve_as_of_ts(
- self, repo: Any, commit_index: dict[str, list[_CommitRec]] | None = None
- ) -> float | None:
- """Optional reference 'now' for recency windows (90d/30d, age, decay).
-
- Default (env unset) returns ``None`` → callers anchor to wall-clock
- ``now()``, preserving the live-product meaning of "churned lately /
- is_stable" as *relative to today*.
-
- When ``REPOWISE_GIT_WINDOW_ANCHOR`` is truthy (e.g. ``head``), anchor
- instead to the repo's most recent commit timestamp. This makes indexing
- deterministic and correct for **historical checkouts**: scoring a
- worktree at an old commit then measures the 90 days before *that* commit
- rather than an empty window in its future. Used by the defect benchmark,
- which scores repos at a past T0 — without it every windowed process
- signal (churn, entropy, co-change, congestion) is silently zero."""
+ def _resolve_as_of_ts(self, repo: Any) -> float | None:
+ """Reference 'now' for every history window (90d/30d, age, decay, blame).
+
+ The committer date of the indexed commit (HEAD), so the same tree scores
+ the same whenever it is indexed, and a historical checkout measures the
+ window before *that* commit. This is the anchor the defect benchmark
+ calibrates on. Full index, update, idle refresh and fix events all
+ resolve it here, so they agree whenever HEAD does.
+
+ ``REPOWISE_GIT_WINDOW_ANCHOR=now`` opts back into wall-clock time and
+ returns ``None``, which every consumer reads as ``now()``. So does a
+ repo whose HEAD cannot be read."""
anchor = os.environ.get("REPOWISE_GIT_WINDOW_ANCHOR", "").strip().lower()
- if anchor in ("", "0", "false", "no", "now"):
+ if anchor in _WALL_CLOCK_ANCHORS:
return None
try:
- if commit_index:
- ts = max(
- (c.ts for recs in commit_index.values() for c in recs if c.ts > 0),
- default=0.0,
- )
- if ts > 0:
- return float(ts)
return float(repo.head.commit.committed_date)
except Exception:
return None
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 032de3cb9..140557071 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
@@ -203,8 +203,8 @@ def compute_prior_defects(
) -> 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
+ *as_of_ts* anchors the window's end (the indexed commit's committer date;
+ ``None`` means 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.
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index aec791c70..f0ba67ea0 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 = (32, 2, 2)
+_STAMPS = (33, 2, 2)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:
diff --git a/tests/unit/ingestion/test_git_window_anchor.py b/tests/unit/ingestion/test_git_window_anchor.py
new file mode 100644
index 000000000..b3687a04a
--- /dev/null
+++ b/tests/unit/ingestion/test_git_window_anchor.py
@@ -0,0 +1,186 @@
+"""Git history windows are measured from the indexed commit, not the wall clock.
+
+The same tree indexed on two different days must produce the same git metadata
+and the same blame-based health findings. The clock is stubbed so the test
+proves the product never reads it, and a wall-clock control proves the stub
+actually bites.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.code_age_volatility import (
+ CodeAgeVolatilityDetector,
+)
+from repowise.core.analysis.health.complexity import FunctionComplexity
+from repowise.core.analysis.health.function_blame_rollup import build_function_blame_rows
+from repowise.core.ingestion.git_indexer import GitIndexer, file_history, prior_defects
+from repowise.core.ingestion.git_indexer.file_history import DECAY_REFRESH_KEYS
+from repowise.core.ingestion.git_indexer.function_blame import BlameIndex
+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+# Two "todays": one just after the last commit, one years later.
+_NOW_A = datetime(2024, 3, 20, tzinfo=UTC).timestamp()
+_NOW_B = datetime(2026, 9, 1, tzinfo=UTC).timestamp()
+_HEAD_DATE = "2024-03-15T00:00:00"
+
+
+def _stub_clock(monkeypatch: pytest.MonkeyPatch, now: float) -> None:
+ class _Frozen(datetime):
+ @classmethod
+ def now(cls, tz=None): # type: ignore[override]
+ return datetime.fromtimestamp(now, tz=tz)
+
+ monkeypatch.setattr(time, "time", lambda: now)
+ monkeypatch.setattr(file_history, "datetime", _Frozen)
+ monkeypatch.setattr(prior_defects, "datetime", _Frozen)
+
+
+def _build_repo(root) -> None:
+ import git as gitpython
+
+ repo = gitpython.Repo.init(root)
+ with repo.config_writer() as cw:
+ cw.set_value("user", "name", "Alice")
+ cw.set_value("user", "email", "[email protected]")
+
+ def commit(files: dict[str, str], msg: str, date: str) -> None:
+ for name, content in files.items():
+ (root / name).write_text(content)
+ repo.index.add(list(files))
+ repo.index.commit(msg, author_date=date, commit_date=date)
+
+ body = "".join(f"def f{i}(x):\n return x + {i}\n\n" for i in range(6))
+ commit({"a.py": body, "b.py": "y = 0\n"}, "feat: add modules", "2021-01-01T00:00:00")
+ for i in range(5):
+ text = body.replace(f"x + {i}", f"x * {i + 10}")
+ date = f"2024-0{1 + i % 3}-0{i + 1}T00:00:00"
+ commit({"a.py": text, "b.py": f"y = {i}\n"}, f"fix: bug {i} in f{i}", date)
+ commit({"b.py": "y = 99\n"}, "feat: tune b", _HEAD_DATE)
+ repo.close()
+
+
+async def _index(root, monkeypatch, now: float) -> dict[str, dict]:
+ _stub_clock(monkeypatch, now)
+ _summary, rows = await GitIndexer(root, tier=GitIndexTier.FULL).index_repo("r")
+ return {row["file_path"]: row for row in rows}
+
+
+def _comparable(row: dict) -> dict:
+ return {k: v for k, v in row.items() if k != "blame_index"}
+
+
+def _health(meta: dict) -> tuple[list, list]:
+ idx = meta["a.py"]["blame_index"]
+ fns = tuple(
+ FunctionComplexity(
+ name=f"f{i}",
+ start_line=3 * i + 1,
+ end_line=3 * i + 2,
+ ccn=1,
+ max_nesting=0,
+ cognitive=0,
+ nloc=2,
+ )
+ for i in range(6)
+ )
+ ctx = FileContext(
+ file_path="a.py",
+ language="python",
+ nloc=18,
+ has_test_file=False,
+ module=None,
+ all_functions=fns,
+ blame_index=idx,
+ )
+ findings = [(f.function_name, f.details) for f in CodeAgeVolatilityDetector().detect(ctx)]
+
+ class _Pf:
+ class file_info: # noqa: N801
+ path = "a.py"
+
+ walked = [(_Pf, type("Fcx", (), {"functions": list(fns)})())]
+ rows = build_function_blame_rows(walked, meta)
+ return findings, rows
+
+
+async def test_same_commit_two_clocks_same_metadata_and_health(tmp_path, monkeypatch) -> None:
+ monkeypatch.delenv("REPOWISE_GIT_WINDOW_ANCHOR", raising=False)
+ _build_repo(tmp_path)
+
+ first = await _index(tmp_path, monkeypatch, _NOW_A)
+ health_a = _health(first)
+ second = await _index(tmp_path, monkeypatch, _NOW_B)
+ health_b = _health(second)
+
+ assert {k: _comparable(v) for k, v in first.items()} == {
+ k: _comparable(v) for k, v in second.items()
+ }
+ assert health_a == health_b
+ # The windows are live: HEAD's trailing 90 days hold the 2024 commits.
+ assert first["a.py"]["commit_count_90d"] == 5
+ assert first["a.py"]["prior_defect_count"] > 0
+ head_ts = int(datetime.fromisoformat(_HEAD_DATE).replace(tzinfo=UTC).timestamp())
+ assert first["a.py"]["blame_index"].as_of_ts == head_ts
+ assert json.loads(first["a.py"]["co_change_partners_json"])
+
+
+async def test_wall_clock_opt_in_still_reads_the_clock(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "now")
+ _build_repo(tmp_path)
+
+ first = await _index(tmp_path, monkeypatch, _NOW_A)
+ second = await _index(tmp_path, monkeypatch, _NOW_B)
+
+ assert first["a.py"]["commit_count_90d"] == 5
+ assert second["a.py"]["commit_count_90d"] == 0
+ assert first["a.py"]["prior_defect_count"] > second["a.py"]["prior_defect_count"]
+
+
+async def test_update_uses_the_same_anchor_as_a_full_index(tmp_path, monkeypatch) -> None:
+ monkeypatch.delenv("REPOWISE_GIT_WINDOW_ANCHOR", raising=False)
+ _build_repo(tmp_path)
+ full = await _index(tmp_path, monkeypatch, _NOW_A)
+
+ _stub_clock(monkeypatch, _NOW_B)
+ sink: dict[str, dict] = {}
+ changed = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_changed_files(
+ ["b.py"], all_files={"a.py", "b.py"}, idle_decay_sink=sink
+ )
+
+ changed_b = {row["file_path"]: row for row in changed}["b.py"]
+ for key in (*DECAY_REFRESH_KEYS, "age_days"):
+ assert changed_b[key] == full["b.py"][key], key
+ for key, value in sink["a.py"].items():
+ assert value == full["a.py"][key], key
+
+
+def test_code_age_volatility_measures_from_the_blame_anchor(monkeypatch) -> None:
+ day = 86400
+ anchor = int(_NOW_A)
+ lines = {ln: (f"a{ln:039d}", anchor - 800 * day) for ln in range(1, 8)}
+ lines.update({ln: (f"b{ln:039d}", anchor - 3 * day) for ln in range(8, 11)})
+ fc = FunctionComplexity(
+ name="legacy", start_line=1, end_line=10, ccn=1, max_nesting=0, cognitive=0, nloc=10
+ )
+ ctx = FileContext(
+ file_path="a.py",
+ language="python",
+ nloc=10,
+ has_test_file=False,
+ module=None,
+ all_functions=(fc,),
+ blame_index=BlameIndex(lines=lines, as_of_ts=anchor),
+ )
+
+ monkeypatch.setattr(time, "time", lambda: _NOW_B)
+ findings = CodeAgeVolatilityDetector().detect(ctx)
+
+ assert len(findings) == 1
+ assert findings[0].details == {"median_age_days": 800, "recent_mod_count": 3}
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index 6495c86f6..cff4384ce 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -405,6 +405,8 @@ class TestStableClassification:
f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f{_iso(ts)}\x1f\x1ffeat: old commit {i}\x1f"
)
mock_repo.git.log.return_value = "\n".join(log_lines)
+ # HEAD moved on today in another file; this one sat idle.
+ mock_repo.head.commit.committed_date = int(datetime.now(UTC).timestamp())
meta = indexer._index_file("stable_file.py", mock_repo)
@@ -448,9 +450,8 @@ class TestStableClassification:
class TestGitWindowAnchor:
- """REPOWISE_GIT_WINDOW_ANCHOR anchors recency windows to the repo's most
- recent commit instead of wall-clock now() — default off (product unchanged),
- on for historical T0 scoring so windowed signals aren't silently empty."""
+ """Recency windows are anchored to the indexed commit by default;
+ REPOWISE_GIT_WINDOW_ANCHOR=now opts back into wall-clock time."""
def _mock_repo_with_old_commits(self) -> tuple[MagicMock, datetime]:
mock_repo = MagicMock()
@@ -466,16 +467,20 @@ class TestGitWindowAnchor:
mock_repo.head.commit.committed_date = int(old_date.timestamp())
return mock_repo, old_date
- def test_default_uses_wall_clock(self, monkeypatch) -> None:
- monkeypatch.delenv("REPOWISE_GIT_WINDOW_ANCHOR", raising=False)
+ def test_wall_clock_opt_in(self, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "now")
indexer = GitIndexer("/tmp/repo")
mock_repo, _ = self._mock_repo_with_old_commits()
meta = indexer._index_file("f.py", mock_repo)
# 180-day-old commits are outside a now()-anchored 90d window.
assert meta["commit_count_90d"] == 0
- def test_anchor_to_head_commit(self, monkeypatch) -> None:
- monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", "head")
+ @pytest.mark.parametrize("value", [None, "head"])
+ def test_anchor_to_head_commit(self, monkeypatch, value) -> None:
+ if value is None:
+ monkeypatch.delenv("REPOWISE_GIT_WINDOW_ANCHOR", raising=False)
+ else:
+ monkeypatch.setenv("REPOWISE_GIT_WINDOW_ANCHOR", value)
indexer = GitIndexer("/tmp/repo")
mock_repo, _ = self._mock_repo_with_old_commits()
meta = indexer._index_file("f.py", mock_repo)