Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): make emitted references round-trip across tools (#1932)
Raghav Chamadiyac2f915d07c11
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 9bcef5e52..2014cedf7 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -323,6 +323,7 @@ Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.| `context_lines` | int | No | Extra source lines before/after the symbol (0-50, default 0) || `depth` | int | No | Follow the call graph outward from this symbol and include what it calls, with bodies (1-3, default 1 = this symbol only). Out-of-range values clamp. || `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |+| `reference` | object | No | A structured `continuation_reference` or `fetch_reference` emitted by this tool; pass it unchanged to retain both id and repository scope. |**Returns:** For a symbol id or range: the source (bounded at ~600 lines,each line prefixed with its file line number in the same format as a `Read`@@ -611,12 +612,15 @@ Architectural decision intelligence. Falls back to git archaeology when no decis| `query` | string | No | Natural language question about decisions, OR a file/module path || `targets` | list[string] | No | File paths to anchor an NL `query` search to || `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` (only when `query` is given) |+| `id` | string | No | A decision id or `ev_...` evidence id previously emitted by `get_why`; resolves it directly without relevance search |+| `reference` | object | No | An emitted evidence reference object; pass it unchanged to retain both id and repository scope. |**Modes:**1. **NL search**: pass a question, optionally anchored to `targets`: `get_why(query="why JWT over sessions?")` -> searches decision records.2. **Path-based**: pass a file path as `query`: `get_why(query="src/auth/service.ts")` -> returns decisions governing that file plus its origin story.3. **Health dashboard**: no `query`: `get_why()` -> stale decisions, conflicts, ungoverned hotspots.+4. **Reference lookup**: pass `id`: `get_why(id="ev_...")` -> the exact evidence and supporting decision in one call.**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.@@ -654,6 +658,7 @@ Unreachable code, unused exports, unused internals, and zombie packages, sorted| `include_zombie_packages` | boolean | No | Include zombie-package findings (default `true`) || `no_unreachable` | boolean | No | Exclude `unreachable_file` findings (default `false`) || `no_unused_exports` | boolean | No | Exclude `unused_export` findings (default `false`) |+| `finding_id` | string | No | Resolve an emitted stable finding `id` directly in one call |**Returns:** Dead code findings grouped by confidence tier (high >= 0.8, medium, low). Each finding includes: file path, kind, confidence score, line count, and cleanup impact estimate. In workspace mode, confidence is lowered on findings other repos still import.@@ -686,6 +691,8 @@ code-health merge-gate judges it on.| `only` | list[string] | No | Keep just these top-level keys. `include` adds blocks, `only` subtracts them. `mode`, `_meta`, `unresolved`, `known_modules` and each kept list's `*_total` sibling always survive. The three `include` **block** names work as aliases: `biomarkers`→`findings`, `accuracy`→`defect_accuracy`, `refactoring`→`refactoring_plans`. The `include` **dimension** names (`performance`, `defect`, `maintainability`) do not — they filter rows inside several blocks and have no single key to resolve to, so they land in `unknown_only_keys`. Nor does `signals`, which merges into `metrics[].signals` — in targeted mode, where `signals` applies, name `metrics` instead. || `repo` | string | No | *(workspace only)* Target repo alias || `limit` | int | No | Max rows in **every** ranked list (default 20, capped at 50). `0` means no rows; the `*_total` siblings still report the true counts. |+| `finding_id` | string | No | Resolve an emitted stable health-finding `id` directly in one call. |+| `plan_id` | string | No | Resolve an emitted stable refactoring-plan `id` directly in one call. |**Returns:** Dashboard mode (no `targets`) returns a `directive`, repo-level KPIs(hotspot health, average health, worst performer, maintainability / performance@@ -879,7 +886,7 @@ of the ten-tool headline set.Lists the repos this server is serving. No parameters.-**Returns:** In workspace mode, `workspace: true`, the workspace root, the default repo alias, and every configured repo alias (`repos`). In single-repo mode, `workspace: false` and a single `"default"` alias.+**Returns:** In workspace mode, `workspace: true`, the workspace root, the default repo alias, and every configured repo's `alias`, config-relative `path`, and `absolute_path`. Any of those emitted identities can be passed unchanged as `repo` to workspace-aware tools. In single-repo mode, `workspace: false` and a single `"default"` alias.**When to use:** Discovering the `repo` aliases to pass to other tools, especially in workspace mode.@@ -994,7 +1001,7 @@ get_execution_flows(entry_point="src/cli/main.py::main", max_depth=4)Turns one structured refactoring plan from `get_health(include=["refactoring"])` into actual generated code and a unified diff, grounded on the plan plus the real source spans it references. For Extract Class, the result includes an LCOM4 before/after self-check.-**Off by default twice over:** it must be opted into the tool surface (`mcp.tools: ["+generate_refactoring_code"]`), and even then returns `{"error": "disabled", ...}` unless `refactoring.llm.enabled: true` is set in the repo's `.repowise/config.yaml`. When enabled, it uses the repo's configured LLM provider/model (bring your own key) and caches results by a content hash, so an unchanged plan never regenerates.+**Off by default twice over:** it must be opted into the tool surface (`mcp.tools: ["+generate_refactoring_code"]`), and generation remains unavailable unless `refactoring.llm.enabled: true` is set in the repo's `.repowise/config.yaml`. A valid plan id still resolves while generation is disabled, returning the canonical plan plus `generation.available: false`. When enabled, it uses the repo's configured LLM provider/model (bring your own key) and caches results by a content hash, so an unchanged plan never regenerates.**Parameters:**@@ -1016,7 +1023,7 @@ generate_refactoring_code(suggestion_id="a1b2c3d4")In workspace mode (initialized with `repowise init .`), all tools accept an optional `repo` parameter:- **Omit `repo`**: queries the default (primary) repo-- **`repo="backend"`**: targets a specific repo by alias+- **`repo="backend"`**: targets a specific repo by any `alias`, `path`, or `absolute_path` emitted by `list_repos`- **`repo="all"`**: queries across all workspace repos (fully supported by `search_codebase`; `get_context` and `get_overview` also accept it; not supported by `get_symbol`, `get_dependency_path`, or `get_execution_flows`)The MCP server automatically enriches responses with cross-repo intelligence:diff --git a/packages/cli/src/repowise/cli/commands/expand_cmd.py b/packages/cli/src/repowise/cli/commands/expand_cmd.pyindex 4937b8e31..f4bcdcab0 100644--- a/packages/cli/src/repowise/cli/commands/expand_cmd.py+++ b/packages/cli/src/repowise/cli/commands/expand_cmd.py@@ -28,17 +28,14 @@ def expand_command(ref: str, query: str | None) -> None:``repowise distill``. Looks in the current repo's store first, then theuser-level fallback store."""- from repowise.core.distill.markers import MARKER_RE, is_valid_ref+ from repowise.core.distill.markers import normalize_reffrom repowise.core.distill.store import OmissionStore- # Accept a pasted whole marker, not just the bare ref.- if not is_valid_ref(ref):- match = MARKER_RE.search(ref)- if match:- ref = match.group("ref")- if not is_valid_ref(ref):+ normalized = normalize_ref(ref)+ if normalized is None:click.echo(f"Not a valid omission ref: {ref!r} (expected 12 hex chars)", err=True)sys.exit(2)+ ref = normalizedfor db_path in _candidate_stores():if not db_path.exists():diff --git a/packages/core/src/repowise/core/distill/markers.py b/packages/core/src/repowise/core/distill/markers.pyindex 3a3079772..efcf19d70 100644--- a/packages/core/src/repowise/core/distill/markers.py+++ b/packages/core/src/repowise/core/distill/markers.py@@ -18,6 +18,7 @@ _MARKER_TEMPLATE = ()MARKER_RE = re.compile(r"\[repowise#(?P<ref>[0-9a-f]{12}):[^\]]*\]")+OMISSION_ID_RE = re.compile(r"^repowise#(?P<ref>[0-9a-f]{12})$")def render_marker(ref: str, lines_omitted: int, tokens_omitted: int) -> str:@@ -44,3 +45,16 @@ def parse_marker_refs(text: str) -> list[str]:def is_valid_ref(ref: str) -> bool:"""True when *ref* looks like a store key (12 lowercase hex chars)."""return bool(re.fullmatch(r"[0-9a-f]{12}", ref))+++def normalize_ref(value: str) -> str | None:+ """Return the bare store key from any public omission-reference shape."""++ candidate = value.strip()+ if is_valid_ref(candidate):+ return candidate+ direct = OMISSION_ID_RE.fullmatch(candidate)+ if direct:+ return direct.group("ref")+ marker = MARKER_RE.search(candidate)+ return marker.group("ref") if marker else Nonediff --git a/packages/core/src/repowise/core/distill/store.py b/packages/core/src/repowise/core/distill/store.pyindex e5d25586c..b36ba3412 100644--- a/packages/core/src/repowise/core/distill/store.py+++ b/packages/core/src/repowise/core/distill/store.py@@ -42,6 +42,12 @@ CREATE TABLE IF NOT EXISTS omissions (kept_tokens INTEGER NOT NULL,access_count INTEGER NOT NULL DEFAULT 0);+CREATE TABLE IF NOT EXISTS evidence_references (+ ref TEXT PRIMARY KEY,+ content BLOB NOT NULL,+ repository TEXT NOT NULL,+ created_at REAL NOT NULL+);CREATE TABLE IF NOT EXISTS savings (id INTEGER PRIMARY KEY AUTOINCREMENT,created_at REAL NOT NULL,@@ -151,6 +157,9 @@ class OmissionStore:or ``None`` when the ref is unknown/expired. *query* filters thecontent lines exactly as in :meth:`get`."""+ from repowise.core.distill.markers import normalize_ref++ ref = normalize_ref(ref) or ""if not is_valid_ref(ref):return Nonerow = self._conn.execute(@@ -198,6 +207,41 @@ class OmissionStore:)self._conn.commit()+ # -- machine-joinable evidence references -----------------------------++ def put_evidence_reference(+ self, ref: str, content: str, *, repository: str+ ) -> None:+ """Persist one exact evidence object under its canonical public id."""++ blob = zlib.compress(content.encode("utf-8"))+ self._conn.execute(+ """+ INSERT INTO evidence_references (ref, content, repository, created_at)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(ref) DO UPDATE SET+ content = excluded.content,+ repository = excluded.repository,+ created_at = excluded.created_at+ """,+ (ref, blob, repository, time.time()),+ )+ self._conn.commit()++ def get_evidence_reference(self, ref: str) -> dict[str, str] | None:+ """Return one exact persisted evidence object, if present."""++ row = self._conn.execute(+ "SELECT content, repository FROM evidence_references WHERE ref = ?",+ (ref,),+ ).fetchone()+ if row is None:+ return None+ return {+ "content": zlib.decompress(row[0]).decode("utf-8"),+ "repository": row[1],+ }+# -- savings ledger ----------------------------------------------------def record_saving(diff --git a/packages/core/src/repowise/core/workspace/registry.py b/packages/core/src/repowise/core/workspace/registry.pyindex a023f44cd..6034d7b71 100644--- a/packages/core/src/repowise/core/workspace/registry.py+++ b/packages/core/src/repowise/core/workspace/registry.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging+import osimport timefrom collections.abc import Callablefrom dataclasses import dataclass, field@@ -86,6 +87,45 @@ class RepoRegistry:self._contexts: dict[str, RepoContext] = {}self._access_order: dict[str, float] = {}self._vs_tasks: dict[str, asyncio.Task[None]] = {}+ self._validate_public_identities()++ def _identity_key(self, value: str | Path) -> str:+ return os.path.normcase(Path(value).as_posix().rstrip("/") or ".").replace(+ "\\", "/"+ )++ @staticmethod+ def _alias_key(value: str) -> str:+ return value.strip().casefold()++ def _validate_public_identities(self) -> None:+ owners: dict[str, str] = {}+ alias_owners = {+ self._alias_key(entry.alias): entry.alias for entry in self._ws_config.repos+ }+ for entry in self._ws_config.repos:+ if self._alias_key(entry.alias) == "all" or self._identity_key(entry.path) == "all":+ raise ValueError("Workspace repository identity 'all' is reserved")+ identities = {+ self._alias_key(entry.alias),+ self._identity_key(entry.path),+ self._identity_key((self._workspace_root / entry.path).resolve()),+ }+ for path_identity in identities - {self._alias_key(entry.alias)}:+ alias_owner = alias_owners.get(self._alias_key(path_identity))+ if alias_owner is not None and alias_owner != entry.alias:+ raise ValueError(+ "Workspace repository identities collide: "+ f"alias {alias_owner!r} shadows path {path_identity!r} "+ f"from {entry.alias!r}"+ )+ for identity in identities:+ owner = owners.setdefault(identity, entry.alias)+ if owner != entry.alias:+ raise ValueError(+ "Workspace repository identities collide: "+ f"{owner!r} and {entry.alias!r} both expose {identity!r}"+ )# -- Public API --------------------------------------------------------@@ -125,11 +165,24 @@ class RepoRegistry:return self.get_default_alias()if repo == "all":return self.get_all_aliases()- # Validate alias exists- if self._ws_config.get_repo(repo) is None:- available = self.get_all_aliases()- raise ValueError(f"Unknown repo '{repo}'. Available: {available}")- return repo+ # Alias is canonical, but ``list_repos`` also emits each repository's+ # config-relative and absolute path. Accept those identities directly+ # so a discovery result never needs caller-side translation.+ aliases = {self._alias_key(entry.alias): entry.alias for entry in self._ws_config.repos}+ alias = aliases.get(self._alias_key(repo))+ if alias is not None:+ return alias+ candidate = Path(repo)+ candidate_text = self._identity_key(candidate)+ for entry in self._ws_config.repos:+ relative = self._identity_key(entry.path)+ absolute = (self._workspace_root / entry.path).resolve()+ if candidate_text == relative:+ return entry.alias+ if candidate.is_absolute() and candidate.resolve() == absolute:+ return entry.alias+ available = self.get_all_aliases()+ raise ValueError(f"Unknown repo '{repo}'. Available: {available}")async def get(self, alias: str) -> RepoContext:"""Get the ``RepoContext`` for *alias*, loading lazily if needed."""diff --git a/packages/server/src/repowise/server/mcp_server/_budget/collector.py b/packages/server/src/repowise/server/mcp_server/_budget/collector.pyindex 64f35ff4d..88e055b57 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/collector.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/collector.py@@ -20,6 +20,7 @@ from typing import Anyfrom repowise.core.distill.budget import estimate_tokensfrom repowise.core.distill.markers import render_markerfrom repowise.core.distill.store import OmissionStore, default_store_path+from repowise.server.mcp_server._references import omission_referencelogger = logging.getLogger(__name__)@@ -193,7 +194,11 @@ class OmissionCollector:int(existing.get("tokens") or 0) if isinstance(existing, dict) else 0)meta["omitted"] = {- "refs": [*existing_refs, *self._refs],+ "refs": [+ normalized+ for value in [*existing_refs, *self._refs]+ if (normalized := omission_reference(value)) is not None+ ],"tokens": existing_tokens + self._omitted_tokens,"restore": _RESTORE_HINT,}diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 24f5bd419..9103aa356 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -93,7 +93,9 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"origin_story.linked_decisions","decisions[]","code_rationale",- "git_archaeology",+ "git_archaeology.file_commits",+ "git_archaeology.cross_references",+ "git_archaeology.git_log","origin_story",),expansion_argument=None,diff --git a/packages/server/src/repowise/server/mcp_server/_references.py b/packages/server/src/repowise/server/mcp_server/_references.pynew file mode 100644index 000000000..bc1d5ac03--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_references.py@@ -0,0 +1,146 @@+"""Canonical identifiers and evidence references shared by MCP tools.++The identity helpers in this module are presentation-only. They normalize the+coordinates tools already expose; they do not merge persisted records or+manufacture precision that the underlying source cannot verify.+"""++from __future__ import annotations++import hashlib+import json+import posixpath+import re+from collections.abc import Mapping, Sequence+from typing import Any++_OMISSION_REF_RE = re.compile(r"(?:^repowise#|\[repowise#)([0-9a-f]{12})(?:$|:)")+++def repository_identity(repository: str) -> str:+ """Return the canonical, case-insensitive public repository identity."""++ return repository.strip().replace("\\", "/").strip("/").casefold()+++def path_identity(path: str) -> str:+ """Return one repository-relative POSIX path form."""++ normalized = posixpath.normpath(path.strip().replace("\\", "/"))+ return normalized.removeprefix("./")+++def symbol_identity(symbol_id: str) -> str:+ """Return the canonical ``path::Symbol`` public identifier form."""++ path, separator, name = symbol_id.strip().partition("::")+ if not separator:+ return path_identity(path)+ return f"{path_identity(path)}::{name.strip()}"+++def content_id(value: object) -> str:+ """Return the stable compact digest used by public reference identities."""++ 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]:+ """Build a repository-scoped, deterministic evidence reference."""++ identity = {+ "repository": repository_identity(repository),+ "kind": kind,+ **coordinates,+ }+ return {+ "id": f"ev_{content_id(identity)}",+ **identity,+ }+++def omission_reference(value: str) -> str | None:+ """Return the exact omission token accepted by ``get_symbol``."""++ candidate = value.strip()+ if re.fullmatch(r"[0-9a-f]{12}", candidate):+ return f"repowise#{candidate}"+ match = _OMISSION_REF_RE.search(candidate)+ return f"repowise#{match.group(1)}" if match else None+++def source_reference(+ repository: str,+ path: str,+ *,+ lines: Sequence[int] | None = None,+ symbol_id: str | None = None,+ verification_basis: str,+ source_kind: str,+ commit: str | None = None,+) -> dict[str, Any]:+ """Build a source pointer whose ``id`` is accepted by its target tool."""++ normalized_path = path_identity(path)+ valid_range = (+ lines+ and len(lines) == 2+ and all(isinstance(line, int) and line > 0 for line in lines)+ and int(lines[1]) >= int(lines[0])+ )+ if symbol_id:+ identifier = symbol_identity(symbol_id)+ if "::" not in identifier:+ raise ValueError("symbol_id must use the canonical 'path::Symbol' form")+ symbol_path, _separator, _name = identifier.partition("::")+ if symbol_path != normalized_path:+ raise ValueError("symbol_id path must match the reference path")+ kind = "symbol"+ elif valid_range:+ identifier = f"{normalized_path}:{int(lines[0])}-{int(lines[1])}"+ kind = "file_range"+ else:+ identifier = normalized_path+ kind = "file"+ result: dict[str, Any] = {+ "id": identifier,+ "repository": repository_identity(repository),+ "kind": kind,+ "path": normalized_path,+ "verification_basis": verification_basis,+ "source_kind": source_kind,+ }+ if valid_range:+ result["range"] = [int(lines[0]), int(lines[1])]+ if commit:+ result["commit"] = commit.strip().lower()+ return result+++def stable_entity_id(prefix: str, repository: str, coordinates: Mapping[str, object]) -> str:+ """Return a stable public ID for replace-on-analysis persisted rows."""++ identity = {"repository": repository_identity(repository), **coordinates}+ return f"{prefix}_{content_id(identity)}"+++# Compatibility aliases for the get_why-specific module that originally+# owned these primitives. Keeping the private spellings prevents a mechanical+# promotion from changing sealed evidence identities or downstream imports.+_repository_identity = repository_identity+_path_identity = path_identity+_content_id = content_id+_reference = reference+++__all__ = [+ "content_id",+ "omission_reference",+ "path_identity",+ "reference",+ "repository_identity",+ "source_reference",+ "stable_entity_id",+ "symbol_identity",+]diff --git a/packages/server/src/repowise/server/mcp_server/_why_evidence.py b/packages/server/src/repowise/server/mcp_server/_why_evidence.pyindex 4b12fb2f1..458b9ee8a 100644--- a/packages/server/src/repowise/server/mcp_server/_why_evidence.py+++ b/packages/server/src/repowise/server/mcp_server/_why_evidence.py@@ -6,23 +6,32 @@ several commits. The compact ``evidence_refs`` objects emitted here thereforedescribe only the supporting evidence coordinates; decision ids, statuses andlineage 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.+The helpers do not merge persisted records or use text similarity. Evidence+objects are also written to the repo-local sidecar so another server worker can+resolve a just-emitted live or historical reference without scanning Git or+source files."""from __future__ import annotationsimport asyncio-import hashlib+import copyimport json-import posixpathimport re+import sqlite3import subprocess+import threading+from collections import OrderedDictfrom collections.abc import Iterable, Mapping, Sequencefrom pathlib import Pathfrom typing import Any, Literal+from repowise.server.mcp_server._references import (+ _content_id,+ _path_identity,+ _reference,+)+ProvenanceKind = Literal["human_decision","extracted_rationale",@@ -40,6 +49,106 @@ _HISTORICAL_SOURCES = frozenset()_INFERRED_SOURCES = frozenset({"inferred", "semantic"})_FULL_COMMIT_RE = re.compile(r"^[0-9a-fA-F]{40}(?:[0-9a-fA-F]{24})?$")+_REFERENCE_CACHE_LIMIT = 4096+_reference_cache: OrderedDict[tuple[str, str], dict[str, Any]] = OrderedDict()+_reference_cache_lock = threading.Lock()+++def _remember_evidence_references(value: object) -> None:+ if isinstance(value, Mapping):+ identifier = value.get("id")+ repository = value.get("repository")+ if (+ isinstance(identifier, str)+ and identifier.startswith("ev_")+ and isinstance(repository, str)+ ):+ key = (repository, identifier)+ with _reference_cache_lock:+ _reference_cache[key] = copy.deepcopy(dict(value))+ _reference_cache.move_to_end(key)+ while len(_reference_cache) > _REFERENCE_CACHE_LIMIT:+ _reference_cache.popitem(last=False)+ for child in value.values():+ _remember_evidence_references(child)+ elif isinstance(value, list):+ for child in value:+ _remember_evidence_references(child)+++def resolve_cached_evidence_reference(+ repository: str, reference_id: str+) -> dict[str, Any] | None:+ """Return an exact evidence object emitted by this server process."""++ key = (repository, reference_id)+ with _reference_cache_lock:+ cached = _reference_cache.get(key)+ if cached is None:+ return None+ _reference_cache.move_to_end(key)+ return copy.deepcopy(cached)+++def _persist_evidence_references(value: object, repo_root: str | Path) -> bool:+ from repowise.core.distill.store import OmissionStore++ references: dict[str, dict[str, Any]] = {}++ def collect(child: object) -> None:+ if isinstance(child, Mapping):+ identifier = child.get("id")+ repository = child.get("repository")+ if (+ isinstance(identifier, str)+ and identifier.startswith("ev_")+ and isinstance(repository, str)+ ):+ references[identifier] = dict(child)+ for nested in child.values():+ collect(nested)+ elif isinstance(child, list):+ for nested in child:+ collect(nested)++ collect(value)+ if not references:+ return True+ try:+ with OmissionStore.open_default(Path(repo_root)) as store:+ for identifier, reference_value in references.items():+ store.put_evidence_reference(+ identifier,+ json.dumps(reference_value, sort_keys=True, separators=(",", ":")),+ repository=str(reference_value["repository"]),+ )+ except (OSError, sqlite3.Error):+ return False+ return True+++def resolve_persisted_evidence_reference(+ repository: str, reference_id: str, repo_root: str | Path+) -> dict[str, Any] | None:+ """Resolve an exact evidence object emitted by this or another worker."""++ from repowise.core.distill.store import OmissionStore, default_store_path++ db_path = default_store_path(Path(repo_root))+ if not db_path.exists():+ return None+ try:+ with OmissionStore(db_path) as store:+ row = store.get_evidence_reference(reference_id)+ except (OSError, sqlite3.Error):+ return None+ if row is None or row["repository"] != repository:+ return None+ try:+ value = json.loads(row["content"])+ except json.JSONDecodeError:+ return None+ return value if isinstance(value, dict) else Nonedef provenance_for_source(source: str | None) -> ProvenanceKind:@@ -57,32 +166,6 @@ def provenance_for_source(source: str | None) -> ProvenanceKind: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()@@ -218,6 +301,8 @@ def decision_evidence_refs()ref["provenance"] = "historical"ref["source"] = source+ ref["source_kind"] = source or "commit"+ ref["verification_basis"] = "historical"refs.append(ref)evidence_file = getattr(evidence, "evidence_file", None)if evidence_file:@@ -253,6 +338,8 @@ def decision_evidence_refs()ref["provenance"] = provenance_for_source(source)ref["source"] = source+ ref["source_kind"] = source or "unknown"+ ref["verification_basis"] = "indexed"if verification:ref["verification"] = verificationrefs.append(ref)@@ -264,6 +351,8 @@ def decision_evidence_refs()ref["provenance"] = provenance_for_source(getattr(record, "source", None))ref["source"] = getattr(record, "source", None)+ ref["source_kind"] = getattr(record, "source", None) or "unknown"+ ref["verification_basis"] = "indexed"refs.append(ref)unique: dict[tuple[str, object, object], dict[str, Any]] = {}for ref in refs:@@ -367,6 +456,8 @@ def _annotate_commit_row()ref["provenance"] = "historical"ref["source"] = channel+ ref["source_kind"] = channel+ ref["verification_basis"] = "historical"row["evidence_refs"] = [ref]@@ -408,6 +499,7 @@ def annotate_response_evidence(records: Iterable[Any] = (),*,resolved_commits: Mapping[str, str] | None = None,+ repo_root: str | Path | None = None,) -> dict[str, Any]:"""Add self-resolving evidence refs and provenance to every ``get_why`` lane."""@@ -488,10 +580,15 @@ def annotate_response_evidence(]row["evidence_refs"][0]["provenance"] = "extracted_rationale"row["evidence_refs"][0]["source"] = "live_code_rationale"+ row["evidence_refs"][0]["source_kind"] = "code_comment"row["evidence_refs"][0]["verification"] = "exact"+ row["evidence_refs"][0]["verification_basis"] = "live"for row in result.get("episodes") or []:if isinstance(row, dict):_annotate_commit_row(row, repository, resolved_commits, channel="episode")+ _remember_evidence_references(result)+ if repo_root is not None:+ _persist_evidence_references(result, repo_root)return result@@ -508,9 +605,21 @@ async def annotate_response_evidence_async(resolved = await asyncio.to_thread(_resolved_commits, result, record_list, repo_root)- return annotate_response_evidence(- result, repository, record_list, resolved_commits=resolved+ annotated = annotate_response_evidence(+ result,+ repository,+ record_list,+ resolved_commits=resolved,+ )+ persisted = await asyncio.to_thread(+ _persist_evidence_references, annotated, repo_root)+ if not persisted:+ annotated.setdefault("_meta", {})["reference_persistence"] = {+ "available": False,+ "reason": "repo-local evidence sidecar could not be written",+ }+ return annotateddef _annotate_archaeology(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.pyindex 26b314483..a85549f99 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@@ -40,6 +40,7 @@ from repowise.server.mcp_server._helpers import (is_excluded,read_repo_file_text,)+from repowise.server.mcp_server._references import path_identity, symbol_identityfrom repowise.server.mcp_server._symbol_lookup import resolve_symbol_rowsfrom repowise.server.mcp_server.tool_context.enrichment import (_resolve_call_graph,@@ -262,6 +263,8 @@ async def _resolve_one_target(page = await session.get(Page, page_id)target_type = Nonefile_path_for_git: str | None = None+ live_file_meta: GitMetadata | None = None+ live_unindexed_file = False# Set only when a symbol target resolved through the call graph rather than# the symbol index (index-only mode); carries the fields the node has.graph_symbol: GraphNode | None = None@@ -423,21 +426,26 @@ async def _resolve_one_target(# page. Computed from the same function that made the decision,# so the two cannot drift (#1237).size_note = _size_exclusion_note(repo_root, target)- return {- "target": target,- "error": size_note- or (- f"'{target}' exists in the repository but has no wiki page. "- "This usually means the file has too few symbols or is below "- "the PageRank threshold. Run `repowise update` to regenerate docs."- ),- "exists_in_git": True,- "last_commit_at": meta.last_commit_at.isoformat()- if meta.last_commit_at- else None,- "primary_owner": meta.primary_owner_name,- "is_hotspot": meta.is_hotspot,- }+ if size_note:+ return {+ "target": target,+ "error": size_note,+ "exists_in_git": True,+ }+ target_type = "file"+ file_path_for_git = target+ live_file_meta = meta+ page = None++ # A producer can legitimately surface a live repository file that was+ # never indexed into git_metadata (for example, an analysis finding+ # imported from an older index). Its repository-relative path remains+ # a valid public identifier, so resolve it from the live checkout.+ if target_type is None and _file_preview(repo_root, target) is not None:+ target_type = "file"+ file_path_for_git = target+ page = None+ live_unindexed_file = True# Fallback 2b: legacy module ids. Wiki modules used to be keyed by# community ordinal ("community-12"); they are now keyed by directory@@ -531,6 +539,22 @@ async def _resolve_one_target(result_data["target"] = targetresult_data["type"] = target_type+ if target_type == "file" and file_path_for_git:+ result_data["path"] = path_identity(file_path_for_git)+ if live_file_meta is not None:+ result_data["index_status"] = "live_file_without_wiki_page"+ result_data["verification_basis"] = "indexed_plus_live"+ result_data["exists_in_git"] = True+ result_data["last_commit_at"] = (+ live_file_meta.last_commit_at.isoformat()+ if live_file_meta.last_commit_at+ else None+ )+ result_data["primary_owner"] = live_file_meta.primary_owner_name+ result_data["is_hotspot"] = live_file_meta.is_hotspot+ elif live_unindexed_file:+ result_data["index_status"] = "live_file_without_index_record"+ result_data["verification_basis"] = "live"# Tombstone redirect: the page documents a file deleted or renamed since# indexing. A "fresh" card here is an active trap — return the redirect@@ -623,7 +647,7 @@ async def _resolve_one_target("kind": s.kind,"signature": _clean_signature(s.signature),"line": s.start_line,- "symbol_id": s.symbol_id,+ "symbol_id": symbol_identity(s.symbol_id),}for s in visible]@@ -643,6 +667,7 @@ async def _resolve_one_target("signature": _clean_signature(s.signature),"start_line": s.start_line,"end_line": s.end_line,+ "symbol_id": symbol_identity(s.symbol_id),"docstring": (s.docstring or "")[:400],}for s in symbols@@ -840,7 +865,12 @@ async def _resolve_one_target(if len(sym_matches) > 1: # type: ignore[possibly-undefined]docs["candidates"] = filter_dicts_by_key([- {"name": m.name, "kind": m.kind, "file_path": m.file_path}+ {+ "name": m.name,+ "kind": m.kind,+ "file_path": m.file_path,+ "symbol_id": symbol_identity(m.symbol_id),+ }for m in sym_matches[1:5] # type: ignore[possibly-undefined]],"file_path",diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex ea3f00c8d..e54317309 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -34,6 +34,7 @@ from repowise.server.mcp_server._helpers import (resolve_enum_argument,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._references import path_identity, stable_entity_id@dataclass@@ -122,7 +123,7 @@ async def _get_dead_code_all_repos(repo_filtered = _apply_finding_filters(repo_findings, filters)for f in repo_filtered:- serialized = _serialize_finding(f, git_meta_map)+ serialized = _serialize_finding(f, git_meta_map, repository=ctx.alias)serialized["repo"] = ctx.aliasmerged_findings.append(serialized)@@ -276,6 +277,7 @@ async def get_dead_code(include_zombie_packages: bool = True,no_unreachable: bool = False,no_unused_exports: bool = False,+ finding_id: str | None = None,) -> dict:"""Unused exports, unreachable files, zombie packages — tiered by confidence.@@ -300,6 +302,7 @@ async def get_dead_code(include_zombie_packages: monorepo package findings (default true).no_unreachable: skip file-level reachability findings.no_unused_exports: skip public-export findings.+ finding_id: stable ``id`` emitted by a dead-code finding."""# MCP transport rejects payloads above ~25k tokens. A single serialized# finding is ~400 chars, so 3 tiers x ~25 findings keeps us under budget@@ -341,6 +344,24 @@ async def get_dead_code(# --- repo="all": aggregate dead code across all repos ---if repo == "all":+ if finding_id:+ for candidate_ctx in await _resolve_all_contexts():+ resolved = await get_dead_code(+ repo=candidate_ctx.alias,+ min_confidence="low",+ finding_id=finding_id,+ )+ if resolved.get("resolved"):+ resolved["workspace"] = True+ return resolved+ return {+ "mode": "finding",+ "finding_id": finding_id,+ "finding": None,+ "resolved": False,+ "workspace": True,+ "_meta": _build_meta(),+ }result_ws = await _get_dead_code_all_repos(filters, limit, tier, _maybe_limit_note)attach_ignored_arguments(result_ws, ignored)return result_ws@@ -364,11 +385,48 @@ async def get_dead_code(# Phase 4: load git metadata for "last meaningful change" enrichmentgit_meta_map = await _load_git_meta_map(session, repository.id, all_findings)+ reference_repository = ctx.alias or repository.name+ if finding_id:+ match = next(+ (+ row+ for row in all_findings+ if finding_id+ in {row.id, _dead_code_finding_id(row, reference_repository)}+ ),+ None,+ )+ return {+ "mode": "finding",+ "finding_id": finding_id,+ "finding": (+ _serialize_finding(+ match,+ git_meta_map,+ repository=reference_repository,+ )+ if match+ else None+ ),+ "resolved": match is not None,+ "_meta": _build_meta(+ repository=repository,+ targets=[match.file_path] if match else None,+ ),+ }+# --- Apply filters ---filtered = _apply_finding_filters(all_findings, filters)# --- Build tiered structure ---- tiers = _build_tiers(filtered, limit, tier, git_meta_map, collector)+ tiers = _build_tiers(+ filtered,+ limit,+ tier,+ git_meta_map,+ collector,+ repository=reference_repository,+ )# --- Summary across ALL open findings (unfiltered) ---by_kind: dict[str, int] = {}@@ -471,12 +529,37 @@ def _effective_safe(f: Any) -> bool:return effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)-def _serialize_finding(f: Any, git_meta_map: dict | None = None) -> dict:+def _dead_code_finding_id(f: Any, repository: str) -> str:+ return stable_entity_id(+ "finding",+ repository,+ {+ "family": "dead_code",+ "path": path_identity(f.file_path),+ "kind": f.kind,+ "symbol": f.symbol_name or "",+ "line_start": f.start_line,+ "line_end": f.end_line,+ },+ )+++def _serialize_finding(+ f: Any,+ git_meta_map: dict | None = None,+ *,+ repository: str = "default",+) -> dict:"""Serialize a single DeadCodeFinding to dict."""result = {+ "id": _dead_code_finding_id(f, repository),+ "repository": repository,"kind": f.kind,"file_path": f.file_path,"symbol_name": f.symbol_name,+ "symbol_kind": f.symbol_kind,+ "start_line": f.start_line,+ "end_line": f.end_line,"confidence": f.confidence,"reason": f.reason,"safe_to_delete": _effective_safe(f),@@ -507,6 +590,8 @@ def _build_tiers(tier_filter: str | None,git_meta_map: dict | None = None,collector: OmissionCollector | None = None,+ *,+ repository: str = "default",) -> dict:"""Split findings into high/medium/low confidence tiers.@@ -533,7 +618,10 @@ def _build_tiers(collector.add(f"{name}-tier findings beyond limit={limit} ({len(beyond_limit)} dropped)","\n".join(- json.dumps(_serialize_finding(f, git_meta_map), separators=(",", ":"))+ json.dumps(+ _serialize_finding(f, git_meta_map, repository=repository),+ separators=(",", ":"),+ )for f in beyond_limit),)@@ -542,7 +630,10 @@ def _build_tiers("count": len(items),"lines": sum(f.lines for f in items),"safe_count": sum(1 for f in items if _effective_safe(f)),- "findings": [_serialize_finding(f, git_meta_map) for f in items[:limit]],+ "findings": [+ _serialize_finding(f, git_meta_map, repository=repository)+ for f in items[:limit]+ ],"truncated": len(items) > limit,}diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 51ea08a96..5236e4229 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -58,6 +58,7 @@ from repowise.server.mcp_server._helpers import (filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._references import path_identity, stable_entity_id# How much a single execution of each I/O boundary costs, as an order of# magnitude rather than a measurement: a process spawn is milliseconds, a wire@@ -197,7 +198,28 @@ def _rank_emitted(rows: list[Any]) -> list[Any]:return sorted(rows, key=key)-def _serialize_finding(f: HealthFinding) -> dict[str, Any]:+def _health_finding_id(f: HealthFinding, repository: str) -> str:+ try:+ details = json.loads(f.details_json) if f.details_json else {}+ except (TypeError, json.JSONDecodeError):+ details = str(f.details_json or "")+ return stable_entity_id(+ "finding",+ repository,+ {+ "family": "health",+ "path": path_identity(f.file_path),+ "kind": f.biomarker_type,+ "symbol": f.function_name or "",+ "line_start": f.line_start,+ "line_end": f.line_end,+ "reason": f.reason or "",+ "details": details,+ },+ )+++def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[str, Any]:try:details = json.loads(f.details_json) if f.details_json else {}except Exception:@@ -207,6 +229,8 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:{"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {})return {+ "id": _health_finding_id(f, repository),+ "repository": repository,"biomarker_type": f.biomarker_type,"severity": f.severity,"file_path": f.file_path,@@ -227,11 +251,42 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:}-def _serialize_refactoring(r: Any) -> dict[str, Any]:+def _refactoring_plan_id(r: Any, repository: str) -> str:+ suggestion = r.suggestion if isinstance(r, Recommendation) else r+ raw_plan = getattr(suggestion, "plan", None)+ if raw_plan is None:+ raw_plan = getattr(suggestion, "plan_json", None) or "{}"+ try:+ raw_plan = json.loads(raw_plan)+ except (TypeError, json.JSONDecodeError):+ raw_plan = str(raw_plan)+ return stable_entity_id(+ "plan",+ repository,+ {+ "path": path_identity(suggestion.file_path),+ "kind": suggestion.refactoring_type,+ "symbol": suggestion.target_symbol or "",+ "line_start": suggestion.line_start,+ "line_end": suggestion.line_end,+ "source_biomarker": suggestion.source_biomarker or "",+ "plan": raw_plan,+ },+ )+++def _serialize_refactoring(+ r: Any, repository: str | None = None+) -> dict[str, Any]:"""Compatibility adapter; request paths hydrate through the async service."""if isinstance(r, Recommendation):- return r.as_dict()- return build_recommendations([r])[0].as_dict()+ payload = r.as_dict()+ else:+ payload = build_recommendations([r])[0].as_dict()+ if repository is not None:+ payload["id"] = _refactoring_plan_id(r, repository)+ payload["repository"] = repository+ return payload# ``include`` and ``only`` were different vocabularies: the block a caller@@ -864,6 +919,8 @@ async def get_health(only: list[str] | None = None,refactoring_view: str = "canonical",cursor: int = 0,+ finding_id: str | None = None,+ plan_id: str | None = None,) -> dict:"""Code-health scores and findings — self-check a file before/after editing.@@ -876,10 +933,8 @@ async def get_health(include: ``biomarkers`` | ``refactoring`` | ``trend`` | ``coverage`` |``accuracy`` | ``signals`` | ``churn_complexity`` |``performance``/``defect``/``maintainability`` (dimension).- ``performance`` adds causal ``performance_opportunities``; with- ``refactoring``, a compact ``recommendation_lede``. Only adds- blocks; pair with ``only``. Final response budgeting and omission- recovery use the shared MCP delivery contract.+ ``performance`` adds causal opportunities; with ``refactoring``,+ a compact recommendation lede. Pair with ``only`` to project.only: top-level keys to keep; identity, counts, unresolved targets,and recovery metadata survive. ``biomarkers``, ``accuracy``, and``refactoring`` alias; ``performance``, ``defect``, and@@ -890,9 +945,9 @@ async def get_health(performance evidence is capped at 3 rows per opportunity.refactoring_view: ``canonical`` (default) or diversified``file_spread``.- cursor: zero-based offset for top-level ranked collections. Reduced- pages carry an exact next-page call; nested evidence uses omission- references instead.+ cursor: zero-based offset for top-level ranked collections.+ finding_id: stable ``id`` emitted by a health finding.+ plan_id: stable ``id`` emitted by a refactoring plan."""started = perf_counter()# ``0`` means none, matching the ``module_limit`` convention on the REST@@ -1021,6 +1076,70 @@ async def get_health(lang_by_path: dict[str, str] | None = Noneasync with get_session(ctx.session_factory) as session:repository = await _get_repo(session)+ reference_repository = ctx.alias or repository.name++ if finding_id:+ rows = list(+ (+ await session.execute(+ select(HealthFinding).where(+ HealthFinding.repository_id == repository.id,+ HealthFinding.status == "open",+ )+ )+ )+ .scalars()+ .all()+ )+ match = next(+ (+ row+ for row in rows+ if finding_id in {row.id, _health_finding_id(row, reference_repository)}+ ),+ None,+ )+ return {+ "mode": "finding",+ "finding_id": finding_id,+ "finding": (+ _serialize_finding(match, reference_repository) if match else None+ ),+ "resolved": match is not None,+ "_meta": _build_meta(+ repository=repository,+ targets=[match.file_path] if match else None,+ ),+ }++ if plan_id:+ plan_rows = await get_refactoring_suggestions(session, repository.id)+ recommendations = await hydrate_recommendations(+ session, repository.id, plan_rows+ )+ match = next(+ (+ row+ for row in recommendations+ if plan_id+ in {row.id, _refactoring_plan_id(row, reference_repository)}+ ),+ None,+ )+ return {+ "mode": "refactoring_plan",+ "plan_id": plan_id,+ "plan": (+ _serialize_refactoring(match, reference_repository)+ if match+ else None+ ),+ "resolved": match is not None,+ "_meta": _build_meta(+ repository=repository,+ targets=[match.suggestion.file_path] if match else None,+ ),+ }all_metrics_q = select(HealthFileMetric).where(HealthFileMetric.repository_id == repository.id@@ -1500,7 +1619,8 @@ async def get_health(# Capped like every other ranked list, with the total alongside so# the truncation is visible rather than inferred from the length."findings": bounded(- [_serialize_finding(f) for f in finding_rows], "findings"+ [_serialize_finding(f, reference_repository) for f in finding_rows],+ "findings",),"findings_total": findings_total,}@@ -1630,14 +1750,16 @@ async def get_health(], "high_leverage_files"),"high_leverage_files_total": len(by_leverage),"top_findings": bounded(- [_serialize_finding(f) for f in finding_rows], "top_findings"+ [_serialize_finding(f, reference_repository) for f in finding_rows],+ "top_findings",),"top_findings_total": findings_total,# The test half of the same ranked set, in its own bucket so a# thrashing test suite stays visible without competing with# production defect risk for the most-read list."test_findings": bounded(- [_serialize_finding(f) for f in test_finding_rows], "test_findings"+ [_serialize_finding(f, reference_repository) for f in test_finding_rows],+ "test_findings",),"test_findings_total": test_findings_total,# Worst-first, so the cap keeps the modules worth looking at. On a@@ -1676,7 +1798,7 @@ async def get_health(# ``None`` when there isn't enough signal for an honest number.result["defect_accuracy"] = compute_defect_accuracy(all_metrics,- [_serialize_finding(f) for f in accuracy_rows],+ [_serialize_finding(f, reference_repository) for f in accuracy_rows],)if "biomarkers" in include_set and "findings" not in result:@@ -1687,14 +1809,16 @@ async def get_health(# usable. Findings arrive impact-ordered, so the cap keeps the ones# worth reading.result["findings"] = bounded(- [_serialize_finding(f) for f in finding_rows], "findings"+ [_serialize_finding(f, reference_repository) for f in finding_rows],+ "findings",)result["findings_total"] = findings_total# Same production/test split as ``top_findings``: this block only ever# fires in dashboard mode (targeted mode set ``findings`` above), so it# is describing the repo, not a file the caller named.result["test_findings"] = bounded(- [_serialize_finding(f) for f in test_finding_rows], "test_findings"+ [_serialize_finding(f, reference_repository) for f in test_finding_rows],+ "test_findings",)result["test_findings_total"] = test_findings_total@@ -1709,7 +1833,7 @@ async def get_health(cap=min(limit, 6),)for recommendation in selected_recommendations:- payload = recommendation.as_dict()+ payload = _serialize_refactoring(recommendation, reference_repository)validation = payload.pop("validation", None)if validation:profile_id, profile = _validation_profile(validation)@@ -1815,7 +1939,11 @@ async def get_health(),None,)- lead_payload = recommendation_lead.as_dict() if recommendation_lead else None+ lead_payload = (+ _serialize_refactoring(recommendation_lead, reference_repository)+ if recommendation_lead+ else None+ )result["recommendation_lede"] = {"performance_opportunities_total": len(opportunities),"refactoring_plans_total": len(refactoring_recommendations),@@ -1849,7 +1977,9 @@ async def get_health(if lead_payloadelse None),- "performance_plan_id": matching.id if matching else None,+ "performance_plan_id": (+ _refactoring_plan_id(matching, reference_repository) if matching else None+ ),"next_call": (f"get_health(targets={raw_targets!r}, repo={repo!r}, ""include=['performance','refactoring'], limit=3, "@@ -2061,7 +2191,14 @@ async def get_health(if root in result:omission_collector.add(f"{label} beyond emitted cap ({len(dropped)} dropped)",- [row.as_dict() if hasattr(row, "as_dict") else row for row in dropped],+ [+ _serialize_refactoring(row, reference_repository)+ if isinstance(row, Recommendation)+ else row.as_dict()+ if hasattr(row, "as_dict")+ else row+ for row in dropped+ ],)omission_collector.attach(result)result["_meta"]["timing_ms"] = round((perf_counter() - started) * 1000, 2)diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.pyindex 8b4425240..af8c8ffd2 100644--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py@@ -49,27 +49,54 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)ctx = await _resolve_repo_context(repo)repo_path = Path(ctx.path)- if not llm_enrichment_enabled(load_repo_config(repo_path)):- return {- "error": "disabled",- "detail": (- "Refactoring code generation is opt-in. Set 'refactoring.llm.enabled: "- "true' in .repowise/config.yaml to enable it."- ),- }-async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)row = await get_refactoring_suggestion(session, repository.id, suggestion_id)+ if row is None:+ from repowise.core.persistence.crud import get_refactoring_suggestions+ from repowise.server.mcp_server.tool_health import _refactoring_plan_id++ candidates = await get_refactoring_suggestions(session, repository.id)+ row = next(+ (+ candidate+ for candidate in candidates+ if _refactoring_plan_id(candidate, ctx.alias or repository.name)+ == suggestion_id+ ),+ None,+ )if row is None:return {"error": "not_found","detail": f"No refactoring plan with id {suggestion_id!r} in this repo.","_meta": _build_meta(repository=repository),}- sug = (await hydrate_recommendations(session, repository.id, [row]))[0].suggestion+ recommendation = (await hydrate_recommendations(session, repository.id, [row]))[0]+ sug = recommendation.suggestionmeta = _build_meta(repository=repository)+ from repowise.server.mcp_server.tool_health import _serialize_refactoring++ public_plan = _serialize_refactoring(+ recommendation, ctx.alias or repository.name+ )+ if not llm_enrichment_enabled(load_repo_config(repo_path)):+ return {+ "suggestion_id": public_plan["id"],+ "resolved": True,+ "plan": public_plan,+ "generation": {+ "available": False,+ "reason": "disabled",+ "detail": (+ "Refactoring code generation is opt-in. Set "+ "'refactoring.llm.enabled: true' in .repowise/config.yaml to enable it."+ ),+ },+ "_meta": meta,+ }+try:provider = build_enrichment_provider(repo_path)except ValueError as exc:@@ -77,5 +104,7 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path)payload = result.to_dict()+ payload["suggestion_id"] = public_plan["id"]+ payload["resolved"] = Truepayload["_meta"] = metareturn payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_repos.py b/packages/server/src/repowise/server/mcp_server/tool_repos.pyindex 9b12bfdea..498b6146e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_repos.py+++ b/packages/server/src/repowise/server/mcp_server/tool_repos.py@@ -7,6 +7,7 @@ from typing import Anyfrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._references import repository_identitydef _workspace_repos(registry: Any) -> list[dict[str, Any]]:@@ -46,7 +47,7 @@ def _workspace_repos(registry: Any) -> list[dict[str, Any]]:absolute_path = (registry.workspace_root / entry.path).resolve()repos.append({- "alias": entry.alias,+ "alias": repository_identity(entry.alias),"path": entry.path,"absolute_path": absolute_path.as_posix(),"is_default": entry.alias == default_alias,@@ -61,17 +62,21 @@ def _workspace_repos(registry: Any) -> list[dict[str, Any]]:async def list_repos() -> dict[str, Any]:"""List repos available through this MCP server.- In workspace mode this returns every configured workspace repo alias. Use- those aliases as the ``repo`` parameter on workspace-aware tools.+ In workspace mode this returns every configured repository's canonical+ alias, config-relative path, and absolute path. Any emitted identity can+ be passed unchanged as ``repo`` to workspace-aware tools."""registry = _state._registryif registry is not None:return {"workspace": True,"workspace_root": registry.workspace_root.as_posix(),- "default_repo": registry.get_default_alias(),+ "default_repo": repository_identity(registry.get_default_alias()),"repos": _workspace_repos(registry),- "hint": "Use repo='<alias>' on tools that accept a repo parameter.",+ "hint": (+ "Pass any emitted alias, path, or absolute_path unchanged as repo "+ "on workspace-aware tools."+ ),"_meta": _build_meta(),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 22f25a22d..abe580518 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -37,6 +37,7 @@ from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINTfrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._page_paths import file_candidates, hit_file_pathfrom repowise.server.mcp_server._prose_symbols import symbol_backed_pages+from repowise.server.mcp_server._references import path_identity, symbol_identityfrom repowise.server.mcp_server.tool_search_symbols import (_qual_norm,search_paths_single,@@ -485,12 +486,11 @@ def _filter_by_kind(output: list[dict], kind: str | None) -> list[dict]:def _attach_paths(output: list[dict], page_info: dict) -> None:- """Stamp ``target_path``, and ``file`` wherever the page id is not one.+ """Stamp canonical file paths and split symbol ids into their own field.A ``symbol_spotlight``'s target_path is ``file.py::Symbol``: a page id, and- not something a consumer can open. ``target_path`` is left exactly as it is- because callers pipe it into get_symbol, and ``file`` is added beside it so- nothing downstream has to know to split on ``::``.+ not a file path. Preserve it as ``symbol_id`` for ``get_symbol`` and expose+ only the file portion through ``target_path`` / ``file``.This lives in one function because it did not used to. The concept branchof ``search_codebase`` set ``file``; ``_search_single_repo``, which is what@@ -503,7 +503,9 @@ def _attach_paths(output: list[dict], page_info: dict) -> None:for item in output:item["target_path"] = page_info.get(item["page_id"], "")if "::" in item["target_path"]:- item["file"] = item["target_path"].split("::", 1)[0]+ item["symbol_id"] = symbol_identity(item["target_path"])+ item["target_path"] = path_identity(item["target_path"].split("::", 1)[0])+ item["file"] = item["target_path"]def _drop_derivable_page_ids(results: list[dict]) -> list[dict]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex ac3fed62f..713aefef5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -57,6 +57,7 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,+ _is_workspace_mode,_resolve_repo_context,_unsupported_repo_all,is_excluded,@@ -64,6 +65,12 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import symbol_hint as _symbol_hint+from repowise.server.mcp_server._references import (+ omission_reference,+ path_identity,+ source_reference,+ symbol_identity,+)from repowise.server.mcp_server._symbol_lookup import (NAME_SEPARATORS,bare_name,@@ -86,10 +93,6 @@ _log = __import__("logging").getLogger("repowise.mcp.symbol")# token rather than a guessed range read._MAX_SOURCE_LINES = 600-# Omission-ref dispatch: "repowise#<12-hex>" never collides with a-# "{path}::{name}" symbol_id. Also tolerates a pasted whole marker.-_OMISSION_REF_RE = re.compile(r"^repowise#([0-9a-f]{12})$")-# Range-read dispatch: "path/to/file.py:140-180". A single colon followed by# a numeric range never collides with "{path}::{name}" (double colon) or an# omission ref. The escape hatch for everything not indexed as a symbol —@@ -140,6 +143,7 @@ async def _expand_callees(repo_root: Path,depth: int,exclude_spec: Any,+ repository: str = "default",) -> dict[str, Any] | None:"""Breadth-first walk of the call graph from *root_row*, bodies included.@@ -199,7 +203,7 @@ async def _expand_callees(for row in rows:entry: dict[str, Any] = {- "symbol_id": row.symbol_id,+ "symbol_id": symbol_identity(row.symbol_id),"name": row.name,"file": row.file_path,"kind": row.kind,@@ -225,7 +229,15 @@ async def _expand_callees(if len(numbered) > remaining:# Out of budget: name the read that fetches it rather than# dropping the symbol silently.- entry["fetch_with"] = f"{row.file_path}:{check.start_line}-{check.end_line}"+ fetch_reference = source_reference(+ repository,+ row.file_path,+ lines=[check.start_line, check.end_line],+ verification_basis="live",+ source_kind="source",+ )+ entry["fetch_with"] = fetch_reference["id"]+ entry["fetch_reference"] = fetch_referenceomitted.append(entry)continueremaining -= len(numbered)@@ -239,7 +251,15 @@ async def _expand_callees()if end < check.end_line:entry["truncated"] = True- entry["continuation"] = f"{row.file_path}:{end + 1}-{check.end_line}"+ continuation_reference = source_reference(+ repository,+ row.file_path,+ lines=[end + 1, check.end_line],+ verification_basis="live",+ source_kind="source",+ )+ entry["continuation"] = continuation_reference["id"]+ entry["continuation_reference"] = continuation_referenceentries.append(entry)frontier = next_ids@@ -263,17 +283,10 @@ def _clean_symbol_signature(signature: str | None) -> str:def _extract_omission_ref(symbol_id: str) -> str | None:"""Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""- candidate = symbol_id.strip()- match = _OMISSION_REF_RE.match(candidate)- if match:- return match.group(1)- if candidate.startswith("[repowise#"):- from repowise.core.distill.markers import MARKER_RE+ from repowise.server.mcp_server._references import omission_reference- marker = MARKER_RE.search(candidate)- if marker:- return marker.group("ref")- return None+ canonical = omission_reference(symbol_id)+ return canonical.removeprefix("repowise#") if canonical else Nonedef _resolve_omission_ref(@@ -287,6 +300,7 @@ def _resolve_omission_ref("""from repowise.core.distill.store import OmissionStore, default_store_path+ canonical_ref = f"repowise#{ref}"candidates: list[Path] = []if repo_root:candidates.append(default_store_path(Path(str(repo_root))))@@ -314,7 +328,7 @@ def _resolve_omission_ref(if record is None:return {"symbol_id": symbol_id,- "ref": ref,+ "ref": canonical_ref,"error": (f"No stored content for omission ref {ref!r} — it may have ""expired (7-day TTL), been pruned, or been produced in a "@@ -326,7 +340,7 @@ def _resolve_omission_ref(created = record.get("created_at")response: dict[str, Any] = {"symbol_id": symbol_id,- "ref": ref,+ "ref": canonical_ref,"kind": "omission","source": record.get("source"),"original_tokens": record.get("original_tokens"),@@ -412,7 +426,15 @@ async def _resolve_range_read(if range_truncated and e < remainder_end:# Same clean-continuation contract as a truncated symbol read: name the# exact next range instead of leaving the agent to guess it.- response["continuation"] = f"{path}:{e + 1}-{remainder_end}"+ continuation_reference = source_reference(+ ctx.alias,+ path,+ lines=[e + 1, remainder_end],+ verification_basis="live",+ source_kind="source",+ )+ response["continuation"] = continuation_reference["id"]+ response["continuation_reference"] = continuation_referenceresponse["note"] = (f"Range capped at {_MAX_RANGE_LINES} lines; served {s}-{e}. "f"Continue in one call: get_symbol({response['continuation']!r})."@@ -565,7 +587,7 @@ async def _render_ambiguous(text = text_cache[row.file_path]entry: dict[str, Any] = {- "symbol_id": row.symbol_id,+ "symbol_id": symbol_identity(row.symbol_id),"file": row.file_path,"name": row.name,"kind": row.kind,@@ -587,7 +609,15 @@ async def _render_ambiguous(numbered = _number_lines(source, start)if i > 0 and len(numbered) > remaining:- entry["fetch_with"] = f"{row.file_path}:{start}-{end}"+ fetch_reference = source_reference(+ ctx.alias,+ row.file_path,+ lines=[start, end],+ verification_basis="live",+ source_kind="source",+ )+ entry["fetch_with"] = fetch_reference["id"]+ entry["fetch_reference"] = fetch_referencenot_rendered.append(entry)continueremaining -= len(numbered)@@ -634,6 +664,7 @@ async def get_symbol(query: str | None = None,id: str | None = None,depth: int = 1,+ reference: dict[str, Any] | None = None,) -> dict:"""Follow-up read of one symbol whose id another response already gave you.@@ -642,17 +673,10 @@ async def get_symbol(one call instead of many. Reach here for a body that was elided, or for a``continuation`` / omission ref. Never walk a file symbol by symbol.- Raw source of one indexed symbol, bounded (~600 lines). ``source`` uses- Read's exact line-numbered format; treat it as an already-performed Read.- ``verified: true`` = bounds checked (or corrected) against the live file:- no follow-up Read needed. ``bounds: "approximate"`` = the symbol moved and- re-location failed. An ambiguous id (overloads, re-exports) returns ALL- matching bodies in ``candidates``; none is silently chosen. Also serves- live range reads ("path.py:140-180", ≤200 lines, always verified) and- omission refs ("repowise#<12-hex>"). An index miss returns fallback_lines- from a live grep rather than a dead end. When ``truncated`` is true the- response carries a ``continuation`` token: the exact range read that- fetches the remainder; pass it straight back to get_symbol.+ Returns verified, line-numbered source for one indexed symbol, live range,+ or omission ref. Ambiguity returns every candidate; an index miss returns+ live fallback lines. A truncated result carries the exact continuation to+ pass straight back.Args:symbol_id: "path/to/file.py::Name", "path/to/file.py:140-180" for a@@ -663,7 +687,18 @@ async def get_symbol(id: accepted alias for ``symbol_id``.depth: 1 (default) is this symbol alone; 2-3 also returns the bodiesit calls, transitively, in ``callee_bodies``.+ reference: structured source reference emitted by this tool. Its id+ and repository are accepted together without caller translation."""+ if reference:+ if not symbol_id and not id and isinstance(reference.get("id"), str):+ symbol_id = reference["id"]+ if (+ repo is None+ and _is_workspace_mode()+ and isinstance(reference.get("repository"), str)+ ):+ repo = reference["repository"]if repo == "all":return _unsupported_repo_all("get_symbol")ctx = await _resolve_repo_context(repo)@@ -686,17 +721,26 @@ async def get_symbol(omission_ref = _extract_omission_ref(symbol_id)if omission_ref is not None:- return _resolve_omission_ref(symbol_id, omission_ref, query, ctx.path, t0)+ canonical_omission = omission_reference(symbol_id) or symbol_id+ return _resolve_omission_ref(+ canonical_omission, omission_ref, query, ctx.path, t0+ )# Range read: "path/to/file.py:140-180" (single colon + numeric range —# never collides with "{path}::{name}").range_match = _RANGE_ID_RE.match(symbol_id.strip())if range_match and "::" not in symbol_id:+ normalized_path = path_identity(range_match.group("path"))+ range_start = int(range_match.group("start"))+ range_end = int(range_match.group("end"))+ if range_end < range_start:+ range_start, range_end = range_end, range_start+ normalized_id = f"{normalized_path}:{range_start}-{range_end}"return await _resolve_range_read(- symbol_id,- range_match.group("path"),- int(range_match.group("start")),- int(range_match.group("end")),+ normalized_id,+ normalized_path,+ range_start,+ range_end,max(0, min(50, context_lines)),ctx,t0,@@ -826,7 +870,7 @@ async def get_symbol() > _MAX_SOURCE_LINESresponse = {- "symbol_id": row.symbol_id,+ "symbol_id": symbol_identity(row.symbol_id),"file": row.file_path,"name": row.name,"kind": row.kind,@@ -853,7 +897,15 @@ async def get_symbol(# fetches the remainder so the agent never has to guess the next span# (the S1 dogfood found it would otherwise grub-around with a guessed# range, doubling the call cost).- response["continuation"] = f"{row.file_path}:{end + 1}-{check.end_line}"+ continuation_reference = source_reference(+ ctx.alias,+ row.file_path,+ lines=[end + 1, check.end_line],+ verification_basis="live",+ source_kind="source",+ )+ response["continuation"] = continuation_reference["id"]+ response["continuation_reference"] = continuation_referenceresponse["note"] = (f"Symbol body ({check.start_line}-{check.end_line}) exceeds the "f"{_MAX_SOURCE_LINES}-line serve cap; served {start}-{end}. Fetch "@@ -871,7 +923,13 @@ async def get_symbol(if depth > 1:async with get_session(ctx.session_factory) as session:callee_block = await _expand_callees(- session, repository.id, row, repo_root, depth, exclude_spec+ session,+ repository.id,+ row,+ repo_root,+ depth,+ exclude_spec,+ ctx.alias,)if callee_block is not None:response["callee_bodies"] = callee_blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 0179b389a..dbbcc04bc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -38,6 +38,7 @@ from repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,_is_path,+ _is_workspace_mode,_resolve_all_contexts,_resolve_repo_context,_unsupported_repo_all,@@ -73,6 +74,8 @@ async def get_why(query: str | None = None,targets: list[str] | None = None,repo: str | None = None,+ id: str | None = None,+ reference: dict[str, Any] | None = None,) -> dict:"""Why this code is shaped this way — decision records + evidence commits.@@ -89,7 +92,24 @@ async def get_why(targets: optional file paths to anchor the search, or to ask about ontheir own when there is no query.repo: usually omitted.+ id: decision or ``ev_...`` evidence id emitted by this or another tool.+ reference: structured evidence reference. Its id and repository are+ accepted together without caller translation."""+ if reference:+ if id is None and isinstance(reference.get("id"), str):+ id = reference["id"]+ if (+ repo is None+ and _is_workspace_mode()+ and isinstance(reference.get("repository"), str)+ ):+ repo = reference["repository"]+ if id:+ if repo == "all":+ return _unsupported_repo_all("get_why (reference lookup)")+ return await _why_reference(id, repo, reference=reference)+# --- repo="all": search decisions across ALL repos ---if repo == "all":if not query:@@ -114,6 +134,116 @@ async def get_why(return await _why_search(query, targets, repo)+async def _why_reference(+ reference_id: str,+ repo: str | None,+ *,+ reference: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Resolve one emitted decision/evidence id without relevance search."""++ ctx, repository, records, _target_git = await _load_corpus(repo, None)+ async with get_session(ctx.session_factory) as session:+ await _attach_decision_evidence(session, records)++ payload = {+ "decisions": [+ _governing_decision_entry(+ record,+ filter_path_list(+ json.loads(record.affected_files_json or "[]"),+ _get_exclude_spec(ctx.path),+ ),+ [],+ )+ for record in records+ ]+ }+ await annotate_response_evidence_async(+ payload,+ ctx.alias,+ records,+ repo_root=ctx.path,+ )+ matches = [+ row+ for row in payload["decisions"]+ if row["id"] == reference_id+ or any(ref["id"] == reference_id for ref in row.get("evidence_refs", []))+ ]+ matching_refs = {+ ref["id"]: ref+ for row in matches+ for ref in row.get("evidence_refs", [])+ if ref["id"] == reference_id+ }+ if not matches and reference_id.startswith("ev_"):+ live_ref = _resolve_unattached_evidence_reference(+ reference_id, ctx.alias, ctx.path+ )+ if live_ref is not None:+ matching_refs[live_ref["id"]] = live_ref+ if (+ reference is not None+ and matching_refs+ and _evidence_reference_matches_id(reference)+ ):+ matching_refs[reference_id] = dict(reference)+ meta = _build_meta(repository=repository)+ persistence = (payload.get("_meta") or {}).get("reference_persistence")+ if persistence is not None:+ meta["reference_persistence"] = persistence+ return {+ "mode": "reference",+ "reference_id": reference_id,+ "resolved": bool(matches or matching_refs),+ "decisions": matches,+ "evidence_refs": list(matching_refs.values()),+ "_meta": meta,+ }+++def _evidence_reference_matches_id(value: dict[str, Any]) -> bool:+ """Validate the identity-bearing coordinates of a structured evidence ref."""++ from repowise.server.mcp_server._references import reference as build_reference++ identifier = value.get("id")+ repository = value.get("repository")+ kind = value.get("kind")+ if not all(isinstance(item, str) for item in (identifier, repository, kind)):+ return False+ coordinate_keys = {+ "commit": ("commit",),+ "file_range": ("path", "range"),+ "file_content": ("path", "line", "content_id"),+ "legacy": ("path", "content_id", "commit_prefix"),+ }.get(kind)+ if coordinate_keys is None:+ return False+ coordinates = {key: value[key] for key in coordinate_keys if key in value}+ return build_reference(kind, repository, **coordinates)["id"] == identifier+++def _resolve_unattached_evidence_reference(+ reference_id: str,+ repository: str,+ repo_root: str | Path,+) -> dict[str, Any] | None:+ """Resolve evidence not attached to a persisted decision without a repo scan."""++ from repowise.server.mcp_server._references import repository_identity+ from repowise.server.mcp_server._why_evidence import (+ resolve_cached_evidence_reference,+ resolve_persisted_evidence_reference,+ )++ repository = repository_identity(repository)+ return resolve_cached_evidence_reference(+ repository, reference_id+ ) or resolve_persisted_evidence_reference(repository, reference_id, repo_root)++async def _why_workspace_search(query: str) -> dict:"""repo="all": the question single-repo search answers, across the workspace.@@ -653,7 +783,13 @@ def _fit_path_response(result_data["decisions_truncated"] = Trueresult_data["decisions_omitted"] = result_data["decisions_total"] - len(decisions)- _shed("code_rationale", "git_archaeology", "origin_story")+ _shed(+ "code_rationale",+ "git_archaeology.file_commits",+ "git_archaeology.cross_references",+ "git_archaeology.git_log",+ "origin_story",+ )collector.attach(result_data)return result_datadiff --git a/tests/unit/distill/test_store.py b/tests/unit/distill/test_store.pyindex cf13f5b76..27191836b 100644--- a/tests/unit/distill/test_store.py+++ b/tests/unit/distill/test_store.py@@ -42,6 +42,17 @@ def test_get_record_returns_provenance(store: OmissionStore) -> None:assert store.get_record("0" * 12) is None+def test_evidence_reference_roundtrip_uses_exact_public_id(store: OmissionStore) -> None:+ reference = '{"id":"ev_abc","repository":"backend","kind":"file_range"}'+ store.put_evidence_reference("ev_abc", reference, repository="backend")++ assert store.get_evidence_reference("ev_abc") == {+ "content": reference,+ "repository": "backend",+ }+ assert store.get_evidence_reference("ev_missing") is None++def test_get_with_query_filters_lines(store: OmissionStore) -> None:content = "FAILED test_a\npassed test_b\nFAILED test_c"ref = store.put(content, source="cli:test_output", original_tokens=10, kept_tokens=2)diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex 7a71e8142..fcef98d06 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -481,7 +481,7 @@ async def test_get_symbol_resolves_omission_ref(setup_mcp, repo_root: Path):assert result["kind"] == "omission"assert result["content"] == contentassert result["source"] == "mcp:test"- assert result["ref"] == ref+ assert result["ref"] == f"repowise#{ref}"assert "created_at" in resultfiltered = await get_symbol(f"repowise#{ref}", query="^ERROR")diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.pyindex 3d4da5e67..4669c43b6 100644--- a/tests/unit/server/mcp/test_context.py+++ b/tests/unit/server/mcp/test_context.py@@ -419,7 +419,9 @@ async def test_file_on_git_preferred_over_partial_module(setup_mcp_multi):assert t.get("type") != "module"assert t.get("exists_in_git") is Trueassert t["primary_owner"] == "Carol"- assert "error" in t # "exists but has no wiki page" shape+ assert "error" not in t+ assert t["type"] == "file"+ assert t["index_status"] == "live_file_without_wiki_page"@pytest.mark.asyncio@@ -520,7 +522,7 @@ async def test_file_target_callers_bank_the_full_ranked_tail(assert card["callers_emitted"] == 20assert card["callers_reduced_reason"] == "construction_cap"[ref] = result["_meta"]["omitted"]["refs"]- recovered = await get_symbol(f"repowise#{ref}")+ recovered = await get_symbol(ref)assert "src/generated/importer_24.py" in recovered.get("content", ""), recovereddiff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.pynew file mode 100644index 000000000..7b0a3de2c--- /dev/null+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py@@ -0,0 +1,869 @@+"""Sealed cross-tool identifier and evidence-reference round trips."""++from __future__ import annotations++import re+import subprocess+from copy import copy+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any, Literal++import pytest+from sqlalchemy import select++from repowise.core.persistence.models import (+ DeadCodeFinding,+ GraphEdge,+ GraphNode,+ HealthFinding,+ RefactoringSuggestion,+ WikiSymbol,+)+++def _write_numbered_source(root) -> None:+ service = ["# filler" for _ in range(750)]+ service[0] = '"""Authentication service."""'+ service[9] = "class AuthService:"+ service[10:19] = [f" class_value_{i} = {i}" for i in range(9)]+ service[19] = " async def login(self, username: str, password: str):"+ service[20:40] = [f" step_{i} = {i}" for i in range(20)]+ service[40] = " return username"+ service[99] = "def load_users():"+ service[100] = " return []"+ service[700] = "class AfterAuth:"+ service[701] = " pass"++ models = ["# filler" for _ in range(35)]+ models[4] = "class User:"+ models[5:30] = [f" field_{i} = {i}" for i in range(25)]+ models[30] = "def fetch_one():"+ models[31] = " return None"++ files = {+ "src/auth/service.py": "\n".join(service) + "\n",+ "src/auth/middleware.py": "from .service import AuthService\n",+ "src/db/models.py": "\n".join(models) + "\n",+ "src/legacy/old_auth.py": (+ "# Keep this shim because deployed plugins still import it.\n"+ "def old_auth():\n return None\n"+ ),+ "tests/test_service.py": "def test_service():\n assert True\n",+ }+ for relative, content in files.items():+ path = root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+++def reference_repo(tmp_path, monkeypatch, setup_mcp):+ import repowise.server.mcp_server as mcp_mod++ _write_numbered_source(tmp_path)+ (tmp_path / ".repowise").mkdir()+ for args in (+ ["git", "init", "-q"],+ ["git", "config", "user.email", "[email protected]"],+ ["git", "config", "user.name", "Matrix Fixture"],+ ["git", "add", "."],+ ["git", "commit", "-qm", "sealed fixture"],+ ):+ subprocess.run(args, cwd=tmp_path, check=True, capture_output=True)+ with (tmp_path / "src/auth/service.py").open("a", encoding="utf-8") as handle:+ handle.write("# committed matrix change\n")+ for args in (+ ["git", "add", "src/auth/service.py"],+ ["git", "commit", "-qm", "change fixture"],+ ):+ subprocess.run(args, cwd=tmp_path, check=True, capture_output=True)+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))+ return tmp_path+++Status = Literal["PASS", "N/A"]+++@dataclass(frozen=True)+class Ref:+ emitter: str+ kind: str+ value: str+ location: tuple[str, ...]+ expected_path: str | None = None+ expected_name: str | None = None+ expected_object: dict[str, Any] | None = None+ expected_contains: tuple[str, ...] = ()+ entity_family: str | None = None+++@dataclass(frozen=True)+class Cell:+ emitter: str+ kind: str+ target: str+ status: Status+++_PATH_FIELDS = {+ "affected_files",+ "candidate",+ "candidates",+ "citations",+ "entry_points",+ "file",+ "file_path",+ "files",+ "path",+ "source_file",+ "successor_paths",+ "target_path",+ "targets",+ "test_file",+}+_SYMBOL_FIELDS = {+ "callee",+ "callee_id",+ "caller",+ "caller_id",+ "node_id",+ "source_node_id",+ "symbol_id",+ "target_node_id",+}+_DECISION_COLLECTIONS = {+ "decisions",+ "lineage",+ "recent_reversals",+ "top_active",+}+_DECISION_OBJECT_FIELDS = {"newer", "older", "superseded_by"}+_REFERENCE_KINDS = (+ "file",+ "symbol",+ "repository",+ "decision/evidence",+ "omission/continuation",+ "finding",+ "refactoring plan",+)+_EXPECTED_KINDS = {+ "get_answer": {"file"},+ "get_change_risk": set(),+ "get_context": {+ "file",+ "symbol",+ "decision/evidence",+ "omission/continuation",+ },+ "get_dead_code": {"file", "finding"},+ "get_health": {"file", "symbol", "finding", "refactoring plan"},+ "get_overview": {"file"},+ "get_risk": {"file"},+ "get_symbol": {"file", "omission/continuation"},+ "get_why": {"file", "decision/evidence"},+ "search_codebase": {"file", "symbol"},+}++_TARGETS_BY_KIND = {+ "file": ("get_context",),+ "symbol": ("get_context", "get_symbol"),+ "repository": (+ "get_answer",+ "get_change_risk",+ "get_context",+ "get_dead_code",+ "get_health",+ "get_overview",+ "get_risk",+ "get_symbol",+ "get_why",+ "search_codebase",+ ),+ "decision/evidence": ("get_why",),+ "omission/continuation": ("get_symbol",),+ "finding": ("get_dead_code", "get_health"),+ "refactoring plan": ("get_health",),+}+++def _looks_like_path(value: str) -> bool:+ if not value or value.startswith(("http://", "https://", "repowise#")):+ return False+ if " -> " in value or "\n" in value:+ return False+ return "/" in value or "\\" in value or "." in value.rsplit("/", 1)[-1]+++def _append_source_ref(+ refs: list[Ref], emitter: str, value: str, location: tuple[str, ...], row: dict | None+) -> None:+ if re.search(r":\d+-\d+$", value):+ path = value.rsplit(":", 1)[0].replace("\\", "/")+ refs.append(+ Ref(+ emitter,+ "omission/continuation",+ value.replace("\\", "/"),+ location,+ expected_path=path,+ entity_family="continuation",+ )+ )+ elif "::" in value:+ path, symbol = value.split("::", 1)+ refs.append(+ Ref(+ emitter,+ "symbol",+ value.replace("\\", "/"),+ location,+ expected_path=path.replace("\\", "/"),+ expected_name=(row or {}).get("name") or symbol.rsplit("::", 1)[-1],+ )+ )+ elif _looks_like_path(value):+ refs.append(+ Ref(+ emitter,+ "file",+ value.replace("\\", "/"),+ location,+ expected_path=value.replace("\\", "/"),+ )+ )+++def _without_projection_counts(value: Any) -> Any:+ if isinstance(value, dict):+ return {+ key: _without_projection_counts(item)+ for key, item in value.items()+ if not key.endswith(("_emitted", "_total", "_truncated", "_omitted"))+ }+ if isinstance(value, list):+ return [_without_projection_counts(item) for item in value]+ return value+++def _extract_contract_references(+ emitter: str,+ value: Any,+ *,+ location: tuple[str, ...] = (),+ field: str = "",+) -> list[Ref]:+ """Extract public pointers without collapsing duplicate emission sites."""++ refs: list[Ref] = []+ if isinstance(value, dict):+ if field == "evidence_refs" and isinstance(value.get("id"), str):+ refs.append(+ Ref(+ emitter,+ "decision/evidence",+ value["id"],+ location,+ expected_object=value,+ entity_family="evidence",+ )+ )+ identifier = value.get("id")+ if isinstance(identifier, str):+ if field in _DECISION_COLLECTIONS or field in _DECISION_OBJECT_FIELDS:+ refs.append(+ Ref(+ emitter,+ "decision/evidence",+ identifier,+ (*location, "id"),+ entity_family="decision",+ )+ )+ elif identifier.startswith("finding_"):+ refs.append(+ Ref(+ emitter,+ "finding",+ identifier,+ (*location, "id"),+ expected_object=value,+ entity_family="dead_code" if emitter == "get_dead_code" else "health",+ )+ )+ elif identifier.startswith("plan_"):+ refs.append(+ Ref(+ emitter,+ "refactoring plan",+ identifier,+ (*location, "id"),+ expected_object=value,+ )+ )+ for key, item in value.items():+ child_location = (*location, str(key))+ if key == "continuation" and isinstance(item, str):+ refs.append(+ Ref(+ emitter,+ "omission/continuation",+ item,+ child_location,+ entity_family=(+ "omission" if item.startswith("repowise#") else "continuation"+ ),+ )+ )+ elif key == "refs" and field == "omitted" and isinstance(item, list):+ refs.extend(+ Ref(+ emitter,+ "omission/continuation",+ ref,+ (*child_location, str(index)),+ expected_contains=("call_062",)+ if emitter == "get_context"+ else (),+ entity_family="omission",+ )+ for index, ref in enumerate(item)+ if isinstance(ref, str)+ )+ elif key in (_SYMBOL_FIELDS | _PATH_FIELDS) and isinstance(item, str):+ _append_source_ref(refs, emitter, item, child_location, value)+ elif key == "targets" and isinstance(item, dict):+ for target in item:+ if isinstance(target, str):+ _append_source_ref(+ refs,+ emitter,+ target,+ (*child_location, target),+ item.get(target) if isinstance(item.get(target), dict) else None,+ )+ refs.extend(+ _extract_contract_references(+ emitter,+ item,+ location=child_location,+ field=key,+ )+ )+ elif isinstance(value, list):+ for index, item in enumerate(value):+ child_location = (*location, str(index))+ if isinstance(item, str) and field in _PATH_FIELDS:+ _append_source_ref(refs, emitter, item, child_location, None)+ refs.extend(+ _extract_contract_references(+ emitter,+ item,+ location=child_location,+ field=field,+ )+ )+ return refs+++async def _seed_context_omission(session, repository_id: str, root) -> str:+ target = "src/auth/service.py::login"+ now = datetime(2026, 8, 26, tzinfo=UTC)+ session.add(+ GraphNode(+ id="matrix-login-node",+ repository_id=repository_id,+ node_id=target,+ node_type="symbol",+ name="login",+ file_path="src/auth/service.py",+ kind="method",+ start_line=20,+ end_line=41,+ created_at=now,+ )+ )+ session.add_all(+ [+ WikiSymbol(+ id="matrix-load-users",+ repository_id=repository_id,+ file_path="src/auth/service.py",+ symbol_id="src/auth/service.py::load_users",+ name="load_users",+ qualified_name="load_users",+ kind="function",+ signature="def load_users()",+ start_line=100,+ end_line=101,+ language="python",+ created_at=now,+ updated_at=now,+ ),+ WikiSymbol(+ id="matrix-fetch-one",+ repository_id=repository_id,+ file_path="src/db/models.py",+ symbol_id="src/db/models.py::fetch_one",+ name="fetch_one",+ qualified_name="fetch_one",+ kind="function",+ signature="def fetch_one()",+ start_line=31,+ end_line=32,+ language="python",+ created_at=now,+ updated_at=now,+ ),+ ]+ )+ for index in range(63):+ caller = f"src/generated/caller_{index:03d}.py::call_{index:03d}"+ file_path, name = caller.split("::", 1)+ source_path = root / file_path+ source_path.parent.mkdir(parents=True, exist_ok=True)+ source_path.write_text(f"def {name}():\n return {index}\n", encoding="utf-8")+ session.add_all(+ [+ WikiSymbol(+ id=f"matrix-symbol-caller-{index}",+ repository_id=repository_id,+ file_path=file_path,+ symbol_id=caller,+ name=name,+ qualified_name=name,+ kind="function",+ signature=f"def {name}()",+ start_line=1,+ end_line=2,+ language="python",+ created_at=now,+ updated_at=now,+ ),+ GraphNode(+ id=f"matrix-caller-file-{index}",+ repository_id=repository_id,+ node_id=file_path,+ node_type="file",+ name=f"caller_{index:03d}.py",+ file_path=file_path,+ language="python",+ symbol_count=1,+ created_at=now,+ ),+ GraphNode(+ id=f"matrix-caller-{index}",+ repository_id=repository_id,+ node_id=caller,+ node_type="symbol",+ name=name,+ file_path=file_path,+ kind="function",+ start_line=1,+ end_line=2,+ created_at=now,+ ),+ GraphEdge(+ id=f"matrix-in-{index}",+ repository_id=repository_id,+ source_node_id=caller,+ target_node_id=target,+ edge_type="calls",+ confidence=0.99,+ created_at=now,+ ),+ ]+ )+ await session.commit()+ return target+++def _cell_status(emitter: str, kind: str, target: str) -> Status:+ if kind not in _EXPECTED_KINDS[emitter]:+ return "N/A"+ if kind == "finding":+ owner = "get_dead_code" if emitter == "get_dead_code" else "get_health"+ return "PASS" if target == owner else "N/A"+ return "PASS"+++_CELL_LEDGER = tuple(+ Cell(emitter, kind, target, _cell_status(emitter, kind, target))+ for emitter in _EXPECTED_KINDS+ for kind in _REFERENCE_KINDS+ for target in _TARGETS_BY_KIND[kind]+)+++async def test_canonical_emitter_reference_inventory(reference_repo, health_data, session) -> None:+ from repowise.server.mcp_server import (+ get_answer,+ get_change_risk,+ get_context,+ get_dead_code,+ get_health,+ get_overview,+ get_risk,+ get_symbol,+ get_why,+ search_codebase,+ tool_middleware,+ )++ await _seed_plan(session, health_data)+ context_target = await _seed_context_omission(session, health_data, reference_repo)+ calls = {+ "get_answer": (get_answer, ("where is login defined",), {}),+ "get_change_risk": (get_change_risk, ("HEAD",), {"baseline": 0}),+ "get_context": (get_context, (["src/auth/service.py"],), {"include": ["decisions"]}),+ "get_dead_code": (get_dead_code, (), {"min_confidence": "low"}),+ "get_health": (get_health, (), {"include": ["biomarkers", "refactoring"]}),+ "get_overview": (get_overview, (), {"include": ["decisions"]}),+ "get_risk": (get_risk, (["src/auth/service.py"],), {}),+ "get_symbol": (get_symbol, ("src/auth/service.py:1-750",), {}),+ "get_why": (get_why, ("why is JWT used for authentication",), {}),+ "search_codebase": (search_codebase, ("login",), {"mode": "symbol", "limit": 5}),+ }+ responses: dict[str, list[dict[str, Any]]] = {+ name: [await tool_middleware(tool)(*args, **kwargs)]+ for name, (tool, args, kwargs) in calls.items()+ }+ responses["get_context"].append(+ await tool_middleware(get_context)(+ [context_target], include=["callers", "callees"]+ )+ )+ inventory = {+ emitter: [+ ref+ for response_index, response in enumerate(emitter_responses)+ for ref in _extract_contract_references(+ emitter,+ response,+ location=(f"response[{response_index}]",),+ )+ ]+ for emitter, emitter_responses in responses.items()+ }++ assert len(_CELL_LEDGER) == sum(+ len(_TARGETS_BY_KIND[kind])+ for _emitter in _EXPECTED_KINDS+ for kind in _REFERENCE_KINDS+ )+ for cell in _CELL_LEDGER:+ refs = [ref for ref in inventory[cell.emitter] if ref.kind == cell.kind]+ if cell.kind == "finding":+ family = "dead_code" if cell.target == "get_dead_code" else "health"+ refs = [ref for ref in refs if ref.entity_family == family]+ if cell.status == "PASS":+ assert refs, cell+ else:+ assert not refs, cell++ for emitter, refs in inventory.items():+ assert {ref.kind for ref in refs} == _EXPECTED_KINDS[emitter]+ for ref in refs:+ targets = _TARGETS_BY_KIND[ref.kind]+ if ref.kind == "finding":+ targets = (+ "get_dead_code" if ref.entity_family == "dead_code" else "get_health",+ )+ for target in targets:+ if target == "get_context":+ resolved = await tool_middleware(get_context)([ref.value])+ card = resolved["targets"][ref.value]+ assert card.get("error") is None, (ref, card)+ assert card.get("target") == ref.value+ if ref.kind == "symbol":+ _assert_symbol_card(+ resolved,+ ref.value,+ ref.expected_path or "",+ ref.expected_name or "",+ )+ assert "resolved_to" not in card+ else:+ expected_type = (+ "file"+ if "." in (ref.expected_path or "").rsplit("/", 1)[-1]+ else "module"+ )+ assert card["type"] == expected_type, (ref, card)+ assert "resolved_to" not in card+ if expected_type == "file":+ assert card["path"] == ref.expected_path+ assert card.get("docs") or card.get("summary") or card.get("files")+ elif target == "get_symbol":+ resolved = await tool_middleware(get_symbol)(ref.value)+ if ref.kind == "symbol":+ candidate = resolved+ if "candidates" in resolved:+ candidate = next(+ row+ for row in resolved["candidates"]+ if row.get("symbol_id") == ref.value+ )+ assert candidate["verified"] is True+ assert candidate["symbol_id"] == ref.value+ assert candidate["file"] == ref.expected_path+ assert candidate["source"]+ elif ref.entity_family == "omission":+ assert resolved["kind"] == "omission"+ assert resolved["content"]+ if ref.expected_contains:+ assert any(+ marker in resolved["content"]+ for marker in ref.expected_contains+ )+ else:+ path, bounds = ref.value.rsplit(":", 1)+ start_text, end_text = bounds.split("-", 1)+ start, end = int(start_text), int(end_text)+ assert resolved["kind"] == "range"+ assert resolved["file"] == path+ assert resolved["start_line"] == start+ assert resolved["end_line"] == min(end, start + 199)+ assert resolved["verified"] is True+ assert resolved["source"]+ elif target == "get_why":+ resolved = await tool_middleware(get_why)(+ **(+ {"reference": ref.expected_object}+ if ref.entity_family == "evidence"+ else {"id": ref.value}+ )+ )+ assert resolved["resolved"] is True+ if ref.entity_family == "evidence":+ assert ref.expected_object in resolved["evidence_refs"]+ else:+ decision = next(+ row for row in resolved["decisions"] if row["id"] == ref.value+ )+ assert decision["id"] == ref.value+ assert decision.get("title") or decision.get("decision")+ elif target == "get_dead_code":+ resolved = await tool_middleware(get_dead_code)(+ min_confidence="low", finding_id=ref.value+ )+ assert resolved["resolved"] is True+ assert resolved["finding"] == ref.expected_object+ elif target == "get_health" and ref.kind == "finding":+ resolved = await tool_middleware(get_health)(finding_id=ref.value)+ assert resolved["resolved"] is True+ assert _without_projection_counts(+ resolved["finding"]+ ) == _without_projection_counts(ref.expected_object)+ elif target == "get_health":+ resolved = await tool_middleware(get_health)(plan_id=ref.value)+ assert resolved["resolved"] is True+ assert resolved["plan"]["id"] == ref.value+ assert resolved["plan"]["file_path"] == ref.expected_object["file_path"]+++async def _seed_plan(session, repository_id: str) -> None:+ from repowise.core.persistence import crud++ await crud.save_refactoring_suggestions(+ session,+ repository_id,+ [+ {+ "refactoring_type": "extract_method",+ "file_path": "src/auth/service.py",+ "target_symbol": "login",+ "line_start": 20,+ "line_end": 40,+ "plan": {"groups": []},+ "evidence": {},+ "impact_delta": 1.0,+ "effort_bucket": "S",+ "blast_radius": {"dependents_count": 0},+ "confidence": "high",+ "source_biomarker": "complex_method",+ }+ ],+ )+ await session.commit()+++def _assert_symbol_card(result: dict, symbol_id: str, path: str, name: str) -> None:+ card = result["targets"][symbol_id]+ assert card["target"] == symbol_id+ assert card["type"] == "symbol"+ assert card["docs"]["file_path"] == path+ assert card["docs"]["name"] == name+ assert "resolved_to" not in card+++async def test_get_symbol_consumes_symbol_range_and_omission_references_verbatim(+ reference_repo,+) -> None:+ from repowise.server.mcp_server import get_context, get_symbol, search_codebase+ from repowise.server.mcp_server._budget import OmissionCollector++ search = await search_codebase("login", mode="symbol", limit=5)+ symbol_id = next(row["symbol_id"] for row in search["results"] if row["name"] == "login")++ symbol = await get_symbol(symbol_id)+ assert symbol["verified"] is True+ assert symbol["file"] == "src/auth/service.py"+ assert symbol["source"]++ context = await get_context([symbol_id])+ _assert_symbol_card(context, symbol_id, "src/auth/service.py", "login")++ range_id = "src/auth/service.py:20-25"+ source_range = await get_symbol(range_id)+ assert source_range["kind"] == "range"+ assert source_range["file"] == "src/auth/service.py"+ assert source_range["start_line"] == 20+ assert source_range["end_line"] == 25+ assert source_range["verified"] is True+ assert source_range["source"]++ truncated = await get_symbol("src/auth/service.py:1-750")+ continuation = truncated["continuation_reference"]+ continued = await get_symbol(reference=continuation)+ assert continued["symbol_id"] == continuation["id"]+ assert continued["file"] == continuation["path"]+ assert continued["start_line"] == continuation["range"][0]+ assert continued["source"]++ collector = OmissionCollector("matrix", repo_root=reference_repo)+ collector.add("sealed", {"symbol_id": symbol_id, "evidence": "recover me"})+ emitted: dict = {}+ collector.attach(emitted)+ [omission_id] = emitted["_meta"]["omitted"]["refs"]+ assert omission_id.startswith("repowise#")+ recovered = await get_symbol(omission_id)+ assert recovered["kind"] == "omission"+ assert "recover me" in recovered["content"]+++async def test_context_file_card_fallback_is_a_firing_negative_control(+ reference_repo,+) -> None:+ from repowise.server.mcp_server import get_context++ missing_id = "src/auth/service.py::NoSuchMethod"+ result = await get_context([missing_id])+ assert result["targets"][missing_id].get("error") is None+ with pytest.raises(AssertionError):+ _assert_symbol_card(result, missing_id, "src/auth/service.py", "NoSuchMethod")+++ "path",+ [+ "src/auth/middleware.py",+ "src/auth/service.py",+ "src/db/models.py",+ "src/legacy/old_auth.py",+ "src/auth",+ "src/db",+ ],+)+async def test_emitted_file_paths_resolve_to_content(reference_repo, path: str) -> None:+ from repowise.server.mcp_server import get_context++ result = await get_context([path])+ card = result["targets"][path]+ expected_type = "file" if "." in path.rsplit("/", 1)[-1] else "module"+ assert card.get("error") is None+ assert card["target"] == path+ assert card["type"] == expected_type, (path, card)+ assert "resolved_to" not in card+ assert card.get("docs") or card.get("summary") or card.get("files")+++async def test_decision_and_evidence_ids_round_trip_through_get_why(+ reference_repo,+) -> None:+ from repowise.server.mcp_server import get_why++ emitted = await get_why("why is JWT used for authentication")+ decision = next(row for row in emitted["decisions"] if row["id"] == "dec1")+ [evidence] = decision["evidence_refs"]++ decision_result = await get_why(id=decision["id"])+ assert decision_result["resolved"] is True+ assert decision_result["decisions"][0]["id"] == decision["id"]++ evidence_result = await get_why(reference=evidence)+ assert evidence_result["resolved"] is True+ assert evidence_result["evidence_refs"] == [evidence]++ archaeology = await get_why("src/legacy/old_auth.py")+ rationale = archaeology["code_rationale"][0]+ [rationale_ref] = rationale["evidence_refs"]+ from repowise.server.mcp_server import _why_evidence++ with _why_evidence._reference_cache_lock:+ _why_evidence._reference_cache.clear()+ rationale_result = await get_why(reference=rationale_ref)+ assert rationale_result["resolved"] is True+ assert rationale_result["evidence_refs"] == [rationale_ref]+++async def test_finding_and_plan_ids_are_stable_and_resolve_in_one_call(+ reference_repo,+ health_data,+ session,+) -> None:+ from repowise.server.mcp_server import get_dead_code, get_health+ from repowise.server.mcp_server.tool_dead_code import _dead_code_finding_id+ from repowise.server.mcp_server.tool_health import (+ _health_finding_id,+ _refactoring_plan_id,+ )++ await _seed_plan(session, health_data)++ health = await get_health(+ include=["biomarkers", "refactoring"],+ only=["top_findings", "refactoring_plans"],+ limit=10,+ )+ health_finding = health["top_findings"][0]+ health_lookup = await get_health(finding_id=health_finding["id"])+ assert health_lookup["resolved"] is True+ assert health_lookup["finding"] == health_finding++ [plan] = health["refactoring_plans"]+ plan_lookup = await get_health(plan_id=plan["id"])+ assert plan_lookup["resolved"] is True+ assert plan_lookup["plan"]["id"] == plan["id"]++ dead = await get_dead_code(min_confidence="low")+ dead_finding = next(+ row+ for tier in dead["tiers"].values()+ for row in tier["findings"]+ )+ dead_lookup = await get_dead_code(+ min_confidence="low", finding_id=dead_finding["id"]+ )+ assert dead_lookup["resolved"] is True+ assert dead_lookup["finding"] == dead_finding++ # Storage UUID replacement cannot move any public identifier.+ health_row = (await session.execute(select(HealthFinding))).scalars().first()+ dead_row = (await session.execute(select(DeadCodeFinding))).scalars().first()+ plan_row = (await session.execute(select(RefactoringSuggestion))).scalars().first()+ for row, public_id, factory in (+ (health_row, health_finding["id"], _health_finding_id),+ (dead_row, dead_finding["id"], _dead_code_finding_id),+ (plan_row, plan["id"], _refactoring_plan_id),+ ):+ replacement = copy(row)+ replacement.id = "different-storage-uuid"+ assert factory(replacement, "default") == public_iddiff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex fb17b16d1..2c32749ce 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -10,6 +10,8 @@ import jsonimport pytest+from repowise.core.persistence.models import HealthFinding+@pytest.mark.asyncioasync def test_get_health_dashboard(setup_mcp, health_data):@@ -27,6 +29,44 @@ async def test_get_health_dashboard(setup_mcp, health_data):assert "omitted" not in result["_meta"]+async def test_finding_ids_distinguish_same_coordinate_evidence(+ setup_mcp, health_data, session+):+ from repowise.server.mcp_server import get_health++ rows = [+ HealthFinding(+ id=f"storage-{partner}",+ repository_id=health_data,+ file_path="src/auth/service.py",+ biomarker_type="hidden_coupling",+ severity="medium",+ function_name=None,+ line_start=None,+ line_end=None,+ details_json=json.dumps({"partner": partner}),+ health_impact=0.4,+ reason=f"Changes with {partner}",+ status="open",+ )+ for partner in ("src/a.py", "src/b.py")+ ]+ session.add_all(rows)+ await session.commit()++ emitted = await get_health(only=["top_findings"], limit=10)+ findings = [+ row+ for row in emitted["top_findings"]+ if row["biomarker_type"] == "hidden_coupling"+ ]+ assert len({row["id"] for row in findings}) == 2+ for finding in findings:+ resolved = await get_health(finding_id=finding["id"])+ assert resolved["finding"] == finding++@pytest.mark.asyncioasync def test_dashboard_zero_limit_has_exact_ranked_page_recovery(setup_mcp, health_data):from repowise.server.mcp_server import get_healthdiff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.pyindex 567bbf3cc..505631b23 100644--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py@@ -53,7 +53,7 @@ def _assert_wire(result: dict[str, Any], first: str, limit: int) -> None:async def _recover(result: dict[str, Any]) -> str:recovered: list[str] = []for ref in result.get("_meta", {}).get("omitted", {}).get("refs", []):- row = await get_symbol(f"repowise#{ref}")+ row = await get_symbol(ref)assert "error" not in row, rowrecovered.append(row["content"])return "\n".join(recovered)@@ -65,7 +65,7 @@ async def _recover_one(result: dict[str, Any], *sentinels: str) -> str:assert refscontents: list[str] = []for ref in refs:- row = await get_symbol(f"repowise#{ref}")+ row = await get_symbol(ref)assert "error" not in row, rowcontents.append(row["content"])for sentinel in sentinels:@@ -687,7 +687,7 @@ async def test_why_real_adversarial_wire_recovers_decisions_docs_and_episodes(reffor ref in result["_meta"]["omitted"]["refs"]if "_END_7" in (- await get_symbol(f"repowise#{ref}")+ await get_symbol(ref)).get("content", "")]assert len(hidden_body_refs) == 1diff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.pyindex 91db891b8..ce88a29f3 100644--- a/tests/unit/server/mcp/test_refactoring.py+++ b/tests/unit/server/mcp/test_refactoring.py@@ -105,7 +105,10 @@ async def test_generate_code_disabled(factory, _mcp_globals) -> None:_mcp_globals._repo_path = str(repo_dir)result = await generate_refactoring_code(sid)- assert result["error"] == "disabled"+ assert result["resolved"] is True+ assert result["suggestion_id"].startswith("plan_")+ assert result["generation"]["available"] is False+ assert result["generation"]["reason"] == "disabled"@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex c4597c229..c9f6e7e95 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -1105,7 +1105,9 @@ class TestSearchCandidates:result = await search_codebase("how are requests issued", limit=10)hit = result["results"][0]- assert hit["target_path"] == "api/client.go::HTTP"+ assert hit["target_path"] == "api/client.go"+ assert hit["file"] == "api/client.go"+ assert hit["symbol_id"] == "api/client.go::HTTP"assert hit["file"] == "api/client.go"assert result["candidates"] == [{"path": "api/client.go"}]diff --git a/tests/unit/server/mcp/test_why_evidence_contract.py b/tests/unit/server/mcp/test_why_evidence_contract.pyindex c6084c8d2..291e8f1a7 100644--- a/tests/unit/server/mcp/test_why_evidence_contract.py+++ b/tests/unit/server/mcp/test_why_evidence_contract.py@@ -458,6 +458,8 @@ async def test_every_single_repository_query_mode_keeps_the_exact_public_referen"content_id": "8962562181b9a6600ce9","provenance": "historical","source": "readme_mining",+ "source_kind": "readme_mining",+ "verification_basis": "indexed",}calls = [await get_why("why is JWT used for authentication"),diff --git a/tests/unit/server/mcp/test_why_workspace_ranking.py b/tests/unit/server/mcp/test_why_workspace_ranking.pyindex ac2f56a15..7a9f5f350 100644--- a/tests/unit/server/mcp/test_why_workspace_ranking.py+++ b/tests/unit/server/mcp/test_why_workspace_ranking.py@@ -44,7 +44,9 @@ def _decision(rec_id: str, repo_id: str, title: str, body: str, **kw) -> Decisiodef _install(contexts: dict, default: str, root) -> _MockRegistry:import repowise.server.mcp_server as mcp_mod- registry = _MockRegistry(contexts=contexts, default_alias=default)+ registry = _MockRegistry(+ contexts=contexts, default_alias=default, workspace_root=root+ )primary = contexts[default]mcp_mod._registry = registrymcp_mod._workspace_root = str(root)@@ -143,6 +145,8 @@ async def test_a_partial_match_in_an_earlier_store_is_left_under_the_floor(two_r"content_id": "338f3ae3ca60c54e7741","provenance": "human_decision","source": "cli",+ "source_kind": "cli",+ "verification_basis": "indexed",}]@@ -246,7 +250,7 @@ async def test_workspace_search_serves_five_of_nine_answers(tmp_path, monkeypatcassert result["decisions_emitted"] == 5assert result["decisions_reduced_reason"] == "construction_cap"[ref] = result["_meta"]["omitted"]["refs"]- recovered = await get_symbol(f"repowise#{ref}")+ recovered = await get_symbol(ref)assert "Redis session cache decision 8" in recovered["content"]assert '"evidence_refs"' in recovered["content"]finally:diff --git a/tests/unit/server/test_mcp_workspace.py b/tests/unit/server/test_mcp_workspace.pyindex 1b25836ca..3c12a974d 100644--- a/tests/unit/server/test_mcp_workspace.py+++ b/tests/unit/server/test_mcp_workspace.py@@ -8,7 +8,10 @@ from __future__ import annotationsimport asyncioimport json+import subprocessfrom datetime import UTC, datetime+from pathlib import Path+from types import SimpleNamespaceimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine@@ -18,9 +21,12 @@ from repowise.core.persistence.database import init_dbfrom repowise.core.persistence.models import (DeadCodeFinding,DecisionRecord,+ GitMetadata,GraphNode,+ HealthFinding,Page,Repository,+ WikiSymbol,)from repowise.core.persistence.search import FullTextSearchfrom repowise.core.persistence.vector_store import InMemoryVectorStore@@ -93,10 +99,26 @@ async def _make_repo_context(class _MockRegistry:"""Minimal mock RepoRegistry for testing without real workspace files."""- def __init__(self, contexts: dict[str, RepoContext], default_alias: str):+ def __init__(+ self,+ contexts: dict[str, RepoContext],+ default_alias: str,+ workspace_root: Path,+ ):self._contexts = contextsself._default_alias = default_alias- self.workspace_root = __import__("pathlib").Path("/tmp/workspace")+ self.workspace_root = workspace_root+ self.ws_config = SimpleNamespace(+ repos=[+ SimpleNamespace(+ alias=alias,+ path=ctx.path.relative_to(self.workspace_root).as_posix(),+ indexed_at=None,+ last_commit_at_index=None,+ )+ for alias, ctx in contexts.items()+ ]+ )def get_all_aliases(self) -> list[str]:return list(self._contexts.keys())@@ -109,9 +131,15 @@ class _MockRegistry:return self._default_aliasif repo == "all":return self.get_all_aliases()- if repo not in self._contexts:- raise ValueError(f"Unknown repo '{repo}'. Available: {self.get_all_aliases()}")- return repo+ for entry in self.ws_config.repos:+ identities = {+ entry.alias,+ entry.path,+ (self.workspace_root / entry.path).resolve().as_posix(),+ }+ if repo in identities:+ return entry.alias+ raise ValueError(f"Unknown repo '{repo}'. Available: {self.get_all_aliases()}")async def get(self, alias: str) -> RepoContext:return self._contexts[alias]@@ -126,14 +154,33 @@ class _MockRegistry:@pytest.fixture-async def workspace_mcp():+async def workspace_mcp(tmp_path):"""Set up a two-repo workspace for MCP testing."""import repowise.server.mcp_server as mcp_mod+ workspace_root = tmp_path / "workspace"+ backend_root = workspace_root / "backend"+ frontend_root = workspace_root / "web-client"+ for root, name in (+ (backend_root, "backend_probe"),+ (frontend_root, "frontend_probe"),+ ):+ source = root / "src/probe.py"+ source.parent.mkdir(parents=True)+ source.write_text(f"def {name}():\n return {name!r}\n", encoding="utf-8")+ for args in (+ ["git", "init", "-q"],+ ["git", "config", "user.email", "[email protected]"],+ ["git", "config", "user.name", "Workspace Fixture"],+ ["git", "add", "."],+ ["git", "commit", "-qm", f"seed {name}"],+ ):+ subprocess.run(args, cwd=root, check=True, capture_output=True)+# Create two repo contexts with distinct databackend_ctx = await _make_repo_context("backend",- "/tmp/workspace/backend",+ str(backend_root),pages=[Page(id="repo_overview:backend",@@ -152,8 +199,71 @@ async def workspace_mcp():created_at=_NOW,updated_at=_NOW,),+ Page(+ id="file_page:src/probe.py",+ repository_id="repo-backend",+ page_type="file_page",+ title="Backend Probe",+ content="# Backend probe",+ target_path="src/probe.py",+ source_hash="probe-be",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=1.0,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),],extra_models=[+ WikiSymbol(+ id="symbol-backend-probe",+ repository_id="repo-backend",+ file_path="src/probe.py",+ symbol_id="src/probe.py::backend_probe",+ name="backend_probe",+ qualified_name="backend_probe",+ kind="function",+ signature="def backend_probe()",+ start_line=1,+ end_line=2,+ language="python",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ GraphNode(+ id="gn-be-probe",+ repository_id="repo-backend",+ node_id="src/probe.py",+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=True,+ pagerank=0.9,+ betweenness=0.1,+ community_id=1,+ created_at=_NOW,+ ),+ HealthFinding(+ id="hf-be-probe",+ repository_id="repo-backend",+ file_path="src/probe.py",+ biomarker_type="backend_probe_health",+ severity="low",+ function_name="backend_probe",+ reason="Backend fixture finding",+ health_impact=-0.1,+ status="open",+ ),+ GitMetadata(+ id="gm-be-probe",+ repository_id="repo-backend",+ file_path="src/probe.py",+ commit_count_total=2,+ churn_percentile=0.12,+ ),GraphNode(id="gn-be-1",repository_id="repo-backend",@@ -195,7 +305,7 @@ async def workspace_mcp():frontend_ctx = await _make_repo_context("frontend",- "/tmp/workspace/web-client",+ str(frontend_root),pages=[Page(id="repo_overview:frontend",@@ -214,8 +324,71 @@ async def workspace_mcp():created_at=_NOW,updated_at=_NOW,),+ Page(+ id="file_page:src/probe.py",+ repository_id="repo-frontend",+ page_type="file_page",+ title="Frontend Probe",+ content="# Frontend probe",+ target_path="src/probe.py",+ source_hash="probe-fe",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=1.0,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),],extra_models=[+ WikiSymbol(+ id="symbol-frontend-probe",+ repository_id="repo-frontend",+ file_path="src/probe.py",+ symbol_id="src/probe.py::frontend_probe",+ name="frontend_probe",+ qualified_name="frontend_probe",+ kind="function",+ signature="def frontend_probe()",+ start_line=1,+ end_line=2,+ language="python",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ GraphNode(+ id="gn-fe-probe",+ repository_id="repo-frontend",+ node_id="src/probe.py",+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=True,+ pagerank=0.9,+ betweenness=0.1,+ community_id=1,+ created_at=_NOW,+ ),+ HealthFinding(+ id="hf-fe-probe",+ repository_id="repo-frontend",+ file_path="src/probe.py",+ biomarker_type="frontend_probe_health",+ severity="low",+ function_name="frontend_probe",+ reason="Frontend fixture finding",+ health_impact=-0.1,+ status="open",+ ),+ GitMetadata(+ id="gm-fe-probe",+ repository_id="repo-frontend",+ file_path="src/probe.py",+ commit_count_total=9,+ churn_percentile=0.82,+ ),GraphNode(id="gn-fe-1",repository_id="repo-frontend",@@ -259,16 +432,17 @@ async def workspace_mcp():registry = _MockRegistry(contexts={"backend": backend_ctx, "frontend": frontend_ctx},default_alias="backend",+ workspace_root=workspace_root,)# Set workspace statemcp_mod._registry = registry- mcp_mod._workspace_root = "/tmp/workspace"+ mcp_mod._workspace_root = str(workspace_root)mcp_mod._session_factory = backend_ctx.session_factorymcp_mod._fts = backend_ctx.ftsmcp_mod._vector_store = backend_ctx.vector_storemcp_mod._decision_store = backend_ctx.decision_store- mcp_mod._repo_path = "/tmp/workspace/backend"+ mcp_mod._repo_path = str(backend_root)mcp_mod._vector_store_ready = backend_ctx.vector_store_readyyield registry@@ -665,16 +839,117 @@ async def test_overview_all_includes_cross_repo_topology(workspace_mcp_with_enri@pytest.mark.asyncioasync def test_list_repos_discovers_workspace_aliases(workspace_mcp):- from repowise.server.mcp_server import list_repos+ from repowise.server.mcp_server import (+ get_answer,+ get_change_risk,+ get_context,+ get_dead_code,+ get_health,+ get_overview,+ get_risk,+ get_symbol,+ get_why,+ list_repos,+ search_codebase,+ )result = await list_repos()assert result["workspace"] is True- assert result["workspace_root"] == "/tmp/workspace"+ assert result["workspace_root"] == workspace_mcp.workspace_root.as_posix()assert result["default_repo"] == "backend"assert [repo["alias"] for repo in result["repos"]] == ["backend", "frontend"]assert result["repos"][0]["is_default"] is True- assert "repo='<alias>'" in result["hint"]+ repository_targets = {+ "get_answer",+ "get_change_risk",+ "get_context",+ "get_dead_code",+ "get_health",+ "get_overview",+ "get_risk",+ "get_symbol",+ "get_why",+ "search_codebase",+ }+ repository_matrix = {+ ("list_repos", "repository", target): "PASS"+ for target in repository_targets+ }+ repository_matrix.update(+ {+ ("list_repos", kind, "N/A"): "N/A"+ for kind in {+ "file",+ "symbol",+ "decision/evidence",+ "omission/continuation",+ "finding",+ "refactoring plan",+ }+ }+ )+ assert len(repository_matrix) == 16+ for emitted in result["repos"]:+ for field in ("alias", "path", "absolute_path"):+ identity = emitted[field]+ probe = f"{emitted['alias']}_probe"+ symbol_id = f"src/probe.py::{probe}"+ answer = await get_answer(f"where is {probe} defined", repo=identity)+ assert probe in json.dumps(answer)+ change = await get_change_risk("HEAD", repo=identity, baseline=0)+ assert change.get("warning") is None+ assert change["score"] >= 0+ expected_head = subprocess.run(+ ["git", "rev-parse", "--short=12", "HEAD"],+ cwd=workspace_mcp.workspace_root / emitted["path"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ assert change["_meta"]["live_head"] == expected_head+ context = await get_context([symbol_id], repo=identity)+ assert context["targets"][symbol_id]["type"] == "symbol"+ assert context["targets"][symbol_id]["docs"]["name"] == probe++ overview = await get_overview(repo=identity)+ assert overview["title"] == f"{emitted['alias'].title()} Overview"+ health = await get_health(targets=["src/probe.py"], repo=identity)+ assert {+ finding["biomarker_type"]+ for finding in health["findings"]+ } == {f"{emitted['alias']}_probe_health"}+ risk = await get_risk(["src/probe.py"], repo=identity)+ assert risk["targets"]["src/probe.py"]["hotspot_score"] == (+ 0.12 if emitted["alias"] == "backend" else 0.82+ )+ symbol = await get_symbol(symbol_id, repo=identity)+ assert symbol["symbol_id"] == symbol_id+ assert probe in symbol["source"]+ why = await get_why(+ id=f"dec-{'be' if emitted['alias'] == 'backend' else 'fe'}-1",+ repo=identity,+ )+ assert why["resolved"] is True+ assert why["decisions"][0]["id"].startswith(+ f"dec-{'be' if emitted['alias'] == 'backend' else 'fe'}"+ )+ dead = await get_dead_code(repo=identity, min_confidence="low")+ files = {+ finding["file_path"]+ for tier in dead["tiers"].values()+ for finding in tier["findings"]+ }+ assert files == {+ "src/old_handler.py"+ if emitted["alias"] == "backend"+ else "src/legacy/utils.ts"+ }+ search = await search_codebase(+ probe, repo=identity, mode="symbol", limit=5+ )+ assert any(row.get("symbol_id") == symbol_id for row in search["results"])+ assert "alias, path, or absolute_path" in result["hint"]@pytest.mark.asynciodiff --git a/tests/unit/workspace/test_registry.py b/tests/unit/workspace/test_registry.pyindex 5a6d5c096..241c760e8 100644--- a/tests/unit/workspace/test_registry.py+++ b/tests/unit/workspace/test_registry.py@@ -114,6 +114,61 @@ class TestResolveRepoParam:registry = RepoRegistry(tmp_path, config)assert registry.resolve_repo_param("frontend") == "frontend"+ def test_list_repos_path_identities_round_trip(self, tmp_path: Path) -> None:+ config = _make_workspace(tmp_path, ["backend", "frontend"])+ registry = RepoRegistry(tmp_path, config)++ assert registry.resolve_repo_param("frontend") == "frontend"+ assert registry.resolve_repo_param("frontend/") == "frontend"+ assert registry.resolve_repo_param(str((tmp_path / "frontend").resolve())) == "frontend"++ def test_mixed_case_alias_keeps_emitted_identity(self, tmp_path: Path) -> None:+ config = _make_workspace(tmp_path, ["backend"])+ config.repos[0].alias = "BackendAPI"+ config.default_repo = "BackendAPI"+ registry = RepoRegistry(tmp_path, config)++ assert registry.resolve_repo_param("BackendAPI") == "BackendAPI"+ assert registry.resolve_repo_param("backendapi") == "BackendAPI"++ def test_cross_repo_identity_collision_is_rejected(self, tmp_path: Path) -> None:+ for name in ("services", "backend"):+ (tmp_path / name).mkdir()+ config = WorkspaceConfig(+ repos=[+ RepoEntry(path="services", alias="backend"),+ RepoEntry(path="backend", alias="api"),+ ]+ )++ with pytest.raises(ValueError, match="identities collide"):+ RepoRegistry(tmp_path, config)++ def test_alias_cannot_shadow_another_repo_path_by_case(+ self, tmp_path: Path+ ) -> None:+ config = WorkspaceConfig(+ repos=[+ RepoEntry(path="services/api", alias="foo"),+ RepoEntry(path="FOO", alias="service"),+ ]+ )++ with pytest.raises(ValueError, match="shadows path"):+ RepoRegistry(tmp_path, config)++ @pytest.mark.parametrize(+ ("path", "alias"),+ [("service", "all"), ("all", "service")],+ )+ def test_workspace_all_identity_is_reserved(+ self, tmp_path: Path, path: str, alias: str+ ) -> None:+ config = WorkspaceConfig(repos=[RepoEntry(path=path, alias=alias)])++ with pytest.raises(ValueError, match="reserved"):+ RepoRegistry(tmp_path, config)+def test_invalid_alias_raises(self, tmp_path: Path) -> None:config = _make_workspace(tmp_path, ["backend", "frontend"])registry = RepoRegistry(tmp_path, config)