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): read a decision whose files are all gone at HEAD as stale (#2694)

Swati Ahuja7a22a3096152
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 3474313ac..6851568e1 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1121,6 +1121,14 @@ async def _persist_full_update_async(
await apply_revert_supersession(session, repo_id, repo_path)
except Exception as exc:
_skip("Revert supersession", exc)
+ try:
+ from repowise.core.analysis.decisions.head_artifacts import (
+ apply_head_artifact_check,
+ )
+
+ await apply_head_artifact_check(session, repo_id, repo_path)
+ except Exception as exc:
+ _skip("Decision HEAD artifact check", exc)
# Governance findings pass: runs after decisions + staleness.
if timings is not None:
diff --git a/packages/core/alembic/versions/0090_decision_artifacts_gone.py b/packages/core/alembic/versions/0090_decision_artifacts_gone.py
new file mode 100644
index 000000000..04e7d64a3
--- /dev/null
+++ b/packages/core/alembic/versions/0090_decision_artifacts_gone.py
@@ -0,0 +1,34 @@
+"""decision_records: mark a record whose named files are all gone at HEAD.
+
+Local SQLite stores never run Alembic (``init_db``'s reconciler adds missing
+columns), so this migration exists for managed Postgres. Existing rows have
+not been checked yet, hence ``false``; the next index fills it.
+
+Revision ID: 0090
+Revises: 0089
+Create Date: 2026-09-30
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0090"
+down_revision: str | None = "0089"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "decision_records",
+ sa.Column("artifacts_gone", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("decision_records", "artifacts_gone")
diff --git a/packages/core/src/repowise/core/analysis/decisions/head_artifacts.py b/packages/core/src/repowise/core/analysis/decisions/head_artifacts.py
new file mode 100644
index 000000000..abb8ada12
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/head_artifacts.py
@@ -0,0 +1,171 @@
+"""Mark a decision whose named files are all gone at HEAD, so it reads as stale.
+
+A decision naming only code that no longer exists describes history, not the
+repository. This checks every affected file and every backticked path in the
+record's text against the tree at HEAD, after following renames through
+:class:`~repowise.core.ingestion.git_indexer.RenameTrail`. Only when *all* of
+them are absent is ``artifacts_gone`` set, which :func:`.lifecycle.effective_currency`
+reads as ``stale``. It never retires the record: nothing replaced it.
+
+Anything the check cannot judge counts as present: an absolute path, a file
+git does not track but the working tree holds, a module split into a package
+of the same name, or a shallow clone (a rename below the clone's window would
+look like a deletion; ceiling: judging only records whose evidence commits
+are inside the window would lift it).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from collections.abc import Iterable
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.analysis.decisions.reverts import _git_out
+from repowise.core.analysis.doc_drift.extractor import extract
+from repowise.core.analysis.doc_drift.models import DriftKind
+from repowise.core.analysis.doc_drift.resolver import RepoIndex
+from repowise.core.git_refs import is_shallow, tracked_paths_at
+from repowise.core.ingestion.git_indexer.records import RenameTrail, name_status_path
+
+logger = structlog.get_logger(__name__)
+
+__all__ = ["HeadTree", "apply_head_artifact_check", "artifact_paths"]
+
+_TEXT_FIELDS = ("title", "context", "decision", "rationale")
+
+
+def artifact_paths(rec: Any) -> list[str]:
+ """The files *rec* names plus the backticked paths in its text, deduplicated."""
+ try:
+ files = [str(p) for p in json.loads(rec.affected_files_json or "[]") if p]
+ except ValueError:
+ files = []
+ text = "\n".join(getattr(rec, f, "") or "" for f in _TEXT_FIELDS)
+ tokens = [r.target for r in extract(text, "") if r.kind == DriftKind.PATH]
+ return list(dict.fromkeys(p.strip().replace("\\", "/") for p in files + tokens if p.strip()))
+
+
+class HeadTree:
+ """The tracked tree at HEAD, with every rename in history followed forward."""
+
+ def __init__(
+ self,
+ tracked: Iterable[str],
+ renames: Iterable[tuple[str, str]] = (),
+ root: Path | None = None,
+ ) -> None:
+ self._index = RepoIndex.build(frozenset(tracked), {})
+ self._root = root
+ self._trail = RenameTrail()
+ self._moved_from: list[str] = []
+ # Newest first, as RenameTrail expects.
+ for old, new in renames:
+ self._trail.record(old, new)
+ self._moved_from.append(old)
+
+ def _here(self, path: str) -> bool:
+ return path in self._index.files or path in self._index.dirs
+
+ def present(self, path: str) -> bool:
+ """Whether *path* (or what it was renamed to) exists at HEAD."""
+ if _absolute(path) or not path.strip("/"):
+ return True # not repo-relative, so not ours to call missing
+ path = path.strip("/")
+ return self._tracked(path) or self._on_disk(path) or self._moved(path)
+
+ def _tracked(self, path: str) -> bool:
+ if self._here(path) or self._here(self._trail.resolve(path)):
+ return True
+ # A bare file name that still exists somewhere.
+ return "/" not in path and path in self._index.by_basename
+
+ def _on_disk(self, path: str) -> bool:
+ # Untracked but in the working tree: git's silence is not a deletion.
+ return self._root is not None and os.path.exists(self._root / path)
+
+ def _moved(self, path: str) -> bool:
+ stem, dot, _ = path.rpartition(".")
+ if dot and "/" not in path[len(stem) :] and stem in self._index.dirs:
+ return True # a module split into a package of the same name
+ prefix = f"{path}/"
+ # A directory whose files were all moved elsewhere.
+ return any(
+ old.startswith(prefix) and self._here(self._trail.resolve(old))
+ for old in self._moved_from
+ )
+
+ def all_gone(self, paths: list[str]) -> bool:
+ return bool(paths) and not any(self.present(p) for p in paths)
+
+
+def _absolute(path: str) -> bool:
+ return path.startswith("/") or (len(path) > 1 and path[1] == ":")
+
+
+def _history_renames(repo_path: str) -> list[tuple[str, str]] | None:
+ """``(old, new)`` for every rename reachable from HEAD, newest first; None on failure."""
+ out = _git_out(
+ repo_path,
+ "log",
+ "-M",
+ "--diff-filter=R",
+ "--name-status",
+ "--relative",
+ "--format=",
+ "HEAD",
+ )
+ if out is None:
+ return None
+ pairs = []
+ for line in out.splitlines():
+ new, old = name_status_path(line)
+ if old:
+ pairs.append((old, new))
+ return pairs
+
+
+def _head_tree(root: Path, paths: Iterable[list[str]]) -> HeadTree | None:
+ """The tree to judge against, or None when git cannot answer in full."""
+ tracked = tracked_paths_at(str(root), "HEAD") # the commit, not the index
+ if not tracked:
+ return None # an empty tree would flag everything
+ tree = HeadTree(tracked, root=root)
+ # The history walk is paid only when something is missing before renames.
+ if not any(tree.all_gone(p) for p in paths):
+ return tree
+ renames = _history_renames(str(root))
+ # Without renames a moved file would read as deleted.
+ return None if renames is None else HeadTree(tracked, renames, root)
+
+
+async def apply_head_artifact_check(
+ session: Any, repository_id: str, repo_path: Path | str | None
+) -> dict[str, int]:
+ """Set ``artifacts_gone`` on every record in *repository_id*. Idempotent."""
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import DecisionRecord
+
+ result = {"gone": 0, "back": 0}
+ if not repo_path or not Path(repo_path).exists() or is_shallow(str(repo_path)):
+ return result
+ query = select(DecisionRecord).where(DecisionRecord.repository_id == repository_id)
+ records = list((await session.execute(query)).scalars().all())
+ paths = {rec.id: artifact_paths(rec) for rec in records}
+ tree = _head_tree(Path(repo_path), paths.values())
+ if tree is None:
+ return result
+
+ for rec in records:
+ gone = tree.all_gone(paths[rec.id])
+ if gone != bool(rec.artifacts_gone):
+ rec.artifacts_gone = gone
+ result["gone" if gone else "back"] += 1
+ if any(result.values()):
+ await session.flush()
+ logger.info("decisions.head_artifacts", **result)
+ return result
diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
index c48bff253..29f49f767 100644
--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
@@ -29,6 +29,7 @@ __all__ = [
"DECISION_KINDS",
"DECISION_STATUS_ORDER",
"GRANTING_ACTIONS",
+ "HISTORY_CURRENCIES",
"NEEDS_REVIEW_STALENESS",
"REVIEW_LANES",
"SPLIT_MARKERS",
@@ -77,6 +78,7 @@ DECISION_CURRENCIES: tuple[str, ...] = (
"active", # accepted and still describes the code
"needs_review", # accepted, but the code it names has moved
"uncheckable", # accepted, but names nothing the repository can be asked about
+ "stale", # accepted, but nothing it names exists at HEAD any more
"superseded", # replaced by a later decision, via an explicit lineage edge
"dismissed", # authority withdrawn; kept for history
)
@@ -115,8 +117,8 @@ def bundles_decisions(text: str) -> bool:
return any(marker in low for marker in SPLIT_MARKERS)
-#: The currencies a person or artifact can *set*. ``needs_review`` and
-#: ``uncheckable`` are also derived from the code by :func:`effective_currency`,
+#: The currencies a person or artifact can *set*. ``needs_review``,
+#: ``uncheckable`` and ``stale`` are also derived from the code by :func:`effective_currency`,
#: which is why the stored set is smaller than the vocabulary.
STORED_CURRENCIES: tuple[str, ...] = (
"active",
@@ -148,9 +150,9 @@ def status_rank(status: str) -> int:
#: The review lanes, which partition a repository: every record is in exactly
#: one, and the five sum to the total. ``candidates`` is the absence of an
-#: acceptance; the other four are the currencies, with ``superseded`` and
-#: ``dismissed`` folded into ``history`` because a reader working a queue does
-#: not need those apart. ``governing`` is deliberately not here: it is the
+#: acceptance; the other four are the currencies, with ``superseded``,
+#: ``dismissed`` and ``stale`` folded into ``history`` because a reader working
+#: a queue does not need those apart. ``governing`` is deliberately not here: it is the
#: roll-up of ``active`` and ``needs_review``, so it overlaps two lanes and
#: belongs in a filter rather than in a tab row.
REVIEW_LANES: tuple[str, ...] = (
@@ -161,6 +163,9 @@ REVIEW_LANES: tuple[str, ...] = (
"history",
)
+#: The currencies the ``history`` lane holds: none of them binds new work.
+HISTORY_CURRENCIES: frozenset[str] = frozenset({"superseded", "dismissed", "stale"})
+
#: What an acceptance row records having happened.
ACCEPTANCE_ACTIONS: tuple[str, ...] = (
"accepted",
@@ -269,6 +274,7 @@ def effective_currency(
has_scope: bool,
staleness: float,
repo_wide: bool = False,
+ artifacts_gone: bool = False,
) -> str:
"""The currency to show for a decision stored at *stored*.
@@ -281,6 +287,10 @@ def effective_currency(
no file, which makes ``uncheckable`` a complaint about it being what it is,
and it has no files that can move, which makes ``needs_review`` a reading of
a staleness score measured over nothing.
+
+ *artifacts_gone* says every file and path the record names is absent at
+ HEAD, renames followed: it describes code that no longer exists, so it is
+ ``stale`` history. Never ``superseded``, which needs a successor.
"""
if stored != "active":
return stored if stored in DECISION_CURRENCIES else "active"
@@ -288,6 +298,8 @@ def effective_currency(
return "active"
if not has_scope:
return "uncheckable"
+ if artifacts_gone:
+ return "stale"
if staleness >= NEEDS_REVIEW_STALENESS:
return "needs_review"
return "active"
@@ -452,6 +464,7 @@ _CURRENCY_TO_LEGACY: dict[str, str] = {
"active": "active",
"needs_review": "active",
"uncheckable": "active",
+ "stale": "active",
"superseded": "superseded",
"dismissed": "deprecated",
}
diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.py
index b078ea7ae..870ee500c 100644
--- a/packages/core/src/repowise/core/persistence/crud/authority.py
+++ b/packages/core/src/repowise/core/persistence/crud/authority.py
@@ -30,6 +30,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.lifecycle import (
ACCEPTANCE_ACTIONS,
ACCEPTER_SESSION_MAX,
+ HISTORY_CURRENCIES,
NO_SCOPE_BLOCKER,
STORED_CURRENCIES,
AcceptanceRequirement,
@@ -179,18 +180,48 @@ async def accepted_decision_ids(
) -> set[str]:
"""Ids of every accepted decision in *repository_id*.
- With *governing_only*, drops the ones whose authority has been withdrawn
- (``superseded``, ``dismissed``) so the caller is left with what still binds.
+ With *governing_only*, drops the ones in the history lane (withdrawn, or
+ naming only files gone at HEAD) so the caller is left with what still binds.
The subquery picks the highest ``seq`` per decision, which is the append-only
log's way of saying "current".
"""
- q = select(DecisionAcceptance.decision_id, DecisionAcceptance.currency).join(
- *_latest_acceptance_join(repository_id)
- )
- rows = (await session.execute(q)).all()
if not governing_only:
- return {did for did, _ in rows}
- return {did for did, currency in rows if currency not in ("superseded", "dismissed")}
+ q = select(DecisionAcceptance.decision_id).join(*_latest_acceptance_join(repository_id))
+ return set((await session.execute(q)).scalars().all())
+ q = (
+ select(DecisionAcceptance.decision_id, DecisionAcceptance.currency, *_CURRENCY_COLUMNS)
+ .join(*_latest_acceptance_join(repository_id))
+ .join(DecisionRecord, DecisionRecord.id == DecisionAcceptance.decision_id)
+ )
+ return {
+ did
+ for did, stored, *cols in (await session.execute(q)).all()
+ if _row_currency(stored, *cols) not in HISTORY_CURRENCIES
+ }
+
+
+#: The record columns :func:`effective_currency` reads, for queries that skip the ORM row.
+_CURRENCY_COLUMNS = (
+ DecisionRecord.affected_files_json,
+ DecisionRecord.affected_modules_json,
+ DecisionRecord.staleness_score,
+ DecisionRecord.kind,
+ DecisionRecord.artifacts_gone,
+)
+
+
+def _row_currency(
+ stored: str, files_json: Any, modules_json: Any, staleness: Any, kind: Any, gone: Any
+) -> str:
+ """:func:`effective_currency` over the :data:`_CURRENCY_COLUMNS` of one record."""
+ fields = {"affected_files": files_json, "affected_modules": modules_json, "kind": kind}
+ return effective_currency(
+ stored,
+ has_scope=bool(record_scope(fields)),
+ staleness=staleness or 0.0,
+ repo_wide=is_repo_wide(fields),
+ artifacts_gone=bool(gone),
+ )
async def decision_currencies(
@@ -221,15 +252,15 @@ async def decision_currencies(
currency = stored.get(record.id)
if currency is None:
continue
- out[record.id] = effective_currency(
- currency,
- has_scope=bool(_record_scope(record)),
- staleness=record.staleness_score,
- repo_wide=_is_repo_wide(record),
- )
+ out[record.id] = _record_currency(currency, record)
return out
+def _record_currency(stored: str, record: DecisionRecord) -> str:
+ """:func:`effective_currency` for an ORM *record* stored at *stored*."""
+ return _row_currency(stored, *(getattr(record, c.key) for c in _CURRENCY_COLUMNS))
+
+
def _latest_acceptance_join(repository_id: str) -> tuple[Any, Any]:
"""Target and ON clause restricting a query to each decision's current row."""
latest_seq = (
@@ -308,13 +339,7 @@ async def count_decisions_by_lane(
"""
rows = (
await session.execute(
- select(
- DecisionRecord.id,
- DecisionRecord.affected_files_json,
- DecisionRecord.affected_modules_json,
- DecisionRecord.staleness_score,
- DecisionRecord.kind,
- ).where(
+ select(DecisionRecord.id, *_CURRENCY_COLUMNS).where(
DecisionRecord.repository_id == repository_id,
# Tombstoned candidates are excluded; a decision that was
# accepted and then withdrawn is not, because it is history
@@ -361,23 +386,13 @@ async def count_decisions_by_lane(
"governing": 0,
"total": len(rows),
}
- for did, files_json, modules_json, staleness, kind in rows:
+ for did, *cols in rows:
acceptance = stored.get(did)
if acceptance is None:
counts["candidates"] += 1
continue
- fields = {
- "affected_files": files_json,
- "affected_modules": modules_json,
- "kind": kind,
- }
- currency = effective_currency(
- acceptance,
- has_scope=bool(record_scope(fields)),
- staleness=staleness or 0.0,
- repo_wide=is_repo_wide(fields),
- )
- counts["history" if currency in ("superseded", "dismissed") else currency] += 1
+ currency = _row_currency(acceptance, *cols)
+ counts["history" if currency in HISTORY_CURRENCIES else currency] += 1
if is_governing(currency):
counts["governing"] += 1
return counts
@@ -388,13 +403,7 @@ async def current_currency(session: AsyncSession, record: DecisionRecord) -> str
acceptance = await latest_acceptance(session, record.id)
if acceptance is None:
return None
- has_scope = bool(_record_scope(record))
- return effective_currency(
- acceptance.currency,
- has_scope=has_scope,
- staleness=record.staleness_score,
- repo_wide=_is_repo_wide(record),
- )
+ return _record_currency(acceptance.currency, record)
async def resolve_decision_id(session: AsyncSession, decision_id: str) -> str | None:
diff --git a/packages/core/src/repowise/core/persistence/crud/decision_health.py b/packages/core/src/repowise/core/persistence/crud/decision_health.py
index f789c698b..0a7168005 100644
--- a/packages/core/src/repowise/core/persistence/crud/decision_health.py
+++ b/packages/core/src/repowise/core/persistence/crud/decision_health.py
@@ -8,7 +8,7 @@ from dataclasses import dataclass, field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.decisions.lifecycle import status_rank
+from repowise.core.analysis.decisions.lifecycle import HISTORY_CURRENCIES, status_rank
from repowise.core.analysis.decisions.scope import binds_to_paths
from ..models import DecisionRecord, GitMetadata
@@ -84,6 +84,8 @@ class _Lanes:
# identically to a record whose code genuinely has not moved, so
# they are counted separately rather than banked as fresh.
"unscoped": 0,
+ # Accepted records whose named files are all gone at HEAD.
+ "historical": 0,
}
)
stale: list[DecisionRecord] = field(default_factory=list)
@@ -113,8 +115,9 @@ class _Lanes:
self.counts["proposed"] += 1
self.proposed.append(d)
return
- if currency in ("superseded", "dismissed"):
- self.counts[currency] += 1
+ if currency in HISTORY_CURRENCIES:
+ # ``stale`` counts apart: that key already means needs_review here.
+ self.counts["historical" if currency == "stale" else currency] += 1
self.retired.append((currency, d))
return
self.counts["active"] += 1
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 0b5ecedb8..887ea0a27 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1141,6 +1141,8 @@ class DecisionRecord(Base):
DateTime(timezone=True), nullable=True
)
staleness_score: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
+ # Every file and path the record names is absent at HEAD, renames followed.
+ artifacts_gone: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=false())
superseded_by: Mapped[str | None] = mapped_column(String(32), nullable=True)
created_at: Mapped[datetime] = mapped_column(
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 683e356d2..428223fad 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -2136,6 +2136,12 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
await apply_revert_supersession(session, repo_id, getattr(result, "repo_path", None))
except Exception as _revert_err:
logger.debug("revert_supersession_skipped", error=str(_revert_err))
+ try:
+ from repowise.core.analysis.decisions.head_artifacts import apply_head_artifact_check
+
+ await apply_head_artifact_check(session, repo_id, getattr(result, "repo_path", None))
+ except Exception as _artifact_err:
+ logger.debug("head_artifact_check_skipped", error=str(_artifact_err))
# ---- Governance findings (additive pass, after decisions are persisted) ----
# Runs after bulk_upsert_decisions + detect_supersessions_and_conflicts so
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 8f158c2bb..5d5dbf15b 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -12,7 +12,7 @@ from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.decisions.lifecycle import is_governing
+from repowise.core.analysis.decisions.lifecycle import HISTORY_CURRENCIES, is_governing
from repowise.core.analysis.decisions.scope import binds_to_paths
from repowise.core.persistence.models import (
Repository,
@@ -520,7 +520,8 @@ def _alignment_score(
else ""
)
return "low", (
- "Every accepted decision here is deprecated/superseded. "
+ "Every accepted decision here is deprecated/superseded, or names only "
+ "files that no longer exist. "
"This file likely contains technical debt that should be migrated." + trailer
)
if candidates:
@@ -570,7 +571,7 @@ def _compute_alignment(
deprecated = [
d
for d in governing
- if currencies.get(d["id"]) in ("superseded", "dismissed")
+ if currencies.get(d["id"]) in HISTORY_CURRENCIES
]
# Repository-wide, not scoped to the matched records: the sibling
# denominator is drawn from decisions naming *other* files in the same
@@ -609,7 +610,8 @@ def _compute_alignment(
"governing_count": len(governing),
"active_count": len(accepted),
"candidate_count": len(candidates),
- # Accepted once and withdrawn since, whether superseded or dismissed.
+ # Accepted once and now history: superseded, dismissed, or naming only
+ # files gone at HEAD.
"deprecated_count": len(deprecated),
"uncheckable_count": len(uncheckable),
"stale_count": len(stale),
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 2871639c9..d4fa6f76d 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -13,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.lifecycle import (
AGREEMENT_KIND,
ARCHITECTURAL_KIND,
+ HISTORY_CURRENCIES,
is_governing,
)
from repowise.core.persistence import crud, decision_graph
@@ -82,7 +83,7 @@ def _in_lane(currency: str | None, lane: str) -> bool:
if lane == "governing":
return currency is not None and is_governing(currency)
if lane == "history":
- return currency in ("superseded", "dismissed")
+ return currency in HISTORY_CURRENCIES
return currency == lane
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index e2fd4c5a9..8e88bddd3 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -164,6 +164,7 @@ export const DECISION_CURRENCIES = [
"active",
"needs_review",
"uncheckable",
+ "stale",
"superseded",
"dismissed",
] as const;
@@ -182,6 +183,7 @@ export const DECISION_CURRENCY_LABELS: Record<DecisionCurrency, string> = {
active: "Active",
needs_review: "Needs review",
uncheckable: "Uncheckable",
+ stale: "Stale",
superseded: "Superseded",
dismissed: "Dismissed",
};
@@ -192,6 +194,7 @@ export const DECISION_CURRENCY_DESCRIPTIONS: Record<DecisionCurrency, string> =
needs_review: "Accepted, but the code it names has moved since.",
uncheckable:
"Accepted, but it names no file or module, so nothing checks it against the code.",
+ stale: "Accepted, but nothing it names exists in the code any more.",
superseded: "Replaced by a later decision.",
dismissed: "Authority withdrawn. Kept for history.",
};
diff --git a/packages/ui/src/decisions/decision-review-lanes.tsx b/packages/ui/src/decisions/decision-review-lanes.tsx
index 89978d3cf..fae29b7ed 100644
--- a/packages/ui/src/decisions/decision-review-lanes.tsx
+++ b/packages/ui/src/decisions/decision-review-lanes.tsx
@@ -78,7 +78,7 @@ const LANE_DESCRIPTION: Record<DecisionLane, string> = {
uncheckable:
"Accepted decisions that name no file or module. Nothing can check them against the code and no agent editing a file will be given one. Add the paths they govern and they move to Active.",
history:
- "Decisions that were accepted and then withdrawn, superseded or dismissed. Kept so the record of what changed survives.",
+ "Decisions that were accepted and then withdrawn, superseded or dismissed, or whose files no longer exist. Kept so the record of what changed survives.",
};
/** An empty lane says what will fill it and what the reader can do next. */
diff --git a/tests/fixtures/decision_vocabulary.json b/tests/fixtures/decision_vocabulary.json
index a4f334d34..763451478 100644
--- a/tests/fixtures/decision_vocabulary.json
+++ b/tests/fixtures/decision_vocabulary.json
@@ -28,6 +28,7 @@
"active",
"needs_review",
"uncheckable",
+ "stale",
"superseded",
"dismissed"
],
diff --git a/tests/unit/analysis/test_decision_vocabulary_contract.py b/tests/unit/analysis/test_decision_vocabulary_contract.py
index 5f98b36ac..bcb169ac1 100644
--- a/tests/unit/analysis/test_decision_vocabulary_contract.py
+++ b/tests/unit/analysis/test_decision_vocabulary_contract.py
@@ -97,10 +97,9 @@ def test_review_lanes_match_lifecycle() -> None:
def test_review_lanes_are_the_currencies_plus_candidates() -> None:
"""The five partition a repository, so they must cover the vocabulary."""
lanes = set(_FIXTURE["review_lanes"])
- assert lanes == (set(_FIXTURE["currencies"]) | {"candidates"}) - {
- "superseded",
- "dismissed",
- } | {"history"}
+ assert lanes == (set(_FIXTURE["currencies"]) | {"candidates"}) - set(
+ lifecycle.HISTORY_CURRENCIES
+ ) | {"history"}
def test_the_acceptance_blocker_sentences_are_stable() -> None:
diff --git a/tests/unit/persistence/test_decision_head_artifacts.py b/tests/unit/persistence/test_decision_head_artifacts.py
new file mode 100644
index 000000000..69ae5766c
--- /dev/null
+++ b/tests/unit/persistence/test_decision_head_artifacts.py
@@ -0,0 +1,236 @@
+"""A decision whose named files are all gone at HEAD reads as stale history.
+
+Renames are followed, so a moved file is not missing; a deleted directory is.
+The record is never retired for this: its status and successor stay as they were.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.decisions.head_artifacts import (
+ HeadTree,
+ apply_head_artifact_check,
+ artifact_paths,
+)
+from repowise.core.analysis.decisions.lifecycle import effective_currency
+from repowise.core.persistence.crud.authority import (
+ count_decisions_by_lane,
+ current_currency,
+)
+from repowise.core.persistence.models import DecisionRecord
+from tests.unit.persistence.helpers import accept, insert_repo
+
+
+def _git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
+
+
+def _write(repo: Path, rel: str, text: str = "x = 1\n") -> None:
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+
+def repo_root(tmp_path: Path) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init", "-q", "-b", "main")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "T")
+ _git(repo, "config", "commit.gpgsign", "false")
+ for rel in (
+ "src/old_name.py",
+ "legacy/a.py",
+ "legacy/b.py",
+ "pkg/core.py",
+ "pkg/util.py",
+ "tools/why.py",
+ ):
+ _write(repo, rel, f"# {rel}\n" + "value = 1\n" * 20)
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "initial")
+ # A rename, then a second rename of the same file: the trail follows both.
+ _git(repo, "mv", "src/old_name.py", "src/mid_name.py")
+ _git(repo, "commit", "-q", "-m", "rename once")
+ (repo / "lib").mkdir()
+ _git(repo, "mv", "src/mid_name.py", "lib/new_name.py")
+ _git(repo, "commit", "-q", "-m", "rename twice")
+ # A whole directory deleted, and another moved.
+ _git(repo, "rm", "-q", "-r", "legacy")
+ _git(repo, "mv", "pkg", "core")
+ _git(repo, "commit", "-q", "-m", "drop legacy, move pkg")
+ # A module split into a package of the same name, too different to be a rename.
+ _git(repo, "rm", "-q", "tools/why.py")
+ _write(repo, "tools/why/__init__.py", "from .modes import run\n")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "split why into a package")
+ return repo
+
+
+async def _record(session, repo_id: str, title: str, files: list[str], **kw) -> DecisionRecord:
+ rec = DecisionRecord(
+ repository_id=repo_id,
+ title=title,
+ source="git_archaeology",
+ affected_files_json=json.dumps(files),
+ **kw,
+ )
+ session.add(rec)
+ await session.flush()
+ return rec
+
+
+def test_artifact_paths_reads_files_and_backticked_paths():
+ rec = DecisionRecord(
+ title="Use `src/app.py` for the entry point",
+ affected_files_json=json.dumps(["src/a.py"]),
+ decision="Keep config in `conf/settings.toml`, never in prose like and/or.",
+ rationale="",
+ context="",
+ )
+ assert artifact_paths(rec) == ["src/a.py", "src/app.py", "conf/settings.toml"]
+
+
+def test_head_tree_follows_renames_and_directory_moves():
+ tree = HeadTree(
+ ["lib/new.py", "core/x.py"],
+ [("src/mid.py", "lib/new.py"), ("src/old.py", "src/mid.py"), ("pkg/x.py", "core/x.py")],
+ )
+ assert tree.present("src/old.py")
+ assert tree.present("pkg") # every file moved, so the directory lives on
+ assert tree.present("new.py") # a bare name found anywhere
+ assert tree.present("core.py") # a module split into the package core/
+ assert tree.present("/abs/path.py") # not repo-relative, so not judged
+ assert not tree.present("legacy")
+ assert tree.all_gone(["legacy/a.py", "gone.py"])
+ assert not tree.all_gone(["legacy/a.py", "src/old.py"])
+ assert not tree.all_gone([])
+
+
+def test_stale_is_derived_only_for_an_active_scoped_record():
+ assert (
+ effective_currency("active", has_scope=True, staleness=1.0, artifacts_gone=True) == "stale"
+ )
+ assert effective_currency("active", has_scope=False, staleness=0.0, artifacts_gone=True) == (
+ "uncheckable"
+ )
+ # A currency a person set is not argued with.
+ assert (
+ effective_currency("superseded", has_scope=True, staleness=0.0, artifacts_gone=True)
+ == "superseded"
+ )
+
+
+async def test_renamed_file_is_not_missing_and_deleted_directory_is(async_session, repo_root):
+ repo = await insert_repo(async_session)
+ renamed = await _record(async_session, repo.id, "Entry point", ["src/old_name.py"])
+ deleted = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py", "legacy/b.py"])
+ # A path named only in the text counts too.
+ text_only = await _record(
+ async_session, repo.id, "Legacy text", [], decision="`legacy/b.py` stays sync."
+ )
+ moved_dir = await _record(async_session, repo.id, "Core pkg", ["pkg/core.py"])
+ mixed = await _record(async_session, repo.id, "Mixed", ["legacy/a.py", "pkg/util.py"])
+ split = await _record(async_session, repo.id, "Why module", ["tools/why.py"])
+ # Untracked but present in the working tree: not deleted.
+ _write(repo_root, "notes/local.md")
+ local = await _record(async_session, repo.id, "Local notes", ["notes/local.md"])
+ text_keeps = await _record(
+ async_session,
+ repo.id,
+ "Mentions a live file",
+ ["legacy/a.py"],
+ rationale="See `core/util.py` for the replacement.",
+ )
+ await async_session.flush()
+
+ result = await apply_head_artifact_check(async_session, repo.id, str(repo_root))
+
+ assert result == {"gone": 2, "back": 0}
+ assert deleted.artifacts_gone and text_only.artifacts_gone
+ for rec in (renamed, moved_dir, mixed, text_keeps, local, split):
+ assert not rec.artifacts_gone, rec.title
+ # Idempotent: a second pass changes nothing.
+ assert await apply_head_artifact_check(async_session, repo.id, str(repo_root)) == {
+ "gone": 0,
+ "back": 0,
+ }
+
+
+async def test_gone_decision_is_stale_history_never_superseded(async_session, repo_root):
+ repo = await insert_repo(async_session)
+ why = {"rationale": "Chosen deliberately.", "evidence_commits_json": '["abc1234"]'}
+ gone = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py"], **why)
+ live = await _record(async_session, repo.id, "Entry point", ["src/old_name.py"], **why)
+ await accept(async_session, gone.id)
+ await accept(async_session, live.id)
+
+ await apply_head_artifact_check(async_session, repo.id, str(repo_root))
+
+ assert await current_currency(async_session, gone) == "stale"
+ assert await current_currency(async_session, live) == "active"
+ assert gone.status == "active" and gone.superseded_by is None
+ lanes = await count_decisions_by_lane(async_session, repo.id)
+ assert lanes["history"] == 1 and lanes["active"] == 1 and lanes["governing"] == 1
+
+
+async def test_restored_file_clears_the_mark(async_session, repo_root):
+ repo = await insert_repo(async_session)
+ rec = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py"])
+ await apply_head_artifact_check(async_session, repo.id, str(repo_root))
+ assert rec.artifacts_gone
+
+ _write(repo_root, "legacy/a.py")
+ _git(repo_root, "add", "-A")
+ _git(repo_root, "commit", "-q", "-m", "bring legacy back")
+
+ assert await apply_head_artifact_check(async_session, repo.id, str(repo_root)) == {
+ "gone": 0,
+ "back": 1,
+ }
+ assert not rec.artifacts_gone
+
+
+async def test_staged_deletion_is_not_gone_until_committed(async_session, repo_root):
+ repo = await insert_repo(async_session)
+ rec = await _record(async_session, repo.id, "Core util", ["core/util.py"])
+ _git(repo_root, "rm", "-q", "core/util.py")
+
+ assert await apply_head_artifact_check(async_session, repo.id, str(repo_root)) == {
+ "gone": 0,
+ "back": 0,
+ }
+ assert not rec.artifacts_gone
+
+
+async def test_no_checkout_changes_nothing(async_session, tmp_path):
+ repo = await insert_repo(async_session)
+ rec = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py"])
+ assert await apply_head_artifact_check(async_session, repo.id, None) == {"gone": 0, "back": 0}
+ # A directory git cannot answer for is not an empty tree.
+ assert await apply_head_artifact_check(async_session, repo.id, str(tmp_path)) == {
+ "gone": 0,
+ "back": 0,
+ }
+ assert not rec.artifacts_gone
+
+
+async def test_failed_rename_walk_changes_nothing(async_session, repo_root, monkeypatch):
+ """Without renames a moved file would read as deleted, so nothing is judged."""
+ from repowise.core.analysis.decisions import head_artifacts
+
+ monkeypatch.setattr(head_artifacts, "_history_renames", lambda _root: None)
+ repo = await insert_repo(async_session)
+ rec = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py"])
+
+ assert await apply_head_artifact_check(async_session, repo.id, str(repo_root)) == {
+ "gone": 0,
+ "back": 0,
+ }
+ assert not rec.artifacts_gone
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 31211e4fa..11586ed14 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -712,3 +712,37 @@ def test_cross_references_match_whole_tokens_not_substrings():
assert [r["message"] for r in refs] == ["Invalidate auth cache on logout"]
assert refs[0]["matched_terms"] == ["auth", "cache"]
+
+
+async def test_get_why_targets_do_not_bind_a_record_whose_files_are_gone(session, setup_mcp):
+ """A record naming only files gone at HEAD is history, not a binding rule."""
+ import json
+
+ from repowise.core.persistence.crud.authority import accept_decision
+ from repowise.core.persistence.models import DecisionRecord
+ from repowise.server.mcp_server import get_why
+
+ path = "src/other/legacy.py"
+ records = [
+ DecisionRecord(
+ id=f"gone{flag}",
+ repository_id=setup_mcp,
+ title=f"Legacy rule {flag}",
+ rationale="why",
+ affected_files_json=json.dumps([path]),
+ source="pr",
+ artifacts_gone=flag,
+ )
+ for flag in (True, False)
+ ]
+ session.add_all(records)
+ await session.flush()
+ for record in records:
+ await accept_decision(session, record, accepter="test", evidence=["pr#1"])
+ await session.flush()
+
+ result = await get_why("why legacy", targets=[path])
+
+ governing = result["target_context"][path]["governing_decisions"]
+ assert [d["id"] for d in governing] == ["goneFalse"]