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): bind a record to the directories it governs, and measure staleness (#1322)

Raghav Chamadiya4bfefe291c67
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 212c26da4..ae46cd601 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -167,22 +167,33 @@ never walked back to `proposed` by a later extraction.
## Staleness
-A decision is only useful while it still describes the code. Every record carries
-a `staleness_score` between 0 and 1, recomputed per affected file:
-
-- The file no longer exists: `1.0`.
-- The file has not changed since the decision was recorded: `0.0`.
-- Otherwise it grows with 90-day commit count and file age.
-- Plus `0.3` when a commit *after* the decision was recorded contains a conflict
- signal ("replace", "remove", "deprecate", "migrate away", "revert", "drop")
- and shares topic words with the decision text.
-
-The record's score is the mean across its affected files. `>= 0.5` is stale
-everywhere: `repowise decision list --stale-only`, the health summary, and the
-staleness column in the CLI table.
-
-Staleness also decays the relevance of a decision when it is injected into a
-session, so guidance that stopped being true stops being pushed.
+A decision is only useful while it still describes the code, and that is a
+question the repository can answer rather than one worth guessing at. Every
+record carries a `staleness_score` between 0 and 1: **the fraction of its
+affected files that have been committed to since the decision was recorded.**
+
+- None of them has changed: `0.0`.
+- All of them have: `1.0`.
+- A file the repository does not track counts as changed, because a record
+ naming something absent cannot be shown to still hold.
+
+`>= 0.5` is stale everywhere: `repowise decision list --stale-only`, the health
+summary, and the staleness column in the CLI table.
+
+There is deliberately no constant in that definition. An earlier version grew
+the score with 90-day commit volume and record age, and added a boost when a
+later commit *message* contained words like "migrate away"; both were fitted to
+one repository's history and to English commit prose, and the result was a
+number that moved for reasons unrelated to whether the code had moved.
+
+**A record that names no file scores 0.0 and is not fresh** — the question
+cannot be asked of it at all. `repowise decision health` counts those
+separately, as *unscoped*, rather than banking them as current.
+
+For one record on demand, `repowise decision show` and `get_why` on a path go
+further and ask git directly, printing what it says: *"nothing in the 3 files it
+governs has changed since 2026-05-02"*. That costs a subprocess, so it is served
+only where one is affordable — never from an editor hook or during an update.
## Session-mined decisions
@@ -231,8 +242,11 @@ the code is written.
Every injected decision id is recorded locally. On the next `repowise update` the
session miner checks whether the guidance was followed or contradicted by your
-corrections in that session and adjusts the decision's staleness accordingly.
-That is the feedback loop: guidance you keep overriding fades out.
+corrections in that session and stores that verdict on the injection, where
+`repowise hook stats` reports the split. It deliberately does not touch the
+record's staleness: whether you overrode a decision is a judgement about the
+record, staleness is a measurement of the code, and one of those is per-machine
+while the other travels with the repository.
Decisions also land in the generated `CLAUDE.md` (active records, freshest
first) and in `get_overview()`, `get_context()`, and the `governance_risk` flag
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index 5aab88504..5c8eeb09e 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -211,12 +211,12 @@ workspace overlays, MCP responses, and CLI output.
| Decision source | Provenance of a record. | `DecisionRecord.source` | `inline_marker`, `git_archaeology`, `readme_mining`, `cli` |
| Decision confidence | Source-specific extraction confidence. | `DecisionExtractor` | `0.95` inline LLM, `0.70` git signal, `0.60` README mining, `1.0` manual |
| Affected files | Files linked to a decision from graph neighbors, commit files, or manual input. | `DecisionExtractor` | `["src/auth.py", "src/session.py"]` |
-| Affected modules | Top-level modules inferred from affected files or text. | `_infer_modules()` | `["src", "packages"]` |
+| Affected modules | Directories the affected files live in, deduped and capped; for records that name no file, the deepest directories mentioned in the decision text. | `resolve_module_nodes()` and `_infer_modules_from_text()` | `["packages/core/src/repowise/core/pipeline", "tests/unit/pipeline"]` |
| Decision tags | Topic labels inferred from keywords or LLM output. | `_infer_tags()` and prompts | `auth`, `database`, `api`, `security`, `testing` |
| Decision status | Lifecycle state. | `DecisionRecord.status` | `proposed`, `active`, `deprecated`, `superseded` |
-| Decision staleness score | 0 to 1 score indicating code has moved since a decision. | `DecisionExtractor.compute_staleness()` and `crud.recompute_decision_staleness()` | `0.63` |
-| Conflict boost | Staleness increase when newer commit messages contain contradiction signals and overlap decision text. | `compute_staleness()` | `+0.3` for "migrate away" touching the same concept |
-| Decision health summary | Counts and lists for stale, proposed, and ungoverned hotspots. | `get_decision_health_summary()` and server/CLI routes | `{active: 10, stale: 2, proposed: 3}` |
+| Decision staleness score | Fraction of a decision's affected files committed to since the decision was recorded. A file the repository does not track counts as changed. 0 for a decision naming no file, since the question cannot be asked of it. | `DecisionExtractor.compute_staleness()` and `crud.recompute_decision_staleness()` | `0.25` when 1 of 4 governed files has moved |
+| Decision still-true sentence | Read-time answer from `git rev-list` on whether a decision's files changed since it was made. Served where a subprocess is affordable (`get_why` path mode, `repowise decision show`), never on a hook or update path; absent when git cannot decide. | `precedent.currency.describe_decision_currency()` | `nothing in the 3 files it governs has changed since 2026-05-02` |
+| Decision health summary | Counts and lists for stale, proposed, unscoped, and ungoverned hotspots. | `get_decision_health_summary()` and server/CLI routes | `{active: 10, stale: 2, unscoped: 6, proposed: 3}` |
| Ungoverned hotspot | Hot file without related architectural decision coverage. | Decision health computation | `src/payments/processor.py` |
## Security Findings
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 248ac98d8..d4cd6fdb0 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -16,6 +16,7 @@ from repowise.cli.helpers import (
run_async,
)
from repowise.core.analysis.decisions.provenance import LISTABLE_SOURCES
+from repowise.core.precedent.currency import describe_decision_currency
#: The ladder's real sources plus the no-filter sentinel. Derived, because the
#: hand-written copy had drifted: it offered ``readme_mining`` (since retired)
@@ -295,8 +296,19 @@ def decision_show(decision_id: str, path: str | None) -> None:
f"[bold]{rec.title}[/bold]",
f"Status: {rec.status} | Source: {rec.source} | Confidence: {rec.confidence:.0%}",
f"Staleness: {rec.staleness_score:.2f}",
- "",
]
+ # The stored score is a proportion; this is the fact behind it, asked of
+ # git at read time. `show` is one record on demand, which is exactly where
+ # a subprocess is affordable — nothing on the hook or update path may do
+ # this. None means git could not decide, and then we say nothing.
+ currency = describe_decision_currency(
+ repo_path,
+ created_at=rec.created_at,
+ nodes=json.loads(rec.affected_files_json or "[]"),
+ )
+ if currency:
+ lines.append(f"[dim]{currency}[/dim]")
+ lines.append("")
if rec.context:
lines.append(f"[cyan]Context:[/cyan] {rec.context}")
if rec.decision:
@@ -512,6 +524,11 @@ def decision_health(path: str | None) -> None:
stats_table.add_row("Active decisions", str(summary.get("active", 0)))
stats_table.add_row("Proposed (needs review)", f"[yellow]{summary.get('proposed', 0)}[/yellow]")
stats_table.add_row("Stale decisions", f"[red]{summary.get('stale', 0)}[/red]")
+ unscoped = summary.get("unscoped", 0)
+ if unscoped:
+ # Not folded into "stale": these were never checked, which is a
+ # different thing from checked and found to have drifted.
+ stats_table.add_row("Unscoped (cannot be checked)", f"[yellow]{unscoped}[/yellow]")
stats_table.add_row("Deprecated", str(summary.get("deprecated", 0)))
console.print(stats_table)
diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.py
index c58fd620b..db3a182ed 100644
--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py
+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py
@@ -710,16 +710,18 @@ async def run_update_evolution(
regen.update(governed)
result["superseded"] += 1
elif kind == "amended":
- # Keep it active but mark it stale so its drift is visible, and
- # re-render its governed pages to reflect the amendment.
- dec.staleness_score = max(dec.staleness_score, 0.6)
+ # Re-render the governed pages so the amendment shows up there.
+ # It no longer clamps ``staleness_score``: that column is now a
+ # measured fact — the fraction of the governed files that have
+ # changed since the record was born — and a judge's verdict
+ # written into it made the same number mean two different things
+ # depending on which writer ran last. The amendment is visible in
+ # the regenerated pages and in the run's own counters.
dec.updated_at = now
regen.update(governed)
result["amended"] += 1
elif kind == "reaffirmed":
- # Still holds — relax staleness; no regen needed.
- dec.staleness_score = min(dec.staleness_score, 0.2)
- dec.updated_at = now
+ # Still holds — nothing to re-render, and nothing to write.
result["reaffirmed"] += 1
await session.flush()
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 5eea8beff..c333c76a3 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -47,6 +47,7 @@ from typing import Any
import structlog
from repowise.core.analysis.decisions.gate import apply_substring_gate
+from repowise.core.analysis.decisions.scope import resolve_module_nodes
from .prompts import (
_SYSTEM_PROMPT,
@@ -109,6 +110,17 @@ def _as_aware_utc(value: datetime) -> datetime:
return value.astimezone(UTC)
+def _coerce_dt(value: datetime | str) -> datetime:
+ """Parse an ISO string into a datetime, passing datetimes through.
+
+ Both shapes reach staleness: the ORM hands back datetimes, while the git
+ metadata map carries whatever was persisted, which for SQLite is a string.
+ """
+ if isinstance(value, str):
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return value
+
+
# ---------------------------------------------------------------------------
# Data models
# ---------------------------------------------------------------------------
@@ -1116,22 +1128,6 @@ class DecisionExtractor:
# Staleness computation (static method)
# ------------------------------------------------------------------
- # Keywords that signal a decision may have been contradicted or superseded.
- _CONFLICT_SIGNALS = frozenset(
- {
- "replace",
- "remove",
- "deprecate",
- "switch from",
- "migrate away",
- "drop",
- "revert",
- "undo",
- "disable",
- "eliminate",
- }
- )
-
@staticmethod
def compute_staleness(
decision_created_at: datetime,
@@ -1139,92 +1135,47 @@ class DecisionExtractor:
git_meta_map: dict[str, dict],
decision_text: str = "",
) -> float:
- """Compute staleness score for a decision. Returns 0.0-1.0.
-
- In addition to commit volume and age, checks whether recent commit
- messages contain keywords that conflict with the decision text
- (e.g. decision says "use Redis" but a recent commit says "migrate
- away from Redis"). This boosts staleness when the underlying code
- may have diverged from the decision's intent.
+ """Fraction of *affected_files* that have changed since the record's birth.
+
+ A fact about the code, not a judgement about the record: 0.0 means
+ nothing it governs has moved, 1.0 means all of it has. There is no
+ tuned constant left in it, which is the point — the previous formula
+ was ``commit_count / 15 * 0.7 + age_days / 365 * 0.3``, whose divisors
+ were fitted to one repository's history and produced ~0 for almost
+ every record here regardless of whether the code had moved.
+
+ Also gone: a keyword boost that read recent commit *messages* for words
+ like "migrate away". That inferred intent from English prose, which
+ does not travel, and it mixed a guess into a value other surfaces
+ store and compare.
+
+ *decision_text* is accepted and unused, so the two call sites keep
+ working; it goes when they do.
+
+ 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.
"""
if not affected_files:
+ # No scope, so the question cannot be asked. Callers distinguish
+ # this from a genuine 0.0 by the empty file list, and
+ # `decision health` reports it as unscoped rather than fresh.
return 0.0
- now = datetime.now(UTC)
- scores: list[float] = []
- decision_lower = decision_text.lower()
-
+ created = _as_aware_utc(_coerce_dt(decision_created_at)) if decision_created_at else None
+ changed = 0
for fp in affected_files:
meta = git_meta_map.get(fp)
if meta is None:
- scores.append(1.0) # File missing / not tracked
+ changed += 1 # named but not tracked — cannot be shown to hold
continue
-
last_commit = meta.get("last_commit_at")
- if last_commit and decision_created_at:
- if isinstance(last_commit, str):
- last_commit = datetime.fromisoformat(last_commit.replace("Z", "+00:00"))
- last_commit = _as_aware_utc(last_commit)
- _created = decision_created_at
- if isinstance(_created, str):
- _created = datetime.fromisoformat(_created.replace("Z", "+00:00"))
- _created = _as_aware_utc(_created)
- if last_commit > _created:
- age_days = (now - _created).days
- commit_count = meta.get("commit_count_90d", 0)
- base_score = min(
- 1.0,
- commit_count / 15 * 0.7 + age_days / 365 * 0.3,
- )
-
- # Keyword conflict boost: check if recent commits
- # contradict the decision's content.
- conflict_boost = 0.0
- if decision_lower:
- sig_json = meta.get("significant_commits_json", "[]")
- try:
- sig_commits = (
- json.loads(sig_json) if isinstance(sig_json, str) else sig_json
- )
- except (json.JSONDecodeError, TypeError):
- sig_commits = []
- for sc in sig_commits:
- sc_date = sc.get("date", "")
- # Only consider commits after the decision was created
- if sc_date and sc_date > _created.isoformat():
- msg_lower = sc.get("message", "").lower()
- for signal in DecisionExtractor._CONFLICT_SIGNALS:
- if signal in msg_lower:
- # Check if the commit message shares meaningful
- # words with the decision text (context overlap)
- msg_words = set(msg_lower.split())
- dec_words = set(decision_lower.split())
- overlap = msg_words & dec_words - {
- "the",
- "a",
- "an",
- "to",
- "in",
- "for",
- "and",
- "or",
- "of",
- "is",
- "was",
- "with",
- }
- if len(overlap) >= 2:
- conflict_boost = max(conflict_boost, 0.3)
- break
-
- score = min(1.0, base_score + conflict_boost)
- scores.append(score)
- else:
- scores.append(0.0)
- else:
- scores.append(0.0)
+ if not last_commit or created is None:
+ continue
+ if _as_aware_utc(_coerce_dt(last_commit)) > created:
+ changed += 1
- return round(sum(scores) / len(scores), 3) if scores else 0.0
+ return round(changed / len(affected_files), 3)
# ------------------------------------------------------------------
# Main entry point
@@ -1484,25 +1435,32 @@ class DecisionExtractor:
return "\n".join(out)
def _infer_modules(self, file_paths: list[str]) -> list[str]:
- """Infer top-level module paths from file paths."""
- modules: set[str] = set()
- for fp in file_paths:
- parts = fp.replace("\\", "/").split("/")
- if len(parts) > 1:
- modules.add(parts[0])
- return sorted(modules)
+ """Infer the module paths a record governs from the files it names."""
+ return resolve_module_nodes(file_paths)
def _infer_modules_from_text(self, text: str) -> list[str]:
- """Infer module names by matching text against graph nodes."""
+ """Infer module paths by matching *text* against graph directories.
+
+ Used only by the sources that name no files (git archaeology, PRs), so
+ the text is all the linkage there is. Matching is on the *deepest*
+ directory mentioned rather than its first segment: in a packages/
+ layout every node starts with ``packages``, so a first-segment match
+ fires on any text that happens to say the word.
+ """
if not self._graph:
return []
- modules: set[str] = set()
text_lower = text.lower()
+ candidates: set[str] = set()
for node in self._graph.nodes:
- parts = node.replace("\\", "/").split("/")
- if len(parts) > 1 and parts[0].lower() in text_lower:
- modules.add(parts[0])
- return sorted(modules)[:5]
+ parent, sep, _ = str(node).replace("\\", "/").strip("/").rpartition("/")
+ if sep and parent:
+ candidates.add(parent)
+
+ matched = {d for d in candidates if d.lower() in text_lower}
+ # Keep only the deepest match on each branch: a text naming
+ # ``packages/core/.../decisions`` should not also claim every ancestor.
+ deepest = {d for d in matched if not any(o != d and o.startswith(d + "/") for o in matched)}
+ return sorted(deepest, key=lambda d: (-d.count("/"), d))[:5]
def _infer_tags(self, text: str) -> list[str]:
"""Infer tags from decision text."""
diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.py
index 1e931ee85..f0560a967 100644
--- a/packages/core/src/repowise/core/analysis/decisions/scope.py
+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py
@@ -11,7 +11,37 @@ from __future__ import annotations
from collections.abc import Sequence
-__all__ = ["derive_decision_scope"]
+__all__ = ["derive_decision_scope", "resolve_module_nodes"]
+
+#: Upper bound on the directories one record may claim. A record naming files
+#: across more directories than this is not scoped by its module list anyway —
+#: its files are the scope — and an unbounded list is what turns a stored
+#: column into a second copy of the tree.
+_MAX_MODULES = 12
+
+
+def resolve_module_nodes(files: Sequence[str] | None) -> list[str]:
+ """Return the directories that *files* live in, deduped and sorted.
+
+ The one convention for a record's module linkage. Two disagreeing ones
+ were in use before: the first path segment, which in a packages/ layout
+ yields ``packages`` or ``tests`` for essentially every record, and the
+ containing directory. This is the second, because it is the only one that
+ is real by construction — a directory holding a file the record names
+ exists whether or not a graph was built, so no caller needs one.
+
+ Root-level files contribute nothing: a record naming ``README.md`` is
+ scoped by that file, not by the repository.
+ """
+ seen: dict[str, None] = {}
+ for f in files or []:
+ if not f:
+ continue
+ norm = f.replace("\\", "/").strip("/")
+ parent, sep, _ = norm.rpartition("/")
+ if sep and parent:
+ seen.setdefault(parent, None)
+ return sorted(seen)[:_MAX_MODULES]
def derive_decision_scope(
@@ -29,7 +59,7 @@ def derive_decision_scope(
outranks the evidence-file fallback
- exactly one affected file → ``file``
- otherwise count distinct modules — the explicitly linked ones, or when
- none are linked, the top-level directories of the affected files: one →
+ none are linked, the directories the affected files live in: one →
``module``, several → ``cross-module``; multiple root-level files with
no directory stay ``file``.
@@ -45,7 +75,9 @@ def derive_decision_scope(
if len(files) == 1:
return "file"
if not modules:
- modules = {f.split("/", 1)[0] for f in files if "/" in f}
+ # Same convention as resolve_module_nodes, so a record scored before
+ # its modules were backfilled reports the granularity it will keep.
+ modules = set(resolve_module_nodes(sorted(files)))
if not modules:
return "file"
return "module" if len(modules) == 1 else "cross-module"
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 866d6be38..5c30e977d 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -1059,7 +1059,16 @@ async def recompute_decision_staleness(
repository_id: str,
git_meta_map: dict[str, dict],
) -> int:
- """Recompute staleness_score for all active decisions. Returns update count."""
+ """Recompute staleness_score for all active decisions. Returns update count.
+
+ Also 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
+ predate the fix carry it. Deriving here rather than in a data migration
+ keeps the single-repair-path rule — the one this repo already learned when
+ an alembic migration and a runtime repair disagreed about confidence.
+ """
result = await session.execute(
select(DecisionRecord).where(
DecisionRecord.repository_id == repository_id,
@@ -1073,7 +1082,11 @@ async def recompute_decision_staleness(
affected = json.loads(dec.affected_files_json)
if affected:
affected_by_id[dec.id] = affected
+
+ modules_updated = _backfill_module_nodes(decisions, affected_by_id)
if not affected_by_id:
+ if modules_updated:
+ await session.flush()
return 0
git_meta_map = await _fill_git_meta_gaps(
@@ -1092,23 +1105,47 @@ async def recompute_decision_staleness(
from repowise.core.analysis.decision_extractor import DecisionExtractor
- decision_text = f"{dec.title} {dec.decision} {dec.rationale}"
new_score = DecisionExtractor.compute_staleness(
dec.created_at,
affected,
git_meta_map,
- decision_text=decision_text,
)
if abs(new_score - dec.staleness_score) > 0.01:
dec.staleness_score = round(new_score, 3)
dec.updated_at = now
updated += 1
- if updated:
+ if updated or modules_updated:
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.
return updated
+def _backfill_module_nodes(
+ decisions: list[DecisionRecord],
+ affected_by_id: dict[str, list[str]],
+) -> int:
+ """Re-derive each record's module linkage from its files. Returns rows moved.
+
+ Records naming no file are left alone: there is nothing to derive from, and
+ an invented scope is worse than an absent one.
+ """
+ from repowise.core.analysis.decisions.scope import resolve_module_nodes
+
+ moved = 0
+ for dec in decisions:
+ affected = affected_by_id.get(dec.id)
+ if not affected:
+ continue
+ derived = resolve_module_nodes(affected)
+ if derived != json.loads(dec.affected_modules_json or "[]"):
+ dec.affected_modules_json = json.dumps(derived)
+ moved += 1
+ return moved
+
+
async def get_stale_decisions(
session: AsyncSession,
repository_id: str,
@@ -1144,6 +1181,11 @@ async def get_decision_health_summary(
"superseded": 0,
"dismissed": 0,
"stale": 0,
+ # Active records naming no file. They score 0.0 because the staleness
+ # question cannot be asked of them, which renders identically to a
+ # record whose code genuinely has not moved — so they are counted
+ # separately rather than banked as fresh.
+ "unscoped": 0,
}
stale_decisions: list[DecisionRecord] = []
proposed_decisions: list[DecisionRecord] = []
@@ -1156,7 +1198,10 @@ async def get_decision_health_summary(
if d.staleness_score >= 0.5:
counts["stale"] += 1
stale_decisions.append(d)
- for fp in json.loads(d.affected_files_json):
+ affected_files = json.loads(d.affected_files_json)
+ if not affected_files:
+ counts["unscoped"] += 1
+ for fp in affected_files:
governed_files.add(fp)
elif d.status == "proposed":
proposed_decisions.append(d)
diff --git a/packages/core/src/repowise/core/precedent/currency.py b/packages/core/src/repowise/core/precedent/currency.py
new file mode 100644
index 000000000..14906a756
--- /dev/null
+++ b/packages/core/src/repowise/core/precedent/currency.py
@@ -0,0 +1,118 @@
+"""Is this claim still true? — the one git question, and its two callers.
+
+A claim bound to code can be checked rather than guessed: ask git whether
+anything in its scope has changed since it was born. That is arithmetic, not
+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
+handling, one implementation; the alternative was a second copy that would
+drift from this one the first time either grew a flag.
+
+Cost, measured on this checkout (1,011 commits): 55-66 ms cold and warm. That
+is 0.5% of a ``get_answer`` synthesis and fine there. It is **not** fine on a
+hook path (155 ms total budget) or on ``update`` (a 200 ms ceiling), and no
+caller on either may reach this module.
+
+Every failure mode returns ``None``. A budget that quietly produces a partial
+count is worse than no answer, so the caller decides what silence means.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Sequence
+from datetime import datetime
+from pathlib import Path
+
+__all__ = ["commits_since", "describe_decision_currency"]
+
+#: Hard ceiling on the one subprocess. Generous against the 55-66 ms measured
+#: here, because a large repository is slower and a timeout costs the answer.
+GIT_TIMEOUT_S = 5.0
+
+
+def commits_since(
+ root: Path | str,
+ *,
+ since_commit: str | None = None,
+ since_date: datetime | None = None,
+ nodes: Sequence[str] = (),
+ timeout: float = GIT_TIMEOUT_S,
+) -> int | None:
+ """``git rev-list --count`` over *nodes* since a commit or a date.
+
+ Exactly one of *since_commit* / *since_date* is used, commit first when
+ both are given (a sha is exact where a timestamp is a boundary). Returns
+ ``None`` on every failure — bad ref, git missing, timeout, unparsable
+ output — never a partial count.
+
+ *timeout* is a parameter because the two callers bought different budgets:
+ ``get_answer`` sits inside a multi-second synthesis and can wait, while a
+ CLI command answering one record should give up sooner.
+ """
+ if since_commit:
+ rev = f"{since_commit}..HEAD"
+ extra: list[str] = []
+ elif since_date is not None:
+ rev = "HEAD"
+ extra = [f"--since={since_date.isoformat()}"]
+ else:
+ return None
+
+ cmd = ["git", "rev-list", "--count", *extra, rev]
+ if nodes:
+ cmd += ["--", *nodes]
+ try:
+ completed = subprocess.run(
+ cmd,
+ cwd=str(root),
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ except (subprocess.TimeoutExpired, OSError):
+ return None
+ if completed.returncode != 0:
+ return None
+ try:
+ return int(completed.stdout.strip())
+ except ValueError:
+ return None
+
+
+def describe_decision_currency(
+ root: Path | str,
+ *,
+ created_at: datetime | None,
+ nodes: Sequence[str],
+) -> str | None:
+ """One sentence on whether a decision's code has moved since it was made.
+
+ ``None`` means git could not decide and the caller should say nothing —
+ silence beats a number nobody can stand behind.
+
+ The unscoped case gets a sentence rather than silence, and deliberately.
+ A record naming no file scores 0.0 in the stored column because the
+ question cannot be asked of it, and 0.0 renders identically to a record
+ 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.
+ """
+ scope = [n for n in nodes if n]
+ if not scope:
+ return "not bound to any file, so whether it still holds cannot be checked"
+ if created_at is None:
+ return None
+
+ count = commits_since(root, 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}"
+ commits = "1 commit" if count == 1 else f"{count} commits"
+ return f"the {files} it governs changed in {commits} since {on}"
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 2aedbc049..51ab7d228 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -61,6 +61,7 @@ from repowise.core.analysis.decisions.provenance import (
verify_quote,
)
from repowise.core.analysis.decisions.rationale_comments import CAUSAL_MARKERS
+from repowise.core.analysis.decisions.scope import resolve_module_nodes
from repowise.core.distill.corrections import command_anchor
from repowise.core.sessions import INTENT_TURNS, Event, get_adapter
from repowise.core.sessions.cursor import iter_new_events
@@ -549,7 +550,7 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted
structured = row["structured"]
status = "active" if row["first_promotion"] else "proposed"
files = _relative_files(structured.get("affected_files") or row["files"], repo_root)
- modules = sorted({f.rsplit("/", 1)[0] for f in files if "/" in f})
+ modules = resolve_module_nodes(files)
confidence = compute_confidence(
rank_for_source("session"),
row["observations"],
@@ -582,9 +583,6 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted
#: had time to react (or end) before "no contradiction" reads as "followed".
INJECTION_EVAL_MIN_AGE_SECONDS = 3600.0
-#: Staleness levels mirroring run_update_evolution's amended/reaffirmed moves.
-_CONTRADICTED_STALENESS = 0.6
-_FOLLOWED_STALENESS = 0.2
async def apply_injection_feedback(
@@ -600,9 +598,11 @@ async def apply_injection_feedback(
sidecar's ``injections`` table), check the same session's mined user
corrections: a correction that contradicts the shown decision (the
:func:`~repowise.core.analysis.decisions.evolution.contradicts` heuristic)
- marks it contradicted and bumps staleness so the evolution machinery
- surfaces the drift; otherwise the guidance counts as followed and
- staleness relaxes, the same reaffirm move ``run_update_evolution`` makes.
+ marks it contradicted; otherwise the guidance counts as followed. The
+ verdict is stored on the injection row and nowhere else: it used to also
+ clamp the decision's ``staleness_score``, which is now a measured fact
+ about whether the governed files moved, and a per-machine session verdict
+ may not overwrite a value the dashboard and hosted both read.
Deliberately binary for v1 (followed / contradicted); the
followed-vs-ignored split and relevance decay are the validation-gated
@@ -666,20 +666,10 @@ async def apply_injection_feedback(
verdict="contradicted" if verdicts.get(decision_id) else "followed",
)
- from datetime import UTC, datetime
-
- for decision_id, contradicted in verdicts.items():
- rec = records[decision_id]
- if contradicted:
- rec.staleness_score = max(rec.staleness_score, _CONTRADICTED_STALENESS)
- summary["contradicted"] += 1
- else:
- rec.staleness_score = min(rec.staleness_score, _FOLLOWED_STALENESS)
- summary["followed"] += 1
- rec.updated_at = datetime.now(UTC)
+ for contradicted in verdicts.values():
+ summary["contradicted" if contradicted else "followed"] += 1
store.commit()
- await db_session.flush()
finally:
store.close()
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index ca6fac293..4b7b7b14e 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -387,7 +387,6 @@ def _sibling_coverage(file_path: str, governing: list[dict], all_decisions: list
for d in all_decisions:
affected = json.loads(d.affected_files_json)
- json.loads(d.affected_modules_json)
for af in affected:
af_dir = "/".join(af.split("/")[:-1])
if af_dir == dir_path and af != file_path:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py b/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
index b6e78ebbf..e2441dd2b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/episodes.py
@@ -32,10 +32,10 @@ import asyncio
import json
import logging
import re
-import subprocess
import time
from pathlib import Path
+from repowise.core.precedent.currency import commits_since
from repowise.core.precedent.store import EpisodeStore, default_store_path
from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget
@@ -310,29 +310,11 @@ def _commits_since(root: Path, birth_commit: str, nodes: list[str]) -> int | Non
The one sanctioned read-time computation in this path, and it is bounded:
a single plumbing call with a hard timeout, measured at 55-66 ms against
- get_answer's multi-second synthesis. A budget that quietly produces a
- partial count is worse than no answer, so every failure mode returns None
- and the caller decides what silence means.
+ get_answer's multi-second synthesis. The call itself lives in
+ :mod:`repowise.core.precedent.currency`, shared with the decision layer,
+ which asks the same question from a date instead of a birth commit.
"""
- cmd = ["git", "rev-list", "--count", f"{birth_commit}..HEAD"]
- if nodes:
- cmd += ["--", *nodes]
- try:
- completed = subprocess.run(
- cmd,
- cwd=str(root),
- capture_output=True,
- text=True,
- timeout=_GIT_TIMEOUT_S,
- )
- except (subprocess.TimeoutExpired, OSError):
- return None
- if completed.returncode != 0:
- return None
- try:
- return int(completed.stdout.strip())
- except ValueError:
- return None
+ return commits_since(root, since_commit=birth_commit, nodes=nodes, timeout=_GIT_TIMEOUT_S)
def _recorded_on(birth_at: float) -> str:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index 0cc66499b..f81a5eeee 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import contextlib
import json
import re
@@ -16,6 +17,7 @@ from repowise.core.persistence.models import (
DecisionRecord,
GitMetadata,
)
+from repowise.core.precedent.currency import describe_decision_currency
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server._budget import OmissionCollector, effective_char_budget
from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale
@@ -352,13 +354,26 @@ async def _why_path(query: str, repo: str | None) -> dict:
# not whichever 8 the table scan happened to yield first.
matched.sort(key=_path_decision_sort_key)
governing = []
- for d in matched[:_MAX_PATH_DECISIONS]:
+ for rank, d in enumerate(matched[:_MAX_PATH_DECISIONS]):
# Walk supersedes/refines back to roots so the answer is a
# lineage chain (sessions → JWT → OAuth2), not a flat list.
lineage = await build_lineage_chain(session, d.id)
- governing.append(
- _governing_decision_entry(d, json.loads(d.affected_files_json), lineage)
- )
+ entry = _governing_decision_entry(d, json.loads(d.affected_files_json), lineage)
+ # Ask git whether the top record still holds — and only the top
+ # one. The query is ~60 ms, which is affordable once inside an MCP
+ # call and is not affordable eight times; the record ranked first
+ # is the one a reader acts on. Everything below it keeps the
+ # stored proportion, which needed no subprocess to compute.
+ if rank == 0:
+ sentence = await asyncio.to_thread(
+ describe_decision_currency,
+ ctx.path,
+ created_at=d.created_at,
+ nodes=json.loads(d.affected_files_json or "[]"),
+ )
+ if sentence:
+ entry["still_true"] = sentence
+ governing.append(entry)
origin_story = _build_origin_story(query, git_meta, governing)
_trim_commit_text(origin_story)
diff --git a/tests/unit/analysis/test_decision_node_sets.py b/tests/unit/analysis/test_decision_node_sets.py
new file mode 100644
index 000000000..65361d9f6
--- /dev/null
+++ b/tests/unit/analysis/test_decision_node_sets.py
@@ -0,0 +1,189 @@
+"""The scope a decision binds to, and the staleness question asked of it.
+
+Two properties are load-bearing here and are asserted rather than assumed: a
+record in a ``packages/`` layout must bind to the directories its files
+actually live in (the old first-path-segment rule made almost every record in
+such a repo claim ``packages`` or ``tests``), and staleness must be a fact
+about whether those files moved rather than a formula with fitted divisors.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+from repowise.core.analysis.decision_extractor import DecisionExtractor
+from repowise.core.analysis.decisions.scope import derive_decision_scope, resolve_module_nodes
+
+_BIRTH = datetime(2026, 1, 1, tzinfo=UTC)
+_BEFORE = _BIRTH - timedelta(days=10)
+_AFTER = _BIRTH + timedelta(days=10)
+
+
+# -- node sets ---------------------------------------------------------------
+
+
+def test_record_binds_to_real_directories_not_the_first_path_segment() -> None:
+ """The defect this exists for: everything in this layout scoping to `packages`."""
+ modules = resolve_module_nodes(
+ [
+ "packages/core/src/repowise/core/pipeline/persist.py",
+ "packages/core/src/repowise/core/pipeline/incremental.py",
+ "tests/unit/pipeline/test_persist.py",
+ ]
+ )
+
+ assert modules == [
+ "packages/core/src/repowise/core/pipeline",
+ "tests/unit/pipeline",
+ ]
+ assert "packages" not in modules
+ assert "tests" not in modules
+
+
+def test_files_sharing_a_directory_collapse_to_one_module() -> None:
+ assert resolve_module_nodes(["a/b/one.py", "a/b/two.py", "a/b/three.py"]) == ["a/b"]
+
+
+def test_root_level_files_contribute_no_module() -> None:
+ """A record naming README.md is scoped by that file, not by the repository."""
+ assert resolve_module_nodes(["README.md", "setup.py"]) == []
+
+
+def test_windows_separators_and_empties_are_normalised() -> None:
+ assert resolve_module_nodes(["pkg\\mod\\x.py", "", "pkg/mod/y.py"]) == ["pkg/mod"]
+
+
+def test_module_list_is_bounded() -> None:
+ """An unbounded list is a second copy of the tree in a text column."""
+ many = [f"dir{i}/file.py" for i in range(50)]
+ assert len(resolve_module_nodes(many)) == 12
+
+
+def test_granularity_agrees_with_the_module_convention() -> None:
+ """Two files in sibling packages are cross-module, not one `packages` module."""
+ files = ["packages/core/a.py", "packages/cli/b.py"]
+
+ assert derive_decision_scope(files, None) == "cross-module"
+ assert derive_decision_scope(["packages/core/a.py", "packages/core/b.py"], None) == "module"
+
+
+# -- staleness as a fact -----------------------------------------------------
+
+
+def _meta(last_commit_at: datetime) -> dict:
+ return {"last_commit_at": last_commit_at, "commit_count_90d": 99}
+
+
+def test_untouched_scope_reads_still_true() -> None:
+ score = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py", "b.py"],
+ {"a.py": _meta(_BEFORE), "b.py": _meta(_BEFORE)},
+ )
+
+ assert score == 0.0
+
+
+def test_changed_scope_does_not_read_still_true() -> None:
+ score = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py", "b.py"],
+ {"a.py": _meta(_AFTER), "b.py": _meta(_AFTER)},
+ )
+
+ assert score == 1.0
+
+
+def test_score_is_the_fraction_of_the_scope_that_moved() -> None:
+ score = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py", "b.py", "c.py", "d.py"],
+ {
+ "a.py": _meta(_AFTER),
+ "b.py": _meta(_BEFORE),
+ "c.py": _meta(_BEFORE),
+ "d.py": _meta(_BEFORE),
+ },
+ )
+
+ assert score == 0.25
+
+
+def test_commit_volume_no_longer_moves_the_score() -> None:
+ """The old formula's divisors were fitted to one repository's history.
+
+ Two records over untouched files must score identically no matter how busy
+ those files are, which the ``commit_count / 15`` term did not manage.
+ """
+ quiet = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py"],
+ {"a.py": {"last_commit_at": _BEFORE, "commit_count_90d": 0}},
+ )
+ busy = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py"],
+ {"a.py": {"last_commit_at": _BEFORE, "commit_count_90d": 400}},
+ )
+
+ assert quiet == busy == 0.0
+
+
+def test_age_alone_no_longer_moves_the_score() -> None:
+ """A decade-old record over code nobody touched is still true."""
+ ancient = datetime(2015, 1, 1, tzinfo=UTC)
+
+ score = DecisionExtractor.compute_staleness(
+ ancient,
+ ["a.py"],
+ {"a.py": _meta(datetime(2015, 6, 1, tzinfo=UTC) - timedelta(days=200))},
+ )
+
+ assert score == 0.0
+
+
+def test_commit_prose_no_longer_boosts_the_score() -> None:
+ """The keyword boost read English commit messages and inferred intent."""
+ score = DecisionExtractor.compute_staleness(
+ _BIRTH,
+ ["a.py"],
+ {
+ "a.py": {
+ "last_commit_at": _BEFORE,
+ "significant_commits_json": (
+ '[{"date": "2026-06-01T00:00:00+00:00",'
+ ' "message": "migrate away from redis, drop the cache"}]'
+ ),
+ }
+ },
+ decision_text="use redis for the cache",
+ )
+
+ assert score == 0.0
+
+
+def test_a_file_the_repo_does_not_track_cannot_be_shown_to_hold() -> None:
+ score = DecisionExtractor.compute_staleness(_BIRTH, ["gone.py"], {})
+
+ assert score == 1.0
+
+
+def test_sqlite_naive_and_string_timestamps_both_compare() -> None:
+ """The ORM hands back datetimes; SQLite hands back strings. Both arrive."""
+ score = DecisionExtractor.compute_staleness(
+ _BIRTH.replace(tzinfo=None),
+ ["a.py"],
+ {"a.py": {"last_commit_at": _AFTER.isoformat().replace("+00:00", "Z")}},
+ )
+
+ assert score == 1.0
+
+
+def test_unscoped_record_scores_zero_and_that_is_not_freshness() -> None:
+ """0.0 here means "cannot be asked", which `decision health` reports apart.
+
+ Asserted so the pairing stays deliberate: the score alone cannot tell the
+ two apart, which is exactly why the unscoped count and the read-time
+ sentence both exist.
+ """
+ assert DecisionExtractor.compute_staleness(_BIRTH, [], {}) == 0.0
diff --git a/tests/unit/persistence/test_decision_staleness_recompute.py b/tests/unit/persistence/test_decision_staleness_recompute.py
index 7c002ff31..5dc68f72b 100644
--- a/tests/unit/persistence/test_decision_staleness_recompute.py
+++ b/tests/unit/persistence/test_decision_staleness_recompute.py
@@ -119,3 +119,55 @@ async def test_file_the_index_has_never_seen_still_scores_stale(session):
rec = await session.get(DecisionRecord, "d1")
assert updated == 1
assert rec.staleness_score == pytest.approx(1.0)
+
+
+# -- module-linkage backfill --------------------------------------------------
+#
+# The rows a user already has carry the first-path-segment scope, which in a
+# packages/ layout is `packages` or `tests` for nearly every record. This is
+# the named migration for them: re-derived in the repair pass that already
+# runs on every update, not in a data migration that would have to agree with
+# the runtime path forever.
+
+
+async def test_existing_rows_have_their_module_scope_re_derived(session):
+ import json
+
+ rec = await _add_decision(session, files=["packages/core/src/pipeline/persist.py"], staleness=0.0)
+ rec.affected_modules_json = json.dumps(["packages"]) # the pre-change shape
+ await session.flush()
+ await _add_git_metadata(session, "packages/core/src/pipeline/persist.py", days_ago=60, commits=1)
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert json.loads(rec.affected_modules_json) == ["packages/core/src/pipeline"]
+
+
+async def test_backfill_is_not_reported_as_a_rescore(session):
+ """The count callers print is "N decisions rescored"; a silent repair is not one."""
+ import json
+
+ rec = await _add_decision(session, files=["a/b/c.py"], staleness=0.0)
+ rec.affected_modules_json = json.dumps(["a"])
+ await session.flush()
+ await _add_git_metadata(session, "a/b/c.py", days_ago=60, commits=1)
+
+ updated = await recompute_decision_staleness(session, _REPO_ID, {})
+
+ assert updated == 0
+ rec = await session.get(DecisionRecord, "d1")
+ assert json.loads(rec.affected_modules_json) == ["a/b"]
+
+
+async def test_a_record_naming_no_file_keeps_its_scope_rather_than_inventing_one(session):
+ import json
+
+ rec = await _add_decision(session, files=[], staleness=0.0)
+ rec.affected_modules_json = json.dumps(["packages"])
+ await session.flush()
+
+ await recompute_decision_staleness(session, _REPO_ID, {})
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert json.loads(rec.affected_modules_json) == ["packages"]
diff --git a/tests/unit/precedent/test_currency.py b/tests/unit/precedent/test_currency.py
new file mode 100644
index 000000000..ec625a18e
--- /dev/null
+++ b/tests/unit/precedent/test_currency.py
@@ -0,0 +1,133 @@
+"""The one git question, asked against a real checkout.
+
+Real ``git`` rather than a mocked subprocess on purpose: the value of this
+module is that it delegates the judgement to git, so a test that stubs git out
+would assert only that the string formatting works.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+import pytest
+
+from repowise.core.precedent.currency import commits_since, describe_decision_currency
+
+#: Commit timestamps are pinned rather than taken from the clock. ``--since``
+#: has one-second resolution, so a fixture that commits twice in the same
+#: second cannot distinguish "born before" from "born after" — which is the
+#: only thing these tests are checking.
+_BIRTH_TIME = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)
+_LATER_TIME = datetime(2026, 3, 1, 12, 0, tzinfo=UTC)
+#: Between the two commits, so a record born here has one commit after it.
+_BETWEEN = datetime(2026, 2, 1, 12, 0, tzinfo=UTC)
+
+
+def _git(repo: Path, *args: str, when: datetime | None = None) -> str:
+ env = dict(os.environ)
+ if when is not None:
+ stamp = when.isoformat()
+ env["GIT_AUTHOR_DATE"] = stamp
+ env["GIT_COMMITTER_DATE"] = stamp
+ out = subprocess.run(
+ ["git", *args],
+ cwd=str(repo),
+ capture_output=True,
+ text=True,
+ check=True,
+ env=env,
+ )
+ return out.stdout.strip()
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "checkout"
+ root.mkdir()
+ _git(root, "init", "-q")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "t")
+ (root / "kept.py").write_text("original\n", encoding="utf-8")
+ (root / "moved.py").write_text("original\n", encoding="utf-8")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-q", "-m", "birth", when=_BIRTH_TIME)
+ return root
+
+
+def _touch_and_commit(repo: Path, name: str, when: datetime = _LATER_TIME) -> None:
+ (repo / name).write_text("changed\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", f"touch {name}", when=when)
+
+
+# -- the primitive -----------------------------------------------------------
+
+
+def test_counts_commits_since_a_birth_commit_scoped_to_nodes(repo: Path) -> None:
+ birth = _git(repo, "rev-parse", "HEAD")
+ _touch_and_commit(repo, "moved.py")
+
+ assert commits_since(repo, since_commit=birth, nodes=["moved.py"]) == 1
+ assert commits_since(repo, since_commit=birth, nodes=["kept.py"]) == 0
+
+
+def test_counts_commits_since_a_date(repo: Path) -> None:
+ """Decision records have a created_at and no birth commit column."""
+ _touch_and_commit(repo, "moved.py")
+
+ assert commits_since(repo, since_date=_BETWEEN, nodes=["moved.py"]) == 1
+ assert commits_since(repo, since_date=_BETWEEN, nodes=["kept.py"]) == 0
+ # A record born before the checkout's first commit sees all of it.
+ assert commits_since(repo, since_date=_BIRTH_TIME - timedelta(days=1), nodes=["moved.py"]) == 2
+
+
+def test_every_failure_mode_returns_none_rather_than_a_partial_count(
+ repo: Path, tmp_path: Path
+) -> None:
+ birth = _git(repo, "rev-parse", "HEAD")
+
+ assert commits_since(repo, since_commit="not-a-ref", nodes=["kept.py"]) is None
+ assert commits_since(tmp_path / "nowhere", since_commit=birth) is None
+ # Neither anchor given: nothing to measure from.
+ assert commits_since(repo, nodes=["kept.py"]) is None
+
+
+# -- the decision-facing sentence --------------------------------------------
+
+
+def test_untouched_scope_reads_as_still_holding(repo: Path) -> None:
+ _touch_and_commit(repo, "moved.py")
+
+ sentence = describe_decision_currency(repo, created_at=_BETWEEN, nodes=["kept.py"])
+
+ assert sentence is not None
+ assert "nothing in the file it governs has changed" in sentence
+
+
+def test_changed_scope_says_so_with_a_count(repo: Path) -> None:
+ _touch_and_commit(repo, "moved.py")
+
+ sentence = describe_decision_currency(
+ repo, created_at=_BETWEEN, nodes=["moved.py", "kept.py"]
+ )
+
+ assert sentence is not None
+ assert "the 2 files it governs changed in 1 commit since" in sentence
+
+
+def test_unscoped_record_says_it_cannot_be_checked(repo: Path) -> None:
+ """The half a 0.0 score cannot express: never checkable, not checked-and-fresh."""
+ sentence = describe_decision_currency(repo, created_at=datetime.now(UTC), nodes=[])
+
+ assert sentence == "not bound to any file, so whether it still holds cannot be checked"
+
+
+def test_silence_when_git_cannot_decide(tmp_path: Path) -> None:
+ sentence = describe_decision_currency(
+ tmp_path / "not-a-repo", created_at=datetime.now(UTC), nodes=["a.py"]
+ )
+
+ assert sentence is None
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 4ab134859..80defb7da 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -385,6 +385,45 @@ async def test_get_why_path_caps_records_and_keeps_the_active_one_first(session,
assert result["alignment"]["governing_count"] == 31
+async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, monkeypatch):
+ """The sanctioned read-time query is one call, not one per governing record.
+
+ Measured at ~66 ms against this repo, so eight of them would be ~530 ms on
+ a path that also does everything else. The record ranked first is the one
+ a reader acts on; the rest keep the stored proportion, which cost nothing.
+ """
+ from repowise.server.mcp_server import get_why, tool_why
+
+ calls: list[tuple] = []
+
+ def _fake(root, *, created_at, nodes):
+ calls.append((root, tuple(nodes)))
+ return "nothing in the 1 file it governs has changed since 2026-01-01"
+
+ monkeypatch.setattr(tool_why, "describe_decision_currency", _fake)
+ await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)
+
+ result = await get_why("src/auth/service.py")
+
+ assert len(calls) == 1
+ assert "still_true" in result["decisions"][0]
+ assert all("still_true" not in d for d in result["decisions"][1:])
+
+
+async def test_get_why_stays_silent_when_git_cannot_decide(session, setup_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_why, tool_why
+
+ monkeypatch.setattr(
+ tool_why, "describe_decision_currency", lambda root, **kw: None
+ )
+
+ result = await get_why("src/auth/service.py")
+
+ assert all("still_true" not in d for d in result["decisions"])
+
+
@pytest.mark.asyncio
async def test_get_why_path_projects_wide_affected_files(session, setup_mcp):
from repowise.server.mcp_server import get_why
diff --git a/tests/unit/sessions/test_injection_feedback.py b/tests/unit/sessions/test_injection_feedback.py
index d23327410..7fd7d2751 100644
--- a/tests/unit/sessions/test_injection_feedback.py
+++ b/tests/unit/sessions/test_injection_feedback.py
@@ -94,15 +94,21 @@ async def test_uncontradicted_injection_counts_as_followed(session, tmp_path):
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
assert summary == {"followed": 1, "contradicted": 0}
+ # The verdict lands on the injection ledger and nowhere else. It used to
+ # also relax the record's staleness, which is now a measured fact about
+ # whether the governed files moved — a per-machine session verdict may not
+ # overwrite a value the dashboard and hosted both read.
rec = await session.get(DecisionRecord, "d1")
- assert rec.staleness_score == pytest.approx(0.2)
+ assert rec.staleness_score == pytest.approx(0.5)
# Judged once: a second pass finds nothing unevaluated.
again = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
assert again == {"followed": 0, "contradicted": 0}
-async def test_contradicting_correction_bumps_staleness(session, tmp_path):
+async def test_contradicting_correction_is_recorded_without_touching_staleness(
+ session, tmp_path
+):
session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
await _add_decision(session, "d1", staleness=0.1)
_record_injection(tmp_path, "sess-1", "d1", _OLD_ENOUGH)
@@ -113,8 +119,10 @@ async def test_contradicting_correction_bumps_staleness(session, tmp_path):
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
assert summary == {"followed": 0, "contradicted": 1}
+ # Contradiction is a judgement about the record; staleness is a fact about
+ # the code. The first no longer writes the second.
rec = await session.get(DecisionRecord, "d1")
- assert rec.staleness_score == pytest.approx(0.6)
+ assert rec.staleness_score == pytest.approx(0.1)
async def test_unrelated_correction_still_counts_as_followed(session, tmp_path):