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(decisions): fill last_code_change from the dates staleness already reads (#2357)

Raghav Chamadiyadd2a317dbdcf
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 873c7f7ec..b9da3a873 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -1269,6 +1269,26 @@ class DecisionExtractor:
return round(changed / len(affected_files), 3)
+ @staticmethod
+ def last_code_change(
+ affected_files: list[str],
+ git_meta_map: dict[str, dict],
+ ) -> datetime | None:
+ """When the code a decision governs last moved, or None.
+
+ Reduces the same inputs :meth:`compute_staleness` reads: that counts
+ how many files moved since the record was born, this reports when the
+ most recent of them moved. None where the question cannot be answered,
+ meaning no scope or no git metadata for anything the record names.
+ """
+ dates: list[datetime] = []
+ for file_path in affected_files:
+ meta = git_meta_map.get(file_path)
+ last_commit = meta.get("last_commit_at") if meta else None
+ if last_commit:
+ dates.append(_as_aware_utc(_coerce_dt(last_commit)))
+ return max(dates) if dates else None
+
# ------------------------------------------------------------------
# Main entry point
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 5b8a5f85f..d970b86d9 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -1536,7 +1536,9 @@ async def recompute_decision_staleness(
) -> int:
"""Recompute staleness_score for all active decisions. Returns update count.
- Also re-derives ``affected_modules_json`` from the files each record names.
+ Also fills ``last_code_change`` from the same per-file dates the score is
+ counted from, and re-derives ``affected_modules_json`` from the files each
+ record names.
The two belong in one pass because they are one repair: a record's module
linkage used to be the first path segment, which in a ``packages/`` layout
made almost every record claim ``packages`` or ``tests``, and the rows that
@@ -1573,17 +1575,36 @@ async def recompute_decision_staleness(
now = _now_utc()
updated = 0
+ dated = 0
+ # Function-local, like every other analysis import here: the persistence
+ # layer cannot depend on analysis at module scope.
+ from repowise.core.analysis.decisions.extractor import (
+ DecisionExtractor,
+ _as_aware_utc,
+ )
+
for dec in decisions:
affected = affected_by_id.get(dec.id)
if not affected:
continue
+
+ # Before the conventions skip below: a date is a fact about the code,
+ # not a score, so it is filled for every scoped record.
+ last_change = DecisionExtractor.last_code_change(affected, git_meta_map)
+ stored = dec.last_code_change
+ # SQLite drops tzinfo, so an aware value would differ from the naive
+ # one it just wrote and rewrite ``updated_at`` on every run.
+ if last_change != (_as_aware_utc(stored) if stored else None):
+ dec.last_code_change = last_change
+ dec.updated_at = now
+ dated += 1
+
# The source writes its own conformance share, and a git-diff score
- # would overwrite it. The module backfill above still applies.
+ # would overwrite it. Only the score is skipped; the repairs above
+ # still apply.
if dec.source == "conventions":
continue
- from repowise.core.analysis.decision_extractor import DecisionExtractor
-
new_score = DecisionExtractor.compute_staleness(
dec.created_at,
affected,
@@ -1594,11 +1615,11 @@ async def recompute_decision_staleness(
dec.updated_at = now
updated += 1
- if updated or modules_updated:
+ if updated or modules_updated or dated:
await session.flush()
# Deliberately the staleness count alone. The callers print this as
- # "N decisions rescored"; folding a silent module repair into it would
- # report a rescore that did not happen.
+ # "N decisions rescored"; folding the module repair or the date fill into
+ # it would report a rescore that did not happen.
return updated
diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsx
index 639edd5f4..87fa87ac5 100644
--- a/packages/ui/__tests__/decisions/decision-detail.test.tsx
+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx
@@ -149,6 +149,26 @@ describe("DecisionDetail", () => {
expect(screen.queryByText(/Invalid Date/i)).not.toBeInTheDocument();
});
+ it("says when the governed code last moved, once the field is populated", () => {
+ // The line is guarded on the field, which no writer filled until the
+ // staleness pass began deriving it, so it had never rendered.
+ renderView(
+ <DecisionDetail
+ decision={makeDecision({ last_code_change: "2026-03-04T05:06:07Z" })}
+ adapter={makeAdapter()}
+ />,
+ );
+
+ expect(screen.getByText(/Affected files last changed/)).toBeInTheDocument();
+ expect(screen.queryByText(/Invalid Date/i)).not.toBeInTheDocument();
+ });
+
+ it("says nothing about the governed code when the date is unknown", () => {
+ renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);
+
+ expect(screen.queryByText(/Affected files last changed/)).not.toBeInTheDocument();
+ });
+
it("reports what moved as a count, not as a proportion", () => {
// Was "Staleness 42%" in a meta ribbon. A proportion has no reading at a
// glance; the count it is a proportion of does.
diff --git a/tests/unit/persistence/test_decision_staleness_recompute.py b/tests/unit/persistence/test_decision_staleness_recompute.py
index 5dc68f72b..ecb3b72a6 100644
--- a/tests/unit/persistence/test_decision_staleness_recompute.py
+++ b/tests/unit/persistence/test_decision_staleness_recompute.py
@@ -26,6 +26,11 @@ from repowise.core.persistence.models import (
_REPO_ID = "repo1"
+def _aware(value: datetime) -> datetime:
+ """SQLite hands back naive datetimes for a tz-aware column."""
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
@pytest.fixture
async def session():
engine = create_async_engine(
@@ -171,3 +176,65 @@ async def test_a_record_naming_no_file_keeps_its_scope_rather_than_inventing_one
rec = await session.get(DecisionRecord, "d1")
assert json.loads(rec.affected_modules_json) == ["packages"]
+
+
+# --- last_code_change rides the same pass ----------------------------------
+
+
+async def test_the_date_is_the_latest_commit_across_the_files_it_governs(session):
+ await _add_decision(session, files=["src/a.py", "src/b.py"], staleness=0.0)
+ await _add_git_metadata(session, "src/a.py", days_ago=60, commits=1)
+ await _add_git_metadata(session, "src/b.py", days_ago=5, commits=1)
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+
+ rec = await session.get(DecisionRecord, "d1")
+ expected = datetime.now(UTC) - timedelta(days=5)
+ assert rec.last_code_change is not None
+ assert abs(_aware(rec.last_code_change) - expected) < timedelta(minutes=1)
+
+
+async def test_a_record_naming_nothing_tracked_keeps_no_date(session):
+ """It scores 1.00 stale on the same evidence, so a date would be invented."""
+ await _add_decision(session, files=["src/untracked.py"], staleness=0.0)
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert rec.last_code_change is None
+ assert rec.staleness_score == pytest.approx(1.0)
+
+
+async def test_the_date_does_not_churn_updated_at_on_a_second_pass(session):
+ """SQLite drops tzinfo, so a naive round trip would differ from the aware
+ value that wrote it and re-stamp every record on every run."""
+ await _add_decision(session, files=["src/a.py"], staleness=0.0)
+ await _add_git_metadata(session, "src/a.py", days_ago=60, commits=1)
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+ rec = await session.get(DecisionRecord, "d1")
+ first_date, first_stamp = rec.last_code_change, rec.updated_at
+
+ # Force the round trip the guard exists for: the second pass has to read
+ # the naive value back out of SQLite, not the aware one still in memory.
+ session.expire_all()
+ await recompute_decision_staleness(session, _REPO_ID, {})
+ await session.refresh(rec)
+
+ assert rec.last_code_change == first_date
+ assert rec.updated_at == first_stamp
+
+
+async def test_a_conventions_record_still_gets_a_date(session):
+ """The conventions skip protects its own staleness, which is a score. A
+ date is a fact about the code and is filled for every scoped record."""
+ rec = await _add_decision(session, files=["src/a.py"], staleness=0.42)
+ rec.source = "conventions"
+ await session.flush()
+ await _add_git_metadata(session, "src/a.py", days_ago=3, commits=1)
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+ await session.refresh(rec)
+
+ assert rec.last_code_change is not None
+ assert rec.staleness_score == pytest.approx(0.42), "its own score is untouched"