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): tell an agent a candidate from a rule it can follow (#2420)

Raghav Chamadiyaf95c9c9290d8
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
index 767234ded..f288363a4 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
@@ -3,12 +3,14 @@
Two delivery moments, both pure indexed-SQLite lookups (no LLM, no network,
target well under 100ms):
- * SessionStart — score the repo's active decisions against the session's
- likely working set (dirty/staged files, branch-vs-main changed files, the
- previous session's edited files, branch-name tokens) expanded one hop via
- import edges and co-change partners, and inject the top few under a hard
- token cap. Relevance or silence: nothing clears the floor, nothing is
- injected. Never top-confidence-globally.
+ * SessionStart — score the repo's decisions against the session's likely
+ working set (dirty/staged files, branch-vs-main changed files, the previous
+ session's edited files, branch-name tokens) expanded one hop via import
+ edges and co-change partners, and inject the top few under a hard token
+ cap. Relevance or silence: nothing clears the floor, nothing is injected.
+ Never top-confidence-globally. Two labelled sections under two separate
+ caps: accepted decisions, then the candidates nobody has agreed to. The
+ second cannot shrink the first. A dismissed record is in neither.
* Edit-time (PostToolUse Edit/Write) — when the edited file has a governing
decision (via decision_node_links), say so once per session per decision,
under a strict per-session cap.
@@ -66,6 +68,21 @@ _W_GLOBAL_RULE = 0.5
#: costs at most one slot until it is dismissed.
_MAX_GLOBAL_RULES = 2
+#: Budget for the candidate section, held separately from ``_TOKEN_CAP`` rather
+#: than carved out of it. A shared cap would mean every candidate admitted
+#: displaces an accepted decision that is injected today, which is the one
+#: thing restoring candidates must not do; a separate cap makes the trade
+#: explicit and bounded instead. Tighter than the accepted block by design:
+#: nobody has agreed to any of these.
+_CANDIDATE_TOKEN_CAP = 120
+#: Never more than this many candidates, whatever the token budget allows.
+_MAX_CANDIDATE_ITEMS = 2
+#: And at most one of those slots may go to an unlinked repo-wide rule. A
+#: repo-wide candidate clears the relevance floor on every session by
+#: construction, so without this the lane would never carry a candidate that
+#: is actually about the files in hand.
+_MAX_CANDIDATE_GLOBALS = 1
+
#: Branch-name tokens that identify workflow, not topic.
_GENERIC_BRANCH_TOKENS = frozenset(
{
@@ -340,12 +357,45 @@ def _kind_column(conn: sqlite3.Connection) -> str:
def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:
"""Accepted, current decisions with their node links, as plain dicts."""
+ return _load_decisions(
+ conn,
+ "status = 'active' AND " + _accepted_clause(conn, "decision_records"),
+ )
+
+
+def _load_candidate_decisions(conn: sqlite3.Connection) -> list[dict]:
+ """Records nobody has accepted, and that nobody has tombstoned either.
+
+ The mirror image of :func:`_load_active_decisions`, and the same statuses
+ ``_answer_context.fetch_relevant_decisions`` reads: ``active`` and
+ ``proposed`` are live claims, while ``deprecated``, ``superseded`` and
+ ``dismissed`` are history and must not be put to an agent as something to
+ consider. Dismissed is the load-bearing one — a candidate tombstoned
+ without ever having been accepted carries no acceptance row, so the
+ acceptance test alone reads it as an ordinary candidate.
+
+ On a store that predates the entity split :func:`_accepted_clause` is
+ ``1 = 1``, so this returns nothing at all. That is the right answer rather
+ than a degradation: such a store cannot tell a candidate from a decision,
+ and the fallback it does have already delivers its records through the
+ accepted path. Guessing here would inject its whole review queue.
+ """
+ return _load_decisions(
+ conn,
+ "status IN ('active', 'proposed') AND NOT ("
+ + _accepted_clause(conn, "decision_records")
+ + ")",
+ )
+
+
+def _load_decisions(conn: sqlite3.Connection, where: str) -> list[dict]:
+ """Decision rows matching *where*, with their node links, as plain dicts."""
try:
rows = conn.execute(
"SELECT id, title, decision, rationale, confidence, staleness_score, source, "
+ _kind_column(conn)
- + " FROM decision_records WHERE status = 'active' AND "
- + _accepted_clause(conn, "decision_records")
+ + " FROM decision_records WHERE "
+ + where
).fetchall()
except sqlite3.Error:
return []
@@ -453,40 +503,48 @@ def _format_decision_line(decision: dict) -> str:
return line
-def _session_decision_block(repo_path: Path, session_id: str) -> str | None:
- """The relevance-ranked SessionStart decision block, or None (silence)."""
- conn = _open_wiki_ro(repo_path)
- if conn is None:
- return None
- try:
- decisions = _load_active_decisions(conn)
- if not decisions:
- return None
- seeds, branch = _collect_seeds(repo_path)
- hop = _expand_one_hop(conn, seeds)
- tokens = _branch_tokens(branch)
+_ACCEPTED_HEADER = (
+ "[repowise] Standing decisions relevant to this session's working set "
+ "(accumulated from prior sessions; follow them unless the user says otherwise):"
+)
- scored = [(d, _score_decision(d, set(seeds), hop, tokens)) for d in decisions]
- scored = [(d, s) for d, s in scored if s >= _RELEVANCE_FLOOR]
- if not scored:
- return None
- scored.sort(key=lambda pair: pair[1], reverse=True)
- finally:
- conn.close()
+#: Candidates are mined, not agreed. The header carries the whole of that
+#: distinction in the transcript, so it says it in words rather than leaving an
+#: agent to infer a lane from a blank line.
+_CANDIDATE_HEADER = (
+ "[repowise] Proposed but NOT accepted - mined from prior sessions and "
+ "awaiting review. Weigh these; do not treat them as rules:"
+)
- header = (
- "[repowise] Standing decisions relevant to this session's working set "
- "(accumulated from prior sessions; follow them unless the user says otherwise):"
- )
+
+def _rank(
+ decisions: list[dict], seeds: set[str], hop: set[str], tokens: list[str]
+) -> list[dict]:
+ """Decisions above the relevance floor, most relevant first."""
+ scored = [(d, _score_decision(d, seeds, hop, tokens)) for d in decisions]
+ scored = [(d, score) for d, score in scored if score >= _RELEVANCE_FLOOR]
+ scored.sort(key=lambda pair: pair[1], reverse=True)
+ return [d for d, _ in scored]
+
+
+def _select_lines(
+ ranked: list[dict], header: str, token_cap: int, max_items: int, max_globals: int
+) -> tuple[list[str], list[dict]]:
+ """Render *ranked* under its own caps.
+
+ Returns the header plus the rendered lines, and the decisions behind them.
+ The caps are arguments rather than module reads because the two sections
+ are budgeted separately, which is the point of having two.
+ """
lines = [header]
- budget = _TOKEN_CAP - _estimate_tokens(header)
+ budget = token_cap - _estimate_tokens(header)
shown: list[dict] = []
globals_shown = 0
- for decision, _score in scored:
- if len(shown) >= _MAX_ITEMS:
+ for decision in ranked:
+ if len(shown) >= max_items:
break
is_global = _is_repo_wide(decision)
- if is_global and globals_shown >= _MAX_GLOBAL_RULES:
+ if is_global and globals_shown >= max_globals:
continue
line = _format_decision_line(decision)
cost = _estimate_tokens(line)
@@ -497,13 +555,62 @@ def _session_decision_block(repo_path: Path, session_id: str) -> str | None:
shown.append(decision)
if is_global:
globals_shown += 1
- if not shown:
+ return lines, shown
+
+
+def _session_decision_block(repo_path: Path, session_id: str) -> str | None:
+ """The relevance-ranked SessionStart decision block, or None (silence).
+
+ Two sections under two budgets: accepted decisions under ``_TOKEN_CAP``,
+ exactly as before, then candidates under ``_CANDIDATE_TOKEN_CAP``. The
+ accepted section is selected first and nothing in the second can reduce
+ what it holds, so restoring candidates cannot cost an agent a rule it is
+ given today. Either section may come back empty; the block is emitted when
+ either one is not.
+ """
+ conn = _open_wiki_ro(repo_path)
+ if conn is None:
+ return None
+ try:
+ decisions = _load_active_decisions(conn)
+ candidates = _load_candidate_decisions(conn)
+ if not decisions and not candidates:
+ return None
+ seeds, branch = _collect_seeds(repo_path)
+ seed_set = set(seeds)
+ hop = _expand_one_hop(conn, seeds)
+ tokens = _branch_tokens(branch)
+ ranked = _rank(decisions, seed_set, hop, tokens)
+ ranked_candidates = _rank(candidates, seed_set, hop, tokens)
+ finally:
+ conn.close()
+
+ accepted_lines, shown = _select_lines(
+ ranked, _ACCEPTED_HEADER, _TOKEN_CAP, _MAX_ITEMS, _MAX_GLOBAL_RULES
+ )
+ candidate_lines, candidates_shown = _select_lines(
+ ranked_candidates,
+ _CANDIDATE_HEADER,
+ _CANDIDATE_TOKEN_CAP,
+ _MAX_CANDIDATE_ITEMS,
+ _MAX_CANDIDATE_GLOBALS,
+ )
+ lines: list[str] = []
+ if shown:
+ lines += accepted_lines
+ if candidates_shown:
+ lines += candidate_lines
+ if not lines:
return None
from repowise.cli.hook_ledger import _record_injections
block = "\n".join(lines)
_record_injections(
- repo_path, session_id, [d["id"] for d in shown], node_id="", chars=len(block)
+ repo_path,
+ session_id,
+ [d["id"] for d in shown + candidates_shown],
+ node_id="",
+ chars=len(block),
)
return block
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 76f298b6c..7ae33752e 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -393,7 +393,7 @@ async def list_decisions(
if accepted is not None:
predicate = accepted_predicate()
q = q.where(predicate if accepted else ~predicate)
- order = _decision_order(sort)
+ order = decision_priority_order(sort)
if accepted is False and sort != "recent":
# A candidates page is a review queue, so it leads with the rows the
# acceptance contract would take rather than the highest-confidence
@@ -422,8 +422,14 @@ _STATUS_RANK = {
}
-def _decision_order(sort: str) -> tuple[Any, ...]:
- """ORDER BY terms for :func:`list_decisions`."""
+def decision_priority_order(sort: str = "priority") -> tuple[Any, ...]:
+ """ORDER BY terms for :func:`list_decisions`.
+
+ Public because it is the order the Decisions page renders, and an agent
+ surface that serves the same records in a different order is a divergence
+ a reader has to reconcile by hand. ``get_context`` imports it rather than
+ re-spelling the three terms, so the two cannot drift apart silently.
+ """
if sort == "recent":
return (DecisionRecord.created_at.desc(),)
rank = case(_STATUS_RANK, value=DecisionRecord.status, else_=len(DECISION_STATUS_ORDER))
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index d00c5c6f7..8f0bcf9b8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -17,7 +17,12 @@ Optional ``include`` parameter widens the response:
- include=["last_change"]→ last commit date and author
- include=["metrics"] → PageRank, betweenness, percentile ranks
- include=["community"] → community membership + neighbors
- - include=["decisions"] → full decision records (default returns titles only)
+ - include=["decisions"] → decisions governing the target, in three labelled
+ lanes: ``decisions`` (accepted and binding),
+ ``candidates`` (proposed, nobody has agreed),
+ ``history`` (accepted then withdrawn). The last
+ two appear only when non-empty, and are capped.
+ A dismissed record is in none of them.
- include=["skeleton"] → body-elided file rendering (signatures + top-PageRank bodies)
- include=["health"] → code-health scores and biomarkers for the target
- include=["doc_drift"] → documents that name this file, and their drift
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index 2920859af..8435a5656 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -17,12 +17,19 @@ from typing import Any
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.decisions.lifecycle import is_governing
from repowise.core.generation.page_selection import STALE_STATUSES
from repowise.core.ingestion.models import (
NON_DEPENDENCY_EDGE_TYPES,
SYMBOL_USE_EDGE_TYPES,
)
-from repowise.core.persistence.crud import get_kg_layers, get_kg_tour_steps
+from repowise.core.persistence.crud import (
+ accepted_predicate,
+ decision_currencies,
+ decision_priority_order,
+ get_kg_layers,
+ get_kg_tour_steps,
+)
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import (
DecisionRecord,
@@ -66,6 +73,11 @@ from repowise.server.mcp_server.tool_risk.assessment import fix_annotation
#: all, and nothing in the code or its history says whether that is a decision
#: or an omission. This constant only names the cut that already existed.
_MAX_USED_BY = 20
+#: Caps for the two decision lanes that are not the accepted one. A candidate
+#: is a review request rather than a rule, and a withdrawn decision is context,
+#: so neither is worth spending the shared response budget the card needs.
+_MAX_CANDIDATES = 3
+_MAX_DECISION_HISTORY = 2
#: Bound parameters per rank lookup. SQLite's ceiling is 999 before 3.32 and
#: 32,766 after, and which applies depends on the libsqlite3 linked at runtime.
@@ -1066,32 +1078,97 @@ async def _resolve_one_target(
# --- Decisions ---
if include is None or "decisions" in include:
+ # Acceptance is authority, and the status column is not it. This query
+ # used to select every record for the repository with no status, no
+ # acceptance and no dismissed filter and assign the whole list to
+ # ``decisions``, so a machine-mined candidate and a dismissed tombstone
+ # both reached an agent as a rule the repository had settled on.
+ #
+ # The lanes are ``get_why`` path mode's, spelled the same way on
+ # purpose: ``decisions`` is accepted and still binding, ``candidates``
+ # is never accepted, ``history`` is accepted and withdrawn. Two agent
+ # tools answering the same question in two vocabularies is the divergence
+ # the split exists to remove.
+ #
+ # The order is ``decision_priority_order``, which is what the Decisions
+ # page renders through ``crud.list_decisions(sort="priority")``. Ordering
+ # is shared rather than restated so the two surfaces cannot drift.
+ #
+ # The dismissed filter is ``count_decisions_by_lane``'s, and for its
+ # reason: ``dismiss_candidate`` writes ``status = "dismissed"`` both for
+ # a candidate tombstoned so re-extraction never re-proposes it and for a
+ # decision somebody accepted and later withdrew. Only the acceptance row
+ # tells the two apart. A bare ``status != "dismissed"`` drops both, which
+ # loses the withdrawn decision from every lane instead of putting it in
+ # the one that exists for it — and the Decisions page's History lane
+ # shows exactly those records, so dropping them here is a divergence.
res = await session.execute(
- select(DecisionRecord).where(
+ select(DecisionRecord)
+ .where(
DecisionRecord.repository_id == repo_id,
+ or_(DecisionRecord.status != "dismissed", accepted_predicate()),
)
+ .order_by(*decision_priority_order())
)
- all_decisions = res.scalars().all()
- governing = []
+ all_decisions = list(res.scalars().all())
+ currencies = await decision_currencies(session, repo_id, all_decisions)
+ governing: list[dict[str, Any]] = []
+ candidates: list[dict[str, Any]] = []
+ history: list[dict[str, Any]] = []
for d in all_decisions:
affected_files = json.loads(d.affected_files_json)
affected_modules = json.loads(d.affected_modules_json)
- if (
+ if not (
target in affected_files
or target in affected_modules
or (file_path_for_git and file_path_for_git in affected_files)
):
- governing.append(
- {
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "decision": _decision_body(d),
- "rationale": d.rationale,
- "confidence": d.confidence,
- }
- )
+ continue
+ entry: dict[str, Any] = {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "decision": _decision_body(d),
+ "rationale": d.rationale,
+ "confidence": d.confidence,
+ }
+ currency = currencies.get(d.id)
+ if currency is None:
+ entry["authority"] = "candidate"
+ candidates.append(entry)
+ elif is_governing(currency):
+ entry["authority"] = "accepted"
+ entry["currency"] = currency
+ governing.append(entry)
+ else:
+ entry["authority"] = "withdrawn"
+ entry["currency"] = currency
+ history.append(entry)
result_data["decisions"] = governing
+ # The response budget is one ceiling over the whole payload, not one
+ # per block, so an uncapped new lane does not appear beside the card —
+ # it displaces the docs and symbols the caller asked for. Accepted
+ # decisions keep the behaviour they have (a set acceptance keeps small
+ # by construction); the two lanes this adds are capped where they are
+ # built, and what a cap drops is recoverable through the collector.
+ if candidates:
+ cap_collection(
+ result_data,
+ "candidates",
+ candidates,
+ _MAX_CANDIDATES,
+ collector,
+ label=f"{target} :: candidates beyond cap={_MAX_CANDIDATES}",
+ )
+ if history:
+ cap_collection(
+ result_data,
+ "history",
+ history,
+ _MAX_DECISION_HISTORY,
+ collector,
+ label=f"{target} :: decision history beyond cap={_MAX_DECISION_HISTORY}",
+ )
# --- Freshness ---
#
diff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.py
index 09443ff69..2f8c16929 100644
--- a/tests/unit/cli/test_augment_decision_inject.py
+++ b/tests/unit/cli/test_augment_decision_inject.py
@@ -148,7 +148,14 @@ async def test_silence_without_wiki_db(tmp_path):
assert decision_inject._session_decision_block(tmp_path, "sess-1") is None
-async def test_proposed_and_dismissed_never_injected(tmp_path, monkeypatch):
+async def test_an_accepted_record_off_status_reaches_neither_lane(tmp_path, monkeypatch):
+ """Accepted, but not ``active``: not a standing decision and not a candidate.
+
+ Both specs carry an acceptance row, so neither is candidate material; and
+ neither is ``active``, so neither is a standing decision. A store in this
+ shape is inconsistent, and the right response to it is silence rather than
+ a guess about which half to believe.
+ """
await _build_wiki_db(
tmp_path,
[
@@ -629,6 +636,228 @@ def test_detached_head_yields_no_branch(tmp_path, monkeypatch):
assert branch == ""
+# ---------------------------------------------------------------------------
+# The candidate lane at SessionStart
+# ---------------------------------------------------------------------------
+
+
+_CANDIDATE = {
+ "id": "d-cand",
+ "title": "Rotate the auth keys nightly",
+ "decision": "keys are rotated on a nightly cron",
+ "accepted": False,
+ "status": "proposed",
+ "links": [("src/core/auth.py", "file")],
+}
+
+
+async def test_a_candidate_reaches_the_session_labelled_as_one(tmp_path, monkeypatch):
+ """The other half of the contract from the tombstone, and the harder half.
+
+ Before this the hook filtered on acceptance and nothing else, so a store
+ with zero acceptance rows injected nothing at all. Restoring candidates as
+ an unlabelled second stream would have been worse than the silence.
+ """
+ await _build_wiki_db(tmp_path, [_CANDIDATE])
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+
+ assert block is not None
+ assert "Rotate the auth keys nightly" in block
+ assert "NOT accepted" in block
+ assert "Standing decisions" not in block
+
+
+async def test_an_accepted_decision_is_told_apart_from_a_candidate(tmp_path, monkeypatch):
+ """Both reach the agent, in that order, under their own headers."""
+ await _build_wiki_db(tmp_path, [_AUTH_DECISION, _CANDIDATE])
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+
+ assert block is not None
+ lines = block.splitlines()
+ accepted_at = next(i for i, ln in enumerate(lines) if "Standing decisions" in ln)
+ candidate_at = next(i for i, ln in enumerate(lines) if "NOT accepted" in ln)
+ jwt_at = next(i for i, ln in enumerate(lines) if "Use JWT auth" in ln)
+ rotate_at = next(i for i, ln in enumerate(lines) if "Rotate the auth keys" in ln)
+ assert accepted_at < jwt_at < candidate_at < rotate_at
+
+
+async def test_a_dismissed_candidate_reaches_nobody(tmp_path, monkeypatch):
+ """A tombstone carries no acceptance row when it was never accepted, so the
+ acceptance test alone reads it as an ordinary candidate."""
+ await _build_wiki_db(
+ tmp_path,
+ [{**_CANDIDATE, "id": "d-tomb", "title": "Tombstoned rule", "status": "dismissed"}],
+ )
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None
+
+
+async def test_candidates_cannot_displace_an_accepted_decision(tmp_path, monkeypatch):
+ """The budgets are separate, and that is what makes restoring the lane safe.
+
+ The accepted section is selected first under the cap it has always had. A
+ shared budget would mean every candidate admitted costs a rule somebody
+ actually agreed to.
+ """
+ long_text = "this decision line pads the token budget " * 8
+ accepted = [
+ {
+ "id": f"d-a{i}",
+ "title": f"Accepted number {i}",
+ "decision": long_text,
+ "links": [("src/core/auth.py", "file")],
+ }
+ for i in range(8)
+ ]
+ candidates = [
+ {
+ "id": f"d-c{i}",
+ "title": f"Candidate number {i}",
+ "decision": long_text,
+ "accepted": False,
+ "status": "proposed",
+ "links": [("src/core/auth.py", "file")],
+ }
+ for i in range(8)
+ ]
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ alone = tmp_path / "alone"
+ await _build_wiki_db(alone, accepted)
+ both = tmp_path / "both"
+ await _build_wiki_db(both, [*accepted, *candidates])
+
+ block_alone = decision_inject._session_decision_block(alone, "s1")
+ block_both = decision_inject._session_decision_block(both, "s2")
+ assert block_alone is not None and block_both is not None
+
+ def accepted_lines(block: str) -> list[str]:
+ out, seen = [], False
+ for ln in block.splitlines():
+ if "Standing decisions" in ln:
+ seen = True
+ continue
+ if "NOT accepted" in ln:
+ break
+ if seen:
+ out.append(ln)
+ return out
+
+ assert accepted_lines(block_both) == accepted_lines(block_alone)
+ assert any("Candidate number" in ln for ln in block_both.splitlines())
+ # And the accepted section is still the size it was before candidates
+ # existed: eight padded decisions fill it to ``_MAX_ITEMS`` under the
+ # unchanged ``_TOKEN_CAP``. Comparing the two runs alone cannot see a
+ # budget that shrank for both of them.
+ assert len(accepted_lines(block_alone)) == decision_inject._MAX_ITEMS
+
+
+async def test_the_candidate_lane_has_its_own_caps(tmp_path, monkeypatch):
+ long_text = "this candidate line pads the token budget " * 8
+ await _build_wiki_db(
+ tmp_path,
+ [
+ {
+ "id": f"d-c{i}",
+ "title": f"Candidate number {i}",
+ "decision": long_text,
+ "accepted": False,
+ "status": "proposed",
+ "links": [("src/core/auth.py", "file")],
+ }
+ for i in range(8)
+ ],
+ )
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+ assert block is not None
+ lines = block.splitlines()
+ assert sum("Candidate number" in ln for ln in lines) <= decision_inject._MAX_CANDIDATE_ITEMS
+ # Asserted against the accepted cap, not against the candidate one: a test
+ # that reads the constant it is pinning passes whatever that constant is
+ # set to, which is how a budget merged back into ``_TOKEN_CAP`` would go
+ # unnoticed. Half is the loosest reading of "tighter" that still bites.
+ assert decision_inject._CANDIDATE_TOKEN_CAP < decision_inject._TOKEN_CAP
+ assert decision_inject._estimate_tokens(block) <= decision_inject._TOKEN_CAP // 2
+
+
+async def test_a_repo_wide_candidate_never_takes_the_whole_lane(tmp_path, monkeypatch):
+ """A repo-wide candidate clears the floor on every session by construction,
+ so without its own cap the lane would never carry one about the files in
+ hand — and on this store there are thirty of them."""
+ rules = [
+ {
+ "id": f"d-g{i}",
+ "title": f"Global candidate {i}",
+ "decision": f"always follow global candidate number {i}",
+ "source": "session",
+ "kind": AGREEMENT_KIND,
+ "accepted": False,
+ "status": "proposed",
+ # High enough that a repo-wide rule outscores the linked candidate
+ # below (0.5 base vs 0.6 x 0.5 for a seed-file hit). Without that
+ # the linked one leads on relevance whatever the cap is, and the
+ # cap is not what the test would be measuring.
+ "confidence": 1.0,
+ "links": [],
+ }
+ for i in range(5)
+ ]
+ await _build_wiki_db(tmp_path, [*rules, {**_CANDIDATE, "confidence": 0.5}])
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+ assert block is not None
+ lines = block.splitlines()
+ assert (
+ sum("Global candidate" in ln for ln in lines)
+ <= decision_inject._MAX_CANDIDATE_GLOBALS
+ )
+ # The load-bearing half: the lower-scoring linked candidate still gets a
+ # slot, which is only true while the globals are held below the item cap.
+ assert "Rotate the auth keys nightly" in block
+
+
+async def test_a_pre_split_store_yields_no_candidates(tmp_path, monkeypatch):
+ """Such a store cannot tell a candidate from a decision, so it must not try.
+
+ ``_accepted_clause`` degrades to ``1 = 1`` there, which the candidate query
+ negates to nothing. Guessing instead would put the whole review queue of
+ every store written before the split in front of an agent.
+ """
+ await _build_wiki_db(tmp_path, [_AUTH_DECISION, _CANDIDATE])
+ conn = sqlite3.connect(tmp_path / ".repowise" / "wiki.db")
+ conn.execute("DROP TABLE decision_acceptances")
+ conn.commit()
+ conn.close()
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+ assert block is not None
+ assert "NOT accepted" not in block
+ assert "Rotate the auth keys nightly" not in block
+
+
+async def test_candidate_injections_are_recorded(tmp_path, monkeypatch):
+ """The usage-feedback miner has to be able to ask whether a candidate the
+ agent was shown was then followed or contradicted."""
+ await _build_wiki_db(tmp_path, [_AUTH_DECISION, _CANDIDATE])
+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])
+
+ assert decision_inject._session_decision_block(tmp_path, "sess-9") is not None
+
+ conn = sqlite3.connect(tmp_path / ".repowise" / "sessions" / "sessions.db")
+ ids = {r[0] for r in conn.execute("SELECT decision_id FROM injections").fetchall()}
+ conn.close()
+ assert ids == {"d-auth", "d-cand"}
+
+
async def test_a_candidate_is_never_injected(tmp_path):
"""A record with no acceptance is review material, not guidance.
diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.py
index 4669c43b6..2d3ce42b4 100644
--- a/tests/unit/server/mcp/test_context.py
+++ b/tests/unit/server/mcp/test_context.py
@@ -136,9 +136,10 @@ async def test_get_context_single_file(setup_mcp):
# Last change
assert t["last_change"]["author"] == "Alice"
assert t["last_change"]["days_ago"] == 443
- # Decisions
- assert len(t["decisions"]) >= 1
- assert any(d["title"] == "Use JWT for authentication" for d in t["decisions"])
+ # Decisions. The fixture record is ``proposed`` with no acceptance behind
+ # it, so it is a candidate — it used to be served as a governing decision.
+ assert t["decisions"] == []
+ assert any(d["title"] == "Use JWT for authentication" for d in t["candidates"])
# Freshness
assert t["freshness"]["confidence_score"] == 0.85
assert t["freshness"]["freshness_status"] == "fresh"
diff --git a/tests/unit/server/mcp/test_context_decision_lanes.py b/tests/unit/server/mcp/test_context_decision_lanes.py
new file mode 100644
index 000000000..769732990
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_decision_lanes.py
@@ -0,0 +1,285 @@
+"""``get_context`` serves decisions in lanes, and a tombstone in none of them.
+
+The block this pins used to select every ``DecisionRecord`` for the repository
+with no status filter, no acceptance filter and no dismissed filter, and assign
+the whole list to ``decisions``. A machine-mined candidate and a dismissed
+tombstone both reached an agent as a rule the repository had settled on.
+
+Both halves of the contract are tested here, because the easy half is the
+tombstone. An accepted decision must still reach an agent exactly as it does
+today, a candidate must reach it *distinguishably*, and the order must be the
+one the Decisions page renders.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import delete
+
+from repowise.core.persistence.models import DecisionAcceptance, DecisionRecord
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+_TARGET = "src/auth/service.py"
+
+
+def _record(rid: str, did: str, title: str, *, status: str, confidence: float = 0.8):
+ return DecisionRecord(
+ id=did,
+ repository_id=rid,
+ title=title,
+ status=status,
+ context="ctx",
+ decision=f"{title} body",
+ rationale=f"{title} rationale",
+ alternatives_json=json.dumps([]),
+ consequences_json=json.dumps([]),
+ affected_files_json=json.dumps([_TARGET]),
+ affected_modules_json=json.dumps([]),
+ tags_json=json.dumps([]),
+ source="session",
+ confidence=confidence,
+ staleness_score=0.0,
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+
+
+def _acceptance(rid: str, did: str, currency: str) -> DecisionAcceptance:
+ return DecisionAcceptance(
+ repository_id=rid,
+ decision_id=did,
+ seq=1,
+ action="accepted" if currency == "active" else currency,
+ currency=currency,
+ reason="a reason",
+ scope_json=json.dumps([_TARGET]),
+ evidence_json=json.dumps(["commit"]),
+ accepter="tester",
+ )
+
+
+async def _lanes(session, rid, records) -> dict:
+ """Seed *records* and return the target card ``get_context`` builds.
+
+ The shared fixture ships two decisions of its own; this file controls its
+ whole decision population so a lane assertion is about what it seeded.
+ """
+ await session.execute(delete(DecisionRecord))
+ for r in records:
+ session.add(r)
+ await session.flush()
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context([_TARGET], include=["decisions"], compact=True)
+ return result["targets"][_TARGET]
+
+
+async def test_an_accepted_decision_still_reaches_the_agent(session, setup_mcp):
+ """The half that is not the tombstone, and the one worth breaking."""
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-acc", "Accepted rule", status="active"),
+ _acceptance(rid, "d-acc", "active"),
+ ],
+ )
+ titles = [d["title"] for d in t["decisions"]]
+ assert "Accepted rule" in titles
+ entry = next(d for d in t["decisions"] if d["title"] == "Accepted rule")
+ # Every field the old block emitted is still emitted, unchanged.
+ assert entry["id"] == "d-acc"
+ assert entry["status"] == "active"
+ assert entry["decision"] == "Accepted rule body"
+ assert entry["rationale"] == "Accepted rule rationale"
+ assert entry["confidence"] == 0.8
+ # Plus the lane label, which is the new part.
+ assert entry["authority"] == "accepted"
+ assert entry["currency"] == "active"
+
+
+async def test_a_candidate_reaches_the_agent_in_its_own_lane(session, setup_mcp):
+ rid = setup_mcp
+ t = await _lanes(
+ session, rid, [_record(rid, "d-cand", "Mined guess", status="proposed")]
+ )
+ assert [d["title"] for d in t["decisions"]] == []
+ assert [d["title"] for d in t["candidates"]] == ["Mined guess"]
+ assert t["candidates"][0]["authority"] == "candidate"
+
+
+async def test_a_status_column_alone_is_not_authority(session, setup_mcp):
+ """``status = 'active'`` with no acceptance behind it is still a candidate.
+
+ The column is a projection every writer keeps in step, so it agrees right
+ up until something writes it without an acceptance — which is what
+ ``unretire_auto_superseded`` and the resume path both do.
+ """
+ rid = setup_mcp
+ t = await _lanes(
+ session, rid, [_record(rid, "d-lying", "Active but unagreed", status="active")]
+ )
+ assert [d["title"] for d in t["decisions"]] == []
+ assert [d["title"] for d in t["candidates"]] == ["Active but unagreed"]
+
+
+async def test_a_dismissed_candidate_reaches_nobody(session, setup_mcp):
+ """A candidate dismissed without ever being accepted carries no acceptance
+ row, so the acceptance test alone reads its tombstone as a live candidate.
+ Only the SQL exclusion keeps it out — and it must keep out *this* record
+ without also keeping out the accepted-then-withdrawn one below."""
+ rid = setup_mcp
+ t = await _lanes(
+ session, rid, [_record(rid, "d-tomb", "Tombstoned", status="dismissed")]
+ )
+ assert "Tombstoned" not in [d["title"] for d in t["decisions"]]
+ assert "Tombstoned" not in [d["title"] for d in t.get("candidates", [])]
+ assert "Tombstoned" not in [d["title"] for d in t.get("history", [])]
+
+
+async def test_a_withdrawn_decision_is_history_not_a_rule(session, setup_mcp):
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-sup", "Superseded rule", status="superseded"),
+ _acceptance(rid, "d-sup", "superseded"),
+ ],
+ )
+ assert "Superseded rule" not in [d["title"] for d in t["decisions"]]
+ assert [d["title"] for d in t["history"]] == ["Superseded rule"]
+ assert t["history"][0]["authority"] == "withdrawn"
+
+
+async def test_lanes_are_ordered_the_way_the_decisions_page_orders(session, setup_mcp):
+ """Same records, same order, on both surfaces.
+
+ ``decision_priority_order`` is what ``crud.list_decisions(sort="priority")``
+ passes, and that is what the Decisions page renders. Within the candidate
+ lane the order that reaches an agent has to be the order a person reading
+ the dashboard sees, or the two disagree about which guess matters most.
+ """
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-low", "Low confidence", status="proposed", confidence=0.2),
+ _record(rid, "d-high", "High confidence", status="proposed", confidence=0.9),
+ _record(rid, "d-mid", "Mid confidence", status="proposed", confidence=0.5),
+ ],
+ )
+ assert [d["title"] for d in t["candidates"]] == [
+ "High confidence",
+ "Mid confidence",
+ "Low confidence",
+ ]
+
+
+async def test_the_candidate_lane_is_capped(session, setup_mcp):
+ """The response budget is one ceiling over the whole payload, so an
+ uncapped lane does not appear beside the card — it displaces it."""
+ from repowise.server.mcp_server.tool_context import targets as targets_mod
+
+ rid = setup_mcp
+ n = targets_mod._MAX_CANDIDATES + 3
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, f"d-c{i}", f"Guess {i}", status="proposed", confidence=0.9)
+ for i in range(n)
+ ],
+ )
+ assert len(t["candidates"]) == targets_mod._MAX_CANDIDATES
+
+
+async def test_an_accepted_decision_that_names_nothing_is_not_a_rule(session, setup_mcp):
+ """``uncheckable`` is accepted but not governing.
+
+ ``is_governing`` is ``{"active", "needs_review"}``, so an accepted decision
+ the repository can no longer check does not belong in the lane an agent
+ reads as the rules. Tested beside ``superseded`` because the two reach the
+ withdrawn branch by different routes.
+ """
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-unch", "Cannot be checked", status="active"),
+ _acceptance(rid, "d-unch", "uncheckable"),
+ ],
+ )
+ assert [d["title"] for d in t["decisions"]] == []
+ assert [d["title"] for d in t["history"]] == ["Cannot be checked"]
+
+
+async def test_a_decision_accepted_then_dismissed_is_history(session, setup_mcp):
+ """The other dismissal route, and it is not a tombstone.
+
+ ``dismiss_candidate`` writes ``status = "dismissed"`` for both a candidate
+ nobody ever agreed to and a decision somebody accepted and later withdrew.
+ Only the acceptance row tells them apart. Filtering on the status alone
+ drops the withdrawn decision from every lane, while the Decisions page's
+ History lane still shows it — which is the divergence this phase exists to
+ remove, pointing the other way.
+ """
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-wd", "Withdrawn outright", status="dismissed"),
+ _acceptance(rid, "d-wd", "dismissed"),
+ ],
+ )
+ assert [d["title"] for d in t["decisions"]] == []
+ assert [d["title"] for d in t.get("candidates", [])] == []
+ assert [d["title"] for d in t["history"]] == ["Withdrawn outright"]
+ assert t["history"][0]["authority"] == "withdrawn"
+
+
+async def test_the_history_lane_is_capped(session, setup_mcp):
+ from repowise.server.mcp_server.tool_context import targets as targets_mod
+
+ rid = setup_mcp
+ n = targets_mod._MAX_DECISION_HISTORY + 3
+ records = []
+ for i in range(n):
+ records.append(_record(rid, f"d-h{i}", f"Retired {i}", status="superseded"))
+ records.append(_acceptance(rid, f"d-h{i}", "superseded"))
+ t = await _lanes(session, rid, records)
+ assert len(t["history"]) == targets_mod._MAX_DECISION_HISTORY
+
+
+async def test_empty_lanes_cost_nothing(session, setup_mcp):
+ """``decisions`` is always present; the two added lanes appear only when
+ they hold something, so the common card does not grow two empty lists."""
+ rid = setup_mcp
+ t = await _lanes(
+ session,
+ rid,
+ [
+ _record(rid, "d-only", "Accepted only", status="active"),
+ _acceptance(rid, "d-only", "active"),
+ ],
+ )
+ assert "decisions" in t
+ assert "history" not in t
diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
index a36e05993..7ef55b45e 100644
--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
@@ -132,8 +132,15 @@ _SYMBOL_FIELDS = {
"symbol_id",
"target_node_id",
}
+# Every lane that carries decision ids, not just the accepted one. A candidate
+# and a withdrawn decision are followable to ``get_why`` exactly as a governing
+# one is, so a consumer that can follow one can follow all three; listing only
+# ``decisions`` would have made the inventory blind to two thirds of what
+# ``get_context`` and ``get_why`` both emit.
_DECISION_COLLECTIONS = {
"decisions",
+ "candidates",
+ "history",
"lineage",
"recent_reversals",
"top_active",