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(mcp): add canonical get_why evidence references (#1927)

Raghav Chamadiya7f1acb50fb08
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.py
index e0f32a312..a4bb65c9a 100644
--- a/packages/cli/src/repowise/cli/commands/why_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py
@@ -17,6 +17,14 @@ def _capped(values: list, cap: int = _LIST_CAP) -> list:
return list(values or [])[:cap]
+def _with_trust(projected: dict, source: dict) -> dict:
+ """Keep the compact evidence contract visible in default agent output."""
+ for key in ("source", "provenance", "evidence_refs", "restates"):
+ if key in source:
+ projected[key] = source[key]
+ return projected
+
+
def _project_decision(decision: dict) -> dict:
"""One decision record, trimmed to the decision and why it was taken."""
out = {
@@ -34,17 +42,17 @@ def _project_decision(decision: dict) -> dict:
out["affected_files_total"] = total
if decision.get("still_true"):
out["still_true"] = decision["still_true"]
- return out
+ return _with_trust(out, decision)
def _project_episode(episode: dict) -> dict:
- return {
+ return _with_trust({
"kind": episode.get("kind", ""),
"subject": episode.get("subject", ""),
"recorded": episode.get("recorded", ""),
"evidence": episode.get("evidence", ""),
"still_true": episode.get("still_true", ""),
- }
+ }, episode)
_ARCH_LAYERS = (
@@ -71,7 +79,10 @@ def _project_archaeology(arch: dict) -> dict:
rows = arch.get(key) or []
if not rows:
continue
- out[key] = [{f: c.get(f, "") for f in fields} for c in _capped(rows)]
+ out[key] = [
+ _with_trust({f: c.get(f, "") for f in fields}, c)
+ for c in _capped(rows)
+ ]
if len(rows) > len(out[key]):
out[f"{key}_total"] = len(rows)
return out
@@ -173,12 +184,12 @@ def project(payload: dict) -> dict:
commits = origin.get("key_commits") or []
if commits:
out["origin_story"]["key_commits"] = [
- {
+ _with_trust({
"sha": c.get("sha", ""),
"date": c.get("date", ""),
"author": c.get("author", ""),
"message": c.get("message", ""),
- }
+ }, c)
for c in _capped(commits)
]
@@ -205,7 +216,9 @@ def project(payload: dict) -> dict:
out["git_archaeology"] = _project_archaeology(payload["git_archaeology"])
if payload.get("code_rationale"):
out["code_rationale"] = [
- {k: entry.get(k) for k in ("path", "lines", "comment")}
+ _with_trust(
+ {k: entry.get(k) for k in ("path", "lines", "comment")}, entry
+ )
for entry in _capped(payload["code_rationale"])
]
if payload.get("target_context"):
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index dbdd25959..24f5bd419 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -85,6 +85,20 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
expansion_argument="include",
protected=("answer", "confidence", "citations", "next_action_hint"),
),
+ "get_why": ResponseBudgetContract(
+ "blocks",
+ (
+ "related_documentation",
+ "episodes",
+ "origin_story.linked_decisions",
+ "decisions[]",
+ "code_rationale",
+ "git_archaeology",
+ "origin_story",
+ ),
+ expansion_argument=None,
+ protected=("mode", "query", "path", "paths", "target_context", "alignment"),
+ ),
"get_overview": ResponseBudgetContract(
"blocks",
(
diff --git a/packages/server/src/repowise/server/mcp_server/_why_evidence.py b/packages/server/src/repowise/server/mcp_server/_why_evidence.py
new file mode 100644
index 000000000..4b12fb2f1
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_why_evidence.py
@@ -0,0 +1,527 @@
+"""Canonical evidence identity and provenance for :mod:`tool_why` payloads.
+
+Evidence identity is deliberately separate from decision identity. A commit or
+source range can support several real decisions, while one decision can cite
+several commits. The compact ``evidence_refs`` objects emitted here therefore
+describe only the supporting evidence coordinates; decision ids, statuses and
+lineage remain untouched.
+
+The helpers are presentation-only. They do not merge persisted records, use
+text similarity, or introduce another response registry that budgeting could
+leave dangling.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import posixpath
+import re
+import subprocess
+from collections.abc import Iterable, Mapping, Sequence
+from pathlib import Path
+from typing import Any, Literal
+
+ProvenanceKind = Literal[
+ "human_decision",
+ "extracted_rationale",
+ "historical",
+ "inferred",
+ "unknown",
+]
+
+_HUMAN_SOURCES = frozenset({"adr", "cli", "session"})
+_RATIONALE_SOURCES = frozenset(
+ {"code_comment", "comment", "inline_marker", "rationale_comment"}
+)
+_HISTORICAL_SOURCES = frozenset(
+ {"changelog", "commit", "git_archaeology", "pr", "readme_mining"}
+)
+_INFERRED_SOURCES = frozenset({"inferred", "semantic"})
+_FULL_COMMIT_RE = re.compile(r"^[0-9a-fA-F]{40}(?:[0-9a-fA-F]{24})?$")
+
+
+def provenance_for_source(source: str | None) -> ProvenanceKind:
+ """Translate a legacy extractor label into the public trust vocabulary."""
+
+ normalized = (source or "").strip().lower()
+ if normalized in _HUMAN_SOURCES:
+ return "human_decision"
+ if normalized in _RATIONALE_SOURCES:
+ return "extracted_rationale"
+ if normalized in _HISTORICAL_SOURCES:
+ return "historical"
+ if normalized in _INFERRED_SOURCES:
+ return "inferred"
+ return "unknown"
+
+
+def _repository_identity(repository: str) -> str:
+ return repository.strip().replace("\\", "/").strip("/").casefold()
+
+
+def _path_identity(path: str) -> str:
+ normalized = posixpath.normpath(path.strip().replace("\\", "/"))
+ return normalized.removeprefix("./")
+
+
+def _content_id(value: object) -> str:
+ raw = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:20]
+
+
+def _reference(kind: str, repository: str, **coordinates: object) -> dict[str, Any]:
+ identity = {
+ "repository": _repository_identity(repository),
+ "kind": kind,
+ **coordinates,
+ }
+ return {
+ "id": f"ev_{_content_id(identity)}",
+ **identity,
+ }
+
+
+def _commit_value(value: object) -> str:
+ if isinstance(value, str):
+ return value.strip()
+ if isinstance(value, Mapping):
+ for key in ("commit", "sha", "subject", "id"):
+ candidate = value.get(key)
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return ""
+
+
+def _full_commit(
+ value: object, resolved_commits: Mapping[str, str] | None = None
+) -> str | None:
+ candidate = _commit_value(value).lower()
+ if _FULL_COMMIT_RE.fullmatch(candidate):
+ return candidate
+ if len(candidate) < 7 or not re.fullmatch(r"[0-9a-f]+", candidate):
+ return None
+ return (resolved_commits or {}).get(candidate)
+
+
+def commit_reference(
+ repository: str,
+ commit: object,
+ *,
+ resolved_commits: Mapping[str, str] | None = None,
+ fallback: object | None = None,
+) -> dict[str, Any]:
+ """Reference a full commit, or conservatively isolate incomplete history."""
+
+ resolved = _full_commit(commit, resolved_commits)
+ if resolved is not None:
+ return _reference("commit", repository, commit=resolved)
+ raw = _commit_value(commit)
+ legacy = {"commit_prefix": raw, "context": fallback}
+ return _reference(
+ "legacy",
+ repository,
+ content_id=_content_id(legacy),
+ **({"commit_prefix": raw} if raw else {}),
+ )
+
+
+def file_reference(
+ repository: str,
+ path: str,
+ lines: Sequence[int] | None,
+ *,
+ fallback: object | None = None,
+) -> dict[str, Any]:
+ """Reference an exact source range; never equate it with the whole file."""
+
+ normalized_path = _path_identity(path)
+ if lines and len(lines) == 2 and all(isinstance(line, int) and line > 0 for line in lines):
+ start, end = int(lines[0]), int(lines[1])
+ if end >= start:
+ return _reference(
+ "file_range",
+ repository,
+ path=normalized_path,
+ range=[start, end],
+ )
+ return _reference(
+ "legacy",
+ repository,
+ path=normalized_path,
+ content_id=_content_id({"path": normalized_path, "context": fallback}),
+ )
+
+
+def content_reference(
+ repository: str,
+ path: str,
+ lines: Sequence[int] | None,
+ content: str,
+ *,
+ fallback: object | None = None,
+) -> dict[str, Any]:
+ """Reference source text without manufacturing an unavailable end line."""
+
+ normalized_path = _path_identity(path)
+ normalized_content = " ".join(content.split())
+ start = lines[0] if lines and isinstance(lines[0], int) and lines[0] > 0 else None
+ if normalized_content and start is not None:
+ coordinates: dict[str, Any] = {
+ "path": normalized_path,
+ "line": start,
+ "content_id": _content_id(normalized_content),
+ }
+ ref = _reference("file_content", repository, **coordinates)
+ if (
+ len(lines or ()) == 2
+ and isinstance(lines[1], int)
+ and lines[1] >= start
+ ):
+ ref["range"] = [start, int(lines[1])]
+ return ref
+ return file_reference(repository, path, lines, fallback=fallback)
+
+
+def _decision_commits(record: Any) -> list[object]:
+ raw = getattr(record, "evidence_commits_json", None) or "[]"
+ try:
+ commits = json.loads(raw) if isinstance(raw, str) else raw
+ except (TypeError, json.JSONDecodeError):
+ return []
+ return list(commits) if isinstance(commits, list) else []
+
+
+def decision_evidence_refs(
+ record: Any,
+ repository: str,
+ *,
+ resolved_commits: Mapping[str, str] | None = None,
+) -> list[dict[str, Any]]:
+ """Return every piece of evidence cited by one decision record."""
+
+ evidence_rows = list(getattr(record, "_why_evidence_rows", ()) or ())
+ if not evidence_rows:
+ evidence_rows = [record]
+ refs: list[dict[str, Any]] = []
+ for evidence in evidence_rows:
+ source = getattr(evidence, "source", None)
+ commit = getattr(evidence, "evidence_commit", None)
+ commits = [commit] if commit else _decision_commits(evidence)
+ for commit in commits:
+ ref = commit_reference(
+ repository,
+ commit,
+ resolved_commits=resolved_commits,
+ fallback={"evidence_id": getattr(evidence, "id", None)},
+ )
+ ref["provenance"] = "historical"
+ ref["source"] = source
+ refs.append(ref)
+ evidence_file = getattr(evidence, "evidence_file", None)
+ if evidence_file:
+ start = getattr(evidence, "evidence_line", None)
+ quote = getattr(evidence, "source_quote", "") or ""
+ verification = getattr(evidence, "verification", None)
+ if quote and verification in (None, "exact"):
+ ref = content_reference(
+ repository,
+ evidence_file,
+ [start, start] if start else None,
+ quote,
+ fallback={"evidence_id": getattr(evidence, "id", None)},
+ )
+ elif start and verification in (None, "exact"):
+ ref = file_reference(
+ repository,
+ evidence_file,
+ [start, start] if start else None,
+ fallback={"evidence_id": getattr(evidence, "id", None)},
+ )
+ else:
+ ref = _reference(
+ "legacy",
+ repository,
+ path=_path_identity(evidence_file),
+ content_id=_content_id(
+ {
+ "evidence_id": getattr(evidence, "id", None),
+ "source_quote": quote,
+ }
+ ),
+ )
+ ref["provenance"] = provenance_for_source(source)
+ ref["source"] = source
+ if verification:
+ ref["verification"] = verification
+ refs.append(ref)
+ if not refs:
+ ref = _reference(
+ "legacy",
+ repository,
+ content_id=_content_id({"decision_id": record.id}),
+ )
+ ref["provenance"] = provenance_for_source(getattr(record, "source", None))
+ ref["source"] = getattr(record, "source", None)
+ refs.append(ref)
+ unique: dict[tuple[str, object, object], dict[str, Any]] = {}
+ for ref in refs:
+ unique[(ref["id"], ref.get("provenance"), ref.get("source"))] = ref
+ return sorted(
+ unique.values(),
+ key=lambda ref: (ref["id"], str(ref.get("provenance")), str(ref.get("source"))),
+ )
+
+
+def decision_collapse_key(record: Any) -> tuple[object, ...] | None:
+ """Conservative local restatement key, independent of public evidence ids.
+
+ The raw extractor source remains part of this compatibility merge. All
+ commits participate, and only full commit ids or exact source points are
+ safe enough to collapse. Missing ranges therefore retain both records.
+ """
+
+ source = (getattr(record, "source", None) or "").strip().lower()
+ if getattr(record, "status", None) == "superseded" or getattr(
+ record, "superseded_by", None
+ ):
+ return None
+ commits = [_full_commit(commit) for commit in _decision_commits(record)]
+ if commits and all(commits):
+ return ("commits", source, *sorted(set(commits)))
+ evidence_file = getattr(record, "evidence_file", None)
+ evidence_line = getattr(record, "evidence_line", None)
+ if evidence_file and isinstance(evidence_line, int) and evidence_line > 0:
+ return ("file_point", source, _path_identity(evidence_file), evidence_line)
+ return None
+
+
+def _resolved_commits(
+ result: object, records: Iterable[Any], repo_root: str | Path | None
+) -> dict[str, str]:
+ candidates: set[str] = set()
+ for record in records:
+ for value in _decision_commits(record):
+ candidate = _commit_value(value).lower()
+ if re.fullmatch(r"[0-9a-f]{7,64}", candidate):
+ candidates.add(candidate)
+ for evidence in getattr(record, "_why_evidence_rows", ()) or ():
+ candidate = _commit_value(getattr(evidence, "evidence_commit", None)).lower()
+ if re.fullmatch(r"[0-9a-f]{7,64}", candidate):
+ candidates.add(candidate)
+
+ def visit(value: object) -> None:
+ if isinstance(value, Mapping):
+ for key, child in value.items():
+ if key in {"commit", "sha", "subject"}:
+ candidate = _commit_value(child).lower()
+ if re.fullmatch(r"[0-9a-f]{7,64}", candidate):
+ candidates.add(candidate)
+ visit(child)
+ elif isinstance(value, list):
+ for child in value:
+ visit(child)
+
+ visit(result)
+ resolved = {candidate: candidate for candidate in candidates if _FULL_COMMIT_RE.fullmatch(candidate)}
+ prefixes = sorted(candidates - resolved.keys())
+ if not prefixes or repo_root is None:
+ return resolved
+ root = Path(repo_root)
+ try:
+ proc = subprocess.run(
+ ["git", "cat-file", "--batch-check=%(objectname) %(objecttype)"],
+ cwd=str(root),
+ input="".join(f"{prefix}^{{commit}}\n" for prefix in prefixes),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=None,
+ timeout=10,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return resolved
+ for prefix, line in zip(prefixes, proc.stdout.splitlines(), strict=False):
+ parts = line.split()
+ if len(parts) == 2 and parts[1] == "commit" and _FULL_COMMIT_RE.fullmatch(parts[0]):
+ resolved[prefix] = parts[0].lower()
+ return resolved
+
+
+def _annotate_commit_row(
+ row: dict[str, Any],
+ repository: str,
+ resolved_commits: Mapping[str, str],
+ *,
+ channel: str,
+) -> None:
+ commit = row.get("commit") or row.get("sha") or row.get("subject")
+ row["provenance"] = "historical"
+ ref = commit_reference(
+ repository,
+ commit,
+ resolved_commits=resolved_commits,
+ fallback={"channel": channel, "row": row},
+ )
+ ref["provenance"] = "historical"
+ ref["source"] = channel
+ row["evidence_refs"] = [ref]
+
+
+def _annotate_origin(
+ origin: dict[str, Any],
+ repository: str,
+ resolved_commits: Mapping[str, str],
+ records_by_id: Mapping[str, Any],
+ records_by_title: Mapping[str, list[Any]],
+) -> None:
+ if origin.get("available"):
+ origin["provenance"] = "historical"
+ for row in origin.get("key_commits") or []:
+ if isinstance(row, dict):
+ _annotate_commit_row(row, repository, resolved_commits, channel="origin")
+ for linked in origin.get("linked_decisions") or []:
+ if not isinstance(linked, dict):
+ continue
+ linked["provenance"] = "inferred"
+ candidates = records_by_title.get(str(linked.get("title") or ""), [])
+ record = candidates[0] if len(candidates) == 1 else None
+ if record is not None:
+ linked["decision_id"] = record.id
+ linked["decision_provenance"] = provenance_for_source(record.source)
+ linked_refs: list[dict[str, Any]] = []
+ for row in linked.get("evidence_commits") or []:
+ if isinstance(row, dict):
+ _annotate_commit_row(
+ row, repository, resolved_commits, channel="origin_link"
+ )
+ linked_refs.extend(row["evidence_refs"])
+ if linked_refs:
+ linked["evidence_refs"] = linked_refs
+
+
+def annotate_response_evidence(
+ result: dict[str, Any],
+ repository: str,
+ records: Iterable[Any] = (),
+ *,
+ resolved_commits: Mapping[str, str] | None = None,
+) -> dict[str, Any]:
+ """Add self-resolving evidence refs and provenance to every ``get_why`` lane."""
+
+ record_list = list(records)
+ records_by_id = {record.id: record for record in record_list}
+ records_by_title: dict[str, list[Any]] = {}
+ for record in record_list:
+ records_by_title.setdefault(record.title, []).append(record)
+ resolved_commits = dict(resolved_commits or _resolved_commits(result, record_list, None))
+
+ def annotate_decision(row: dict[str, Any]) -> None:
+ record = records_by_id.get(str(row.get("id") or row.get("decision_id") or ""))
+ if record is None:
+ row.setdefault("provenance", "inferred" if row.get("snippet") else "unknown")
+ return
+ row["provenance"] = provenance_for_source(record.source)
+ row["evidence_refs"] = decision_evidence_refs(
+ record, repository, resolved_commits=resolved_commits
+ )
+ for lineage in row.get("lineage") or []:
+ if not isinstance(lineage, dict):
+ continue
+ lineage_record = records_by_id.get(str(lineage.get("id") or ""))
+ lineage["provenance"] = provenance_for_source(
+ getattr(lineage_record, "source", None) or lineage.get("source")
+ )
+ if lineage.get("relation"):
+ lineage["relation_provenance"] = "inferred"
+ if lineage_record is not None:
+ lineage["evidence_refs"] = decision_evidence_refs(
+ lineage_record, repository, resolved_commits=resolved_commits
+ )
+
+ for key in ("decisions", "stale_decisions", "proposed_awaiting_review"):
+ for row in result.get(key) or []:
+ if isinstance(row, dict):
+ annotate_decision(row)
+
+ origins: list[dict[str, Any]] = []
+ origin_story = result.get("origin_story")
+ if isinstance(origin_story, dict):
+ origins.append(origin_story)
+ for context in (result.get("target_context") or {}).values():
+ if not isinstance(context, dict):
+ continue
+ for row in context.get("governing_decisions") or []:
+ if isinstance(row, dict):
+ candidates = records_by_title.get(str(row.get("title") or ""), [])
+ if len(candidates) == 1:
+ row["id"] = candidates[0].id
+ annotate_decision(row)
+ origin = context.get("origin")
+ if isinstance(origin, dict):
+ origins.append(origin)
+ archaeology = context.get("git_archaeology")
+ if isinstance(archaeology, dict):
+ _annotate_archaeology(archaeology, repository, resolved_commits)
+ for origin in origins:
+ _annotate_origin(
+ origin, repository, resolved_commits, records_by_id, records_by_title
+ )
+
+ archaeology = result.get("git_archaeology")
+ if isinstance(archaeology, dict):
+ _annotate_archaeology(archaeology, repository, resolved_commits)
+ for row in result.get("code_rationale") or []:
+ if not isinstance(row, dict):
+ continue
+ row["provenance"] = "extracted_rationale"
+ row["evidence_refs"] = [
+ content_reference(
+ repository,
+ str(row.get("path") or ""),
+ row.get("lines"),
+ str(row.get("comment") or ""),
+ fallback={"comment": row.get("comment")},
+ )
+ ]
+ row["evidence_refs"][0]["provenance"] = "extracted_rationale"
+ row["evidence_refs"][0]["source"] = "live_code_rationale"
+ row["evidence_refs"][0]["verification"] = "exact"
+ for row in result.get("episodes") or []:
+ if isinstance(row, dict):
+ _annotate_commit_row(row, repository, resolved_commits, channel="episode")
+ return result
+
+
+async def annotate_response_evidence_async(
+ result: dict[str, Any],
+ repository: str,
+ records: Iterable[Any] = (),
+ *,
+ repo_root: str | Path,
+) -> dict[str, Any]:
+ """Resolve Git prefixes off the event loop, then annotate synchronously."""
+
+ record_list = list(records)
+ resolved = await asyncio.to_thread(
+ _resolved_commits, result, record_list, repo_root
+ )
+ return annotate_response_evidence(
+ result, repository, record_list, resolved_commits=resolved
+ )
+
+
+def _annotate_archaeology(
+ archaeology: dict[str, Any],
+ repository: str,
+ resolved_commits: Mapping[str, str],
+) -> None:
+ archaeology["provenance"] = "historical"
+ for key in ("file_commits", "cross_references", "git_log"):
+ for row in archaeology.get(key) or []:
+ if isinstance(row, dict):
+ _annotate_commit_row(
+ row, repository, resolved_commits, channel=f"archaeology:{key}"
+ )
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 5d313686c..3d8554f00 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -14,6 +14,7 @@ from sqlalchemy import select
from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
+ DecisionEvidence,
DecisionRecord,
GitMetadata,
)
@@ -43,6 +44,10 @@ from repowise.server.mcp_server._helpers import (
is_excluded,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._why_evidence import (
+ annotate_response_evidence_async,
+ decision_collapse_key,
+)
from repowise.server.mcp_server._why_relevance import (
clears_floor,
question_terms,
@@ -73,7 +78,9 @@ async def get_why(
("why is auth using JWT?"), a file path (governing decisions + origin
story + alignment score), a question anchored to targets, or no query
(decision health dashboard). Falls back to git archaeology when no
- decisions exist for a path — never empty.
+ decisions exist for a path — never empty. Evidence-bearing rows carry an
+ explicit ``provenance`` and self-contained ``evidence_refs``; matching ids
+ mean shared evidence, not independent corroboration.
Args:
query: question, file/module path, or omit for the dashboard.
@@ -134,7 +141,7 @@ async def _why_workspace_search(query: str) -> dict:
not to pool the statistics underneath the floor that exists.
"""
contexts = await _resolve_all_contexts()
- scored: list[tuple[tuple[float, float, int], str, str, Any, list[str]]] = []
+ scored: list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]] = []
for ctx in contexts:
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
@@ -145,7 +152,7 @@ async def _why_workspace_search(query: str) -> dict:
# sha would fold into one and a repo would lose its record.
key_by_id = {d.id: key for key, d in ranked}
for d, folded in _collapse_restatements([d for _, d in ranked]):
- scored.append((key_by_id[d.id], ctx.alias, d.id, d, folded))
+ scored.append((key_by_id[d.id], ctx.alias, ctx, d.id, d, folded))
if not scored:
return {
@@ -160,9 +167,14 @@ async def _why_workspace_search(query: str) -> dict:
# The store's own key first, so relevance, occurrence count and status decide
# as they do within one repo; alias and id only settle what those three leave
# equal, and are here so the answer is the same on two runs.
- scored.sort(key=lambda t: (t[0], t[1], t[2]))
+ scored.sort(key=lambda t: (t[0], t[1], t[3]))
+ selected = scored[:_MAX_WORKSPACE_DECISIONS]
+ for selected_ctx in {entry[2].alias: entry[2] for entry in selected}.values():
+ selected_records = [entry[4] for entry in selected if entry[2] is selected_ctx]
+ async with get_session(selected_ctx.session_factory) as session:
+ await _attach_decision_evidence(session, selected_records)
decisions: list[dict] = []
- for _, alias, _id, d, folded in scored[:_MAX_WORKSPACE_DECISIONS]:
+ for _, alias, selected_ctx, _id, d, folded in selected:
entry = {
"repo": alias,
"id": d.id,
@@ -175,6 +187,9 @@ async def _why_workspace_search(query: str) -> dict:
}
if folded:
entry["restates"] = folded
+ await annotate_response_evidence_async(
+ {"decisions": [entry]}, alias, [d], repo_root=selected_ctx.path
+ )
decisions.append(entry)
return {
"mode": "search",
@@ -198,7 +213,7 @@ async def _why_health_dashboard(repo: str | None) -> dict:
proposed = health["proposed_awaiting_review"]
ungoverned = health["ungoverned_hotspots"]
- return {
+ result_data = {
"mode": "health",
"summary": (
f"{health['summary'].get('active', 0)} active · "
@@ -231,6 +246,13 @@ async def _why_health_dashboard(repo: str | None) -> dict:
"conflicts": health.get("conflicts", [])[:10],
"_meta": _build_meta(repository=repository),
}
+ await _attach_decision_evidence(session, [*stale, *proposed])
+ return await annotate_response_evidence_async(
+ result_data,
+ ctx.alias,
+ [*stale, *proposed],
+ repo_root=ctx.path,
+ )
# --- Path-mode cap and projection -------------------------------------------
@@ -570,6 +592,10 @@ async def _why_path(query: str, repo: str | None) -> dict:
collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)
result_data["_meta"] = _build_meta(repository=repository)
+ await _attach_response_decision_evidence(session, result_data, all_decisions)
+ await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
return _fit_path_response(result_data, ctx.path, collector=collector)
@@ -736,7 +762,7 @@ async def _lineage_for_matches(ctx: Any, keyword_matches: list) -> dict[str, lis
return lineage_by_id
-def _evidence_key(d: Any) -> tuple[str, str] | None:
+def _evidence_key(d: Any) -> tuple[object, ...] | None:
"""The evidence a record cites, as a merge key, or ``None`` when it cites none.
Re-extraction paraphrases a record's prose but not its provenance. The
@@ -747,19 +773,17 @@ def _evidence_key(d: Any) -> tuple[str, str] | None:
like that, which is why one query could return five phrasings of one
decision.
- So the key is the cited evidence plus the extractor that read it, never the
- text. Normalising titles would need a tuned similarity threshold, and a
- wrong merge there hides a human-confirmed record. Keeping ``source`` in the
- key also means two extractors that independently found the same commit stay
- separate, which is the provenance-accretion case ``decision_evidence``
- already models.
+ So the key is every cited full commit, or one exact source range, plus the
+ extractor that read it, never the text. Normalising titles would need a
+ tuned similarity threshold, and a wrong merge there hides a human-confirmed
+ record. Incomplete commit hashes and file-only coordinates return ``None``:
+ preserving an apparent duplicate is safer than erasing a real decision.
+
+ This local decision-restatement key is intentionally narrower than the
+ public evidence ids. A commit can support several real decisions, so shared
+ public evidence never merges decision rows by itself.
"""
- commits = json.loads(getattr(d, "evidence_commits_json", None) or "[]")
- if commits:
- return (d.source or "", f"commit:{commits[0]}")
- if d.evidence_file:
- return (d.source or "", f"file:{d.evidence_file}")
- return None
+ return decision_collapse_key(d)
def _collapse_restatements(records: list) -> list[tuple[Any, list[str]]]:
@@ -769,7 +793,7 @@ def _collapse_restatements(records: list) -> list[tuple[Any, list[str]]]:
*before* the lineage walk, which costs a query per surviving record. Records
citing no evidence at all cannot be compared this way and are always kept.
"""
- by_evidence: dict[tuple[str, str], int] = {}
+ by_evidence: dict[tuple[object, ...], int] = {}
out: list[tuple[Any, list[str]]] = []
for d in records:
key = _evidence_key(d)
@@ -858,12 +882,22 @@ async def _build_target_context(
target_context: dict[str, Any] = {}
for t in targets:
- t_governing = []
+ governing_records = []
for d in all_decisions:
affected = json.loads(d.affected_files_json)
affected_mods = json.loads(d.affected_modules_json)
if t in affected or any(t.startswith(m + "/") for m in affected_mods):
- t_governing.append({"title": d.title, "status": d.status})
+ governing_records.append(d)
+ governing_records.sort(key=_path_decision_sort_key)
+ t_governing = [
+ {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "source": d.source,
+ }
+ for d in governing_records[:_MAX_PATH_DECISIONS]
+ ]
git_m = target_git.get(t)
ctx_entry: dict[str, Any] = {
"governing_decisions": t_governing,
@@ -874,6 +908,8 @@ async def _build_target_context(
"summary": f"No git history for {t}.",
},
}
+ if len(governing_records) > _MAX_PATH_DECISIONS:
+ ctx_entry["governing_decisions_total"] = len(governing_records)
# Git archaeology fallback when no decisions found
if not t_governing:
ctx_entry["git_archaeology"] = await _git_archaeology_fallback(
@@ -926,6 +962,10 @@ async def _why_no_match(
rationale = _mine_rationale(ctx.path, targets, query)
if rationale:
result["code_rationale"] = rationale
+ await _hydrate_response_decision_evidence(ctx, result, all_decisions)
+ await annotate_response_evidence_async(
+ result, ctx.alias, all_decisions, repo_root=ctx.path
+ )
result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
return result
@@ -948,6 +988,68 @@ async def _decision_corpus(session: Any, repository_id: str, exclude_spec: Any)
return [d for d in records if not decision_is_excluded(d, exclude_spec)]
+async def _attach_decision_evidence(session: Any, records: list) -> None:
+ """Attach all persisted provenance rows with one bounded query.
+
+ ``DecisionRecord`` is the compatibility headline. The child rows are the
+ canonical accreted evidence and must travel with it when trust metadata is
+ projected, without introducing an N+1 query in workspace or search modes.
+ """
+ if not records:
+ return
+ ids = [record.id for record in records]
+ rows = list(
+ (
+ await session.execute(
+ select(DecisionEvidence)
+ .where(DecisionEvidence.decision_id.in_(ids))
+ .order_by(
+ DecisionEvidence.source_rank.desc(),
+ DecisionEvidence.created_at.asc(),
+ DecisionEvidence.id.asc(),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ by_decision: dict[str, list[DecisionEvidence]] = {}
+ for row in rows:
+ by_decision.setdefault(row.decision_id, []).append(row)
+ for record in records:
+ record._why_evidence_rows = by_decision.get(record.id, [])
+
+
+async def _attach_response_decision_evidence(
+ session: Any, result: dict[str, Any], records: list
+) -> None:
+ """Hydrate only decision rows that the bounded response will expose."""
+ ids: set[str] = set()
+
+ def visit(value: object) -> None:
+ if isinstance(value, dict):
+ candidate = value.get("id") or value.get("decision_id")
+ if isinstance(candidate, str):
+ ids.add(candidate)
+ for child in value.values():
+ visit(child)
+ elif isinstance(value, list):
+ for child in value:
+ visit(child)
+
+ visit(result)
+ await _attach_decision_evidence(
+ session, [record for record in records if record.id in ids]
+ )
+
+
+async def _hydrate_response_decision_evidence(
+ ctx: Any, result: dict[str, Any], records: list
+) -> None:
+ async with get_session(ctx.session_factory) as session:
+ await _attach_response_decision_evidence(session, result, records)
+
+
async def _load_corpus(repo: str | None, targets: list[str] | None) -> tuple:
"""Repo context, the rankable decision corpus, and git metadata for targets.
@@ -979,7 +1081,7 @@ async def _why_targets(targets: list[str], repo: str | None) -> dict:
return await _why_path(targets[0], repo)
ctx, repository, all_decisions, target_git = await _load_corpus(repo, targets)
- return {
+ result_data = {
"mode": "path",
"paths": targets,
"target_context": await _build_target_context(
@@ -987,6 +1089,10 @@ async def _why_targets(targets: list[str], repo: str | None) -> dict:
),
"_meta": _build_meta(repository=repository, targets=targets),
}
+ await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
+ return await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:
@@ -1044,18 +1150,15 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -
if episodes:
result_data["episodes"] = episodes
+ await _hydrate_response_decision_evidence(ctx, result_data, all_decisions)
+ await annotate_response_evidence_async(
+ result_data, ctx.alias, all_decisions, repo_root=ctx.path
+ )
result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
- # Deliberately *not* routed through `_fit_path_response`. This mode has no
- # budget pass and predates this block, but that function is written for the
- # path response's shape: search mode keeps `origin_story` and
- # `git_archaeology` inside `target_context`, so the two blocks it would
- # drop whole are no-ops here and the only thing it can actually shed is
- # this mode's primary payload. Measured on a realistic six-target
- # response, it emptied `decisions` entirely and was still over budget —
- # strictly worse than leaving it alone. What this block adds is bounded by
- # construction (three episodes, each body capped), which is the obligation
- # it owes; giving the whole mode a budget pass is a separate change with
- # its own drop order to design.
+ # Episode overflow is banked here because it is produced before the shared
+ # final budget pass. The middleware owns the complete search-mode shed
+ # order after trust metadata is attached; routing this shape through the
+ # path-only fitter would discard its primary decision lane prematurely.
collector = bank_overflow(pending, tool="get_why", repo_root=ctx.path)
if collector is not None:
collector.attach(result_data)
@@ -1251,6 +1354,7 @@ async def _run_git_log(
results.append(
{
"sha": parts[0][:12],
+ "commit": parts[0],
"author": parts[1],
"date": parts[2][:10],
"message": parts[3],
@@ -1287,6 +1391,7 @@ async def _run_git_log(
results.append(
{
"sha": parts[0][:12],
+ "commit": parts[0],
"author": parts[1],
"date": parts[2][:10],
"message": parts[3],
diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.py
index c2d7e4f8f..83f979c2f 100644
--- a/tests/unit/cli/test_tool_adapter_commands.py
+++ b/tests/unit/cli/test_tool_adapter_commands.py
@@ -496,6 +496,63 @@ def test_why_projection_keeps_the_handles_on_what_truncation_removed():
assert out["dropped_decisions"] == ["id7"]
+def test_why_projection_keeps_evidence_identity_and_provenance():
+ ref = {
+ "id": "ev_shared",
+ "repository": "default",
+ "kind": "commit",
+ "commit": "a" * 40,
+ "provenance": "historical",
+ "source": "episode",
+ }
+ payload = {
+ "mode": "search",
+ "decisions": [
+ {
+ "id": "d1",
+ "title": "Decision",
+ "source": "session",
+ "provenance": "human_decision",
+ "evidence_refs": [ref],
+ "restates": ["d0"],
+ }
+ ],
+ "episodes": [
+ {
+ "kind": "code_fix",
+ "provenance": "historical",
+ "evidence_refs": [ref],
+ }
+ ],
+ "git_archaeology": {
+ "git_log": [
+ {
+ "sha": "a" * 12,
+ "provenance": "historical",
+ "evidence_refs": [ref],
+ }
+ ]
+ },
+ "code_rationale": [
+ {
+ "path": "a.py",
+ "lines": [1, 2],
+ "comment": "because",
+ "provenance": "extracted_rationale",
+ "evidence_refs": [ref],
+ }
+ ],
+ }
+
+ out = project_why(payload)
+
+ assert out["decisions"][0]["evidence_refs"] == [ref]
+ assert out["decisions"][0]["restates"] == ["d0"]
+ assert out["episodes"][0]["evidence_refs"] == [ref]
+ assert out["git_archaeology"]["git_log"][0]["evidence_refs"] == [ref]
+ assert out["code_rationale"][0]["evidence_refs"] == [ref]
+
+
def test_why_dashboard_projection_caps_each_list_with_its_total():
out = project_why(WHY_DASHBOARD_PAYLOAD)
assert out["counts"] == {"active": 37, "stale": 14}
diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.py
index cd987454e..c9f829df2 100644
--- a/tests/unit/server/mcp/test_response_budget_contracts.py
+++ b/tests/unit/server/mcp/test_response_budget_contracts.py
@@ -22,6 +22,8 @@ from repowise.server.mcp_server._budget import (
def _payload(tool: str, pad: int) -> dict[str, Any]:
if tool == "get_health":
pad = min(pad, 10_000)
+ if tool == "get_why":
+ pad = min(pad, 9_000)
rows = [{"id": i, "evidence": f"EVIDENCE_{tool}_{i}_" + "x" * pad} for i in range(3)]
meta = {"contract_version": 1, "indexed_commit": "a" * 12}
if tool == "get_context":
@@ -58,6 +60,30 @@ def _payload(tool: str, pad: int) -> dict[str, Any]:
"retrieval": rows,
"_meta": meta,
}
+ if tool == "get_why":
+ decisions = [
+ {
+ "id": row["id"],
+ "title": f"Decision {row['id']}",
+ "rationale": row["evidence"],
+ "provenance": "historical",
+ "evidence_refs": [
+ {
+ "id": f"ev_{row['id']}",
+ "repository": "test-repo",
+ "kind": "commit",
+ "commit": f"{row['id']:040x}",
+ }
+ ],
+ }
+ for row in rows
+ ]
+ return {
+ "mode": "search",
+ "query": "why is the response bounded",
+ "decisions": decisions,
+ "_meta": meta,
+ }
if tool == "get_health":
return {
"mode": "dashboard",
@@ -102,6 +128,7 @@ def _enforce(tool: str, payload: dict[str, Any], include: list[str] | None = Non
("get_risk", "directive"),
("get_change_risk", "classification"),
("get_answer", "answer"),
+ ("get_why", "query"),
("get_overview", "title"),
("get_health", "directive"),
],
@@ -140,6 +167,7 @@ def test_default_payload_goldens_keep_action_fields_and_exact_accounting(
("get_risk", "directive"),
("get_change_risk", "classification"),
("get_answer", "answer"),
+ ("get_why", "query"),
("get_overview", "title"),
("get_health", "directive"),
],
@@ -190,6 +218,15 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(
finally:
store.close()
assert any(value is not None and f"EVIDENCE_{tool}" in value for value in recovered)
+ if tool == "get_why":
+ assert len(refs) == 1
+ recovered_payload = recovered[0] or ""
+ emitted_ids = {row["id"] for row in result["decisions"]}
+ for row_id in set(range(3)) - emitted_ids:
+ assert f'"id": {row_id}' in recovered_payload
+ assert f'"id": "ev_{row_id}"' in recovered_payload
+ for row_id in emitted_ids:
+ assert f'"id": {row_id}' not in recovered_payload
if tool == "get_health":
joined = recovered[0] or ""
emitted_ids = {row["id"] for row in result["high_leverage_files"]}
@@ -295,6 +332,29 @@ async def test_middleware_budgets_after_trust_metadata(
assert accounting["serialized_chars"] <= DEFAULT_RESPONSE_CHARS
+async def test_get_why_middleware_accounts_after_trust_and_keeps_refs_recoverable(
+ setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import repowise.server.mcp_server as mcp_mod
+
+ (tmp_path / ".repowise").mkdir()
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+
+ async def get_why() -> dict:
+ return _payload("get_why", 15_000)
+
+ result = await tool_middleware(get_why)()
+ accounting = result["_meta"]["response_budget"]
+ assert result["_meta"]["contract_version"] == 1
+ assert accounting["serialized_chars"] == len(
+ json.dumps(result, separators=(",", ":"), default=str)
+ )
+ assert accounting["serialized_chars"] <= DEFAULT_RESPONSE_CHARS
+ assert all(row["evidence_refs"] for row in result["decisions"])
+ assert len(result["_meta"]["omitted"]["refs"]) == 1
+
+
@pytest.mark.asyncio
async def test_budget_repo_root_follows_workspace_alias(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/server/mcp/test_why_evidence_contract.py b/tests/unit/server/mcp/test_why_evidence_contract.py
new file mode 100644
index 000000000..c6084c8d2
--- /dev/null
+++ b/tests/unit/server/mcp/test_why_evidence_contract.py
@@ -0,0 +1,543 @@
+"""Sealed trust fixture for ``get_why`` evidence identity and provenance."""
+
+from __future__ import annotations
+
+import json
+from copy import deepcopy
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.persistence.models import DecisionEvidence
+from repowise.server.mcp_server._why_evidence import (
+ annotate_response_evidence,
+ decision_collapse_key,
+ provenance_for_source,
+)
+from repowise.server.mcp_server.tool_why import _rank_keyword_matches
+
+_A = "a" * 40
+_B = "b" * 40
+_C = "c" * 40
+_D = "d" * 40
+_E = "e" * 40
+_F = "f" * 40
+
+
+def _record(
+ id_: str,
+ *,
+ title: str,
+ source: str = "pr",
+ commits: list[str] | None = None,
+ evidence_file: str | None = None,
+ evidence_line: int | None = None,
+ source_quote: str = "",
+ files: list[str] | None = None,
+ status: str = "proposed",
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=id_,
+ title=title,
+ status=status,
+ source=source,
+ evidence_commits_json=json.dumps(commits or []),
+ evidence_file=evidence_file,
+ evidence_line=evidence_line,
+ source_quote=source_quote,
+ affected_files_json=json.dumps(files or []),
+ affected_modules_json="[]",
+ decision="Keep the cache bounded and deterministic",
+ rationale="Avoid unbounded memory while preserving stable behavior",
+ context="The cache needs a fixed policy",
+ consequences_json="[]",
+ tags_json="[]",
+ confidence=0.9,
+ staleness_score=0.0,
+ )
+
+
+def sealed_evidence_fixture() -> tuple[list[SimpleNamespace], dict]:
+ target = "src/cache.py"
+ records = [
+ _record(
+ "governing",
+ title="Bound the target cache",
+ source="session",
+ commits=[_A, _B],
+ files=[target],
+ status="active",
+ ),
+ _record(
+ "reextract",
+ title="Re-extracted cache bound",
+ source="session",
+ commits=[_B, _A],
+ files=[target],
+ status="active",
+ ),
+ _record("standing", title="Repository-wide cache guidance", commits=[_C]),
+ _record("similar-one", title="Keep cache behavior stable", commits=[_D]),
+ _record("similar-two", title="Keep cache behavior stable", commits=[_E]),
+ _record(
+ "range",
+ title="Explain the cache range",
+ source="inline_marker",
+ evidence_file="src\\cache.py",
+ evidence_line=20,
+ source_quote="exact supporting range",
+ ),
+ _record("legacy", title="Legacy cache note", evidence_file=target),
+ _record("old", title="Old cache choice", commits=[_F], status="superseded"),
+ _record("new", title="Replacement cache choice", commits=[_A], status="active"),
+ ]
+ payload = {
+ "mode": "search",
+ "query": "why is the target cache bounded",
+ "decisions": [
+ {
+ "id": "governing",
+ "title": "Bound the target cache",
+ "status": "active",
+ "source": "session",
+ "restates": ["reextract"],
+ },
+ {
+ "id": "similar-one",
+ "title": "Keep cache behavior stable",
+ "status": "proposed",
+ "source": "pr",
+ },
+ {
+ "id": "similar-two",
+ "title": "Keep cache behavior stable",
+ "status": "proposed",
+ "source": "pr",
+ },
+ {
+ "id": "new",
+ "title": "Replacement cache choice",
+ "status": "active",
+ "source": "pr",
+ "lineage": [
+ {
+ "id": "old",
+ "title": "Old cache choice",
+ "status": "superseded",
+ "source": "pr",
+ "relation": "supersedes",
+ },
+ {
+ "id": "new",
+ "title": "Replacement cache choice",
+ "status": "active",
+ "source": "pr",
+ "relation": None,
+ },
+ ],
+ },
+ ],
+ "code_rationale": [
+ {"path": target, "lines": [20, 22], "comment": "exact supporting range"},
+ {"path": target, "lines": [30, 32], "comment": "different range"},
+ ],
+ "git_archaeology": {
+ "triggered": True,
+ "file_commits": [{"sha": _C, "message": "independent history"}],
+ "cross_references": [],
+ "git_log": [],
+ },
+ "episodes": [
+ {
+ "tier": "git",
+ "kind": "code_fix",
+ "subject": _A,
+ "recorded": "same commit as the governing decision",
+ "evidence": "commit a",
+ "scope": [target],
+ }
+ ],
+ }
+ return records, payload
+
+
+def test_provenance_vocabulary_is_explicit_and_legacy_safe() -> None:
+ assert provenance_for_source("session") == "human_decision"
+ assert provenance_for_source("inline_marker") == "extracted_rationale"
+ assert provenance_for_source("git_archaeology") == "historical"
+ assert provenance_for_source("inferred") == "inferred"
+ assert provenance_for_source("future_extractor") == "unknown"
+
+
+def test_sealed_fixture_shares_identity_without_merging_decisions(
+ sealed_evidence_fixture,
+) -> None:
+ records, payload = sealed_evidence_fixture
+ result = annotate_response_evidence(payload, "Repo-A", records)
+
+ decisions = {row["id"]: row for row in result["decisions"]}
+ governing_refs = decisions["governing"]["evidence_refs"]
+ assert len(governing_refs) == 2
+ assert all(ref["id"] != decisions["governing"]["id"] for ref in governing_refs)
+ assert decisions["governing"]["provenance"] == "human_decision"
+ assert decisions["governing"]["source"] == "session"
+ assert decisions["governing"]["restates"] == ["reextract"]
+
+ episode_ref = result["episodes"][0]["evidence_refs"][0]
+ assert episode_ref["id"] in {ref["id"] for ref in governing_refs}
+ assert episode_ref["provenance"] == "historical"
+ assert result["episodes"][0]["provenance"] == "historical"
+
+ similar_one = decisions["similar-one"]["evidence_refs"][0]
+ similar_two = decisions["similar-two"]["evidence_refs"][0]
+ assert similar_one["id"] != similar_two["id"]
+ assert {"similar-one", "similar-two"} <= decisions.keys()
+
+ lineage = decisions["new"]["lineage"]
+ assert [(row["id"], row["status"]) for row in lineage] == [
+ ("old", "superseded"),
+ ("new", "active"),
+ ]
+ assert lineage[0]["relation_provenance"] == "inferred"
+
+
+def test_exact_source_content_joins_and_different_source_ranges_do_not(
+ sealed_evidence_fixture,
+) -> None:
+ records, payload = sealed_evidence_fixture
+ result = annotate_response_evidence(payload, "Repo-A", records)
+ range_record = next(record for record in records if record.id == "range")
+ range_result = annotate_response_evidence(
+ {"decisions": [{"id": "range", "source": "inline_marker"}]},
+ "Repo-A",
+ [range_record],
+ )
+ decision_ref = range_result["decisions"][0]["evidence_refs"][0]
+ exact, different = result["code_rationale"]
+
+ assert exact["provenance"] == "extracted_rationale"
+ assert exact["evidence_refs"][0]["id"] == decision_ref["id"]
+ assert exact["evidence_refs"][0]["range"] == [20, 22]
+ assert decision_ref["range"] == [20, 20]
+ assert different["evidence_refs"][0]["id"] != decision_ref["id"]
+
+
+def test_restatement_key_uses_all_commits_and_rejects_incomplete_ranges(
+ sealed_evidence_fixture,
+) -> None:
+ records, _ = sealed_evidence_fixture
+ by_id = {record.id: record for record in records}
+
+ assert decision_collapse_key(by_id["governing"]) == decision_collapse_key(
+ by_id["reextract"]
+ )
+ assert decision_collapse_key(by_id["similar-one"]) != decision_collapse_key(
+ by_id["similar-two"]
+ )
+ assert decision_collapse_key(by_id["legacy"]) is None
+ assert decision_collapse_key(by_id["old"]) is None
+
+
+def test_commit_references_are_deduplicated_and_ordered() -> None:
+ record = _record(
+ "multi", title="Multiple commits", commits=[_B, _A, _B], status="active"
+ )
+ reverse = _record(
+ "multi", title="Multiple commits", commits=[_A, _B], status="active"
+ )
+
+ first = annotate_response_evidence({"decisions": [{"id": "multi"}]}, "Repo-A", [record])
+ second = annotate_response_evidence(
+ {"decisions": [{"id": "multi"}]}, "Repo-A", [reverse]
+ )
+
+ assert first["decisions"][0]["evidence_refs"] == second["decisions"][0][
+ "evidence_refs"
+ ]
+ assert len(first["decisions"][0]["evidence_refs"]) == 2
+
+
+def test_shared_evidence_does_not_collapse_a_superseded_decision() -> None:
+ old = _record(
+ "old", title="Old choice", commits=[_A], status="superseded"
+ )
+ new = _record("new", title="New choice", commits=[_A], status="active")
+
+ assert decision_collapse_key(old) is None
+ assert decision_collapse_key(new) is not None
+
+
+def test_incomplete_coordinates_remain_conservative() -> None:
+ first = _record("legacy-one", title="Same words", evidence_file="src/cache.py")
+ second = _record("legacy-two", title="Same words", evidence_file="src/cache.py")
+ payload = {"decisions": [{"id": first.id}, {"id": second.id}]}
+
+ result = annotate_response_evidence(payload, "Repo-A", [first, second])
+ refs = [row["evidence_refs"][0] for row in result["decisions"]]
+ assert refs[0]["kind"] == refs[1]["kind"] == "legacy"
+ assert refs[0]["id"] != refs[1]["id"]
+
+
+def test_unknown_source_is_preserved_without_claiming_stronger_provenance() -> None:
+ record = _record("future", title="Future source", source="future_extractor")
+ payload = {"decisions": [{"id": record.id, "source": record.source}]}
+
+ result = annotate_response_evidence(payload, "Repo-A", [record])
+ assert result["decisions"][0]["source"] == "future_extractor"
+ assert result["decisions"][0]["provenance"] == "unknown"
+
+
+def test_accreted_evidence_preserves_each_source_role() -> None:
+ record = _record("accreted", title="Accreted", source="session")
+ record._why_evidence_rows = [
+ SimpleNamespace(
+ id="human-evidence",
+ source="session",
+ evidence_commit=None,
+ evidence_file="docs/decision.md",
+ evidence_line=8,
+ source_quote="Choose bounded caching",
+ verification="exact",
+ ),
+ SimpleNamespace(
+ id="comment-evidence",
+ source="inline_marker",
+ evidence_commit=None,
+ evidence_file="src/cache.py",
+ evidence_line=20,
+ source_quote="exact supporting range",
+ verification="exact",
+ ),
+ SimpleNamespace(
+ id="fuzzy-evidence",
+ source="inline_marker",
+ evidence_commit=None,
+ evidence_file="src/cache.py",
+ evidence_line=44,
+ source_quote="approximately the same rationale",
+ verification="fuzzy",
+ ),
+ ]
+
+ result = annotate_response_evidence(
+ {"decisions": [{"id": record.id, "source": record.source}]},
+ "Repo-A",
+ [record],
+ )
+ decision = result["decisions"][0]
+
+ assert decision["provenance"] == "human_decision"
+ assert {ref["provenance"] for ref in decision["evidence_refs"]} == {
+ "human_decision",
+ "extracted_rationale",
+ }
+ assert {ref["source"] for ref in decision["evidence_refs"]} == {
+ "session",
+ "inline_marker",
+ }
+ fuzzy = next(ref for ref in decision["evidence_refs"] if ref.get("verification") == "fuzzy")
+ assert fuzzy["kind"] == "legacy"
+ assert "line" not in fuzzy and "range" not in fuzzy
+
+
+def test_orphan_semantic_decision_does_not_invent_evidence_identity() -> None:
+ result = annotate_response_evidence(
+ {"decisions": [{"id": "semantic-only", "snippet": "nearest decision"}]},
+ "Repo-A",
+ )
+
+ assert result["decisions"] == [
+ {
+ "id": "semantic-only",
+ "snippet": "nearest decision",
+ "provenance": "inferred",
+ }
+ ]
+
+
+async def test_persisted_evidence_rows_accrete_into_the_public_decision(
+ setup_mcp, factory
+) -> None:
+ from repowise.server.mcp_server import get_why
+
+ async with factory() as session:
+ session.add_all(
+ [
+ DecisionEvidence(
+ id="evidence-human",
+ decision_id="dec1",
+ source="session",
+ source_rank=5,
+ evidence_file="docs/auth.md",
+ evidence_line=4,
+ source_quote="Use JWT for all API authentication",
+ confidence=1.0,
+ verification="exact",
+ ),
+ DecisionEvidence(
+ id="evidence-rationale",
+ decision_id="dec1",
+ source="inline_marker",
+ source_rank=2,
+ evidence_file="src/auth/service.py",
+ evidence_line=12,
+ source_quote="JWT keeps authentication stateless",
+ confidence=0.9,
+ verification="exact",
+ ),
+ ]
+ )
+ await session.commit()
+
+ result = await get_why("why is JWT used for authentication")
+ path_result = await get_why("src/auth/service.py")
+ decision = next(row for row in result["decisions"] if row["id"] == "dec1")
+ path_decision = next(row for row in path_result["decisions"] if row["id"] == "dec1")
+
+ assert {ref["provenance"] for ref in decision["evidence_refs"]} == {
+ "human_decision",
+ "extracted_rationale",
+ }
+ assert {ref["source"] for ref in decision["evidence_refs"]} == {
+ "session",
+ "inline_marker",
+ }
+ assert path_decision["evidence_refs"] == decision["evidence_refs"]
+
+
+def test_evidence_ids_are_order_independent_and_repository_scoped(
+ sealed_evidence_fixture,
+) -> None:
+ records, payload = sealed_evidence_fixture
+ forward = annotate_response_evidence(deepcopy(payload), "Repo-A", records)
+ reverse = annotate_response_evidence(deepcopy(payload), "Repo-A", list(reversed(records)))
+ other_repo = annotate_response_evidence(deepcopy(payload), "Repo-B", records)
+ with_freshness = deepcopy(payload)
+ with_freshness["_meta"] = {"indexed_commit": _A, "live_head": _B}
+ with_freshness = annotate_response_evidence(with_freshness, "Repo-A", records)
+
+ def ids(result: dict) -> dict[str, list[str]]:
+ return {
+ row["id"]: [ref["id"] for ref in row["evidence_refs"]]
+ for row in result["decisions"]
+ }
+
+ assert ids(forward) == ids(reverse)
+ assert ids(forward) == ids(with_freshness)
+ assert ids(forward)["governing"] != ids(other_repo)["governing"]
+ assert forward["episodes"][0]["evidence_refs"][0]["repository"] == "repo-a"
+ assert other_repo["episodes"][0]["evidence_refs"][0]["repository"] == "repo-b"
+
+
+def test_target_governing_record_ranks_before_unrelated_standing_decision(
+ sealed_evidence_fixture,
+) -> None:
+ records, _ = sealed_evidence_fixture
+ by_id = {record.id: record for record in records}
+ ranked = _rank_keyword_matches(
+ [by_id["standing"], by_id["governing"]],
+ "why is the cache guidance bounded",
+ {"src/cache.py"},
+ )
+
+ assert ranked[0].id == "governing"
+
+
+async def test_every_single_repository_query_mode_keeps_the_exact_public_reference(
+ setup_mcp,
+) -> None:
+ from repowise.server.mcp_server import get_why
+
+ expected = {
+ "id": "ev_3d722ae232bb20add04b",
+ "repository": "default",
+ "kind": "legacy",
+ "content_id": "8962562181b9a6600ce9",
+ "provenance": "historical",
+ "source": "readme_mining",
+ }
+ calls = [
+ await get_why("why is JWT used for authentication"),
+ await get_why(
+ "authentication approach",
+ targets=["src/auth/service.py"],
+ ),
+ await get_why("src/auth/service.py"),
+ await get_why(targets=["src/auth/service.py"]),
+ ]
+ for result in calls:
+ decision = next(row for row in result["decisions"] if row["id"] == "dec1")
+ assert decision["source"] == "readme_mining"
+ assert decision["provenance"] == "historical"
+ assert decision["evidence_refs"] == [expected]
+ assert list(decision)[-2:] == ["provenance", "evidence_refs"]
+
+ multi_target = await get_why(
+ targets=["src/auth/service.py", "src/auth/middleware.py"]
+ )
+ target_decision = multi_target["target_context"]["src/auth/service.py"][
+ "governing_decisions"
+ ][0]
+ assert target_decision == {
+ "id": "dec1",
+ "title": "Use JWT for authentication",
+ "status": "proposed",
+ "source": "readme_mining",
+ "provenance": "historical",
+ "evidence_refs": [expected],
+ }
+
+ dashboard = await get_why()
+ proposed = next(row for row in dashboard["proposed_awaiting_review"] if row["id"] == "dec1")
+ assert proposed["source"] == "readme_mining"
+ assert proposed["provenance"] == "historical"
+ assert proposed["evidence_refs"] == [expected]
+
+
+async def test_every_single_repository_mode_is_exactly_accounted_after_middleware(
+ setup_mcp,
+) -> None:
+ from repowise.server.mcp_server import get_why, tool_middleware
+
+ call = tool_middleware(get_why)
+ results = [
+ await call("why is JWT used for authentication"),
+ await call("src/auth/service.py"),
+ await call(targets=["src/auth/service.py", "src/auth/middleware.py"]),
+ await call(),
+ ]
+
+ for result in results:
+ accounting = result["_meta"]["response_budget"]
+ assert accounting["serialized_chars"] == len(
+ json.dumps(result, separators=(",", ":"), default=str)
+ )
+ assert accounting["serialized_chars"] <= accounting["limit_chars"]
+
+
+async def test_no_decision_and_unsupported_modes_remain_compatible(setup_mcp) -> None:
+ from repowise.server.mcp_server import get_why
+
+ fallback = await get_why("src/other/utils.py")
+ assert list(fallback)[:5] == [
+ "mode",
+ "path",
+ "decisions",
+ "origin_story",
+ "alignment",
+ ]
+ assert fallback["decisions"] == []
+ assert fallback["git_archaeology"]["provenance"] == "historical"
+
+ unsupported = await get_why(repo="all")
+ assert unsupported == {
+ "error": (
+ "repo='all' is not supported for get_why (health dashboard). "
+ "Specify a repo alias instead. Available: []"
+ )
+ }
diff --git a/tests/unit/server/mcp/test_why_search_payload.py b/tests/unit/server/mcp/test_why_search_payload.py
index ab836c860..9cbf29b20 100644
--- a/tests/unit/server/mcp/test_why_search_payload.py
+++ b/tests/unit/server/mcp/test_why_search_payload.py
@@ -99,7 +99,7 @@ async def test_search_collapses_restatements_of_one_decision(session, setup_mcp)
setup_mcp,
id_=f"restate{n}",
title=f"Zebrafish caching, phrasing {n}",
- commits=["deadbeef"],
+ commits=["deadbeef" * 5],
confidence=0.9 - n / 100,
)
@@ -116,8 +116,20 @@ async def test_search_keeps_records_citing_different_commits_apart(session, setu
"""The key is the cited evidence, so two real decisions must not merge."""
from repowise.server.mcp_server import get_why
- await _seed(session, setup_mcp, id_="ev1", title="Zebrafish caching one", commits=["aaa"])
- await _seed(session, setup_mcp, id_="ev2", title="Zebrafish caching two", commits=["bbb"])
+ await _seed(
+ session,
+ setup_mcp,
+ id_="ev1",
+ title="Zebrafish caching one",
+ commits=["a" * 40],
+ )
+ await _seed(
+ session,
+ setup_mcp,
+ id_="ev2",
+ title="Zebrafish caching two",
+ commits=["b" * 40],
+ )
result = await get_why("why zebrafish caching")
served = {d["id"] for d in result["decisions"]}
diff --git a/tests/unit/server/mcp/test_why_workspace_ranking.py b/tests/unit/server/mcp/test_why_workspace_ranking.py
index 69d84bd8d..8ccd308aa 100644
--- a/tests/unit/server/mcp/test_why_workspace_ranking.py
+++ b/tests/unit/server/mcp/test_why_workspace_ranking.py
@@ -65,10 +65,18 @@ async def _uninstall(registry: _MockRegistry) -> None:
setattr(mcp_mod, attr, None)
-async def _store(tmp_path, alias: str, records: list) -> tuple:
+async def _store(
+ tmp_path, alias: str, records: list, *, repo_name: str | None = None
+) -> tuple:
repo_dir = tmp_path / alias
repo_dir.mkdir()
- return await _make_repo_context(alias, str(repo_dir), pages=[], extra_models=records)
+ return await _make_repo_context(
+ alias,
+ str(repo_dir),
+ pages=[],
+ extra_models=records,
+ repo_name=repo_name,
+ )
@pytest.fixture
@@ -123,7 +131,20 @@ async def test_a_partial_match_in_an_earlier_store_is_left_under_the_floor(two_r
assert result["workspace"] is True
assert [d["id"] for d in result["decisions"]] == ["b-1"]
- assert result["decisions"][0]["repo"] == "beta"
+ decision = result["decisions"][0]
+ assert decision["repo"] == "beta"
+ assert decision["source"] == "cli"
+ assert decision["provenance"] == "human_decision"
+ assert decision["evidence_refs"] == [
+ {
+ "id": "ev_fb245a52dbd371b929d4",
+ "repository": "beta",
+ "kind": "legacy",
+ "content_id": "338f3ae3ca60c54e7741",
+ "provenance": "human_decision",
+ "source": "cli",
+ }
+ ]
@pytest.mark.asyncio
@@ -212,3 +233,44 @@ async def test_workspace_search_serves_five_of_nine_answers(tmp_path):
assert len(result["decisions"]) == 5
finally:
await _uninstall(registry)
+
+
+async def test_workspace_and_single_repo_share_alias_scoped_evidence_ids(tmp_path):
+ """A persisted display name must not change identity across query modes."""
+ import json
+
+ from repowise.server.mcp_server import get_why, tool_middleware
+
+ ctx = await _store(
+ tmp_path,
+ "frontend",
+ [
+ _decision(
+ "fe-1",
+ "repo-frontend",
+ "Redis session cache",
+ "Use Redis as the session cache backend",
+ evidence_commits_json='["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]',
+ )
+ ],
+ repo_name="web-client",
+ )
+ registry = _install({"frontend": ctx}, "frontend", tmp_path)
+ try:
+ query = "why is Redis the session cache backend"
+ call = tool_middleware(get_why)
+ single = await call(query=query, repo="frontend")
+ workspace = await call(query=query, repo="all")
+
+ single_ref = single["decisions"][0]["evidence_refs"][0]
+ workspace_ref = workspace["decisions"][0]["evidence_refs"][0]
+ assert single_ref == workspace_ref
+ assert single_ref["repository"] == "frontend"
+ for result in (single, workspace):
+ accounting = result["_meta"]["response_budget"]
+ assert accounting["serialized_chars"] == len(
+ json.dumps(result, separators=(",", ":"), default=str)
+ )
+ finally:
+ await _uninstall(registry)