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(why): name the decision lanes the health dashboard only counted (#2322)

Raghav Chamadiyaa15ed85b73e1
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 7399a249a..27a4e3a1c 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -791,10 +791,12 @@ Architectural decision intelligence. Falls back to git archaeology when no decis
1. **NL search**: pass a question, optionally anchored to `targets`: `get_why(query="why JWT over sessions?")` -> searches decision records.
2. **Path-based**: pass a file path as `query`: `get_why(query="src/auth/service.ts")` -> returns three lanes, `decisions` (accepted, governing), `candidates` (nobody accepted them) and `history` (accepted and since replaced), plus the file's origin story.
-3. **Health dashboard**: no `query`: `get_why()` -> stale decisions, conflicts, ungoverned hotspots.
+3. **Health dashboard**: no `query`: `get_why()` -> stale decisions, conflicts, ungoverned hotspots, retired records and accepted records that name no file.
4. **Reference lookup**: pass `id`: `get_why(id="ev_...")` -> the exact evidence and supporting decision in one call.
-**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.
+**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, ungoverned hotspots, `retired_decisions` and `unscoped_decisions`.
+
+Two health-mode lanes `counts` reported as a bare number now name their records: `retired_decisions` (superseded, deprecated, dismissed — each row carries its `lane`) and `unscoped_decisions` (accepted records naming no file). Five rows each, ranked, remainder in `_meta.omitted`; full sizes stay in `counts`, split across the three status keys for the retired lane. `active` stays count-only.
`answer_basis` names the strongest lane the response rests on: `decision`, `episode`, `rationale`, `archaeology`, or `documentation`. Only `decision` is a ruling; the rest are evidence to weigh. Absent when no lane was served, and on the health dashboard.
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.py
index 2a39517a8..10482b013 100644
--- a/packages/cli/src/repowise/cli/commands/why_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py
@@ -138,8 +138,9 @@ def project(payload: dict) -> dict:
and target_context
dashboard kept summary, counts, and the head of each of
stale_decisions / proposed_awaiting_review /
- ungoverned_hotspots / conflicts, with the
- full count beside it
+ ungoverned_hotspots / conflicts /
+ retired_decisions / unscoped_decisions, with
+ the full count beside it
================== ===========================================
Dropped throughout: a decision's ``context``, ``consequences``,
@@ -237,7 +238,14 @@ def project(payload: dict) -> dict:
for target, entry in payload["target_context"].items()
}
- for key in ("stale_decisions", "proposed_awaiting_review", "ungoverned_hotspots", "conflicts"):
+ for key in (
+ "stale_decisions",
+ "proposed_awaiting_review",
+ "ungoverned_hotspots",
+ "conflicts",
+ "retired_decisions",
+ "unscoped_decisions",
+ ):
values = payload.get(key)
if values:
out[key] = _capped(values)
@@ -412,6 +420,8 @@ def _render(projected: dict) -> None:
("Stale decisions", "stale_decisions"),
("Proposed, awaiting review", "proposed_awaiting_review"),
("Conflicts", "conflicts"),
+ ("Retired", "retired_decisions"),
+ ("Accepted, naming no file", "unscoped_decisions"),
):
rows = projected.get(key) or []
if rows:
@@ -464,6 +474,8 @@ _RENDERABLE_BLOCKS = (
"proposed_awaiting_review",
"conflicts",
"ungoverned_hotspots",
+ "retired_decisions",
+ "unscoped_decisions",
"related_documentation",
"episodes",
)
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 9ae85309c..b649879ed 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -16,7 +16,7 @@ from sqlalchemy import case, delete, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core import __version__
-from repowise.core.analysis.decisions.lifecycle import DECISION_STATUS_ORDER
+from repowise.core.analysis.decisions.lifecycle import DECISION_STATUS_ORDER, status_rank
from repowise.core.analysis.decisions.provenance import (
SOURCE_RANK,
compute_confidence,
@@ -1559,11 +1559,15 @@ async def get_decision_health_summary(
) -> dict:
"""Return decision health: counts by lane, stale decisions, ungoverned hotspots.
- The three list fields are returned ranked worst-first: stale by staleness,
- proposed by confidence, ungoverned hotspots by temporal hotspot score. A
+ The five list fields are returned ranked worst-first: stale by staleness,
+ proposed by confidence, ungoverned hotspots by temporal hotspot score,
+ retired by lane (history before tombstone) and unscoped by confidence. A
caller that shows only the first few shows the few that matter.
Callers may truncate; they must not re-order.
+ ``retired_decisions`` holds ``(lane, record)`` pairs: the lane is derived
+ from the acceptance, which the ``status`` column may disagree with.
+
Counts the acceptance, not the status column. The key names are the ones
every caller already renders, and they keep their product meaning:
``active`` is what governs, ``proposed`` is what nobody has accepted. What
@@ -1598,6 +1602,12 @@ async def get_decision_health_summary(
}
stale_decisions: list[DecisionRecord] = []
proposed_decisions: list[DecisionRecord] = []
+ # Counted-only lanes. The record is in hand at the ``continue`` that drops
+ # it, so naming it costs no query. ``retired`` carries its lane because
+ # that lane is derived from the acceptance where there is one, and a
+ # record's ``status`` column may disagree with it.
+ retired_decisions: list[tuple[str, DecisionRecord]] = []
+ unscoped_decisions: list[DecisionRecord] = []
# Files an *accepted* decision names. A candidate naming a hotspot does not
# make it governed, and counting one did: it removed the file from
@@ -1613,15 +1623,18 @@ async def get_decision_health_summary(
# never be counted as.
if d.status in ("dismissed", "deprecated", "superseded"):
counts[d.status] = counts.get(d.status, 0) + 1
+ retired_decisions.append((d.status, d))
else:
counts["proposed"] += 1
proposed_decisions.append(d)
continue
if currency == "superseded":
counts["superseded"] += 1
+ retired_decisions.append(("superseded", d))
continue
if currency == "dismissed":
counts["dismissed"] += 1
+ retired_decisions.append(("dismissed", d))
continue
counts["active"] += 1
if currency == "needs_review":
@@ -1629,6 +1642,7 @@ async def get_decision_health_summary(
stale_decisions.append(d)
if currency == "uncheckable":
counts["unscoped"] += 1
+ unscoped_decisions.append(d)
for fp in json.loads(d.affected_files_json):
governed_files.add(fp)
@@ -1670,6 +1684,11 @@ async def get_decision_health_summary(
# back-filled; the id tiebreak makes the key total, so two runs agree.
stale_decisions.sort(key=lambda d: (-(d.staleness_score or 0.0), d.id))
proposed_decisions.sort(key=lambda d: (-(d.confidence or 0.0), d.id))
+ # Retired by lane, history before tombstone. Not by ``updated_at``: it
+ # moves on any write, so it does not say when a record was retired.
+ # ``unscoped`` by confidence, the key ``proposed`` already uses.
+ retired_decisions.sort(key=lambda pair: (status_rank(pair[0]), pair[1].id))
+ unscoped_decisions.sort(key=lambda d: (-(d.confidence or 0.0), d.id))
# Phase 3B: surface contradictory active decisions (conflicts_with edges).
from ..decision_graph import list_conflict_edges
@@ -1697,4 +1716,6 @@ async def get_decision_health_summary(
"proposed_awaiting_review": proposed_decisions,
"ungoverned_hotspots": ungoverned,
"conflicts": conflicts,
+ "retired_decisions": retired_decisions,
+ "unscoped_decisions": unscoped_decisions,
}
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 85b805c26..455cb6b9f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -490,6 +490,8 @@ async def _why_health_dashboard(repo: str | None) -> dict:
stale = health["stale_decisions"]
proposed = health["proposed_awaiting_review"]
ungoverned = health["ungoverned_hotspots"]
+ retired = health["retired_decisions"]
+ unscoped = health["unscoped_decisions"]
result_data = {
"mode": "health",
@@ -522,6 +524,17 @@ async def _why_health_dashboard(repo: str | None) -> dict:
],
"ungoverned_hotspots": ungoverned,
"conflicts": list(health.get("conflicts", [])),
+ # Lanes ``counts`` reported as a number with no list. Query and
+ # path mode do reach these records, but only if you already know
+ # the question or the path — no mode enumerates either lane, which
+ # is what an orientation call is for. ``active`` stays count-only:
+ # it is the lane every other mode exists to serve.
+ "retired_decisions": [
+ {"id": d.id, "title": d.title, "lane": lane} for lane, d in retired
+ ],
+ "unscoped_decisions": [
+ {"id": d.id, "title": d.title, "confidence": d.confidence} for d in unscoped
+ ],
"_meta": _build_meta(repository=repository),
}
for entry in result_data["stale_decisions"]:
@@ -545,6 +558,8 @@ async def _why_health_dashboard(repo: str | None) -> dict:
("proposed_awaiting_review", _MAX_HEALTH_PROPOSED),
("ungoverned_hotspots", _MAX_HEALTH_UNGOVERNED),
("conflicts", 10),
+ ("retired_decisions", _MAX_HEALTH_RETIRED),
+ ("unscoped_decisions", _MAX_HEALTH_RETIRED),
):
cap_collection(
result_data,
@@ -651,11 +666,19 @@ _KEYWORD_POOL = 24
#: verdict. Halved now that ``get_decision_health_summary`` ranks what it
#: returns: cutting an unranked list only makes a list nobody reads shorter,
#: cutting a ranked one keeps the part that is worth reading. The full sizes stay
-#: legible in ``counts`` and in the summary line, so nothing is silently dropped.
+#: legible in ``counts`` and in the summary line, and every row cut here is
+#: recoverable through the omission collector, so nothing is silently dropped.
+#:
+#: That clause needs a list to be true of: for a count-only lane there was
+#: nothing to recover, which is why the two below exist.
_MAX_HEALTH_STALE = 5
_MAX_HEALTH_PROPOSED = 5
_MAX_HEALTH_UNGOVERNED = 8
+#: Retired records and accepted records naming no file. Same 5 as its peers:
+#: a pointer into history, not a place to read it from.
+_MAX_HEALTH_RETIRED = 5
+
def _authority_of(decision_id: str, accepted: set[str]) -> str:
"""``"accepted"`` when an acceptance binds this record, else ``"candidate"``.
diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.py
index 83f979c2f..334b0176e 100644
--- a/tests/unit/cli/test_tool_adapter_commands.py
+++ b/tests/unit/cli/test_tool_adapter_commands.py
@@ -935,3 +935,25 @@ def test_why_renders_a_dominant_author_as_a_percentage_not_a_fraction():
assert _owner_share(0.9956) == "100%"
assert _owner_share(80.0) == "80%"
assert _owner_share(None) == "?"
+
+
+def test_why_dashboard_projection_keeps_the_newly_named_lanes():
+ """``project_why`` keeps dashboard keys by a hardcoded tuple, so a new lane
+ is dropped here until it is added.
+ """
+ payload = {
+ "mode": "health",
+ "summary": "1 active",
+ "counts": {"active": 1, "superseded": 2, "unscoped": 1},
+ "retired_decisions": [
+ {"id": "r1", "title": "Retired one", "lane": "superseded"},
+ {"id": "r2", "title": "Retired two", "lane": "dismissed"},
+ ],
+ "unscoped_decisions": [{"id": "u1", "title": "Scopeless", "confidence": 0.4}],
+ }
+
+ out = project_why(payload)
+
+ assert [row["id"] for row in out["retired_decisions"]] == ["r1", "r2"]
+ assert out["retired_decisions"][1]["lane"] == "dismissed"
+ assert [row["id"] for row in out["unscoped_decisions"]] == ["u1"]
diff --git a/tests/unit/persistence/test_decision_health_named_lanes.py b/tests/unit/persistence/test_decision_health_named_lanes.py
new file mode 100644
index 000000000..67c625d3c
--- /dev/null
+++ b/tests/unit/persistence/test_decision_health_named_lanes.py
@@ -0,0 +1,142 @@
+"""The lanes ``get_decision_health_summary`` counted and then discarded.
+
+``counts`` reported them as a number and named none of the records, although
+each is in hand at the ``continue`` that drops it. ``active`` stays count-only
+on purpose, so that has a test too.
+"""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.persistence.crud import get_decision_health_summary
+from repowise.core.persistence.models import DecisionRecord
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _add(
+ session,
+ repo_id: str,
+ *,
+ rec_id: str,
+ status: str,
+ confidence: float = 1.0,
+ files: list[str] | None = None,
+) -> DecisionRecord:
+ record = DecisionRecord(
+ id=rec_id,
+ repository_id=repo_id,
+ title=f"Decision {rec_id}",
+ decision=f"{rec_id} because reasons",
+ rationale=f"the alternative to {rec_id} was measured worse",
+ status=status,
+ confidence=confidence,
+ affected_files_json=json.dumps(files or []),
+ source="changelog",
+ )
+ session.add(record)
+ await session.flush()
+ return record
+
+
+async def test_retired_records_are_named_not_only_counted(async_session):
+ repo = await insert_repo(async_session)
+ for rec_id, status in (("s1", "superseded"), ("d1", "deprecated"), ("x1", "dismissed")):
+ await _add(async_session, repo.id, rec_id=rec_id, status=status)
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["summary"]["superseded"] == 1
+ assert health["summary"]["deprecated"] == 1
+ assert health["summary"]["dismissed"] == 1
+ # Ranked by lane, history before tombstone, per DECISION_STATUS_ORDER.
+ assert [(lane, d.id) for lane, d in health["retired_decisions"]] == [
+ ("superseded", "s1"),
+ ("deprecated", "d1"),
+ ("dismissed", "x1"),
+ ]
+
+
+async def test_every_counted_retired_record_is_named(async_session):
+ """A list naming only some of what it counted is the same defect in a list."""
+ repo = await insert_repo(async_session)
+ for index in range(4):
+ await _add(async_session, repo.id, rec_id=f"s{index}", status="superseded")
+ for index in range(3):
+ await _add(async_session, repo.id, rec_id=f"x{index}", status="dismissed")
+
+ health = await get_decision_health_summary(async_session, repo.id)
+ counts = health["summary"]
+
+ assert counts["superseded"] + counts["deprecated"] + counts["dismissed"] == len(
+ health["retired_decisions"]
+ )
+
+
+async def test_an_accepted_record_naming_no_file_is_named_as_unscoped(async_session):
+ """Accepted, so not in the proposed queue; names no file, so path mode
+ cannot reach it either.
+ """
+ from repowise.core.persistence.crud.authority import accept_decision
+
+ repo = await insert_repo(async_session)
+ record = await _add(async_session, repo.id, rec_id="u1", status="active", confidence=0.4)
+ # An acceptance must name a scope, so accept with one then strip it:
+ # ``uncheckable`` is derived from the record, not the acceptance.
+ await accept_decision(
+ async_session, record, accepter="test", evidence=["seed:u1"], scope=["src/u1.py"]
+ )
+ record.affected_files_json = "[]"
+ record.affected_modules_json = "[]"
+ await async_session.flush()
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["summary"]["unscoped"] == 1
+ assert [d.id for d in health["unscoped_decisions"]] == ["u1"]
+
+
+async def test_unscoped_records_come_back_most_confident_first(async_session):
+ """Insertion order and id order both disagree with the answer."""
+ from repowise.core.persistence.crud.authority import accept_decision
+
+ repo = await insert_repo(async_session)
+ for rec_id, confidence in (("a1", 0.30), ("b2", 0.55), ("c3", 0.80), ("d4", 0.95)):
+ record = await _add(
+ async_session, repo.id, rec_id=rec_id, status="active", confidence=confidence
+ )
+ await accept_decision(
+ async_session,
+ record,
+ accepter="test",
+ evidence=[f"seed:{rec_id}"],
+ scope=[f"src/{rec_id}.py"],
+ )
+ record.affected_files_json = "[]"
+ record.affected_modules_json = "[]"
+ record.confidence = confidence
+ await async_session.flush()
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert [d.id for d in health["unscoped_decisions"]] == ["d4", "c3", "b2", "a1"]
+
+
+async def test_a_governing_record_is_in_neither_new_lane(async_session):
+ """The discriminator: the new lists must not absorb an active decision."""
+ from repowise.core.persistence.crud.authority import accept_decision
+
+ repo = await insert_repo(async_session)
+ record = await _add(
+ async_session, repo.id, rec_id="g1", status="active", files=["src/g1.py"]
+ )
+ await accept_decision(
+ async_session, record, accepter="test", evidence=["seed:g1"], scope=["src/g1.py"]
+ )
+ await async_session.flush()
+
+ health = await get_decision_health_summary(async_session, repo.id)
+
+ assert health["summary"]["active"] == 1
+ assert health["retired_decisions"] == []
+ assert health["unscoped_decisions"] == []
diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
index 23a045a4b..280da7af8 100644
--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
@@ -751,6 +751,8 @@ async def test_why_health_and_targets_only_modes_are_bounded_and_recoverable(
"conflicts": [
{"detail": f"HEALTH_CONFLICT_{index}"} for index in range(12)
],
+ "retired_decisions": [("superseded", record) for record in records],
+ "unscoped_decisions": records,
}
monkeypatch.setattr(crud_mod, "get_decision_health_summary", sealed_health)
diff --git a/tests/unit/server/mcp/test_why_health_payload.py b/tests/unit/server/mcp/test_why_health_payload.py
index 57aebeb9d..0c6217a6a 100644
--- a/tests/unit/server/mcp/test_why_health_payload.py
+++ b/tests/unit/server/mcp/test_why_health_payload.py
@@ -14,6 +14,7 @@ import json
import pytest
+from repowise.core.analysis.decisions.lifecycle import status_rank
from repowise.core.persistence.models import DecisionRecord
from repowise.server.mcp_server.tool_why import (
_MAX_HEALTH_PROPOSED,
@@ -45,6 +46,21 @@ def oversized_health(monkeypatch):
stale = [_record(f"s{i}", staleness=1.0 - i / 100) for i in range(20)]
proposed = [_record(f"p{i}", confidence=1.0 - i / 100) for i in range(20)]
ungoverned = [f"src/hot_{i}.py" for i in range(20)]
+ # Two ``superseded`` rows, fewer than the cap: a lane-ranked list starts
+ # with them, so five or more would let a hardcoded lane pass. Inserted out
+ # of rank order so an unranked list fails too.
+ retired_lanes = ["dismissed"] * 9 + ["superseded"] * 2 + ["deprecated"] * 9
+ retired = [(lane, _record(f"r{i:02d}")) for i, lane in enumerate(retired_lanes)]
+ retired.sort(key=lambda pair: (status_rank(pair[0]), pair[1].id))
+ unscoped = [_record(f"u{i}", confidence=1.0 - i / 100) for i in range(20)]
+ conflicts = [
+ {
+ "src": {"id": "c-src", "title": "Left", "status": "active"},
+ "dst": {"id": "c-dst", "title": "Right", "status": "active"},
+ "confidence": 0.8,
+ "evidence": "both name src/a.py",
+ }
+ ]
async def _fake(session, repository_id):
return {
@@ -52,11 +68,13 @@ def oversized_health(monkeypatch):
"stale_decisions": stale,
"proposed_awaiting_review": proposed,
"ungoverned_hotspots": ungoverned,
- "conflicts": [],
+ "conflicts": conflicts,
+ "retired_decisions": retired,
+ "unscoped_decisions": unscoped,
}
monkeypatch.setattr(crud, "get_decision_health_summary", _fake)
- return stale, proposed, ungoverned
+ return stale, proposed, ungoverned, retired, unscoped
@pytest.mark.asyncio
@@ -89,7 +107,7 @@ async def test_health_takes_the_front_of_each_list_without_re_sorting_it(
"""
from repowise.server.mcp_server import get_why
- stale, proposed, ungoverned = oversized_health
+ stale, proposed, ungoverned, _retired, _unscoped = oversized_health
result = await get_why()
assert [d["id"] for d in result["stale_decisions"]] == [
@@ -113,3 +131,50 @@ async def test_health_still_states_the_sizes_it_is_not_showing(setup_mcp, oversi
# The summary line is where the ungoverned total survives. It has no
# counter of its own, so cutting the list without this would hide it.
assert "20 ungoverned hotspots" in result["summary"]
+
+
+async def test_health_names_the_lanes_it_used_to_only_count(setup_mcp, oversized_health):
+ """A count with no way to learn which records it counted was the defect."""
+ from repowise.server.mcp_server import get_why
+
+ _stale, _proposed, _ungoverned, retired, unscoped = oversized_health
+ result = await get_why()
+
+ # Pairwise, not on the head: a lane-ranked list heads with ``superseded``
+ # whatever the rows say.
+ assert [(row["id"], row["lane"]) for row in result["retired_decisions"]] == [
+ (record.id, lane) for lane, record in retired[:5]
+ ]
+ assert [row["id"] for row in result["unscoped_decisions"]] == [
+ record.id for record in unscoped[:5]
+ ]
+
+
+async def test_health_states_the_sizes_of_the_new_lanes_too(setup_mcp, oversized_health):
+ """A cap is only honest while what it cut is still reachable."""
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why()
+
+ assert result["retired_decisions_total"] == 20
+ assert result["retired_decisions_emitted"] == 5
+ assert result["unscoped_decisions_total"] == 20
+ assert result["unscoped_decisions_emitted"] == 5
+
+
+async def test_health_leaves_the_conflicts_lane_alone(setup_mcp, oversized_health):
+ """``conflicts`` already names both sides; pinned so it is not thinned to
+ match its neighbours.
+ """
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why()
+ conflict = result["conflicts"][0]
+
+ assert conflict["src"] == {"id": "c-src", "title": "Left", "status": "active"}
+ assert conflict["dst"] == {"id": "c-dst", "title": "Right", "status": "active"}
+ assert conflict["confidence"] == 0.8
+ assert conflict["evidence"] == "both name src/a.py"