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(decisions): measure staleness from the commit that landed a decision (#4357)

Raghav Chamadiyada35e82fc77d
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 33c259b94..275134867 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -109,10 +109,12 @@ on every read. `superseded` and `dismissed` are set by a person.
- Staleness score: each record carries `staleness_score` between 0 and 1, the
fraction of its governed files committed to since the decision was recorded.
- A file the repository does not track counts as changed. At 0.5 or above a
- record is stale for `decision list --stale-only`, the health summary and the
- `needs_review` currency. A record that names no file scores 0.0 and is
- counted separately as unscoped. `repowise decision show` and `get_why` on a
+ A record written before its evidence commits landed counts from the commit
+ that landed them: the commit itself on the main line, or the one squash that
+ names it and changes its files. A file the repository does not track counts
+ as changed. At 0.5 or above a record is stale for `decision list --stale-only`,
+ the health summary and the `needs_review` currency. A record that names no
+ file scores 0.0 and is counted separately as unscoped. `repowise decision show` and `get_why` on a
path also ask git directly for one record and print what changed.
- Sticky review: a dismissed candidate is kept as a tombstone, so re-indexing
never proposes it again. A later extraction never walks an accepted decision
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 661959a2c..ceb7597b4 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -686,6 +686,7 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:
repo_path,
created_at=rec.created_at,
nodes=json.loads(rec.affected_files_json or "[]"),
+ evidence_commits=json.loads(rec.evidence_commits_json or "[]"),
)
if fmt == "json":
emit_json({"query": decision_id, "decision": _decision_json(rec, signed, currency)})
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/full_persist.py b/packages/cli/src/repowise/cli/commands/update_cmd/full_persist.py
index a9c44bad7..7416eab0e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/full_persist.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/full_persist.py
@@ -198,7 +198,7 @@ async def upsert_decisions(ctx: FullUpdatePersist) -> None:
provider=ctx.provider,
)
if ctx.git_meta_map:
- await recompute_decision_staleness(session, repo_id, ctx.git_meta_map)
+ await recompute_decision_staleness(session, repo_id, ctx.git_meta_map, ctx.repo_path)
DECISION_STEPS: tuple[Step, ...] = (
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
index 6900ab6c7..4824894d4 100644
--- a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
+++ b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
@@ -305,9 +305,11 @@ def stale_decision(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
tier="plan",
horizons=("quarter",),
severity="medium",
- title=f"Update the decision “{d.title}”: the code it governs has moved on",
- impact="Agents and reviewers still follow it, so they are steered by a rule the code no longer keeps.",
- why=(WhyFact("status", "Accepted, drifting"),),
+ # The evidence is commits to its files, not a broken rule, so the
+ # row asks for a review and claims nothing more.
+ title=f"Review the decision “{d.title}”: the files it governs changed since it was recorded",
+ impact="Agents and reviewers still follow it, and nobody has checked it against those changes.",
+ why=(WhyFact("status", "Accepted, its files changed since"),),
target_kind="decision",
target_path=d.id,
surface="decisions",
@@ -316,7 +318,7 @@ def stale_decision(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
done_when="The decision is re-accepted, amended or superseded.",
commands=(
ActionCommand.call(
- "The decision, the code it governs, and how it drifted",
+ "The decision, the files it governs, and what changed",
"get_why",
{"id": d.id},
cli="repowise decision health",
diff --git a/packages/core/src/repowise/core/analysis/decisions/landing.py b/packages/core/src/repowise/core/analysis/decisions/landing.py
new file mode 100644
index 000000000..c02a849ef
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/landing.py
@@ -0,0 +1,184 @@
+"""Where a decision's own evidence commits reached the main line.
+
+A decision recorded on a branch names that branch's commits, and the squash
+that lands them comes later. Staleness counts only commits after the landing,
+so the commit that carried the decision is not read as drift from it.
+
+A commit on HEAD's first-parent line landed as itself. A branch commit landed
+in the one first-parent commit after it that names it: its subject, less a
+trailing ``(#N)``, is the commit's subject (a squash titled after it), or its
+body lists ``* <subject>`` (the squash body GitHub writes), and it changes a
+file the commit changed, so a generic subject cannot match an unrelated change
+by name alone. Anything else,
+including a commit merged by a merge commit or a name two commits share, is
+left unresolved and its record keeps its creation time as the anchor, so an
+unresolved commit only ever leaves a record as stale as it was.
+"""
+
+from __future__ import annotations
+
+import re
+import subprocess
+from collections.abc import Iterable
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+
+import structlog
+
+from repowise.core.analysis.git_cli import run_git
+
+logger = structlog.get_logger(__name__)
+
+_SHA = re.compile(r"[0-9a-f]{7,40}")
+_FIELD = "\x1f"
+_RECORD = "\x1e"
+# Files follow the last field, from ``--name-only``.
+_FORMAT = f"--format={_RECORD}%H{_FIELD}%ct{_FIELD}%s{_FIELD}%b{_FIELD}"
+
+
+@dataclass(frozen=True)
+class Landing:
+ """The first-parent commit that carried an evidence commit, and its commit time."""
+
+ sha: str
+ at: datetime
+
+
+@dataclass(frozen=True)
+class _Commit:
+ at: datetime
+ subject: str
+ body: str
+ files: frozenset[str]
+
+
+def evidence_landings(
+ repo_path: Path | str, evidence: Iterable[str], *, timeout: float | None = None
+) -> dict[str, Landing]:
+ """Each stored evidence sha that can be placed on the main line, mapped to its landing.
+
+ Three git calls for the whole set, each bounded by *timeout* when given.
+ Values that are not shas (session ids) and commits git does not hold are
+ skipped; a git failure gives ``{}``.
+ """
+ keys = {e.strip().lower() for e in evidence if isinstance(e, str)}
+ wanted = sorted(k for k in keys if _SHA.fullmatch(k))
+ if not wanted:
+ return {}
+ try:
+ own = _commits(repo_path, wanted, timeout)
+ line = _first_parent(repo_path, min(c.at for c in own.values()), timeout) if own else {}
+ except (OSError, subprocess.SubprocessError):
+ logger.debug("decision_landing_unreadable", exc_info=True)
+ return {}
+ names = _names(line)
+ out: dict[str, Landing] = {}
+ for stored, full in _expand(wanted, own).items():
+ landing = _landing(full, own[full], line, names)
+ if landing is not None:
+ out[stored] = landing
+ return out
+
+
+def record_landing(
+ evidence_commits: Iterable[str], landings: dict[str, Landing], born: datetime | None
+) -> Landing | None:
+ """The latest landing among a record's evidence commits, when it is after *born*."""
+ from .staleness import _as_aware_utc
+
+ keys = (e.strip().lower() for e in evidence_commits if isinstance(e, str))
+ found = [landings[k] for k in keys if k in landings]
+ if not found or born is None:
+ return None
+ latest = max(found, key=lambda landing: landing.at)
+ return latest if latest.at > _as_aware_utc(born) else None
+
+
+def _names(line: dict[str, _Commit]) -> dict[str, set[str]]:
+ """Branch-commit subject -> the first-parent commits that name it."""
+ from .reverts import _strip_pr_suffix
+
+ names: dict[str, set[str]] = {}
+ for sha, commit in line.items():
+ names.setdefault(_strip_pr_suffix(commit.subject), set()).add(sha)
+ for row in commit.body.splitlines():
+ if row.startswith("* "):
+ names.setdefault(row[2:].strip(), set()).add(sha)
+ return names
+
+
+def _landing(
+ full: str, own: _Commit, line: dict[str, _Commit], names: dict[str, set[str]]
+) -> Landing | None:
+ if full in line:
+ return Landing(full, line[full].at)
+ later = [
+ s
+ for s in names.get(own.subject.strip(), ())
+ if line[s].at >= own.at and line[s].files & own.files
+ ]
+ # Two candidates means the name does not identify the squash.
+ if len(later) != 1:
+ return None
+ return Landing(later[0], line[later[0]].at)
+
+
+def _expand(wanted: list[str], own: dict[str, _Commit]) -> dict[str, str]:
+ """Stored (possibly short) sha -> the one full sha it names among *own*."""
+ out: dict[str, str] = {}
+ for stored in wanted:
+ matches = [full for full in own if full.startswith(stored)]
+ if len(matches) == 1:
+ out[stored] = matches[0]
+ return out
+
+
+def _commits(
+ repo_path: Path | str, wanted: list[str], timeout: float | None
+) -> dict[str, _Commit]:
+ """Each sha git holds as a commit; missing and ambiguous ones drop."""
+ check = run_git(
+ ["cat-file", "--batch-check=%(objectname) %(objecttype)"],
+ repo_path,
+ input="\n".join(wanted) + "\n",
+ **_bound(timeout),
+ )
+ full = [
+ parts[0]
+ for parts in (row.split() for row in check.stdout.splitlines())
+ if len(parts) == 2 and parts[1] == "commit"
+ ]
+ if not full:
+ return {}
+ shown = run_git(
+ ["log", "--no-walk=unsorted", "--name-only", _FORMAT, *full], repo_path, **_bound(timeout)
+ )
+ return _parse(shown.stdout) if shown.returncode == 0 else {}
+
+
+def _first_parent(
+ repo_path: Path | str, since: datetime, timeout: float | None
+) -> dict[str, _Commit]:
+ shown = run_git(
+ ["log", "--first-parent", "--name-only", f"--since={since.isoformat()}", _FORMAT, "HEAD"],
+ repo_path,
+ **_bound(timeout),
+ )
+ return _parse(shown.stdout) if shown.returncode == 0 else {}
+
+
+def _bound(timeout: float | None) -> dict:
+ """``run_git``'s own ceiling unless the caller bought a tighter one."""
+ return {} if timeout is None else {"timeout": timeout}
+
+
+def _parse(stdout: str) -> dict[str, _Commit]:
+ out: dict[str, _Commit] = {}
+ for record in stdout.split(_RECORD):
+ parts = record.split(_FIELD, 4)
+ if len(parts) == 5 and parts[1].isdigit():
+ at = datetime.fromtimestamp(int(parts[1]), tz=UTC)
+ files = frozenset(f.strip() for f in parts[4].splitlines() if f.strip())
+ out[parts[0].strip()] = _Commit(at, parts[2].strip(), parts[3], files)
+ return out
diff --git a/packages/core/src/repowise/core/analysis/decisions/staleness.py b/packages/core/src/repowise/core/analysis/decisions/staleness.py
index b8c35e207..095779371 100644
--- a/packages/core/src/repowise/core/analysis/decisions/staleness.py
+++ b/packages/core/src/repowise/core/analysis/decisions/staleness.py
@@ -33,6 +33,7 @@ def compute_staleness(
affected_files: list[str],
git_meta_map: dict[str, dict],
decision_text: str = "",
+ landed_at: datetime | None = None,
) -> float:
"""Fraction of *affected_files* that have changed since the record's birth.
@@ -41,6 +42,11 @@ def compute_staleness(
constants and no reading of commit messages. *decision_text* is
accepted and unused so existing call sites keep working.
+ *landed_at* is when the record's own evidence commits reached the main
+ line (see :mod:`.landing`). A record written on a branch is born before
+ the squash that carries it, so the birth is the later of the two: the
+ landing commit is the decision, not a change to it.
+
A file with no git metadata **after** the caller's gap fill counts as
changed: the record names something the repository does not track, so
it cannot be shown to still hold.
@@ -51,7 +57,7 @@ def compute_staleness(
# `decision health` reports it as unscoped rather than fresh.
return 0.0
- created = _as_aware_utc(_coerce_dt(decision_created_at)) if decision_created_at else None
+ created = _anchor(decision_created_at, landed_at)
changed = 0
for fp in affected_files:
meta = git_meta_map.get(fp)
@@ -67,6 +73,14 @@ def compute_staleness(
return round(changed / len(affected_files), 3)
+def _anchor(created_at: datetime | str | None, landed_at: datetime | None) -> datetime | None:
+ """The later of a record's birth and its landing, or None with no birth."""
+ if not created_at:
+ return None
+ created = _as_aware_utc(_coerce_dt(created_at))
+ return max(created, _as_aware_utc(landed_at)) if landed_at is not None else created
+
+
def last_code_change(
affected_files: list[str],
git_meta_map: dict[str, dict],
diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
index 5438d46eb..3afefdf65 100644
--- a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
+++ b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py
@@ -147,7 +147,7 @@ class AnalysisIndexStore(ABC):
@abstractmethod
async def recompute_decision_staleness(
- self, repository_id: str, git_meta_map: dict[str, dict]
+ self, repository_id: str, git_meta_map: dict[str, dict], repo_path: str | None = None
) -> int: ...
@abstractmethod
diff --git a/packages/core/src/repowise/core/persistence/crud/decision_staleness.py b/packages/core/src/repowise/core/persistence/crud/decision_staleness.py
index fb6938052..5174e3483 100644
--- a/packages/core/src/repowise/core/persistence/crud/decision_staleness.py
+++ b/packages/core/src/repowise/core/persistence/crud/decision_staleness.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
from datetime import datetime
+from pathlib import Path
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -57,9 +58,13 @@ async def recompute_decision_staleness(
session: AsyncSession,
repository_id: str,
git_meta_map: dict[str, dict],
+ repo_path: Path | str | None = None,
) -> int:
"""Recompute staleness_score for all active decisions. Returns update count.
+ With *repo_path*, each record is scored from when its own evidence commits
+ landed, when that is after its birth; without it, from its birth alone.
+
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.
@@ -103,6 +108,7 @@ async def recompute_decision_staleness(
{fp for paths in affected_by_id.values() for fp in paths},
)
+ landings = _evidence_landings(repo_path, decisions, affected_by_id)
now = _now_utc()
updated = 0
dated = 0
@@ -122,7 +128,7 @@ async def recompute_decision_staleness(
if dec.source == "conventions":
continue
- if _rescore_staleness(dec, affected, git_meta_map, now):
+ if _rescore_staleness(dec, affected, git_meta_map, now, landings):
updated += 1
if updated or modules_updated or dated:
@@ -152,16 +158,46 @@ def _refresh_last_code_change(
return True
+def _evidence_landings(
+ repo_path: Path | str | None,
+ decisions: list[DecisionRecord],
+ affected_by_id: dict[str, list[str]],
+) -> dict:
+ """Landings of every scoped record's evidence commits, in one git read."""
+ if repo_path is None:
+ return {}
+ from repowise.core.analysis.decisions.landing import evidence_landings
+
+ return evidence_landings(
+ repo_path,
+ (
+ sha
+ for dec in decisions
+ if dec.id in affected_by_id
+ for sha in json.loads(dec.evidence_commits_json or "[]")
+ ),
+ )
+
+
def _rescore_staleness(
- dec: DecisionRecord, affected: list[str], git_meta_map: dict[str, dict], now: datetime
+ dec: DecisionRecord,
+ affected: list[str],
+ git_meta_map: dict[str, dict],
+ now: datetime,
+ landings: dict,
) -> bool:
"""Recompute the git-diff staleness score; True when it moved by more than 0.01."""
from repowise.core.analysis.decisions.extractor import DecisionExtractor
+ from repowise.core.analysis.decisions.landing import record_landing
+ landing = record_landing(
+ json.loads(dec.evidence_commits_json or "[]"), landings, dec.created_at
+ )
new_score = DecisionExtractor.compute_staleness(
dec.created_at,
affected,
git_meta_map,
+ landed_at=landing.at if landing else None,
)
if abs(new_score - dec.staleness_score) > 0.01:
dec.staleness_score = round(new_score, 3)
diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
index 7a52eb6c7..35adbdfdf 100644
--- a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
+++ b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py
@@ -169,10 +169,10 @@ class _SqlAnalysisMixin(AnalysisIndexStore):
return await crud.delete_decision(self._session, decision_id)
async def recompute_decision_staleness(
- self, repository_id: str, git_meta_map: dict[str, dict]
+ self, repository_id: str, git_meta_map: dict[str, dict], repo_path: str | None = None
) -> int:
return await crud.recompute_decision_staleness(
- self._session, repository_id, git_meta_map
+ self._session, repository_id, git_meta_map, repo_path
)
async def get_stale_decisions(
diff --git a/packages/core/src/repowise/core/pipeline/persist/analysis.py b/packages/core/src/repowise/core/pipeline/persist/analysis.py
index 6a48c32f7..0684a3aea 100644
--- a/packages/core/src/repowise/core/pipeline/persist/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/persist/analysis.py
@@ -111,6 +111,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
decision_dicts,
vector_store=vector_store,
git_metadata=result.git_metadata_list,
+ repo_path=getattr(result, "repo_path", None),
)
await apply_decision_lifecycle(session, repo_id, getattr(result, "repo_path", None))
diff --git a/packages/core/src/repowise/core/pipeline/persist/decisions.py b/packages/core/src/repowise/core/pipeline/persist/decisions.py
index f3b69ea83..32ab41c60 100644
--- a/packages/core/src/repowise/core/pipeline/persist/decisions.py
+++ b/packages/core/src/repowise/core/pipeline/persist/decisions.py
@@ -132,13 +132,15 @@ async def store_decisions(
vector_store: Any = None,
git_metadata: Iterable[Any] | None = None,
provider: Any = None,
+ repo_path: Any = None,
) -> list[str]:
"""Upsert ``decisions``, then detect supersession and rescore staleness.
Returns the ids the upsert touched. A failing upsert propagates; the two
passes after it are best-effort. ``git_metadata`` holds per-file git rows
(dicts or dataclasses) for the staleness rescore; ``provider`` enables
- the LLM tiebreaker in supersession detection.
+ the LLM tiebreaker in supersession detection; ``repo_path`` lets the
+ rescore start from when each record's evidence commits landed.
"""
from repowise.core.persistence.crud import (
bulk_upsert_decisions,
@@ -186,7 +188,9 @@ async def store_decisions(
if fp:
git_meta_map[fp] = gm_dict
if git_meta_map:
- updated = await recompute_decision_staleness(session, repo_id, git_meta_map)
+ updated = await recompute_decision_staleness(
+ session, repo_id, git_meta_map, repo_path
+ )
if updated:
logger.info("decision_staleness_recomputed", updated=updated)
except Exception as _stale_err:
diff --git a/packages/core/src/repowise/core/precedent/currency.py b/packages/core/src/repowise/core/precedent/currency.py
index 0f5463b76..2e6baceaf 100644
--- a/packages/core/src/repowise/core/precedent/currency.py
+++ b/packages/core/src/repowise/core/precedent/currency.py
@@ -6,7 +6,8 @@ judgement, and it is the only read-time computation this layer sanctions.
Two shapes of claim ask it. An **episode** is born at a commit, so it asks
``<sha>..HEAD``. A **decision record** has no birth commit column — it has a
-``created_at`` — so it asks ``--since=<date>``. Same call, same failure
+``created_at`` — so it asks ``--since=<date>``, or ``<sha>..HEAD`` from the
+commit that landed it when that came later. Same call, same failure
handling, one implementation; the alternative was a second copy that would
drift from this one the first time either grew a flag.
@@ -134,6 +135,7 @@ def describe_decision_currency(
*,
created_at: datetime | None,
nodes: Sequence[str],
+ evidence_commits: Sequence[str] = (),
) -> str | None:
"""One sentence on whether a decision's code has moved since it was made.
@@ -146,6 +148,10 @@ def describe_decision_currency(
whose code genuinely has not moved. Saying so is the difference between
"checked, and fresh" and "never checkable", which is exactly what a reader
deciding whether to trust it needs.
+
+ A record written before its *evidence_commits* landed counts from after
+ the commit that landed them, the same anchor the stored staleness score
+ uses, so that commit is not reported as a change to it.
"""
scope = [n for n in nodes if n]
if not scope:
@@ -153,11 +159,13 @@ def describe_decision_currency(
if created_at is None:
return None
- count = commits_since(root, since_date=created_at, nodes=scope)
+ since_commit, on = _anchor(root, created_at, evidence_commits)
+ count = commits_since(
+ root, since_commit=since_commit, since_date=created_at, nodes=scope
+ )
if count is None:
return None
- on = created_at.strftime("%Y-%m-%d")
files = "file" if len(scope) == 1 else f"{len(scope)} files"
if count == 0:
return f"nothing in the {files} it governs has changed since {on}"
@@ -165,6 +173,21 @@ def describe_decision_currency(
return f"the {files} it governs changed in {commits} since {on}"
+def _anchor(
+ root: Path | str, created_at: datetime, evidence_commits: Sequence[str]
+) -> tuple[str | None, str]:
+ """The commit to count from and how to date it: the landing of a record
+ written before it, else no commit and the record's own date."""
+ # Function-local: this module's import budget is the store and nothing heavier.
+ from repowise.core.analysis.decisions.landing import evidence_landings, record_landing
+
+ landings = evidence_landings(root, evidence_commits, timeout=GIT_TIMEOUT_S)
+ landing = record_landing(evidence_commits, landings, created_at)
+ if landing is None:
+ return None, created_at.strftime("%Y-%m-%d")
+ return landing.sha, f"{landing.at:%Y-%m-%d} (landed in {landing.sha[:9]})"
+
+
def recorded_on(birth_at: float) -> str:
"""The birth stamp as a date, or a phrase when there is no usable one.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
index 7ce0b085a..58de627c6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
@@ -226,6 +226,7 @@ async def _stamp_still_true(
repo_path,
created_at=top.created_at,
nodes=json.loads(top.affected_files_json or "[]"),
+ evidence_commits=json.loads(top.evidence_commits_json or "[]"),
)
if sentence:
governing[0]["still_true"] = sentence
diff --git a/tests/unit/analysis/test_decision_landing.py b/tests/unit/analysis/test_decision_landing.py
new file mode 100644
index 000000000..fde648462
--- /dev/null
+++ b/tests/unit/analysis/test_decision_landing.py
@@ -0,0 +1,141 @@
+"""A decision recorded on a branch is measured from the commit that landed it.
+
+Real ``git``: the rule is an identity between a branch commit and the squash
+that carried it, so a stubbed subprocess would test only the parsing.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.decisions.landing import evidence_landings, record_landing
+from repowise.core.analysis.decisions.staleness import compute_staleness
+from repowise.core.precedent.currency import describe_decision_currency
+
+_T0 = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)
+_BRANCH = datetime(2026, 1, 2, 12, 0, tzinfo=UTC)
+_RECORDED = datetime(2026, 1, 3, 12, 0, tzinfo=UTC)
+_SQUASH = datetime(2026, 1, 4, 12, 0, tzinfo=UTC)
+_AFTER = datetime(2026, 1, 5, 12, 0, tzinfo=UTC)
+
+
+def _git(repo: Path, *args: str, when: datetime | None = None) -> str:
+ env = dict(os.environ)
+ if when is not None:
+ env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = when.isoformat()
+ out = subprocess.run(
+ ["git", *args], cwd=str(repo), capture_output=True, text=True, check=True, env=env
+ )
+ return out.stdout.strip()
+
+
+def _commit(repo: Path, message: str, when: datetime, content: str) -> str:
+ (repo / "rule.py").write_text(content, encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", message, when=when)
+ return _git(repo, "rev-parse", "HEAD")
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "checkout"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "t")
+ _commit(root, "start", _T0, "start\n")
+ return root
+
+
+def _branch_commit(repo: Path, subject: str) -> str:
+ _git(repo, "checkout", "-q", "-b", "topic")
+ sha = _commit(repo, subject, _BRANCH, "branch\n")
+ _git(repo, "checkout", "-q", "main")
+ return sha
+
+
+def test_a_squash_titled_after_the_branch_commit_lands_it(repo: Path) -> None:
+ branch = _branch_commit(repo, "feat: keep the rule")
+ squash = _commit(repo, "feat: keep the rule (#7)", _SQUASH, "branch\n")
+
+ landing = evidence_landings(repo, [branch[:9]])[branch[:9]]
+
+ assert landing.sha == squash
+ assert landing.at == _SQUASH
+
+
+def test_a_squash_body_listing_the_branch_commit_lands_it(repo: Path) -> None:
+ branch = _branch_commit(repo, "fix: tighten the rule")
+ squash = _commit(
+ repo, "feat: a different title (#8)\n\n* feat: other\n\n* fix: tighten the rule", _SQUASH, "b\n"
+ )
+
+ assert evidence_landings(repo, [branch])[branch].sha == squash
+
+
+def test_two_commits_naming_it_leave_it_unresolved(repo: Path) -> None:
+ branch = _branch_commit(repo, "feat: keep the rule")
+ _commit(repo, "feat: keep the rule (#7)", _SQUASH, "one\n")
+ _commit(repo, "feat: keep the rule (#9)", _AFTER, "two\n")
+
+ assert evidence_landings(repo, [branch]) == {}
+
+
+def test_a_main_line_commit_lands_as_itself_and_session_ids_are_skipped(repo: Path) -> None:
+ own = _commit(repo, "feat: direct", _SQUASH, "direct\n")
+
+ landings = evidence_landings(repo, [own, "06e70f9f-2295-4dff-aed1-01a84b843684"])
+
+ assert list(landings) == [own]
+ assert landings[own].sha == own
+
+
+def test_only_a_landing_after_the_record_moves_its_anchor(repo: Path) -> None:
+ branch = _branch_commit(repo, "feat: keep the rule")
+ _commit(repo, "feat: keep the rule (#7)", _SQUASH, "branch\n")
+ landings = evidence_landings(repo, [branch])
+
+ assert record_landing([branch], landings, _RECORDED) is not None
+ assert record_landing([branch], landings, _AFTER) is None
+
+
+def test_the_landing_commit_is_not_drift_but_a_later_one_is(repo: Path) -> None:
+ branch = _branch_commit(repo, "feat: keep the rule")
+ _commit(repo, "feat: keep the rule (#7)", _SQUASH, "branch\n")
+ landing = record_landing([branch], evidence_landings(repo, [branch]), _RECORDED)
+ meta = {"rule.py": {"last_commit_at": _SQUASH}}
+
+ assert compute_staleness(_RECORDED, ["rule.py"], meta) == 1.0
+ assert compute_staleness(_RECORDED, ["rule.py"], meta, landed_at=landing.at) == 0.0
+ later = {"rule.py": {"last_commit_at": _AFTER}}
+ assert compute_staleness(_RECORDED, ["rule.py"], later, landed_at=landing.at) == 1.0
+
+
+def test_decision_show_counts_from_after_the_landing(repo: Path) -> None:
+ branch = _branch_commit(repo, "feat: keep the rule")
+ _commit(repo, "feat: keep the rule (#7)", _SQUASH, "branch\n")
+
+ sentence = describe_decision_currency(
+ repo, created_at=_RECORDED, nodes=["rule.py"], evidence_commits=[branch]
+ )
+ assert sentence is not None and sentence.startswith("nothing in the file it governs")
+
+ _commit(repo, "refactor: move the rule", _AFTER, "moved\n")
+ sentence = describe_decision_currency(
+ repo, created_at=_RECORDED, nodes=["rule.py"], evidence_commits=[branch]
+ )
+ assert sentence is not None and "changed in 1 commit since 2026-01-04" in sentence
+
+
+def test_a_same_named_commit_that_changes_none_of_its_files_does_not_land_it(repo: Path) -> None:
+ branch = _branch_commit(repo, "fix typo")
+ (repo / "other.py").write_text("x\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "fix typo (#900)", when=_SQUASH)
+
+ assert evidence_landings(repo, [branch]) == {}
diff --git a/tests/unit/persistence/test_decision_staleness_recompute.py b/tests/unit/persistence/test_decision_staleness_recompute.py
index ecb3b72a6..fc34fe108 100644
--- a/tests/unit/persistence/test_decision_staleness_recompute.py
+++ b/tests/unit/persistence/test_decision_staleness_recompute.py
@@ -238,3 +238,25 @@ async def test_a_conventions_record_still_gets_a_date(session):
assert rec.last_code_change is not None
assert rec.staleness_score == pytest.approx(0.42), "its own score is untouched"
+
+
+async def test_the_commit_that_landed_the_record_is_not_scored_as_drift(session, monkeypatch):
+ """A record written on a branch is born before its squash; that squash is the decision."""
+ from repowise.core.analysis.decisions import landing
+
+ landed = datetime.now(UTC) - timedelta(days=10)
+ rec = await _add_decision(session, files=["src/auth.py"], staleness=0.0)
+ rec.evidence_commits_json = '["abc1234"]'
+ session.add(GitMetadata(repository_id=_REPO_ID, file_path="src/auth.py", last_commit_at=landed))
+ await session.flush()
+ monkeypatch.setattr(
+ landing,
+ "evidence_landings",
+ lambda repo_path, evidence: {"abc1234": landing.Landing("f" * 40, landed)},
+ )
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+ assert rec.staleness_score == 1.0
+
+ await recompute_decision_staleness(session, _REPO_ID, {}, "/repo")
+ assert rec.staleness_score == 0.0
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index f68f20340..4ea132614 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -606,7 +606,7 @@ async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, mo
calls: list[tuple] = []
- def _fake(root, *, created_at, nodes):
+ def _fake(root, *, created_at, nodes, evidence_commits=()):
calls.append((root, tuple(nodes)))
return "nothing in the 1 file it governs has changed since 2026-01-01"