Skip to content

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

fix(decisions): stop retiring records on a similarity match, and bound get_why path mode (#1293)

Raghav Chamadiya081a59fa716b
diff --git a/README.md b/README.md
index 411c6897e..6512b5d85 100644
--- a/README.md
+++ b/README.md
@@ -111,7 +111,7 @@ queryable from the CLI, the MCP tools, and the local dashboard.
| **◈ Graph** | Dependency graph across 17 languages · file + symbol nodes · 3-tier call resolution · Leiden communities · PageRank and execution flows · framework-aware route→handler edges | A real graph most tools never build |
| **◈ Git** | Hotspots (churn × complexity) · ownership % · co-change pairs (hidden coupling) · bus factor · which files actually get bug-fixed, and how recently | Behavioural signals static analysis cannot see |
| **◈ Docs** | A generated wiki page per module and file · rebuilt incrementally every commit · freshness and confidence scoring · hybrid search (full-text + vector) · selectable style and output language | Stays current instead of rotting |
-| **◈ Decisions** | Architectural decisions mined from eight sources, evidence-backed, linked to the graph nodes they govern, connected by supersedes / refines / conflicts_with, tracked for staleness | **★ Captured nowhere else** |
+| **◈ Decisions** | Architectural decisions mined from eight sources, evidence-backed, linked to the graph nodes they govern, tracked for staleness | **★ Captured nowhere else** |
| **★ Code health** | **25 deterministic markers**, 1 to 10 per file · three signals: defect risk · maintainability · performance · coverage ingestion · concrete refactoring plans (Extract Class / Helper, Move Method, Break Cycle, Split File) · **zero LLM, under 30s** | **★ Defect-validated, with the fix attached** |
**The whole wiki is generated with no LLM, then upgraded to model-written prose on
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index c49b51dfc..212c26da4 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -129,17 +129,31 @@ Decisions are not a flat list. Typed edges connect them:
| Edge | Meaning |
|------|---------|
-| `supersedes` | The newer decision replaces the older one. Above 0.85 supersession confidence the older record auto-flips to `superseded`; below that it is recorded as a reviewable proposal instead. |
+| `supersedes` | The newer decision replaces the older one, and the older record flips to `superseded`. |
| `refines` | Narrows or extends a decision without reversing it. |
| `relates_to` | Same topic, no ordering claim. |
| `conflicts_with` | Two *active* decisions contradict each other. A governance smell, surfaced in `decision health` and in the code-health layer. |
-Detection is deterministic first. Two decisions have to share a topic (at least
+**Automatic detection of these two edges is currently off.** It scoped a
+conflict by embedding similarity: two decisions had to share a topic (at least
two shared content tokens after stopword removal) and then either straddle an
opposing verb pair (`adopt` / `use` / `introduce` against `drop` / `remove` /
`deprecate` / `revert`) or carry a reversal signal ("replace", "migrate",
-"switch to", "no longer", "in favor of"). An LLM tiebreaker only runs on the
-pairs the heuristic cannot call.
+"switch to", "no longer", "in favor of"), with an LLM tiebreaker on the pairs
+the heuristic could not call. In practice similarity does not scope: among
+descriptions drawn from one repository, a cosine of 0.81 is the baseline rather
+than evidence of a shared topic, so the check fired between unrelated records
+and retired records that were correct. It returns when a conflict is scoped
+structurally — by two decisions touching the same code — with similarity used
+only to rank the candidates that test finds.
+
+It was the only writer of these edges, so **no edges exist while it is off** and
+lineage is empty. Two things still work: the diff-driven evolution pass on
+`repowise update` marks a decision that a new commit reversed, and `repowise
+decision deprecate --superseded-by ID` records the successor on the record
+itself (the `superseded_by` column, not an edge). Records the detector retired
+before it was turned off are restored to `proposed` on the next `init` or
+`update`, and its edges are deleted in the same pass.
`supersedes` and `refines` chain into a **lineage**, so `get_why` can answer
"why is auth structured this way?" with `sessions -> JWT -> OAuth2` rather than
diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.md
index 2d226afe4..4668e8e70 100644
--- a/docs/layers/INTELLIGENCE_LAYERS.md
+++ b/docs/layers/INTELLIGENCE_LAYERS.md
@@ -126,9 +126,14 @@ sources raise confidence rather than overwrite each other.
Decisions form a **graph**: typed edges (`supersedes` / `refines` /
`relates_to` / `conflicts_with`) let `get_why()` answer *"why is auth structured
-this way?"* with a lineage chain (sessions -> JWT -> OAuth2), auto-detect when a
-new commit reverses an old decision, and flag two active decisions that
-contradict each other.
+this way?"* with a lineage chain (sessions -> JWT -> OAuth2). **No edges are
+written today**: the only detector that produced them scoped a conflict by
+similarity, which does not scope, so it is off and the edges it wrote have been
+removed (see `docs/layers/DECISIONS.md`). Lineage stays empty until a
+structural detector replaces it. Retirement itself still works — the
+diff-driven pass on `repowise update` marks a decision a new commit reversed,
+and `repowise decision deprecate --superseded-by` records the successor on the
+record.
These structured records surface everywhere your agent already looks:
`get_why()` for the full archaeology, governing decisions in `get_context()`, a
diff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.md
index bf975fb9f..25d5fbbf4 100644
--- a/docs/start/DASHBOARD.md
+++ b/docs/start/DASHBOARD.md
@@ -254,8 +254,10 @@ concentrated. Useful before a reorg, and before assuming a file has an owner.
**Answers:** why is this code shaped this way?
-Architectural decisions with their evidence drawer, supersession lineage, and a
-decision graph. Decisions are mined from history and PR discussion and can be
+Architectural decisions with their evidence drawer and a decision graph.
+(Supersession lineage renders empty for now — the detector that produced those
+edges is off, see `docs/layers/DECISIONS.md`.) Decisions are mined from history
+and PR discussion and can be
confirmed, edited, or added by hand. This is the view that keeps a "we already
tried that" answer from being lost.
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 e68ca6b42..3042061d3 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -583,13 +583,26 @@ async def _persist_full_update_async(
# Decision records: new markers + harvested decisions, supersession
# detection, staleness recompute.
try:
- # One-shot drain of proposals from the removed code_comment
- # harvest (#751). Confirmed/dismissed rows are kept.
+ # The same three store repairs the full-index path runs, in the
+ # same order (see ``pipeline/persist.py``). They live here too
+ # because a user whose workflow is ``repowise update`` never
+ # takes that path, and every one of them is a repair the store
+ # cannot make for itself: ``superseded`` and the retired-source
+ # backlog both survive re-extraction, and ``source_rank`` is a
+ # value copied into rows rather than derived on read.
+ from repowise.core.analysis.decision_provenance import RETIRED_SOURCES
from repowise.core.persistence.crud import (
purge_proposed_decisions_by_source,
+ reconcile_source_ranks,
+ unretire_auto_superseded,
)
- await purge_proposed_decisions_by_source(session, repo_id, "code_comment")
+ # Before the purge: restoring lands a row at ``proposed``,
+ # which is what the purge deletes.
+ await unretire_auto_superseded(session)
+ for _retired in RETIRED_SOURCES:
+ await purge_proposed_decisions_by_source(session, repo_id, _retired)
+ await reconcile_source_ranks(session)
decision_dicts: list[dict] = []
if new_decision_markers:
diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.py
index 8ef523b04..c58fd620b 100644
--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py
+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py
@@ -49,6 +49,7 @@ logger = structlog.get_logger(__name__)
__all__ = [
"EVOLUTION_SIGNALS",
"RELATED_TAU",
+ "SEMANTIC_SUPERSESSION_ENABLED",
"SUPERSEDE_AUTOFLIP_CONFIDENCE",
"contradicts",
"detect_supersessions_and_conflicts",
@@ -74,6 +75,26 @@ RELATED_TAU = 0.6
# by design — everything below stays a reviewable proposal.
SUPERSEDE_AUTOFLIP_CONFIDENCE = 0.85
+# 3B is OFF. It scoped a conflict by *similarity*, and similarity cannot scope:
+# in a corpus of same-repo PR descriptions cosine 0.81 is the baseline, not
+# topical agreement, so the contradiction heuristic fired between unrelated
+# records that merely shared two engineering tokens and a reversal verb. On this
+# repo it produced 267 edges (one record superseded by 18 others — real
+# supersession is a chain, 18-in is noise) and auto-retired 74 records, 25% of
+# the store, correct ones included.
+#
+# It stays as code rather than a deletion because the *shape* is right and
+# Phase 2 re-enables it structurally: a conflict must require intersecting node
+# sets — two records that touch the same code — and similarity may then rank
+# those candidates but never scope them. The 3B tests flip it to True to
+# exercise the machinery; flipping it in a real run does not work, because both
+# persist paths run ``unretire_auto_superseded`` ahead of the detector and the
+# next run reverts whatever the previous one wrote.
+#
+# ``run_update_evolution`` (3C) is a different mechanism — diff-driven, per
+# changed file, with an LLM verdict — and is not gated by this flag.
+SEMANTIC_SUPERSESSION_ENABLED = False
+
# ---------------------------------------------------------------------------
# Evolution signals (Pass-1 pattern scan) + contradiction heuristics
# ---------------------------------------------------------------------------
@@ -315,8 +336,14 @@ async def detect_supersessions_and_conflicts(
supplied, is a gated tiebreaker for pairs the heuristic misses.
Returns ``{"supersedes": n, "conflicts": n, "flipped": n}``.
+
+ No-op while :data:`SEMANTIC_SUPERSESSION_ENABLED` is False — see the note
+ on that constant. Gated here rather than at the two call sites so one
+ switch covers every caller, present and future.
"""
summary = {"supersedes": 0, "conflicts": 0, "flipped": 0}
+ if not SEMANTIC_SUPERSESSION_ENABLED:
+ return summary
if not touched_ids or vector_store is None:
return summary
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 52fc1361f..1208cbc2a 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -563,6 +563,104 @@ async def reconcile_source_ranks(session: AsyncSession) -> int:
return len(moved)
+#: Prefix ``detect_supersessions_and_conflicts`` stamps on every edge it writes
+#: (``auto-detected: <signal> (sim=0.81)``). It is the only marker that
+#: separates a machine retirement from a human one, so the repair below keys on
+#: it rather than on "has a supersedes edge".
+_AUTO_EDGE_EVIDENCE_PREFIX = "auto-detected:"
+
+
+async def unretire_auto_superseded(session: AsyncSession) -> int:
+ """Undo retirements made by the semantic supersession detector (3B).
+
+ That detector scoped a conflict by cosine similarity and matched unrelated
+ records; it is now off (``SEMANTIC_SUPERSESSION_ENABLED``). Turning it off
+ only stops the *next* bad retirement — the rows it already flipped stay
+ ``superseded``, which is a protected status, so re-extraction will never
+ walk one back and a store would go on reporting a quarter of its corpus as
+ retired-by-nothing. This is the other half of the same change.
+
+ A row is repaired only when all three hold: status ``superseded``,
+ ``superseded_by`` set, and an ``auto-detected:`` supersedes edge from that
+ same successor. ``run_update_evolution`` sets the status without the
+ pairing, the CLI's ``decision deprecate`` writes ``deprecated``, and
+ ``upsert_decision_edge`` has no caller outside 3B — so nothing else in the
+ codebase produces all three.
+
+ One case is knowingly in range: a human can set both fields through
+ ``PATCH /api/repos/{id}/decisions/{id}``, and if they did so by accepting
+ one of this detector's own proposals in the UI, the auto edge is still
+ there and the row is restored to ``proposed``. Accepted rather than
+ guarded: the retirement they confirmed rests on the same bad match as the
+ 74, ``proposed`` keeps the record readable, and ``decision confirm`` or the
+ same PATCH puts it back in one step. The inverse — leaving a wrongly
+ retired record hidden because a human once clicked through — is not
+ recoverable at all.
+
+ Restored to ``proposed``, not ``active``: the flip overwrote the previous
+ status without recording it, and 3B fired on both. ``proposed`` is the
+ lower claim of the two and is recoverable by ``decision confirm``; guessing
+ ``active`` would mint governance a human never granted.
+
+ The edges go too — both kinds it wrote. They are the same artifact from the
+ same detector: ``supersedes`` is what ``build_lineage_chain`` walks, so
+ leaving those would hand ``get_why`` a lineage that still presents the
+ un-retired record as replaced, and ``conflicts_with`` is what the health
+ dashboard counts as a governance smell.
+
+ Not repo-scoped, like ``reconcile_source_ranks``: a workspace store holds
+ several repositories and the detector ran over all of them.
+
+ Idempotent — once repaired the edges are gone, so the next scan matches
+ nothing. Returns the number of records restored.
+ """
+ auto_edges = (
+ (
+ await session.execute(
+ select(DecisionEdge).where(
+ DecisionEdge.kind.in_(("supersedes", "conflicts_with")),
+ DecisionEdge.evidence.startswith(_AUTO_EDGE_EVIDENCE_PREFIX),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ if not auto_edges:
+ return 0
+
+ successors_by_target: dict[str, set[str]] = {}
+ for edge in auto_edges:
+ if edge.kind == "supersedes":
+ successors_by_target.setdefault(edge.dst_decision_id, set()).add(edge.src_decision_id)
+
+ now = _now_utc()
+ restored = 0
+ for target_id, successor_ids in successors_by_target.items():
+ rec = await session.get(DecisionRecord, target_id)
+ if rec is None or rec.status != "superseded" or rec.superseded_by is None:
+ continue
+ if rec.superseded_by not in successor_ids:
+ # Retired by something else. Leave the *status* alone — the edge
+ # still goes, below, because it is this detector's noise either way.
+ continue
+ rec.status = "proposed"
+ rec.superseded_by = None
+ rec.updated_at = now
+ restored += 1
+
+ for edge in auto_edges:
+ await session.delete(edge)
+ await session.flush()
+
+ structlog.get_logger(__name__).info(
+ "decisions.auto_supersessions_reverted",
+ records_restored=restored,
+ edges_deleted=len(auto_edges),
+ )
+ return restored
+
+
async def list_decision_evidence(
session: AsyncSession,
decision_id: str,
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 112368293..25045e675 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1162,6 +1162,24 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
if harvested:
decision_dicts.extend(harvested)
+ # Restore records the semantic supersession detector retired before it was
+ # turned off. ``superseded`` is a protected status, so nothing else will
+ # ever walk these back, and a store that only stops retiring is still a
+ # store with a quarter of its corpus hidden. Runs whether or not this run
+ # produced decisions.
+ #
+ # BEFORE the purge below, not after: restoring puts a row back at
+ # ``proposed``, which is exactly what the purge deletes. Un-retire first and
+ # a run ends in one consistent state — good records visible, retired-source
+ # records gone. The other order leaves a restored changelog row alive for
+ # one run and silently deletes it on the next.
+ try:
+ from repowise.core.persistence.crud import unretire_auto_superseded
+
+ await unretire_auto_superseded(session)
+ except Exception as _unretire_err:
+ logger.debug("decision_unretire_skipped", error=str(_unretire_err))
+
# One-shot drain of proposals left by retired extraction sources; without
# this, DBs indexed before a removal keep a flooded review queue forever
# (#751 for code_comment). Confirmed/dismissed rows are kept.
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 8d7745251..0cc66499b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -17,6 +17,7 @@ from repowise.core.persistence.models import (
GitMetadata,
)
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
from repowise.server.mcp_server._helpers import (
_build_origin_story,
@@ -157,9 +158,53 @@ async def _why_health_dashboard(repo: str | None) -> dict:
}
+# --- Path-mode cap and projection -------------------------------------------
+#
+# Path mode used to return every governing record whole: on ``persist.py`` that
+# was 15 records inlining 241 file paths between them, plus an origin story
+# carrying full commit bodies — 81 854 chars, which the MCP host rejects
+# outright (see ``_budget.budgeter``: over the cap is an isError, not a
+# truncation). The mode that matters most, "what governs this file right before
+# I edit it", hard-failed on exactly the bug-magnet files it exists for.
+#
+# So: rank, project, then enforce. The caps below are the projection; the
+# budget pass after them is the guarantee, since no fixed cap can bound a
+# response whose fields are free text.
+
+#: Governing records kept, best-first. Past ~8 the tail is review-queue noise.
+_MAX_PATH_DECISIONS = 8
+
+#: Paths kept per record. The array answers "how wide is this decision", which
+#: a head plus a total answers as well as 241 paths do.
+_MAX_AFFECTED_FILES = 10
+
+#: Commit *bodies* are the weight in an origin story: the subject is already
+#: capped at 200 chars at ingest, but ``body`` is kept up to 1 KB per
+#: significant commit (``git_indexer/file_history.py``) and up to 10 of those
+#: ride along in ``key_commits``. An origin story reads the intent, not the
+#: whole message.
+_MAX_COMMIT_TEXT_CHARS = 320
+
+#: Headroom left under the budget for ``OmissionCollector.attach``, which adds
+#: ``omission_marker`` + ``_meta.omitted`` *after* the last size check.
+_COLLECTOR_HEADROOM_CHARS = 600
+
+#: Sort order for governing records: what governs beats what was proposed
+#: beats what is retired; then confidence; then freshness.
+_PATH_STATUS_ORDER = {"active": 0, "proposed": 1, "deprecated": 2, "superseded": 3}
+
+
+def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:
+ return (
+ _PATH_STATUS_ORDER.get(d.status, 4),
+ -(d.confidence or 0.0),
+ d.staleness_score or 0.0,
+ )
+
+
def _governing_decision_entry(d: Any, affected_files: list, lineage: list[dict]) -> dict:
"""Serialize a decision that governs a path, including its lineage chain."""
- return {
+ entry = {
"id": d.id,
"title": d.title,
"status": d.status,
@@ -168,12 +213,100 @@ def _governing_decision_entry(d: Any, affected_files: list, lineage: list[dict])
"rationale": d.rationale,
"alternatives": json.loads(d.alternatives_json),
"consequences": json.loads(d.consequences_json),
- "affected_files": affected_files,
+ "affected_files": affected_files[:_MAX_AFFECTED_FILES],
"source": d.source,
"confidence": d.confidence,
"staleness_score": d.staleness_score,
"lineage": lineage if len(lineage) > 1 else [],
}
+ if len(affected_files) > _MAX_AFFECTED_FILES:
+ entry["affected_files_total"] = len(affected_files)
+ return entry
+
+
+def _trim_commit_text(origin_story: dict) -> None:
+ """Cap commit prose in place, wherever the origin story inlines it.
+
+ ``message`` and ``body`` both, because which one carries the weight depends
+ on the repo: a squash-merge repo puts the whole rationale in ``body`` and
+ the ingest keeps it up to 1 KB, while ``message`` is already capped at 200.
+ Capping both means this does not quietly become a no-op if that changes.
+ """
+
+ def _trim(commits: Any) -> None:
+ if not isinstance(commits, list):
+ return
+ for c in commits:
+ if not isinstance(c, dict):
+ continue
+ for field in ("message", "body"):
+ text = c.get(field)
+ if isinstance(text, str) and len(text) > _MAX_COMMIT_TEXT_CHARS:
+ c[field] = text[:_MAX_COMMIT_TEXT_CHARS] + "…"
+
+ _trim(origin_story.get("key_commits"))
+ for linked in origin_story.get("linked_decisions") or []:
+ if isinstance(linked, dict):
+ _trim(linked.get("evidence_commits"))
+
+
+def _fit_path_response(result_data: dict, repo_root: Any) -> dict:
+ """Shrink a path response until it fits the transport budget.
+
+ The projection above bounds the structured fields; this bounds the free
+ text ones, which no fixed cap can — a single record's ``rationale`` is
+ unbounded, and the ungoverned-file branch returns git archaeology instead
+ of decisions and so is not capped by any of them.
+
+ Stages, cheapest loss first:
+
+ 1. Drop ``origin_story.linked_decisions``, which re-inlines each record's
+ title, rationale and matched commits — all of it already in
+ ``decisions``.
+ 2. Drop governing records from the tail, all the way to none if it comes
+ to that. They are sorted best-first, so the tail is review-queue noise,
+ and an empty list plus a marker beats a rejected response.
+ 3. Drop the fallback blocks the ungoverned branch adds
+ (``code_rationale``, then ``git_archaeology``), then ``origin_story``
+ whole. What survives — mode, path, alignment, ``_meta`` — is bounded.
+
+ Every drop goes to the omission store, so the agent gets a
+ ``[repowise#<ref>]`` marker it can expand rather than a silently shortened
+ response. Call after ``_meta`` is set: the collector writes into it.
+ """
+ # Reserved so the marker the collector appends after the last check cannot
+ # itself push the response back over the host cap.
+ budget = effective_char_budget() - _COLLECTOR_HEADROOM_CHARS
+
+ def _over() -> bool:
+ return len(json.dumps(result_data, separators=(",", ":"), default=str)) > budget
+
+ if not _over():
+ return result_data
+
+ collector = OmissionCollector("get_why", repo_root=repo_root)
+
+ def _drop_block(key: str, container: dict) -> None:
+ if _over() and container.get(key):
+ collector.add(key, container.pop(key))
+ result_data["truncated"] = True
+
+ origin_story = result_data.get("origin_story")
+ if isinstance(origin_story, dict):
+ _drop_block("linked_decisions", origin_story)
+
+ decisions: list = result_data.get("decisions") or []
+ while decisions and _over():
+ dropped = decisions.pop()
+ collector.add(f"dropped governing decision {dropped.get('title', '')}", dropped)
+ result_data["truncated"] = True
+ result_data.setdefault("dropped_decisions", []).append(dropped.get("id", ""))
+
+ for key in ("code_rationale", "git_archaeology", "origin_story"):
+ _drop_block(key, result_data)
+
+ collector.attach(result_data)
+ return result_data
async def _why_path(query: str, repo: str | None) -> dict:
@@ -209,24 +342,52 @@ async def _why_path(query: str, repo: str | None) -> dict:
from repowise.core.persistence.decision_graph import build_lineage_chain
+ matched = [
+ d
+ for d in all_decisions
+ if query in json.loads(d.affected_files_json)
+ or query in json.loads(d.affected_modules_json)
+ ]
+ # Rank before capping, so the 8 that survive are the 8 that govern —
+ # not whichever 8 the table scan happened to yield first.
+ matched.sort(key=_path_decision_sort_key)
governing = []
- for d in all_decisions:
- affected_files = json.loads(d.affected_files_json)
- affected_modules = json.loads(d.affected_modules_json)
- if query not in affected_files and query not in affected_modules:
- continue
+ for d in 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, affected_files, lineage))
+ governing.append(
+ _governing_decision_entry(d, json.loads(d.affected_files_json), lineage)
+ )
+
+ origin_story = _build_origin_story(query, git_meta, governing)
+ _trim_commit_text(origin_story)
result_data: dict[str, Any] = {
"mode": "path",
"path": query,
"decisions": governing,
- "origin_story": _build_origin_story(query, git_meta, governing),
- "alignment": _compute_alignment(query, governing, all_decisions),
+ "origin_story": origin_story,
+ # Alignment is scored over every matching record, not just the
+ # ones that survived the cap — it is a coverage number, and
+ # capping its input would make a well-governed hotspot look thin.
+ # It reads only status/staleness/title, so the cheap projection is
+ # the whole of what it needs.
+ "alignment": _compute_alignment(
+ query,
+ [
+ {
+ "title": d.title,
+ "status": d.status,
+ "staleness_score": d.staleness_score,
+ }
+ for d in matched
+ ],
+ all_decisions,
+ ),
}
+ if len(matched) > _MAX_PATH_DECISIONS:
+ result_data["decisions_total"] = len(matched)
# --- Fallback: git archaeology when no decisions found ---
if not governing:
@@ -243,7 +404,7 @@ async def _why_path(query: str, repo: str | None) -> dict:
result_data["code_rationale"] = rationale
result_data["_meta"] = _build_meta(repository=repository)
- return result_data
+ return _fit_path_response(result_data, ctx.path)
# Stop words removed before keyword matching for better signal.
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index 69982b913..f14fab5b4 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -553,7 +553,10 @@ def _build_tool_summary(tool_name: str, result: dict[str, Any]) -> str:
author = (
origin.get("primary_author", "unknown") if origin.get("available") else "unknown"
)
- return f"{len(decisions)} decision(s), alignment: {score}, author: {author}"
+ # ``decisions`` is capped by the path-mode projection; report what
+ # governs the file, not how many survived the cap.
+ total = result.get("decisions_total", len(decisions))
+ return f"{total} decision(s), alignment: {score}, author: {author}"
decisions = result.get("decisions", [])
return f"Found {len(decisions)} decision(s)"
diff --git a/tests/unit/ingestion/test_fs_walk.py b/tests/unit/ingestion/test_fs_walk.py
index 02b3f62a0..4362427f7 100644
--- a/tests/unit/ingestion/test_fs_walk.py
+++ b/tests/unit/ingestion/test_fs_walk.py
@@ -311,9 +311,11 @@ _WALK_ALLOWLIST: dict[tuple[str, str], frozenset[str]] = {
# Repo DISCOVERY: exists to find nested .git dirs, prunes in-place;
# migration onto walk_repo(prune_nested_git=False) is a tracked follow-up.
("core", "workspace/scanner.py"): frozenset({"os.walk"}),
- # Decision mining: pruned in-place walks + an rglob bounded to docs/;
- # migration is a tracked follow-up (sequenced after the source_map reuse).
- ("core", "analysis/decisions/extractor.py"): frozenset({"rglob", "os.walk"}),
+ # Decision mining: pruned in-place walks. The ``rglob`` entry went with the
+ # readme_mining/changelog miners (#1290) — the ADR scan globs a fixed set
+ # of patterns and walks with in-place pruning. Migration onto walk_repo is
+ # a tracked follow-up (sequenced after the source_map reuse).
+ ("core", "analysis/decisions/extractor.py"): frozenset({"os.walk"}),
# Sizes .repowise/ only — repowise-owned, cannot contain junk trees.
("cli", "commands/status_cmd.py"): frozenset({"rglob"}),
# Scans repowise's own packaged web/ui source dirs, not the user repo.
diff --git a/tests/unit/persistence/test_decision_supersession.py b/tests/unit/persistence/test_decision_supersession.py
index 5bcc97a86..c1ca7a94f 100644
--- a/tests/unit/persistence/test_decision_supersession.py
+++ b/tests/unit/persistence/test_decision_supersession.py
@@ -5,19 +5,39 @@ existing one (cosine in the related band) and contradicts it, a typed edge is
recorded: ``supersedes`` (auto-flipping the older above the confidence
threshold) for a clear reversal, ``conflicts_with`` for two active decisions
that disagree with no clear winner. A related-but-compatible pair gets nothing.
+
+**3B ships disabled** — similarity turned out to scope nothing (see
+``SEMANTIC_SUPERSESSION_ENABLED``). These tests cover the machinery Phase 2
+re-enables structurally, so they turn the flag on; the two ``..._disabled`` /
+``..._writes_nothing`` tests below are what pin the shipped default.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
+import pytest
+
from repowise.core.analysis.decision_evolution import detect_supersessions_and_conflicts
+from repowise.core.analysis.decisions import evolution
from repowise.core.persistence.crud import bulk_upsert_decisions, get_decision
from repowise.core.persistence.decision_graph import get_decision_edges
from repowise.core.persistence.vector_store import InMemoryVectorStore
from tests.unit.persistence.helpers import insert_repo
+def enable_3b(monkeypatch):
+ """Turn 3B on for the tests that exercise the machinery behind the flag.
+
+ Patched on the defining module, not the ``decision_evolution`` façade —
+ the function reads its own module global, so patching the star-import
+ re-export would leave the real flag untouched and every test using it
+ would pass vacuously. Not autouse, so the shipped default stays readable.
+ """
+ monkeypatch.setattr(evolution, "SEMANTIC_SUPERSESSION_ENABLED", True)
+
+
class _TopicEmbedder:
"""Places texts on per-topic axes so same-topic-but-distinct texts land in
the related band (~0.69 cosine) — below the dedup threshold (so they stay
@@ -66,7 +86,7 @@ async def _backdate(session, decision_id: str, days: int) -> None:
await session.flush()
-async def test_reversal_creates_supersedes_edge_and_autoflips(async_session):
+async def test_reversal_creates_supersedes_edge_and_autoflips(async_session, enable_3b):
repo = await insert_repo(async_session)
store = InMemoryVectorStore(_TopicEmbedder())
@@ -118,7 +138,7 @@ async def test_reversal_creates_supersedes_edge_and_autoflips(async_session):
assert old.superseded_by == new_id
-async def test_two_active_conflicts_without_reversal(async_session):
+async def test_two_active_conflicts_without_reversal(async_session, enable_3b):
repo = await insert_repo(async_session)
store = InMemoryVectorStore(_TopicEmbedder())
@@ -160,7 +180,7 @@ async def test_two_active_conflicts_without_reversal(async_session):
assert (await get_decision(async_session, b)).status == "active"
-async def test_related_but_compatible_pair_gets_no_edge(async_session):
+async def test_related_but_compatible_pair_gets_no_edge(async_session, enable_3b):
repo = await insert_repo(async_session)
store = InMemoryVectorStore(_TopicEmbedder())
@@ -203,7 +223,43 @@ async def test_related_but_compatible_pair_gets_no_edge(async_session):
assert all_edges == []
-async def test_no_store_is_a_noop(async_session):
+def test_detector_ships_disabled():
+ """Similarity cannot scope a conflict, so 3B is off until Phase 2."""
+ assert evolution.SEMANTIC_SUPERSESSION_ENABLED is False
+
+
+async def test_disabled_detector_writes_nothing(async_session):
+ """With 3B off the same input that flips a record leaves it untouched."""
+ repo = await insert_repo(async_session)
+ store = InMemoryVectorStore(_TopicEmbedder())
+
+ old_ids = await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [_dec("Use sessions for authentication", "use server-side sessions", files=["a.py"])],
+ vector_store=store,
+ )
+ new_ids = await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [_dec("Adopt JWT authentication", "replace sessions with JWT tokens", files=["a.py"])],
+ vector_store=store,
+ )
+ await _backdate(async_session, old_ids[0], days=30)
+
+ summary = await detect_supersessions_and_conflicts(
+ async_session,
+ repo.id,
+ touched_ids=[old_ids[0], new_ids[0]],
+ vector_store=store,
+ )
+
+ assert summary == {"supersedes": 0, "conflicts": 0, "flipped": 0}
+ assert (await get_decision(async_session, old_ids[0])).status == "active"
+ assert await get_decision_edges(async_session, new_ids[0]) == []
+
+
+async def test_no_store_is_a_noop(async_session, enable_3b):
repo = await insert_repo(async_session)
ids = await bulk_upsert_decisions(
async_session,
diff --git a/tests/unit/persistence/test_decision_unretire.py b/tests/unit/persistence/test_decision_unretire.py
new file mode 100644
index 000000000..acf8491b0
--- /dev/null
+++ b/tests/unit/persistence/test_decision_unretire.py
@@ -0,0 +1,183 @@
+"""Un-retiring what the semantic supersession detector (3B) hid.
+
+Turning 3B off stops the next bad retirement and does nothing about the ones
+already made: ``superseded`` is a protected status, so re-extraction will never
+walk one back. ``unretire_auto_superseded`` is the other half of that change —
+it restores the records the detector flipped and deletes the edges it wrote,
+while leaving retirements a human made alone.
+"""
+
+from __future__ import annotations
+
+from repowise.core.persistence.crud import get_decision, unretire_auto_superseded
+from repowise.core.persistence.decision_graph import get_decision_edges, upsert_decision_edge
+from repowise.core.persistence.models import DecisionRecord
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _record(session, repo_id: str, title: str, **kwargs) -> DecisionRecord:
+ rec = DecisionRecord(repository_id=repo_id, title=title, source="pr", **kwargs)
+ session.add(rec)
+ await session.flush()
+ return rec
+
+
+async def test_auto_retired_record_is_restored_and_its_edge_deleted(async_session):
+ repo = await insert_repo(async_session)
+ newer = await _record(async_session, repo.id, "Adopt JWT", status="active")
+ older = await _record(
+ async_session,
+ repo.id,
+ "Use sessions",
+ status="superseded",
+ superseded_by=newer.id,
+ )
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=0.9,
+ evidence="auto-detected: instead of (sim=0.81)",
+ )
+
+ assert await unretire_auto_superseded(async_session) == 1
+
+ restored = await get_decision(async_session, older.id)
+ assert restored.status == "proposed"
+ assert restored.superseded_by is None
+ # The lineage the detector fabricated goes with it.
+ assert await get_decision_edges(async_session, newer.id) == []
+
+
+async def test_human_retirement_is_left_alone(async_session):
+ """No ``auto-detected:`` edge → not the detector's doing → not ours to undo."""
+ repo = await insert_repo(async_session)
+ newer = await _record(async_session, repo.id, "Adopt JWT", status="active")
+ older = await _record(
+ async_session,
+ repo.id,
+ "Use sessions",
+ status="superseded",
+ superseded_by=newer.id,
+ )
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=1.0,
+ evidence="repowise decision deprecate --superseded-by",
+ )
+
+ assert await unretire_auto_superseded(async_session) == 0
+ assert (await get_decision(async_session, older.id)).status == "superseded"
+ assert len(await get_decision_edges(async_session, newer.id)) == 1
+
+
+async def test_auto_edge_to_a_record_retired_by_someone_else_only_drops_the_edge(async_session):
+ """The edge is still the detector's noise; the retirement is not its doing."""
+ repo = await insert_repo(async_session)
+ detector_pick = await _record(async_session, repo.id, "Adopt JWT", status="active")
+ real_successor = await _record(async_session, repo.id, "Adopt OAuth", status="active")
+ older = await _record(
+ async_session,
+ repo.id,
+ "Use sessions",
+ status="superseded",
+ superseded_by=real_successor.id,
+ )
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=detector_pick.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=0.9,
+ evidence="auto-detected: replace (sim=0.83)",
+ )
+
+ assert await unretire_auto_superseded(async_session) == 0
+ assert (await get_decision(async_session, older.id)).status == "superseded"
+ assert await get_decision_edges(async_session, detector_pick.id) == []
+
+
+async def test_fabricated_conflicts_are_dropped_too(async_session):
+ """``conflicts_with`` retires nothing but is counted as a governance smell."""
+ repo = await insert_repo(async_session)
+ a = await _record(async_session, repo.id, "Sync worker IO", status="active")
+ b = await _record(async_session, repo.id, "Async worker IO", status="active")
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=a.id,
+ dst_decision_id=b.id,
+ kind="conflicts_with",
+ confidence=0.8,
+ evidence="auto-detected: opposing-verbs (sim=0.82)",
+ )
+
+ assert await unretire_auto_superseded(async_session) == 0
+ assert await get_decision_edges(async_session, a.id) == []
+ assert (await get_decision(async_session, a.id)).status == "active"
+
+
+async def test_is_idempotent(async_session):
+ repo = await insert_repo(async_session)
+ newer = await _record(async_session, repo.id, "Adopt JWT", status="active")
+ older = await _record(
+ async_session,
+ repo.id,
+ "Use sessions",
+ status="superseded",
+ superseded_by=newer.id,
+ )
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=0.9,
+ evidence="auto-detected: instead of (sim=0.81)",
+ )
+
+ assert await unretire_auto_superseded(async_session) == 1
+ # The edges are gone, so the second pass has nothing to match — and in
+ # particular it does not re-restore a record a human has since re-retired.
+ assert await unretire_auto_superseded(async_session) == 0
+
+
+async def test_restoring_a_retired_source_row_hands_it_to_the_purge(async_session):
+ """``proposed`` is what ``purge_proposed_decisions_by_source`` deletes.
+
+ So a restored ``changelog``/``readme_mining`` row is on its way out, and the
+ persist paths run this repair *before* the purge for that reason: one run
+ then ends in a single consistent state instead of leaving the row alive for
+ one run and silently deleting it on the next.
+ """
+ from repowise.core.analysis.decision_provenance import RETIRED_SOURCES
+ from repowise.core.persistence.crud import purge_proposed_decisions_by_source
+
+ repo = await insert_repo(async_session)
+ newer = await _record(async_session, repo.id, "Adopt JWT", status="active")
+ older = await _record(async_session, repo.id, "Changelog line", status="superseded")
+ older.source = "changelog"
+ older.superseded_by = newer.id
+ await async_session.flush()
+ await upsert_decision_edge(
+ async_session,
+ repository_id=repo.id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=0.9,
+ evidence="auto-detected: replace (sim=0.82)",
+ )
+
+ assert "changelog" in RETIRED_SOURCES
+ assert await unretire_auto_superseded(async_session) == 1
+ assert await purge_proposed_decisions_by_source(async_session, repo.id, "changelog") == 1
+ assert await get_decision(async_session, older.id) is None
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 53a66d7fc..4ab134859 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -288,3 +288,211 @@ async def test_get_why_semantic_decision_namespace_filtering(setup_mcp):
assert not any(d.get("id", "").startswith("file_page:") for d in result["decisions"]), (
"Noise page should not appear in decisions list"
)
+
+
+# ---------------------------------------------------------------------------
+# Path-mode cap and projection
+#
+# Before this, path mode inlined every governing record whole: on a bug-magnet
+# file that measured 81 854 chars, over the MCP host cap, which rejects rather
+# than truncates — so the mode that answers "what governs this file right
+# before I edit it" hard-failed on exactly the files it exists for.
+# ---------------------------------------------------------------------------
+
+
+async def _seed_bulky_decisions(session, rid: str, path: str, count: int) -> None:
+ """``count`` records governing *path*, each as heavy as a real one gets."""
+ import json
+
+ from repowise.core.persistence.models import DecisionRecord
+
+ for i in range(count):
+ session.add(
+ DecisionRecord(
+ id=f"bulk{i}",
+ repository_id=rid,
+ title=f"Bulky decision {i}",
+ status="superseded" if i else "active",
+ context="ctx " * 200,
+ decision="dec " * 200,
+ rationale="why " * 200,
+ affected_files_json=json.dumps([path] + [f"src/f{i}/{n}.py" for n in range(60)]),
+ affected_modules_json=json.dumps([]),
+ source="pr",
+ confidence=0.5,
+ staleness_score=0.0,
+ )
+ )
+ await session.flush()
+
+
+async def test_get_why_path_fits_the_transport_budget(session, setup_mcp):
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server._budget import effective_char_budget
+
+ await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)
+
+ result = await get_why("src/auth/service.py")
+
+ import json as _json
+
+ assert len(_json.dumps(result, default=str)) <= effective_char_budget()
+
+
+async def test_get_why_path_fits_a_narrowed_host_cap(session, setup_mcp, monkeypatch, tmp_path):
+ """The cap alone is not the guarantee — free text is what the budget bounds.
+
+ A user who lowers ``MAX_MCP_OUTPUT_TOKENS`` pulls the ceiling under the
+ projection, which is the case the fixed caps cannot cover on their own.
+ """
+ import json as _json
+
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server._budget import collector as collector_mod
+ from repowise.server.mcp_server._budget import effective_char_budget
+
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "2000")
+ # Drops are recoverable, which means they are written somewhere — send
+ # them to tmp_path instead of the developer's own ~/.repowise.
+ monkeypatch.setattr(
+ collector_mod, "default_store_path", lambda start=None: tmp_path / "omissions.db"
+ )
+ await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)
+
+ result = await get_why("src/auth/service.py")
+
+ assert result["truncated"] is True
+ assert result["dropped_decisions"]
+ assert len(_json.dumps(result, default=str)) <= effective_char_budget()
+
+
+async def test_get_why_path_caps_records_and_keeps_the_active_one_first(session, setup_mcp):
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server.tool_why import _MAX_PATH_DECISIONS
+
+ await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 30)
+
+ result = await get_why("src/auth/service.py")
+
+ assert len(result["decisions"]) <= _MAX_PATH_DECISIONS
+ # Ranked, not table-scan order: the one active record leads.
+ assert result["decisions"][0]["status"] == "active"
+ # And the count that was capped is still reported honestly.
+ assert result["decisions_total"] == 31
+ assert result["alignment"]["governing_count"] == 31
+
+
+async def test_get_why_path_projects_wide_affected_files(session, setup_mcp):
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server.tool_why import _MAX_AFFECTED_FILES
+
+ await _seed_bulky_decisions(session, setup_mcp, "src/auth/service.py", 2)
+
+ result = await get_why("src/auth/service.py")
+ wide = next(d for d in result["decisions"] if d["title"].startswith("Bulky"))
+
+ assert len(wide["affected_files"]) == _MAX_AFFECTED_FILES
+ assert wide["affected_files_total"] == 61
+
+
+async def test_get_why_path_leaves_a_small_response_untouched(session, setup_mcp):
+ """No cap fires on the ordinary case: no truncation flags, full arrays."""
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("src/auth/service.py")
+
+ assert "truncated" not in result
+ assert "decisions_total" not in result
+ jwt = next(d for d in result["decisions"] if d["title"] == "Use JWT for authentication")
+ assert jwt["affected_files"] == ["src/auth/service.py", "src/auth/middleware.py"]
+ assert "affected_files_total" not in jwt
+
+
+async def test_get_why_path_fits_with_one_enormous_record(session, setup_mcp, monkeypatch, tmp_path):
+ """The last record is droppable too — a cap on the count is not a bound.
+
+ One governing record whose free text alone busts the budget is the case a
+ per-record cap cannot reach.
+ """
+ import json as _json
+
+ from repowise.core.persistence.models import DecisionRecord
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server._budget import collector as collector_mod
+ from repowise.server.mcp_server._budget import effective_char_budget
+
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "2000")
+ monkeypatch.setattr(
+ collector_mod, "default_store_path", lambda start=None: tmp_path / "omissions.db"
+ )
+ session.add(
+ DecisionRecord(
+ id="huge",
+ repository_id=setup_mcp,
+ title="One very long decision",
+ status="active",
+ rationale="why " * 6000,
+ affected_files_json=_json.dumps(["src/auth/service.py"]),
+ affected_modules_json=_json.dumps([]),
+ source="pr",
+ )
+ )
+ await session.flush()
+
+ result = await get_why("src/auth/service.py")
+
+ assert result["truncated"] is True
+ assert len(_json.dumps(result, default=str)) <= effective_char_budget()
+
+
+async def test_get_why_path_fits_on_an_ungoverned_file(session, setup_mcp, monkeypatch, tmp_path):
+ """The git-archaeology fallback is budgeted too.
+
+ It is the branch that fires on a file with no decisions — which is most
+ files — and none of the decision-shaped caps touch it.
+ """
+ import json as _json
+
+ from repowise.core.persistence.models import GitMetadata
+ from repowise.server.mcp_server import get_why
+ from repowise.server.mcp_server._budget import collector as collector_mod
+ from repowise.server.mcp_server._budget import effective_char_budget
+
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "2000")
+ monkeypatch.setattr(
+ collector_mod, "default_store_path", lambda start=None: tmp_path / "omissions.db"
+ )
+ session.add(
+ GitMetadata(
+ repository_id=setup_mcp,
+ file_path="src/other/utils.py",
+ commit_count_total=90,
+ significant_commits_json=_json.dumps(
+ [
+ {
+ "sha": f"{i:08x}",
+ "date": "2026-01-01T00:00:00+00:00",
+ "message": f"refactor: rework the utils helper {i}",
+ "author": "Alice",
+ "body": "why " * 250,
+ }
+ for i in range(50)
+ ]
+ ),
+ )
+ )
+ await session.flush()
+
+ result = await get_why("src/other/utils.py")
+
+ assert result["decisions"] == []
+ # The fallback really was over the line — otherwise this test proves nothing.
+ assert result["truncated"] is True
+ assert len(_json.dumps(result, default=str)) <= effective_char_budget()