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): Harden MCP tool surfaces, caching, and trust metadata (#1904)
Raghav Chamadiyac105068de68d
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex b11313243..54d03d8e2 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -6,7 +6,7 @@"url": "https://repowise.dev"},"metadata": {- "description": "The codebase intelligence layer for AI coding agents — graph, git, docs, decisions, and a defect-validated code-health score, exposed to Claude through eleven task-shaped MCP tools.",+ "description": "The codebase intelligence layer for AI coding agents — graph, git, docs, decisions, and a defect-validated code-health score, exposed to Claude through ten task-shaped MCP tools.","homepage": "https://repowise.dev"},"plugins": [diff --git a/README.md b/README.mdindex c15ef9cca..14ffe7120 100644--- a/README.md+++ b/README.md@@ -131,7 +131,8 @@ it written this way? Which files are actually dangerous?* Without an index, therediscovers that answer on every task: grep, read, re-read, forget.Repowise exposes **ten task-shaped MCP tools** to Claude Code, Codex, Cursor, VS Code-and anything else that speaks MCP. Most tools are built around data entities (one+and anything else that speaks MCP: graph, git, docs, decisions, and ten MCP tools+behind one index. See [the canonical surface](#the-ten-mcp-tools). Most tools are built around data entities (onefile, one symbol), which forces agents into long chains of sequential calls. These arebuilt around **tasks**: pass several targets in one call, get complete context back.diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.mdindex 17db61e82..aa24d513c 100644--- a/docs/agent/INTEGRATIONS.md+++ b/docs/agent/INTEGRATIONS.md@@ -73,11 +73,11 @@ name for a host at this tier, which is the point of the tier.## The MCP surface-repowise registers **seventeen MCP tools**. A single-repo server advertises-**eleven** of them by default, and workspace mode adds two more automatically for-**thirteen**. A further **four** are off by default, enabled through the `mcp.tools`-config block or `--tools +name`. The `lean` profile trims the default surface to-**six** tools (seven in workspace mode) for agents on a tight context budget.+repowise registers **seventeen MCP tools**. A single-repo server advertises **ten**+of them by default, and workspace mode adds one more automatically for **eleven**. A+further **six** are off by default, enabled through the `mcp.tools` config block or+`--tools +name`. The `lean` profile trims the default surface to **six** tools+(seven in workspace mode) for agents on a tight context budget.Per-tool detail: [MCP_TOOLS.md](MCP_TOOLS.md).diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 9812125ef..c4dc01eb3 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -2,7 +2,7 @@repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence: dependency graph, git history, documentation, and architectural decisions.-17 tools are registered in total. A single-repo server advertises 11 by default: the ten flagship tools below plus `list_repos`. Workspace mode adds 2 more automatically (`get_architecture`, `get_blast_radius`), for 13. Four further tools are off by default everywhere and must be opted in. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).+17 tools are registered in total. A single-repo server advertises 10 by default: exactly the canonical tools. Workspace mode adds the `list_repos` discovery utility, for 11. 6 specialist tools are opt-in where eligible. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).**Start the MCP server:**@@ -20,7 +20,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport## Contents-**Default tools (single-repo, 11)**+**Canonical tools (default in both modes, 10)**[get_overview](#get_overview) ·[get_answer](#get_answer) ·[get_context](#get_context) ·@@ -30,14 +30,14 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport[get_change_risk](#get_change_risk) ·[get_why](#get_why) ·[get_dead_code](#get_dead_code) ·-[get_health](#get_health) ·+[get_health](#get_health)++**Workspace discovery utility (default in workspace mode, 1)**[list_repos](#list_repos)-**Workspace-only tools (added automatically, 2)**+**Opt-in specialists (6; workspace eligibility still applies)**[get_architecture](#get_architecture) ·-[get_blast_radius](#get_blast_radius)--**Opt-in tools (off by default everywhere, 4)**+[get_blast_radius](#get_blast_radius) ·[get_dependency_path](#get_dependency_path) ·[get_execution_flows](#get_execution_flows) ·[generate_refactoring_code](#generate_refactoring_code) ·@@ -62,7 +62,7 @@ Also see [Configuring the tool surface](#configuring-the-tool-surface), [Reversi| `get_dead_code` | Unreachable code | Cleanup tasks || `get_health` | Code-health marker scores | Before refactoring, find the worst files |-Also always on by default: `list_repos` (repo aliases). See [Supplementary tools](#supplementary-tools).+In workspace mode, `list_repos` is also on by default so repository aliases are discoverable. It is unavailable in single-repo mode because the server is already bound to the only repository. See [Supplementary tools](#supplementary-tools).---@@ -70,9 +70,9 @@ Also always on by default: `list_repos` (repo aliases). See [Supplementary toolsThe default surface is deliberately small: fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's `default`/`requires_workspace` metadata, whether the server is in workspace mode, and an optional override.-- **Default (single-repo):** 11 tools, the ten flagship tools plus `list_repos`.-- **Default (workspace):** those 11 plus `get_architecture` and `get_blast_radius`, added automatically when the server starts inside a workspace. They are never advertised outside one.-- **Opt-in tools:** `get_dependency_path`, `get_execution_flows`, `generate_refactoring_code`, and `get_conformance` are registered but off by default. Turn them on per repo; `get_conformance` only does useful work in workspace mode (name it there).+- **Default (single-repo):** 10 tools, exactly the canonical intelligence set.+- **Default (workspace):** those 10 plus `list_repos`, the workspace discovery utility.+- **Opt-in tools:** `get_dependency_path`, `get_execution_flows`, and `generate_refactoring_code` are eligible in either mode. `get_architecture`, `get_blast_radius`, and `get_conformance` are workspace-only. All six are off by default.**Configure it in `.repowise/config.yaml`** under an `mcp.tools` key. Four shapes are supported:diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 226fcd4aa..2dadddf6b 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -1081,13 +1081,13 @@ and supports two transports:- **stdio**: for Claude Code, Cursor, Cline (add to their MCP config)- **SSE**: for web-based MCP clients (served on port 7338)-### Tools (11 default in single-repo mode)+### Tools (10 default in single-repo mode)Canonical reference: [`docs/agent/MCP_TOOLS.md`](../agent/MCP_TOOLS.md).-A single-repo server advertises **11** tools by default (ten flagship +-`list_repos`). Workspace mode adds `get_architecture` and `get_blast_radius`.-Four more are registered but opt-in (`get_dependency_path`,-`get_execution_flows`, `generate_refactoring_code`, `get_conformance`).+A single-repo server advertises **10** tools by default (the canonical set).+Workspace mode adds `list_repos`. Six specialists are registered but opt-in:+`get_architecture`, `get_blast_radius`, `get_dependency_path`,+`get_execution_flows`, `generate_refactoring_code`, and `get_conformance`.| Tool | What it answers | When to call ||------|----------------|-------------|diff --git a/docs/architecture/pluggable-storage.md b/docs/architecture/pluggable-storage.mdindex 05bca78ff..ed3c2f321 100644--- a/docs/architecture/pluggable-storage.md+++ b/docs/architecture/pluggable-storage.md@@ -216,7 +216,7 @@ broken plugin cannot derail the pipeline.The seams add a layer of indirection but no behavior change for usersof the OSS defaults: `repowise init` still writes to`.repowise/wiki.db`, the in-process graph still owns ingestion, the-eleven MCP tools still expose the same surface, and `repowise --help`+ten MCP tools still expose the same surface, and `repowise --help`lists the same commands in the same order. Plugins extend thedefaults; they don't replace them unless an integration explicitlyswaps an implementation in.diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.mdindex 2f32c2c21..12bc0fcc1 100644--- a/docs/start/USER_GUIDE.md+++ b/docs/start/USER_GUIDE.md@@ -216,7 +216,7 @@ for Codex, `repowise init --codex` writes project-local config. Setup per clientis in [Quickstart](QUICKSTART.md#3-connect-your-agent), and[Codex](../agent/CODEX.md) / [opencode](../agent/OPENCODE.md) have their own guides.-**Eleven tools, task-shaped.** Your agent gets architecture summaries, per-file+**Ten tools, task-shaped.** Your agent gets architecture summaries, per-filetriage cards with callers and ownership, symbol source with exact bounds, riskassessment for a set of changed files, decision lookups and health scores, each inone call rather than a chain. What each one answers, and worked multi-tooldiff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.pyindex d14de36a2..cef04b21e 100644--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py@@ -119,7 +119,7 @@ def _print_network_startup("all_tools",is_flag=True,default=False,- help="Expose every available tool, including opt-in and workspace tools.",+ help="Expose every tool eligible in the current repository/workspace mode.",)def mcp_command(path: str | None,@@ -132,8 +132,8 @@ def mcp_command("""Start the MCP server for editor integration.Exposes a curated set of tools for querying the repowise wiki via the MCP- protocol: eleven by default in single-repo mode, plus two more by default- in workspace mode. Four more are opt-in via ``--tools`` or the+ protocol: ten by default in single-repo mode, plus one more by default+ in workspace mode. Six more are opt-in via ``--tools`` or the``mcp.tools`` config block. Supports stdio(for Claude Code, Codex, Cursor), streamable HTTP, and legacy SSEtransports.diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.pyindex 7d986a00e..aa95a9758 100644--- a/packages/core/src/repowise/core/analysis/security_scan.py+++ b/packages/core/src/repowise/core/analysis/security_scan.py@@ -18,6 +18,7 @@ constraint (migration 0041) makes re-runs idempotent.from __future__ import annotations+import astimport loggingimport refrom datetime import UTC, datetime@@ -31,16 +32,29 @@ logger = logging.getLogger(__name__)# ---------------------------------------------------------------------------# Pattern registry: (compiled_pattern, kind_label, severity)# ---------------------------------------------------------------------------+_CALL_PATTERNS: list[tuple[re.Pattern, str, str]] = [+ (+ re.compile(r"(?<![\w$])(?:[A-Za-z_$][\w$]*\s*\.\s*)*eval\s*\("),+ "eval_call",+ "high",+ ),+ (+ re.compile(r"(?<![\w$])(?:[A-Za-z_$][\w$]*\s*\.\s*)*exec\s*\("),+ "exec_call",+ "high",+ ),+]+_CALL_KINDS = frozenset(kind for _, kind, _ in _CALL_PATTERNS)+_PATTERNS: list[tuple[re.Pattern, str, str]] = [- (re.compile(r"eval\s*\("), "eval_call", "high"),- (re.compile(r"exec\s*\("), "exec_call", "high"),+ *_CALL_PATTERNS,(re.compile(r"pickle\.loads"), "pickle_loads", "high"),(re.compile(r"subprocess\..*shell\s*=\s*True"), "subprocess_shell_true", "high"),(re.compile(r"os\.system"), "os_system", "high"),(re.compile(r"password\s*=\s*['\"]"), "hardcoded_password", "high"),(re.compile(r"(?:api_?key|secret)\s*=\s*['\"]"), "hardcoded_secret", "high"),(re.compile(r'f[\'"].*SELECT.*\{.*\}'), "fstring_sql", "med"),- (re.compile(r'\.execute\(\s*[\'\"]\s*SELECT.*\+'), "concat_sql", "med"),+ (re.compile(r"\.execute\(\s*[\'\"]\s*SELECT.*\+"), "concat_sql", "med"),(re.compile(r"verify\s*=\s*False"), "tls_verify_false", "med"),(re.compile(r"\bmd5\b|\bsha1\b"), "weak_hash", "low"),]@@ -61,18 +75,14 @@ _ANY_PATTERN = re.compile("|".join(f"(?:{p.pattern})" for p, _, _ in _PATTERNS))# on a column-0 line. The span is also capped (~200 chars) as a second bound._SPANNING_PATTERNS: list[tuple[re.Pattern, str, str]] = [(- re.compile(- r"subprocess\.[A-Za-z]+\((?:[^\n]|\n(?=[ \t])){0,200}?shell\s*=\s*True"- ),+ re.compile(r"subprocess\.[A-Za-z]+\((?:[^\n]|\n(?=[ \t])){0,200}?shell\s*=\s*True"),"subprocess_shell_true","high",),]# Symbol names that are informational security hotspots-_SYMBOL_KEYWORDS = re.compile(- r"\b(auth|token|password|jwt|session|crypto)\b", re.IGNORECASE-)+_SYMBOL_KEYWORDS = re.compile(r"\b(auth|token|password|jwt|session|crypto)\b", re.IGNORECASE)# Patterns whose matches are genuine leaked credentials (as opposed to the# broader "code smell" patterns like os.system/eval). Full-history scans@@ -90,6 +100,153 @@ SECRET_KINDS: frozenset[str] = frozenset({"hardcoded_password", "hardcoded_secreSYMBOL_NAME_KINDS: frozenset[str] = frozenset({"security_sensitive_symbol"})+def _mask_comments_and_strings(source: str) -> str:+ """Blank common comments/strings while preserving offsets and newlines."""+ chars = list(source)+ i = 0+ state = "code"+ quote = ""+ triple = False+ template_depth = 0+ while i < len(source):+ if state == "line_comment":+ if source[i] == "\n":+ state = "code"+ else:+ chars[i] = " "+ i += 1+ continue+ if state == "block_comment":+ if source.startswith("*/", i):+ chars[i : i + 2] = [" ", " "]+ i += 2+ state = "code"+ else:+ if source[i] != "\n":+ chars[i] = " "+ i += 1+ continue+ if state == "string":+ marker = quote * (3 if triple else 1)+ if source.startswith(marker, i):+ chars[i : i + len(marker)] = [" "] * len(marker)+ i += len(marker)+ state = "code"+ elif source[i] == "\\":+ chars[i] = " "+ if i + 1 < len(source):+ if source[i + 1] != "\n":+ chars[i + 1] = " "+ i += 2+ else:+ i += 1+ else:+ if source[i] != "\n":+ chars[i] = " "+ i += 1+ continue+ if state == "template":+ if source.startswith("${", i):+ chars[i : i + 2] = [" ", " "]+ i += 2+ template_depth = 1+ state = "code"+ elif source[i] == "`":+ chars[i] = " "+ i += 1+ state = "code"+ elif source[i] == "\\":+ chars[i] = " "+ if i + 1 < len(source):+ if source[i + 1] != "\n":+ chars[i + 1] = " "+ i += 2+ else:+ i += 1+ else:+ if source[i] != "\n":+ chars[i] = " "+ i += 1+ continue++ if template_depth and source[i] == "{":+ template_depth += 1+ i += 1+ elif template_depth and source[i] == "}":+ chars[i] = " "+ template_depth -= 1+ i += 1+ if template_depth == 0:+ state = "template"+ elif source.startswith("//", i) or source[i] == "#":+ width = 2 if source.startswith("//", i) else 1+ chars[i : i + width] = [" "] * width+ i += width+ state = "line_comment"+ elif source.startswith("/*", i):+ chars[i : i + 2] = [" ", " "]+ i += 2+ state = "block_comment"+ elif source[i] == "`":+ chars[i] = " "+ i += 1+ state = "template"+ elif source[i] in {"'", '"'}:+ quote = source[i]+ triple = source.startswith(quote * 3, i)+ width = 3 if triple else 1+ chars[i : i + width] = [" "] * width+ i += width+ state = "string"+ else:+ i += 1+ return "".join(chars)+++def _call_findings(file_path: str, source: str) -> list[dict]:+ """Find executable eval/exec calls with AST or bounded lexical fallback."""+ if file_path.lower().endswith((".py", ".pyi")):+ try:+ tree = ast.parse(source)+ except SyntaxError:+ pass+ else:+ findings = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ if isinstance(node.func, ast.Name):+ call_name = node.func.id+ elif isinstance(node.func, ast.Attribute):+ call_name = node.func.attr+ else:+ continue+ if call_name not in {"eval", "exec"}:+ continue+ line = source.splitlines()[node.lineno - 1].strip()[:120]+ findings.append(+ {+ "kind": f"{call_name}_call",+ "severity": "high",+ "snippet": line,+ "line": node.lineno,+ }+ )+ return findings++ masked = _mask_comments_and_strings(source)+ lines = source.splitlines()+ findings = []+ for pattern, kind, severity in _CALL_PATTERNS:+ for match in pattern.finditer(masked):+ lineno = source.count("\n", 0, match.start()) + 1+ snippet = lines[lineno - 1].strip()[:120] if lineno <= len(lines) else ""+ findings.append(+ {"kind": kind, "severity": severity, "snippet": snippet, "line": lineno}+ )+ return findings++def _is_missing_table_error(exc: Exception) -> bool:"""True when *exc* is a 'no such table' / 'does not exist' failure.@@ -128,11 +285,15 @@ class SecurityScanner:findings: list[dict] = []lines = source.splitlines()+ findings.extend(_call_findings(file_path, source))+# Line-by-line pattern scanfor lineno, line in enumerate(lines, start=1):if not _ANY_PATTERN.search(line):continuefor pattern, kind, severity in _PATTERNS:+ if kind in _CALL_KINDS:+ continueif pattern.search(line):# Trim snippet to keep it concisesnippet = line.strip()[:120]@@ -231,10 +392,7 @@ class SecurityScanner:conflict_suffix = ""else:insert_prefix = "INSERT INTO security_findings "- conflict_suffix = (- " ON CONFLICT ON CONSTRAINT uq_security_finding_provenance "- "DO NOTHING"- )+ conflict_suffix = " ON CONFLICT ON CONSTRAINT uq_security_finding_provenance DO NOTHING"inserted = 0for finding in findings:@@ -245,8 +403,7 @@ class SecurityScanner:+ "(repository_id, file_path, kind, severity, snippet, line_number, ""commit_sha, commit_at, detected_at) ""VALUES (:repo_id, :file_path, :kind, :severity, :snippet, :line, "- ":commit_sha, :commit_at, :detected_at)"- + conflict_suffix+ ":commit_sha, :commit_at, :detected_at)" + conflict_suffix),{"repo_id": self._repo_id,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex c3fe89707..af0ef87e6 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1402,8 +1402,8 @@ class TestCoverageEntry(Base):class AnswerCache(Base):"""Cached LLM-synthesized answers from get_answer.- Keyed by (repo_id, question_hash). The hash is computed from the- normalized question text only — answer cache invalidation on index+ Keyed by (repo_id, question_hash). The hash is a versioned digest of the+ normalized question and normalized scope. Answer cache invalidation on indexchange is handled by deleting rows for a repository when its alembichead advances (cheap to rebuild).@@ -1417,7 +1417,7 @@ class AnswerCache(Base):repository_id: Mapped[str] = mapped_column(String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False)- # SHA-256 hex of the normalized (lowercased + stripped) question.+ # SHA-256 hex of the versioned normalized question + scope identity.question_hash: Mapped[str] = mapped_column(String(64), nullable=False)# Original (un-normalized) question, kept for human inspection.question: Mapped[str] = mapped_column(Text, nullable=False)diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.pyindex 27db7d3a3..5d77f4b48 100644--- a/packages/core/src/repowise/core/registry/__init__.py+++ b/packages/core/src/repowise/core/registry/__init__.py@@ -25,7 +25,7 @@ from .cli_registry import (register_command,register_lazy_command,)-from .mcp_tool_registry import MCPToolRegistry, ToolEntry, mcp_tool_registry+from .mcp_tool_registry import TOOL_TIERS, MCPToolRegistry, ToolEntry, mcp_tool_registryfrom .pipeline_hooks import (HookPhase,HookProgressCallback,@@ -35,6 +35,7 @@ from .pipeline_hooks import ()__all__ = [+ "TOOL_TIERS","CLIRegistry","HookPhase","HookProgressCallback",diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.pyindex 369376f58..9690b16e8 100644--- a/packages/core/src/repowise/core/registry/mcp_tool_registry.py+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py@@ -35,6 +35,8 @@ from collections.abc import Callablefrom dataclasses import dataclassfrom typing import Any+TOOL_TIERS = frozenset({"canonical", "utility", "specialist"})+@dataclass(frozen=True)class ToolEntry:@@ -51,6 +53,9 @@ class ToolEntry:name: strdefault: bool = Truerequires_workspace: bool = False+ tier: str = "canonical"+ surface_order: int = 1000+ trust_kind: str | None = Noneclass MCPToolRegistry:@@ -65,6 +70,9 @@ class MCPToolRegistry:*args: Any,default: bool = True,requires_workspace: bool = False,+ tier: str | None = None,+ surface_order: int = 1000,+ trust_kind: str | None = None,**kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]] | Callable[..., Any]:"""Decorator that schedules a function for FastMCP registration.@@ -77,14 +85,35 @@ class MCPToolRegistry:"""def _add(fn: Callable[..., Any]) -> Callable[..., Any]:+ # Preserve the pre-tier extension API: a default workspace-only+ # tool was valid before tiers existed and is a utility by nature.+ resolved_tier = tier or (+ "utility"+ if default and requires_workspace+ else "canonical"+ if default+ else "specialist"+ )+ if resolved_tier not in TOOL_TIERS:+ raise ValueError(+ f"unknown MCP tool tier {resolved_tier!r}; expected one of {sorted(TOOL_TIERS)}"+ )+ if resolved_tier == "canonical" and (not default or requires_workspace):+ raise ValueError("canonical MCP tools must be default and single-repo eligible")+ if resolved_tier == "specialist" and default:+ raise ValueError("specialist MCP tools must be opt-in (default=False)")self._entries.append(ToolEntry(fn=fn,name=fn.__name__,default=default,requires_workspace=requires_workspace,+ tier=resolved_tier,+ surface_order=surface_order,+ trust_kind=trust_kind,))+ fn.__dict__["__repowise_trust_kind__"] = trust_kindreturn fn# Bare-decorator form: @mcp_tool_registry.register@@ -143,4 +172,4 @@ mcp_tool_registry = MCPToolRegistry()"""Process-wide default registry used by the OSS MCP server."""-__all__ = ["MCPToolRegistry", "ToolEntry", "mcp_tool_registry"]+__all__ = ["TOOL_TIERS", "MCPToolRegistry", "ToolEntry", "mcp_tool_registry"]diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.pyindex 0b883a5c5..7f18ea1a4 100644--- a/packages/core/src/repowise/core/workspace/system_graph.py+++ b/packages/core/src/repowise/core/workspace/system_graph.py@@ -201,16 +201,18 @@ class SystemEdge:class SystemGraph:"""The versioned cross-repo structure: nodes, typed edges, diagnostics."""- version: int = 1+ version: int = 2generated_at: str = ""nodes: list[SystemNode] = field(default_factory=list)edges: list[SystemEdge] = field(default_factory=list)diagnostics: ExtractionDiagnostics = field(default_factory=ExtractionDiagnostics)+ repo_provenance: dict[str, dict[str, str]] = field(default_factory=dict)def to_dict(self) -> dict[str, Any]:return {"version": self.version,"generated_at": self.generated_at,+ "repo_provenance": self.repo_provenance,"nodes": [n.to_dict() for n in self.nodes],"edges": [e.to_dict() for e in self.edges],"diagnostics": self.diagnostics.to_dict(),@@ -221,6 +223,7 @@ class SystemGraph:return cls(version=data.get("version", 1),generated_at=data.get("generated_at", ""),+ repo_provenance=data.get("repo_provenance", {}),nodes=[SystemNode.from_dict(n) for n in data.get("nodes", [])],edges=[SystemEdge.from_dict(e) for e in data.get("edges", [])],diagnostics=ExtractionDiagnostics.from_dict(data.get("diagnostics", {})),@@ -360,8 +363,9 @@ def build_system_graph(boundaries_by_repo: dict[str, list[ServiceBoundary]],diagnostics: ExtractionDiagnostics | None = None,*,- version: int = 1,+ version: int = 2,generated_at: str = "",+ repo_provenance: dict[str, dict[str, str]] | None = None,) -> SystemGraph:"""Assemble the service-granular system graph (pure, no I/O).@@ -421,6 +425,7 @@ def build_system_graph(return SystemGraph(version=version,generated_at=generated_at,+ repo_provenance=repo_provenance or {},nodes=nodes,edges=edges,diagnostics=diagnostics,@@ -438,9 +443,7 @@ def save_system_graph(graph: SystemGraph, workspace_root: Path) -> Path:out_path = data_dir / SYSTEM_GRAPH_FILENAME# Atomic: the MCP enricher reads these artifacts from a separate# process and must never observe a half-written file.- atomic_write_text(- out_path, json.dumps(graph.to_dict(), indent=2, ensure_ascii=False)- )+ atomic_write_text(out_path, json.dumps(graph.to_dict(), indent=2, ensure_ascii=False))return out_path@@ -495,9 +498,7 @@ async def run_system_graph_build(_detect_boundaries_by_repo, ws_config, workspace_root)- diagnostics = build_diagnostics(- store.contracts, store.contract_links, store.extraction_stats- )+ diagnostics = build_diagnostics(store.contracts, store.contract_links, store.extraction_stats)graph = build_system_graph(store.contracts,store.contract_links,@@ -505,6 +506,7 @@ async def run_system_graph_build(boundaries_by_repo,diagnostics,generated_at=datetime.now(UTC).isoformat(),+ repo_provenance=store.repo_provenance,)out_path = save_system_graph(graph, workspace_root)diff --git a/packages/server/README.md b/packages/server/README.mdindex 6c05de87e..8a778847d 100644--- a/packages/server/README.md+++ b/packages/server/README.md@@ -11,7 +11,7 @@ FastAPI REST API, webhook handlers, MCP server, and background job scheduler for| Component | Description ||-----------|-------------|| **REST API** | FastAPI application with full CRUD for repos, pages (with version history), symbols, jobs, git analytics, dead code, decisions, graph intelligence, blast radius, costs, knowledge map, security findings, providers, chat, CLAUDE.md generation, and multi-repo workspace |-| **MCP Server** | 17 registered MCP tools (11 advertised by default in single-repo mode: ten flagship + `list_repos`) for AI coding assistants (Claude Code, Cursor, Cline) |+| **MCP Server** | 17 registered MCP tools (10 advertised by default in single-repo mode: the canonical set) for AI coding assistants (Claude Code, Cursor, Cline) || **Webhooks** | GitHub and GitLab push event handlers — trigger sync jobs automatically on push || **Scheduler** | APScheduler background jobs — polling fallback (auto-syncs diverged repos), stale page detection |@@ -232,9 +232,10 @@ Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently b## MCP Server-repowise registers 17 MCP tools and advertises **11 by default** in single-repo-mode (the ten flagship tools plus `list_repos`). Workspace mode adds two more;-four further tools are opt-in. See [`docs/agent/MCP_TOOLS.md`](../../docs/agent/MCP_TOOLS.md).+repowise registers 17 MCP tools and advertises **10 by default** in single-repo+mode (10 advertised by default, exactly the canonical set). Workspace mode adds+`list_repos`; six specialist tools are opt-in where eligible. See+[`docs/agent/MCP_TOOLS.md`](../../docs/agent/MCP_TOOLS.md).Start the MCP server via:```bashdiff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 995614d7e..f8bc05f89 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -1,13 +1,12 @@"""repowise MCP Server — a curated, configurable tool surface for AI agents.-By default a single-repo server exposes eleven tools (get_answer, get_context,+By default a single-repo server exposes ten tools (get_answer, get_context,get_symbol, search_codebase, get_overview, get_risk, get_change_risk, get_why,-get_dead_code, get_health, list_repos); two more (get_blast_radius, get_architecture) are added-automatically in workspace mode. Four further tools (get_dependency_path,-get_execution_flows, generate_refactoring_code, get_conformance) are registered-but off by default and can be opted in via the ``mcp.tools`` config block or the-``repowise mcp --tools`` flag; get_conformance only does useful work in workspace-mode. The selection layer lives in :mod:`._tool_selection`.+get_dead_code, get_health). Workspace mode also exposes the ``list_repos``+discovery utility by default. Six specialist tools are registered but off by+default and can be opted in via the ``mcp.tools`` config block or the+``repowise mcp --tools`` flag; architecture, blast radius, and conformance are+workspace-only. The selection layer lives in :mod:`._tool_selection`.Exposes the full repowise wiki as queryable tools via the MCP protocol.Supports stdio transport (Claude Code, Cursor, Cline), streamable HTTP, and@@ -104,11 +103,25 @@ def tool_middleware(fn: Any) -> Any:the real composition; ``tests/unit/server/mcp/test_number_precision.py``relies on that to prove no raw double reaches an agent."""+ from functools import wraps+from repowise.server.mcp_server._failure_shield import shield+ from repowise.server.mcp_server._meta import finalize_trust_envelopefrom repowise.server.mcp_server._rounding import quantizefrom repowise.server.mcp_server._savings import instrument- return instrument(quantize(shield(fn)))+ evidence_kind = getattr(fn, "__repowise_trust_kind__", None)++ def trust(inner: Any) -> Any:+ @wraps(inner)+ async def wrapped(*args: Any, **kwargs: Any) -> Any:+ return finalize_trust_envelope(+ await inner(*args, **kwargs), evidence_kind=evidence_kind+ )++ return wrapped++ return instrument(quantize(trust(shield(fn))))def ensure_full_surface() -> Any:@@ -188,9 +201,7 @@ def __getattr__(name: str) -> Any:# has to exist by the time it is handed over.value: Any = ensure_full_surface()elif name in _TOOL_MODULES:- value = getattr(- importlib.import_module(f"{__name__}.{_TOOL_MODULES[name]}"), name- )+ value = getattr(importlib.import_module(f"{__name__}.{_TOOL_MODULES[name]}"), name)elif name in _LAZY_ATTRS:module_name, attr = _LAZY_ATTRS[name]value = getattr(importlib.import_module(f"{__name__}.{module_name}"), attr)diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.pyindex c943cbc4c..9ac0c7eb3 100644--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py@@ -402,7 +402,9 @@ class CrossRepoEnricher:conformance_violations=violations,generated_at=self._system_graph.get("generated_at", ""),)- return metrics.to_dict()+ payload = metrics.to_dict()+ payload["repo_provenance"] = self._system_graph.get("repo_provenance", {})+ return payloaddef get_diagnostics(self) -> dict | None:"""Return just the extraction diagnostics block of the system graph."""diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex d627e16de..07b0d36b2 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -22,6 +22,8 @@ from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any+MCP_CONTRACT_VERSION = 1+# Only warn about age when we have no other signal AND the index is genuinely# old. A short threshold here would nag on every call and train the agent to# ignore the field — defeating the point. 90 days is a deliberate floor: by@@ -223,7 +225,7 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None* ``indexed_commit`` — short SHA the index was built againstConditionally emitted:- * ``live_head`` — only when it differs from the indexed commit+ * ``live_head`` — current checkout commit whenever readable* ``stale_warning`` — only on a real signal (a served target changed,HEAD mismatch with real file changes on a repo-level response, OR veryold with no git)@@ -241,7 +243,7 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None"""if repository is None:return {}- out: dict[str, Any] = {}+ out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION}updated_at = getattr(repository, "updated_at", None)age_days: int | None = None@@ -260,10 +262,11 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = Noneout["indexed_commit"] = indexed_full[:12] if isinstance(indexed_full, str) else indexed_fulllive_full = read_live_head(local_path)+ if live_full:+ out["live_head"] = live_full[:12]if live_full and indexed_full:if live_full != indexed_full:- out["live_head"] = live_full[:12]# HEAD moved, so the index *is* behind, true regardless of which# sub-branch below fires. Emitted unconditionally here (rather than# only on the quiet branches) so consumers can compute a rate:@@ -335,7 +338,7 @@ def build_meta(...extras}"""- out: dict[str, Any] = {}+ out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION}if timing_ms is not None:out["timing_ms"] = round(float(timing_ms), 2)if hint:@@ -350,6 +353,58 @@ def build_meta(return out+def persisted_analysis_meta(+ timestamp: str | None,+ commits: dict[str, str] | None = None,+) -> dict[str, Any]:+ """Trust metadata for a persisted analysis artifact, omitting unknowns."""+ out: dict[str, Any] = {}+ if timestamp:+ out["analysis_timestamp"] = timestamp+ if commits:+ out["analysis_commits"] = commits+ return out+++def finalize_trust_envelope(result: Any, *, evidence_kind: str | None = None) -> Any:+ """Apply the transport-level trust contract to a tool result."""+ if not isinstance(result, dict):+ return result+ raw_meta = result.get("_meta")+ meta = raw_meta if isinstance(raw_meta, dict) else {}+ result["_meta"] = meta+ meta.setdefault("contract_version", MCP_CONTRACT_VERSION)+ if evidence_kind:+ meta.setdefault("evidence_kind", evidence_kind)+ if evidence_kind == "structural":+ meta.setdefault("runtime_breakage_proven", False)+ elif evidence_kind == "generated":+ meta.setdefault("existing_verified_code", False)++ state: dict[str, bool] = {}+ combined = {**result, **meta}+ if any(+ value and (key == "degraded" or key.endswith("_degraded"))+ for key, value in combined.items()+ ):+ state["degraded"] = True+ if any(+ value and (key == "partial" or key.endswith("_partial")) for key, value in combined.items()+ ):+ state["partial"] = True+ if any(+ value and (key == "truncated" or "truncated" in key or key == "omitted")+ for key, value in combined.items()+ ):+ state["truncated"] = True+ if state:+ existing = meta.get("state")+ if isinstance(existing, dict):+ state = {**existing, **state}+ meta["state"] = state+ return result++def _embedder_meta() -> dict[str, Any]:"""Surface embedder degradation (issue #306) in the `_meta` envelope.diff --git a/packages/server/src/repowise/server/mcp_server/_tool_selection.py b/packages/server/src/repowise/server/mcp_server/_tool_selection.pyindex 5fbe52b43..ee568b5a2 100644--- a/packages/server/src/repowise/server/mcp_server/_tool_selection.py+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py@@ -56,6 +56,7 @@ _LEAN_WORKSPACE_EXTRAS = frozenset({"list_repos"})# re-add a tool a previous call removed (the FastMCP manager only supports# removal, not re-registration)._full_surface: dict[str, Any] | None = None+_selected_surface: tuple[bool, frozenset[str]] | None = Nonedef _ensure_registered() -> None:@@ -148,9 +149,7 @@ def resolve_enabled_tools(_log.warning("Ignoring unknown MCP tool in selection: %r", raw)return Noneif not usable(entry):- _log.warning(- "Ignoring workspace-only MCP tool %r outside workspace mode", raw- )+ _log.warning("Ignoring workspace-only MCP tool %r outside workspace mode", raw)return Nonereturn raw@@ -216,11 +215,14 @@ def apply_tool_selection(if override is None:override = _read_config_override(repo_path)+ is_workspace = _is_workspace(repo_path)enabled = resolve_enabled_tools(mcp_tool_registry.entries(),- is_workspace=_is_workspace(repo_path),+ is_workspace=is_workspace,override=override,)+ global _selected_surface+ _selected_surface = (is_workspace, frozenset(enabled))manager = getattr(mcp, "_tool_manager", None)registered = getattr(manager, "_tools", None)@@ -247,6 +249,14 @@ def apply_tool_selection(return enabled+def selected_tool_names(*, is_workspace: bool) -> set[str]:+ """Return the surface selected for this running server, or its default."""+ _ensure_registered()+ if _selected_surface is not None and _selected_surface[0] == is_workspace:+ return set(_selected_surface[1])+ return resolve_enabled_tools(mcp_tool_registry.entries(), is_workspace=is_workspace)++def _tool_description(name: str) -> str:"""One-line description for a tool, from its registered FastMCP schema."""tool = (_full_surface or {}).get(name)@@ -254,6 +264,27 @@ def _tool_description(name: str) -> str:return desc.strip().split("\n", 1)[0].strip()+def registry_tool_rows(entries: Iterable[ToolEntry] | None = None) -> list[dict[str, Any]]:+ """Mode-independent tool catalog derived only from registry metadata."""+ _ensure_registered()+ catalog = list(entries) if entries is not None else mcp_tool_registry.entries()+ single_default = resolve_enabled_tools(catalog, is_workspace=False)+ workspace_default = resolve_enabled_tools(catalog, is_workspace=True)+ return [+ {+ "name": entry.name,+ "description": _tool_description(entry.name),+ "tier": entry.tier,+ "default_single_repo": entry.name in single_default,+ "default_workspace": entry.name in workspace_default,+ "eligible_single_repo": not entry.requires_workspace,+ "eligible_workspace": True,+ "requires_workspace": entry.requires_workspace,+ }+ for entry in sorted(catalog, key=lambda item: (item.surface_order, item.name))+ ]++def describe_tool_surface(repo_path: str | None) -> dict[str, Any]:"""Describe the configurable tool surface for a repo (for the settings UI).@@ -269,22 +300,18 @@ def describe_tool_surface(repo_path: str | None) -> dict[str, Any]:is_workspace = _is_workspace(repo_path)override = _read_config_override(repo_path)- default_surface = resolve_enabled_tools(- entries, is_workspace=is_workspace, override=None- )- enabled = resolve_enabled_tools(- entries, is_workspace=is_workspace, override=override- )+ default_surface = resolve_enabled_tools(entries, is_workspace=is_workspace, override=None)+ enabled = resolve_enabled_tools(entries, is_workspace=is_workspace, override=override)+ rows = registry_tool_rows(entries)tools = [{- "name": e.name,- "description": _tool_description(e.name),- "default": e.name in default_surface,- "requires_workspace": e.requires_workspace,- "enabled": e.name in enabled,+ **row,+ "default": row["name"] in default_surface,+ "eligible": row["eligible_workspace"] if is_workspace else row["eligible_single_repo"],+ "enabled": row["name"] in enabled,}- for e in sorted(entries, key=lambda e: e.name)+ for row in rows]return {"is_workspace": is_workspace,diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex f7dd73da6..16bc68c33 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -178,7 +178,9 @@ from repowise.server.mcp_server.tool_answer.symbols import (_hydrate_symbols_for_hits,)from repowise.server.mcp_server.tool_answer.synthesis import (- _hash_question,+ _hash_answer_identity,+ _hash_question, # backward-compatible re-export for cache migrations/tests+ _normalize_scope,_resolve_provider_for_answer,_resolve_reasoning_for_answer,synthesize,@@ -358,7 +360,7 @@ async def _run_retrieval_pipeline(return _Retrieved(hits, resolved_pool, question_ids, homonyms, flow_paths)[email protected](surface_order=10)async def get_answer(question: str,scope: str | None = None,@@ -426,11 +428,10 @@ async def get_answer(if grounded is not None:return build_data_shape_payload(grounded, t0, repository)- # --- Cache lookup --------------------------------------------------------- # Scope: ignore the (rare) `scope` argument in the cache key for now;- # scoped queries are uncommon and including scope would balloon hit rate- # variance. We hash on (repo_id, normalized_question) only.- qhash = _hash_question(question)+ # Normalize once, then use the same value for retrieval and cache identity.+ # The versioned identity deliberately misses legacy question-only rows.+ normalized_scope = _normalize_scope(scope)+ qhash = _hash_answer_identity(question, normalized_scope)cache_disabled = _cache_disabled()if not cache_disabled:served = await _serve_cached_answer(@@ -446,7 +447,7 @@ async def get_answer(return servedretrieved = await _run_retrieval_pipeline(- question, ctx, scope=scope, exclude_spec=exclude_spec, repo_id=repo_id+ question, ctx, scope=normalized_scope, exclude_spec=exclude_spec, repo_id=repo_id)hits = retrieved.hitsresolved_pool = retrieved.resolved_pool@@ -739,6 +740,13 @@ async def get_answer(if candidates:payload["candidates"] = candidates+ # Persist only the trust-relevant retrieval state. The cache read rebuilds+ # timing/freshness metadata for the current request, then restores this+ # synthesis-time fact so fresh and cached envelopes mean the same thing.+ degraded = _degraded_legs(_retrieval_legs())+ if degraded:+ payload["_retrieval_degraded"] = degraded+if answer_text and not cache_disabled:await _write_answer_cache(payload,@@ -747,9 +755,12 @@ async def get_answer(repository=repository,repo_id=repo_id,qhash=qhash,+ legacy_qhash=_hash_question(question),provider=provider,)+ payload.pop("_retrieval_degraded", None)+payload["_meta"] = _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint(confidence),@@ -762,7 +773,7 @@ async def get_answer(# see it, and ``embedder_live`` stayed true because a configured embedder is# live whether or not this call beat its budget. Named only when a leg# actually fell over, so a healthy response pays nothing for it.- if degraded := _degraded_legs(_retrieval_legs()):+ if degraded:payload["_meta"]["retrieval_degraded"] = degraded_apply_lean_high(payload, question)# After the cache write above and after lean-high (which can removediff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.pyindex b7ac19a5b..36c34c386 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py@@ -1,6 +1,6 @@"""The get_answer answer cache: when a stored row may be served, and how one is written.-Keyed on (repo, normalized question). The read side is mostly a list of reasons+Keyed on (repo, normalized question, normalized scope). The read side is mostly a list of reasonsNOT to serve a row — a stale row is worse than a re-synthesis, because it pins abad answer until the TTL expires and hides every improvement made since."""@@ -153,20 +153,20 @@ async def _serve_cached_answer(with contextlib.suppress(Exception):payload = _json.loads(cached.payload_json)cached_paths = _cached_payload_paths(payload)- if _cache_bypass_reason(- payload, cached.created_at, repository, exclude_spec, cached_paths- ):+ if _cache_bypass_reason(payload, cached.created_at, repository, exclude_spec, cached_paths):return None# Cache-internal fields never reach the consumer (response keys must not# start with "_" except _meta).payload.pop("_indexed_commit", None)payload.pop("_schema_version", None)+ retrieval_degraded = payload.pop("_retrieval_degraded", None)payload["_meta"] = _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,cached=True,hint=_answer_hint(payload.get("confidence", "low")),repository=repository,targets=[p for p in cached_paths if isinstance(p, str) and p],+ extra=({"retrieval_degraded": retrieval_degraded} if retrieval_degraded else None),)_apply_lean_high(payload, question)_trim_served_payload(payload)@@ -184,7 +184,15 @@ async def _serve_cached_answer(async def _write_answer_cache(- payload: dict, *, ctx, question: str, repository, repo_id, qhash: str, provider+ payload: dict,+ *,+ ctx,+ question: str,+ repository,+ repo_id,+ qhash: str,+ legacy_qhash: str,+ provider,) -> None:"""Persist this answer as the cache row for the question (upsert).@@ -192,8 +200,10 @@ async def _write_answer_cache(LOGGED rather than suppressed. A plain INSERT under a blanket suppressviolated ``uq_answer_cache_q`` on every bypass-and-resynthesize round andfailed silently, so hedged and stale rows were never upgraded.- Delete-then-insert in one transaction is the dialect-agnostic upsert, and- the stamped ``_indexed_commit`` is what the read-side freshness check reads.+ Delete-then-insert in one transaction is the dialect-agnostic upsert. It+ also removes the legacy question-only identity on the first successful+ synthesis, while the versioned lookup guarantees that row is never served.+ The stamped ``_indexed_commit`` is what the read-side freshness check reads.The row is a shallow copy taken here, so anything the caller attaches to thepayload after this point reaches the caller and never the cache.@@ -208,7 +218,7 @@ async def _write_answer_cache(await session.execute(delete(AnswerCache).where(AnswerCache.repository_id == repo_id,- AnswerCache.question_hash == qhash,+ AnswerCache.question_hash.in_({qhash, legacy_qhash}),))row = AnswerCache(diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.pyindex b41796d4a..a774b0cfa 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py@@ -13,6 +13,7 @@ import json as _jsonimport loggingimport mathimport os+import posixpathfrom pathlib import Pathfrom repowise.core.reasoning import ReasoningMode, resolve_reasoning@@ -48,6 +49,28 @@ def _hash_question(question: str) -> str:return hashlib.sha256(norm.encode("utf-8")).hexdigest()+def _normalize_scope(scope: str | None) -> str | None:+ """Canonical repo-relative scope used by retrieval and cache identity."""+ if scope is None or not scope.strip():+ return None+ normalized = posixpath.normpath(scope.strip().replace("\\", "/"))+ normalized = normalized.removeprefix("./").strip("/")+ return normalized if normalized and normalized != "." else None+++def _hash_answer_identity(question: str, normalized_scope: str | None) -> str:+ """Versioned answer-cache identity for one normalized question and scope."""+ normalized_question = " ".join(question.lower().strip().split())+ # JSON preserves the distinction between null and every possible scope+ # string (including a literal "<unscoped>") without a sentinel collision.+ identity = _json.dumps(+ ["v2", normalized_question, normalized_scope],+ ensure_ascii=False,+ separators=(",", ":"),+ )+ return hashlib.sha256(identity.encode("utf-8")).hexdigest()++def _resolve_reasoning_for_answer(repo_path: Path | None) -> ReasoningMode:"""Resolve the synthesis reasoning mode from env and repo config."""config = load_repo_config(repo_path) if repo_path is not None else Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.pyindex 829b7e825..f92acace6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py@@ -15,12 +15,13 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import _is_workspace_modefrom repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._meta import persisted_analysis_meta as _analysis_meta#: Cap the per-role member lists in the agent payload; full roles are on REST._MCP_CORE_MEMBER_LIMIT = 25[email protected](requires_workspace=True)[email protected](default=False, requires_workspace=True, surface_order=200, trust_kind="structural")async def get_architecture() -> dict[str, Any]:"""Workspace architecture metrics — coupling, core, and a 1-10 score.@@ -79,5 +80,14 @@ async def get_architecture() -> dict[str, Any]:"conformance_violations": metrics.get("conformance_violations", 0),"role_breakdown": breakdown,"summary": summary,- "_meta": _build_meta(),+ "_meta": _build_meta(+ extra=_analysis_meta(+ metrics.get("generated_at"),+ {+ alias: provenance.get("head")+ for alias, provenance in metrics.get("repo_provenance", {}).items()+ if provenance.get("head")+ },+ )+ ),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.pyindex 39a7f4863..b1417e755 100644--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py@@ -16,6 +16,7 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import _is_workspace_modefrom repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._meta import persisted_analysis_meta as _analysis_meta#: How many impacted services the MCP response carries inline. The full set is#: available via the REST endpoint / the map; here we keep the agent payload@@ -28,7 +29,7 @@ _MCP_IMPACTED_LIMIT = 25_SYMBOL_CONSUMER_LIMIT = 10[email protected](requires_workspace=True)[email protected](default=False, requires_workspace=True, surface_order=210, trust_kind="structural")async def get_blast_radius(targets: list[str],max_depth: int = 3,@@ -119,7 +120,16 @@ async def get_blast_radius("total_impacted": result.total_impacted,"unresolved_targets": result.unresolved_targets,"summary": summary,- "_meta": _build_meta(),+ "_meta": _build_meta(+ extra=_analysis_meta(+ raw.get("generated_at"),+ {+ alias: provenance.get("head")+ for alias, provenance in raw.get("repo_provenance", {}).items()+ if provenance.get("head")+ },+ )+ ),}if symbol_targets:payload["symbol_targets"] = symbol_targets@@ -168,9 +178,7 @@ def _resolve_symbol_targets(# Providers only: a consumer contract's symbol calls a surface rather# than publishing one, so it has no downstream to traverse.contracts = [- c- for c in enricher.get_contracts_for_symbol(raw)- if c.get("role") == "provider"+ c for c in enricher.get_contracts_for_symbol(raw) if c.get("role") == "provider"]nodes = sorted({node for c in contracts if (node := _graph_node_for(nodes_by_repo, c))})if not nodes:@@ -200,9 +208,7 @@ def _resolve_symbol_targets(block: dict[str, Any] = {"symbol_id": raw,"nodes": nodes,- "contract_ids": sorted(- {c["contract_id"] for c in contracts if c.get("contract_id")}- ),+ "contract_ids": sorted({c["contract_id"] for c in contracts if c.get("contract_id")}),"consumers": consumers,"consumer_count": len(links),"consumers_truncated": max(0, len(links) - len(consumers)),diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 0446de735..a505dfc13 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -57,7 +57,7 @@ _SHED_ORDER: tuple[str, ...] = ()[email protected](surface_order=60)async def get_change_risk(revspec: str | None = None,repo: str | None = None,@@ -140,9 +140,7 @@ async def get_change_risk(working_tree=result.working_tree,)collector = OmissionCollector("get_change_risk", repo_root=ctx.path)- payload["impacted_tests"] = await _impacted_tests_block(- ctx, changed, changed_error, collector- )+ payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error, collector)prior_fixes = await _prior_fixes_block(ctx, changed)if prior_fixes is not None:payload["prior_fixes"] = prior_fixes@@ -282,11 +280,7 @@ def _cross_repo_block(alias: str, changed_files: list[str]) -> dict[str, Any] |if (psid := link.get("provider_symbol_id"))else {}),- **(- {"symbol_id": sid}- if (sid := link.get("consumer_symbol_id"))- else {}- ),+ **({"symbol_id": sid} if (sid := link.get("consumer_symbol_id")) else {}),})@@ -297,9 +291,7 @@ def _cross_repo_block(alias: str, changed_files: list[str]) -> dict[str, Any] |for change in enricher.get_breaking_changes_for_repo(alias):if change.get("provider_file") not in touched:continue- cross = [- c for c in change.get("impacted_consumers", []) if c.get("repo") != alias- ]+ cross = [c for c in change.get("impacted_consumers", []) if c.get("repo") != alias]if not cross:continuebreaking_total += 1diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.pyindex 235892421..7f97ee0c5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py@@ -14,6 +14,7 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import _is_workspace_modefrom repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._meta import persisted_analysis_meta as _analysis_meta#: Inline caps so the agent payload stays tight; true counts are reported and the#: full set is on the REST endpoint.@@ -21,7 +22,12 @@ _MCP_VIOLATION_LIMIT = 25_MCP_CYCLE_LIMIT = 25[email protected](default=False, requires_workspace=True)+ default=False,+ requires_workspace=True,+ surface_order=250,+ trust_kind="structural",+)async def get_conformance(repo: str | None = None) -> dict[str, Any]:"""Architecture conformance — dependency-rule violations + cycles.@@ -79,6 +85,12 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:shown_violations = violations[:_MCP_VIOLATION_LIMIT]shown_cycles = cycles[:_MCP_CYCLE_LIMIT]+ graph = enricher.get_system_graph() or {}+ analysis_commits = {+ alias: provenance.get("head")+ for alias, provenance in graph.get("repo_provenance", {}).items()+ if provenance.get("head")+ }if violations or cycles:summary = (@@ -105,5 +117,5 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:"total_cycles": total_cycles,"checked_at": report.get("generated_at"),"summary": summary,- "_meta": _build_meta(),+ "_meta": _build_meta(extra=_analysis_meta(report.get("generated_at"), analysis_commits)),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex db31bb954..a27a5e869 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -77,7 +77,7 @@ _INCLUDE_BLOCKS = frozenset()[email protected](surface_order=20)async def get_context(targets: list[str],include: list[str] | None = None,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 74c53cf03..ea3f00c8d 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@@ -261,7 +261,7 @@ def _resolve_min_confidence(value: float | str, ignored: list[dict[str, Any]]) -return RISK_CAP_CONFIDENCE[email protected](surface_order=100)async def get_dead_code(repo: str | None = None,kind: str | None = None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex 749abd64b..d4b99f4aa 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -1,4 +1,4 @@-"""MCP Tool 6: get_dependency_path — dependency graph path finding."""+"""MCP Tool 6: get_dependency_path — dependency graph path finding."""from __future__ import annotations@@ -25,7 +25,7 @@ from repowise.server.mcp_server._helpers import ()[email protected](default=False)[email protected](default=False, surface_order=220, trust_kind="structural")async def get_dependency_path(source: str, target: str, repo: str | None = None) -> dict:"""Find how two files/modules are connected in the dependency graph.diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.pyindex 137b4f41a..94a93be1b 100644--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py@@ -1,4 +1,4 @@-"""MCP Tool: get_execution_flows — trace how the codebase executes.+"""MCP Tool: get_execution_flows — trace how the codebase executes.Hybrid approach: reads persisted entry-point scores from community_meta_json,then recomputes BFS call-path traces on demand from stored call edges. This@@ -37,7 +37,7 @@ from repowise.server.mcp_server._helpers import (from repowise.server.mcp_server._meta import build_meta as _build_meta[email protected](default=False)[email protected](default=False, surface_order=230, trust_kind="structural")async def get_execution_flows(top_n: int = 10,max_depth: int = 8,@@ -85,9 +85,7 @@ async def get_execution_flows(entry_nodes = [(node, _ep_score(node))]else:# Top-N scored entry points from DB- top_nodes = await get_top_entry_points(- session, repo_id, min_score=0.0, limit=top_n- )+ top_nodes = await get_top_entry_points(session, repo_id, min_score=0.0, limit=top_n)for n in top_nodes:entry_nodes.append((n, _ep_score(n)))diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex ef37ad6fe..906ab3425 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -889,7 +889,7 @@ def _compute_kpis(}[email protected](surface_order=90)async def get_health(targets: list[str] | None = None,include: list[str] | None = None,@@ -1856,8 +1856,7 @@ async def get_health():result["_meta"]["truncated_to_fit"] = droppedresult["_meta"]["truncated_recovery"] = (- "Response exceeded the MCP result cap. Re-request a single block with "- "only=[...] — each list's *_total says what was there."+ "Over MCP result cap. Re-request only=[...] — each list's *_total says what was there.")# Server-side wall clock, as ``get_context`` already reports. Without it a# regression in here is invisible until someone profiles it by hand.diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex e5cca0c93..382ca27f8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -61,6 +61,7 @@ from repowise.server.mcp_server._helpers import (is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._tool_selection import registry_tool_rows, selected_tool_names# Orientation, not a directory listing — the top few modules are enough to# point a fresh agent at the interesting subsystems. The rest are persisted@@ -71,6 +72,26 @@ _MODULE_CAP = 8_H2_SPLIT_RE = re.compile(r"\n(?=#{1,2}\s)")+def _tool_surface_guide(*, is_workspace: bool) -> dict[str, Any]:+ """The advertised surface, projected from the live registry catalog."""+ rows = registry_tool_rows()+ enabled = selected_tool_names(is_workspace=is_workspace)+ default_key = "default_workspace" if is_workspace else "default_single_repo"+ eligible_key = "eligible_workspace" if is_workspace else "eligible_single_repo"+ return {+ "mode": "workspace" if is_workspace else "single_repo",+ "canonical": [row["name"] for row in rows if row["tier"] == "canonical"],+ "default": [row["name"] for row in rows if row[default_key]],+ "enabled": [row["name"] for row in rows if row["name"] in enabled],+ "utilities": [+ row["name"] for row in rows if row["tier"] == "utility" and row[eligible_key]+ ],+ "opt_in": [+ row["name"] for row in rows if row["tier"] == "specialist" and row[eligible_key]+ ],+ }++def _compact_overview_content(content: str) -> str:"""Leading section of the overview essay — the summary paragraph, not the walkthrough.@@ -176,12 +197,16 @@ async def _workspace_overview() -> dict:"total_symbols": total_symbols,"repos": repos_info,"hint": ("Use repo='<alias>' to query a specific repo. Omit repo to use the default."),+ "tool_surface": _tool_surface_guide(is_workspace=True),+ "_meta": _build_meta(),}if cross_repo_topology:result["cross_repo_topology"] = cross_repo_topology- collector = OmissionCollector("get_overview", repo_root=registry.workspace_root if registry else None)- fit_to_budget(result, _WORKSPACE_SHED_ORDER, collector)+ collector = OmissionCollector(+ "get_overview", repo_root=registry.workspace_root if registry else None+ )+ fit_to_budget(result, _WORKSPACE_SHED_ORDER, collector, headroom=800)collector.attach(result)return result@@ -884,10 +909,21 @@ def _build_guided_tour(# Cheapest loss first. Everything not listed answers a question that changes an# agent's next action, so it is never shed.-_WORKSPACE_SHED_ORDER: tuple[str, ...] = ("cross_repo_topology", "repos[]")+_WORKSPACE_SHED_ORDER: tuple[str, ...] = (+ "cross_repo_topology",+ "tool_surface.canonical",+ "tool_surface.default",+ "tool_surface.utilities",+ "tool_surface.opt_in",+ "repos[]",+)_SHED_ORDER: tuple[str, ...] = ("tool_guide",+ "tool_surface.canonical",+ "tool_surface.default",+ "tool_surface.utilities",+ "tool_surface.opt_in","guided_tour_hint","guided_tour","reading_order_hint",@@ -897,11 +933,13 @@ _SHED_ORDER: tuple[str, ...] = ("key_decisions","outline_hint","outline",+ "tool_surface","key_modules[]",+ "content_md",)[email protected](surface_order=80)async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:"""Architecture map for an unfamiliar repo — first call when you don't know your way around.@@ -1079,9 +1117,10 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None"stale_warning in _meta, or a search hit whose sources are [fts] ""only (keyword match, no semantic agreement).",}+ result["tool_surface"] = _tool_surface_guide(is_workspace=_state._registry is not None)result["_meta"] = _build_meta(repository=repository)- fit_to_budget(result, _SHED_ORDER, collector)+ fit_to_budget(result, _SHED_ORDER, collector, headroom=800)collector.attach(result)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.pyindex d7d8bf7f5..8b4425240 100644--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py@@ -20,7 +20,7 @@ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_contextfrom repowise.server.mcp_server._meta import build_meta as _build_meta[email protected](default=False)[email protected](default=False, surface_order=240, trust_kind="generated")async def generate_refactoring_code(suggestion_id: str, repo: str | None = None) -> dict:"""Generate refactored code + a unified diff for one refactoring plan.diff --git a/packages/server/src/repowise/server/mcp_server/tool_repos.py b/packages/server/src/repowise/server/mcp_server/tool_repos.pyindex 15e3672e0..9b12bfdea 100644--- a/packages/server/src/repowise/server/mcp_server/tool_repos.py+++ b/packages/server/src/repowise/server/mcp_server/tool_repos.py@@ -57,7 +57,7 @@ def _workspace_repos(registry: Any) -> list[dict[str, Any]]:return repos[email protected](tier="utility", requires_workspace=True, surface_order=110)async def list_repos() -> dict[str, Any]:"""List repos available through this MCP server.diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex adb9f877f..4c994d2da 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -65,7 +65,7 @@ def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:holder.pop(key, None)[email protected](surface_order=50)async def get_risk(targets: list[str],repo: str | None = None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 6c420a159..12a056b27 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -995,7 +995,7 @@ async def _structured_search(return _fit_search_response(response, contexts[0].path if contexts else None)[email protected](surface_order=40)async def search_codebase(query: str,limit: int = 5,diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex adfee5041..fc8a6d640 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -620,7 +620,7 @@ async def _render_ambiguous(return response[email protected](surface_order=30)async def get_symbol(symbol_id: str | None = None,context_lines: int = 0,diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex e4580f11a..91fe85837 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -51,7 +51,7 @@ from repowise.server.mcp_server._why_relevance import ()[email protected](surface_order=70)async def get_why(query: str | None = None,targets: list[str] | None = None,@@ -405,6 +405,7 @@ def _fit_path_response(under-budget path still attaches: a response that fits can still carry acapped body whose remainder needs advertising."""+def _over() -> bool:return over_budget(result_data, headroom=_COLLECTOR_HEADROOM_CHARS)@@ -987,9 +988,7 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -# distinct decisions — and only walk lineage for what survives.ranked = _rank_keyword_matches(all_decisions, query, target_set)if not ranked:- return await _why_no_match(- query, targets, ctx, repository, all_decisions, target_git- )+ return await _why_no_match(query, targets, ctx, repository, all_decisions, target_git)collapsed = _collapse_restatements(ranked)[:_MAX_SEARCH_DECISIONS]decision_results, doc_results = await _semantic_lanes(ctx, query)lineage_by_id = await _lineage_for_matches(ctx, [d for d, _ in collapsed])diff --git a/packages/server/src/repowise/server/schemas/mcp.py b/packages/server/src/repowise/server/schemas/mcp.pyindex c50902ad8..fe7774a4b 100644--- a/packages/server/src/repowise/server/schemas/mcp.py+++ b/packages/server/src/repowise/server/schemas/mcp.py@@ -10,7 +10,13 @@ class McpToolInfo(BaseModel):name: strdescription: str+ tier: strdefault: bool+ default_single_repo: bool+ default_workspace: bool+ eligible: bool+ eligible_single_repo: bool+ eligible_workspace: boolrequires_workspace: boolenabled: booldiff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.jsonindex d68b71666..cfd175ff1 100644--- a/plugins/claude-code/.claude-plugin/plugin.json+++ b/plugins/claude-code/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "repowise",- "description": "Codebase intelligence for Claude Code. Indexes your codebase into five layers (Graph, Git, Docs, Decisions, Code Health) and exposes them through eleven task-shaped MCP tools — so Claude understands architecture, ownership, hotspots, why code is built the way it is, and where the defect risk lives.",+ "description": "Codebase intelligence for Claude Code. Indexes your codebase into five layers (Graph, Git, Docs, Decisions, Code Health) and exposes them through ten task-shaped MCP tools — so Claude understands architecture, ownership, hotspots, why code is built the way it is, and where the defect risk lives.","version": "0.45.0","author": {"name": "Repowise",diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.pyindex ccbaf0b25..3c534d248 100644--- a/scripts/gen_agent_matrix.py+++ b/scripts/gen_agent_matrix.py@@ -64,13 +64,6 @@ PASTE_CONFIG_HOSTS: tuple[str, ...] = ("Amp",)-#: Default-surface tools the README's curated list leaves out. ``list_repos``-#: answers "which repos is this server serving", which is discovery rather than-#: one of the task-shaped tools the README is selling, and a reader counting-#: capabilities should not have it padding the number. Everything downstream of-#: the README states the real surface instead.-NON_FLAGSHIP_TOOLS: frozenset[str] = frozenset({"list_repos"})-TIER_BLURBS: dict[str, tuple[str, str]] = {"full": ("Full",@@ -164,7 +157,7 @@ def tool_counts() -> dict[str, int]:# about. It is the default surface minus the discovery utilities, and# it is derived here rather than typed, so a twelfth default tool moves# the README too. Docs keep the precise surface numbers.- "flagship": len(default_names - NON_FLAGSHIP_TOOLS),+ "flagship": len([entry for entry in entries if entry.tier == "canonical"]),"workspace": workspace,# The delta is published in its own right ("adds two more"), so it is# derived rather than written as a literal next to a derived total.diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.pyindex 6bf0c12f1..748da8e55 100644--- a/tests/unit/analysis/test_security_scan.py+++ b/tests/unit/analysis/test_security_scan.py@@ -14,6 +14,7 @@ import asynciofrom pathlib import Pathfrom types import SimpleNamespace+import pytestfrom sqlalchemy import textfrom repowise.core.analysis.security_scan import SecurityScanner@@ -31,10 +32,7 @@ CLEAN = b"""def add(a, b):def _fake_result(files: dict[str, bytes]):- parsed = [- SimpleNamespace(file_info=SimpleNamespace(path=p), symbols=[])- for p in files- ]+ parsed = [SimpleNamespace(file_info=SimpleNamespace(path=p), symbols=[]) for p in files]return SimpleNamespace(parsed_files=parsed, source_map=dict(files))@@ -73,9 +71,7 @@ async def _rows(sf) -> list[tuple]:class TestScanFile:def test_line_patterns_fire_on_real_source(self) -> None:scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]- findings = asyncio.run(- scanner.scan_file("a.py", SNIPPY.decode(), symbols=[])- )+ findings = asyncio.run(scanner.scan_file("a.py", SNIPPY.decode(), symbols=[]))kinds = {f["kind"] for f in findings}assert "hardcoded_password" in kindsassert "pickle_loads" in kinds@@ -88,6 +84,53 @@ class TestScanFile:findings = asyncio.run(scanner.scan_file("b.py", CLEAN.decode(), symbols=[]))assert findings == []+ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("eval(payload)\n", {"eval_call"}),+ ("exec (payload)\n", {"exec_call"}),+ ("eval(\n payload\n)\n", {"eval_call"}),+ ("builtins.eval(payload)\n", {"eval_call"}),+ ("retrieval (payload)\n", set()),+ ("my_eval(payload)\n", set()),+ ("# eval(payload)\n", set()),+ ('text = "eval(payload)"\n', set()),+ ('"""exec(payload)"""\n', set()),+ ],+ )+ def test_python_eval_exec_call_corpus(self, source: str, expected: set[str]) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("calls.py", source, symbols=[]))+ assert {row["kind"] for row in findings if row["kind"].endswith("_call")} == expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("eval (payload);\n", {"eval_call"}),+ ("exec\n (payload);\n", {"exec_call"}),+ ("window.eval(payload);\n", {"eval_call"}),+ ("const result = `${eval(payload)}`;\n", {"eval_call"}),+ ("retrieval (payload);\n", set()),+ ("my_eval(payload);\n", set()),+ ("// eval(payload)\n", set()),+ ("/* exec(payload) */\n", set()),+ ('const text = "eval(payload)";\n', set()),+ ],+ )+ def test_fallback_eval_exec_call_corpus(self, source: str, expected: set[str]) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("calls.js", source, symbols=[]))+ assert {row["kind"] for row in findings if row["kind"].endswith("_call")} == expected++ def test_combined_prefilter_uses_the_same_safe_call_boundaries(self) -> None:+ from repowise.core.analysis.security_scan import _ANY_PATTERN++ assert _ANY_PATTERN.search("eval (")+ assert _ANY_PATTERN.search("exec(")+ assert _ANY_PATTERN.search("window.eval(")+ assert not _ANY_PATTERN.search("retrieval (")+ assert not _ANY_PATTERN.search("my_eval(")+def test_single_line_subprocess_shell_true_is_flagged(self) -> None:scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]source = 'subprocess.run("rm -rf " + path, shell=True)\n'@@ -122,11 +165,7 @@ class TestScanFile:def test_spanning_pass_does_not_jump_to_later_shell_true(self) -> None:"""A closed subprocess call must not claim a later column-0 shell=True."""scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]- source = (- 'subprocess.run(["ls"], capture_output=True)\n'- "\n"- "os.popen(cmd, shell=True)\n"- )+ source = 'subprocess.run(["ls"], capture_output=True)\n\nos.popen(cmd, shell=True)\n'findings = asyncio.run(scanner.scan_file("a.py", source, symbols=[]))hits = [f for f in findings if f["kind"] == "subprocess_shell_true"]assert hits == []@@ -182,13 +221,9 @@ class TestPersistSecurityFindings:from repowise.core.persistence import get_sessionasync with get_session(sf) as session:- await persist_security_findings(- _fake_result({"a.py": SNIPPY}), session, "repo-1"- )+ await persist_security_findings(_fake_result({"a.py": SNIPPY}), session, "repo-1")async with get_session(sf) as session:- await persist_security_findings(- _fake_result({"a.py": CLEAN}), session, "repo-1"- )+ await persist_security_findings(_fake_result({"a.py": CLEAN}), session, "repo-1")rows = await _rows(sf)await engine.dispose()return rows@@ -209,9 +244,7 @@ class TestPersistSecurityFindings:sym = SimpleNamespace(name="auth", start_line=7)result = SimpleNamespace(parsed_files=[- SimpleNamespace(- file_info=SimpleNamespace(path="auth.py"), symbols=[sym]- )+ SimpleNamespace(file_info=SimpleNamespace(path="auth.py"), symbols=[sym])],)async with get_session(sf) as session:diff --git a/tests/unit/analysis/test_security_scan_history.py b/tests/unit/analysis/test_security_scan_history.pyindex 30544434e..86465c773 100644--- a/tests/unit/analysis/test_security_scan_history.py+++ b/tests/unit/analysis/test_security_scan_history.py@@ -153,13 +153,9 @@ def test_migration_0041_upgrades_sqlite() -> None:assert "commit_sha" in colsassert "commit_at" in colsuqs = await conn.run_sync(- lambda sync_conn: inspect(sync_conn).get_unique_constraints(- "security_findings"- )- )- assert any(- uq.get("name") == "uq_security_finding_provenance" for uq in uqs+ lambda sync_conn: inspect(sync_conn).get_unique_constraints("security_findings"))+ assert any(uq.get("name") == "uq_security_finding_provenance" for uq in uqs)import asyncio@@ -348,9 +344,7 @@ async def test_history_default_skips_test_fixtures_and_placeholders(assert "docs.py" not in paths, "elided placeholder reported as a credential"-async def test_all_patterns_lifts_the_noise_gate(- session: AsyncSession, secret_repo: Path-) -> None:+async def test_all_patterns_lifts_the_noise_gate(session: AsyncSession, secret_repo: Path) -> None:"""The filtering is the default's promise, not a hard exclusion."""(secret_repo / "tests").mkdir(exist_ok=True)(secret_repo / "tests" / "test_client.py").write_text('password = "fixture-value"\n')@@ -367,6 +361,35 @@ async def test_all_patterns_lifts_the_noise_gate(assert "tests/test_client.py" in paths+async def test_history_all_patterns_uses_call_aware_eval_semantics(+ session: AsyncSession, secret_repo: Path+) -> None:+ path = secret_repo / "calls.py"+ path.write_text(+ "# eval(commented)\n"+ 'text = "eval(in_string)"\n'+ "retrieval (payload)\n"+ "my_eval(payload)\n"+ "eval (payload)\n",+ encoding="utf-8",+ )+ _git(secret_repo, "add", ".")+ _git(secret_repo, "commit", "-m", "add eval corpus")++ scanner = HistorySecurityScanner(session, "repo-1")+ await scanner.scan_history(secret_repo, secrets_only=False)++ rows = (+ await session.execute(+ text(+ "SELECT kind, line_number FROM security_findings "+ "WHERE file_path = 'calls.py' AND kind IN ('eval_call', 'exec_call')"+ )+ )+ ).all()+ assert [tuple(row) for row in rows] == [("eval_call", 5)]++async def test_blob_introductions_resolves_real_blobs(secret_repo: Path) -> None:"""Every source blob rev-list reports must resolve to an introducing commit."""scanner = HistorySecurityScanner.__new__(HistorySecurityScanner)diff --git a/tests/unit/cli/test_agent_matrix.py b/tests/unit/cli/test_agent_matrix.pyindex 57bd73d0d..580b623db 100644--- a/tests/unit/cli/test_agent_matrix.py+++ b/tests/unit/cli/test_agent_matrix.py@@ -78,8 +78,7 @@ def _on_disk(path: Path) -> str:def test_the_generated_matrix_matches_the_registry(path: Path) -> None:expected = GEN.rendered_files()[path]assert path.exists(), (- f"{path.relative_to(ROOT).as_posix()} is missing. "- "Run: python scripts/gen_agent_matrix.py"+ f"{path.relative_to(ROOT).as_posix()} is missing. Run: python scripts/gen_agent_matrix.py")assert _on_disk(path) == expected, (f"{path.relative_to(ROOT).as_posix()} has drifted from the agent registry. "@@ -223,8 +222,7 @@ def test_the_hooks_column_cannot_lie() -> None:#: say "the ten flagship tools" are describing a documented subset rather than#: the default surface.COUNT_CLAIMS: tuple[tuple[str, str, str], ...] = (- # The README and the image at the top of it count the flagship tools, a- # narrower claim than the advertised surface. See NON_FLAGSHIP_TOOLS.+ # The README and the image at the top of it count the canonical tier.("README.md", "flagship", "**{w} task-shaped MCP tools**"),("README.md", "flagship", "## The {w} MCP tools"),("README.md", "flagship", "{W} is a deliberate ceiling"),@@ -295,26 +293,17 @@ COUNT_CLAIMS: tuple[tuple[str, str, str], ...] = (def test_the_flagship_set_is_a_real_subset_of_the_default_surface() -> None:- """Removing a name that is not there would silently do nothing.-- ``flagship`` is the default surface minus :data:`NON_FLAGSHIP_TOOLS`. If a- tool in that set is renamed or made opt-in, the subtraction stops removing- anything and the README's ten quietly becomes the surface's eleven, which- is precisely the drift this file exists to catch.- """+ """The published flagship count is exactly the registry canonical tier."""from repowise.core.registry import mcp_tool_registryfrom repowise.server.mcp_server import ensure_full_surfacefrom repowise.server.mcp_server._tool_selection import resolve_enabled_toolsensure_full_surface()- default = resolve_enabled_tools(mcp_tool_registry.entries(), is_workspace=False)- absent = GEN.NON_FLAGSHIP_TOOLS - default- assert not absent, (- f"{sorted(absent)} are excluded from the flagship count but are not in the "- "default surface, so excluding them does nothing. Update NON_FLAGSHIP_TOOLS "- "in scripts/gen_agent_matrix.py."- )- assert COUNTS["flagship"] == COUNTS["single_repo"] - len(GEN.NON_FLAGSHIP_TOOLS)+ entries = mcp_tool_registry.entries()+ default = resolve_enabled_tools(entries, is_workspace=False)+ canonical = {entry.name for entry in entries if entry.tier == "canonical"}+ assert canonical == default+ assert COUNTS["flagship"] == len(canonical)def test_the_readme_tool_table_lists_exactly_the_flagship_tools() -> None:@@ -333,10 +322,12 @@ def test_the_readme_tool_table_lists_exactly_the_flagship_tools() -> None:f"README.md's tool table lists {len(listed)} tools ({listed}) but the "f"flagship count is {COUNTS['flagship']}.")- excluded = sorted(set(listed) & GEN.NON_FLAGSHIP_TOOLS)- assert not excluded, (- f"{excluded} is excluded from the README's count but has a row in its table."- )+ from repowise.core.registry import mcp_tool_registry+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()+ canonical = {entry.name for entry in mcp_tool_registry.entries() if entry.tier == "canonical"}+ assert set(listed) == canonical@pytest.mark.parametrize(@@ -377,9 +368,7 @@ def _appears(phrase: str, text: str) -> bool:COUNT_CLAIMS,ids=[f"{rel}:{tmpl}" for rel, _, tmpl in COUNT_CLAIMS],)-def test_a_published_tool_count_matches_the_registry(- relpath: str, key: str, template: str-) -> None:+def test_a_published_tool_count_matches_the_registry(relpath: str, key: str, template: str) -> None:path = ROOT / relpathassert path.exists(), f"{relpath} is named in COUNT_CLAIMS but does not exist"expected = _phrase(template, COUNTS[key])diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.pyindex 6318aff96..1ff47bfba 100644--- a/tests/unit/cli/test_freshness_stamp_fixes.py+++ b/tests/unit/cli/test_freshness_stamp_fixes.py@@ -211,7 +211,8 @@ def test_freshness_self_heals_and_silences_false_stale(tmp_path):assert out["indexed_commit"] == head[:12]# HEAD matches the (self-healed) indexed commit → no false "behind" warning.assert "stale_warning" not in out- assert "live_head" not in out+ assert out["live_head"] == head[:12]+ assert out["index_behind"] is False# ---------------------------------------------------------------------------diff --git a/tests/unit/registry/test_mcp_tool_registry.py b/tests/unit/registry/test_mcp_tool_registry.pyindex d2c61090e..8d1c00902 100644--- a/tests/unit/registry/test_mcp_tool_registry.py+++ b/tests/unit/registry/test_mcp_tool_registry.py@@ -52,6 +52,17 @@ def test_tool_alias_matches_register(registry):assert my_tool in registry.tools()+def test_legacy_default_workspace_tool_infers_utility_tier(registry):+ @registry.tool(requires_workspace=True)+ async def workspace_utility() -> dict:+ return {}++ entry = registry.entries()[0]+ assert entry.default is True+ assert entry.requires_workspace is True+ assert entry.tier == "utility"++def test_apply_registers_with_server(registry):@registry.registerasync def t1() -> dict:diff --git a/tests/unit/server/mcp/test_answer_cache.py b/tests/unit/server/mcp/test_answer_cache.pyindex 1ad12999e..26f03887f 100644--- a/tests/unit/server/mcp/test_answer_cache.py+++ b/tests/unit/server/mcp/test_answer_cache.py@@ -125,19 +125,23 @@ async def test_cached_empty_answer_row_is_bypassed(setup_mcp, factory, session,repo = res.scalars().first()# Legacy row: current schema version (so the schema gate passes) but the# old empty-answer gated shape.- session.add(AnswerCache(- repository_id=repo.id,- question_hash=_hash_question(QUESTION),- question=QUESTION,- payload_json=_json.dumps({- "answer": "",- "confidence": "low",- "fallback_targets": ["src/auth/service.py"],- "_schema_version": _ANSWER_SCHEMA_VERSION,- }),- provider_name="mock",- model_name="mock-1",- ))+ session.add(+ AnswerCache(+ repository_id=repo.id,+ question_hash=_hash_question(QUESTION),+ question=QUESTION,+ payload_json=_json.dumps(+ {+ "answer": "",+ "confidence": "low",+ "fallback_targets": ["src/auth/service.py"],+ "_schema_version": _ANSWER_SCHEMA_VERSION,+ }+ ),+ provider_name="mock",+ model_name="mock-1",+ )+ )await session.commit()direct = _Provider("Auth flows through src/auth/service.py via AuthService.check().")@@ -233,3 +237,141 @@ async def test_cache_write_failure_logs_instead_of_silencing(setup_mcp, monkeypaassert result["answer"], "response must survive a cache-write failure"assert any("cache write failed" in r.message for r in caplog.records)+++ ("first_scope", "second_scope"),+ [(None, "src/auth"), ("src/auth", None)],+)+async def test_scoped_and_unscoped_answers_never_cross_contaminate(+ setup_mcp, factory, monkeypatch, first_scope, second_scope+):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_retrieval(monkeypatch, answer_mod)+ provider = _Provider("Scoped cache identity answer (src/auth/service.py).")+ _patch_provider(monkeypatch, answer_mod, provider)++ await get_answer(QUESTION, scope=first_scope)+ await get_answer(QUESTION, scope=second_scope)++ assert provider.calls == 2+ assert len(await _cache_rows(factory)) == 2+++async def test_distinct_scopes_never_cross_contaminate(setup_mcp, factory, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_retrieval(monkeypatch, answer_mod)+ provider = _Provider("Scoped answer (src/auth/service.py).")+ _patch_provider(monkeypatch, answer_mod, provider)++ await get_answer(QUESTION, scope="src/auth")+ await get_answer(QUESTION, scope="src/billing")++ assert provider.calls == 2+ assert len(await _cache_rows(factory)) == 2+++def test_literal_unscoped_scope_cannot_collide_with_absent_scope() -> None:+ from repowise.server.mcp_server.tool_answer.synthesis import _hash_answer_identity++ assert _hash_answer_identity(QUESTION, None) != _hash_answer_identity(QUESTION, "<unscoped>")+++async def test_equivalent_normalized_scopes_share_one_row(setup_mcp, factory, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ seen_scopes: list[str | None] = []++ async def _fake_hydrate(hits, ctx, *, scope=None):+ seen_scopes.append(scope)+ for hit in hits:+ hit.update(+ target_path=hit["page_id"].removeprefix("file_page:"),+ title="auth",+ summary="",+ snippet="",+ page_type="file_page",+ )+ return hits++ _patch_retrieval(monkeypatch, answer_mod)+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)+ provider = _Provider("Normalized scope answer (src/auth/service.py).")+ _patch_provider(monkeypatch, answer_mod, provider)++ await get_answer(QUESTION, scope="./src\\auth//")+ cached = await get_answer(QUESTION, scope="src/auth")++ assert provider.calls == 1+ assert seen_scopes == ["src/auth"]+ assert cached["_meta"]["cached"] is True+ assert len(await _cache_rows(factory)) == 1+++async def test_cached_answer_preserves_retrieval_degradation_metadata(+ setup_mcp, factory, monkeypatch+):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_retrieval(monkeypatch, answer_mod)+ monkeypatch.setattr(answer_mod, "_retrieval_legs", lambda: {"vector": "timeout"})+ monkeypatch.setattr(answer_mod, "_degraded_legs", lambda _legs: ["vector"])+ provider = _Provider("Degraded retrieval answer (src/auth/service.py).")+ _patch_provider(monkeypatch, answer_mod, provider)++ fresh = await get_answer(QUESTION)+ cached = await get_answer(QUESTION)++ assert provider.calls == 1+ assert fresh["_meta"]["retrieval_degraded"] == ["vector"]+ assert cached["_meta"]["retrieval_degraded"] == ["vector"]+ assert cached["_meta"]["cached"] is True+++async def test_legacy_question_only_row_is_bypassed(setup_mcp, factory, session, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer+ from repowise.server.mcp_server.tool_answer.answer import _hash_question+ from repowise.server.mcp_server.tool_answer.config import _ANSWER_SCHEMA_VERSION++ _patch_retrieval(monkeypatch, answer_mod)+ repo = (await session.execute(select(Repository))).scalars().first()+ session.add(+ AnswerCache(+ repository_id=repo.id,+ question_hash=_hash_question(QUESTION),+ question=QUESTION,+ payload_json=_json.dumps(+ {+ "answer": "Legacy answer must not be served.",+ "confidence": "high",+ "citations": ["src/legacy.py"],+ "_schema_version": _ANSWER_SCHEMA_VERSION,+ }+ ),+ provider_name="mock",+ model_name="mock-1",+ )+ )+ await session.commit()++ provider = _Provider("Fresh scoped identity answer (src/auth/service.py).")+ _patch_provider(monkeypatch, answer_mod, provider)+ result = await get_answer(QUESTION)++ assert provider.calls == 1+ assert "Fresh scoped identity" in result["answer"]+ rows = await _cache_rows(factory)+ assert len(rows) == 1+ assert rows[0].question_hash != _hash_question(QUESTION)diff --git a/tests/unit/server/mcp/test_mcp_docs_drift.py b/tests/unit/server/mcp/test_mcp_docs_drift.pyindex 8b00c0c11..2ac323467 100644--- a/tests/unit/server/mcp/test_mcp_docs_drift.py+++ b/tests/unit/server/mcp/test_mcp_docs_drift.py@@ -45,11 +45,13 @@ def test_surface_counts_match_registry(doc_text: str):entries = _entries()total = len(entries)single_default = sum(1 for e in entries if e.default and not e.requires_workspace)- workspace_only = sum(1 for e in entries if e.default and e.requires_workspace)+ workspace_default = sum(1 for e in entries if e.default)+ opt_in = sum(1 for e in entries if not e.default)m = re.search(r"(\d+) tools are registered in total\. A single-repo server advertises "- r"(\d+) by default.*?Workspace mode adds (\d+) more automatically.*?, for (\d+)",+ r"(\d+) by default: exactly the canonical tools\. Workspace mode adds .*?, for "+ r"(\d+)\. (\d+) specialist tools are opt-in",doc_text,flags=re.DOTALL,)@@ -57,11 +59,31 @@ def test_surface_counts_match_registry(doc_text: str):assert [int(g) for g in m.groups()] == [total,single_default,- workspace_only,- single_default + workspace_only,+ workspace_default,+ opt_in,], "MCP_TOOLS.md surface counts drifted from the registry"+def _inventory_names(doc_text: str, heading: str) -> set[str]:+ match = re.search(rf"\*\*{re.escape(heading)}[^\n]*\*\*\n(.*?)(?=\n\n)", doc_text, re.DOTALL)+ assert match, f"missing inventory heading: {heading}"+ return set(re.findall(r"\[([a-z_]+)\]\(#", match.group(1)))+++def test_inventory_tiers_and_mode_eligibility_match_registry(doc_text: str):+ entries = _entries()+ canonical = {entry.name for entry in entries if entry.tier == "canonical"}+ utilities = {entry.name for entry in entries if entry.tier == "utility"}+ specialists = {entry.name for entry in entries if entry.tier == "specialist"}+ assert _inventory_names(doc_text, "Canonical tools") == canonical+ assert _inventory_names(doc_text, "Workspace discovery utility") == utilities+ assert _inventory_names(doc_text, "Opt-in specialists") == specialists++ assert all(entry.default for entry in entries if entry.tier in {"canonical", "utility"})+ assert all(not entry.default for entry in entries if entry.tier == "specialist")+ assert all(entry.requires_workspace for entry in entries if entry.tier == "utility")++def test_lean_profile_paragraph_names_the_lean_tools(doc_text: str):m = re.search(r"\*\*The `lean` profile\*\*.*?(?=\n\n)", doc_text, flags=re.DOTALL)assert m, "MCP_TOOLS.md lean-profile paragraph not found"diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.pyindex 405092747..b3a325abc 100644--- a/tests/unit/server/mcp/test_meta_freshness.py+++ b/tests/unit/server/mcp/test_meta_freshness.py@@ -49,7 +49,7 @@ def test_head_match_is_silent(tmp_path, monkeypatch):out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])assert "stale_warning" not in outassert out["index_behind"] is False- assert "live_head" not in out+ assert out["live_head"] == _INDEXED[:12]def test_no_git_signal_omits_index_behind_entirely(tmp_path, monkeypatch):@@ -233,8 +233,10 @@ def test_no_answer_hint_names_an_external_tool() -> None:from repowise.server.mcp_server._meta import NO_HITS_RECOVERY_HINT, answer_hinthints = [answer_hint(c) for c in ("high", "medium", "low")]- hints += [answer_hint("low", degraded="no-llm-provider", retrieval_quality=q)- for q in ("high", "partial", "weak")]+ hints += [+ answer_hint("low", degraded="no-llm-provider", retrieval_quality=q)+ for q in ("high", "partial", "weak")+ ]assert not [h for h in hints if h and "Grep" in h]assert "Grep" not in NO_HITS_RECOVERY_HINTassert "search_codebase" in NO_HITS_RECOVERY_HINTdiff --git a/tests/unit/server/mcp/test_tool_selection.py b/tests/unit/server/mcp/test_tool_selection.pyindex 961bd8ed6..3f2da4c70 100644--- a/tests/unit/server/mcp/test_tool_selection.py+++ b/tests/unit/server/mcp/test_tool_selection.py@@ -16,24 +16,35 @@ def _fn(name):return f-# A representative catalog: 3 plain defaults, 1 workspace-only, 1 opt-in.+# A representative catalog: canonical defaults, one workspace utility, and specialists.CATALOG = [ToolEntry(_fn("get_answer"), "get_answer"),ToolEntry(_fn("get_context"), "get_context"),- ToolEntry(_fn("list_repos"), "list_repos"),- ToolEntry(_fn("get_blast_radius"), "get_blast_radius", requires_workspace=True),+ ToolEntry(+ _fn("list_repos"),+ "list_repos",+ requires_workspace=True,+ tier="utility",+ ),+ ToolEntry(+ _fn("get_blast_radius"),+ "get_blast_radius",+ default=False,+ requires_workspace=True,+ tier="specialist",+ ),ToolEntry(_fn("get_dependency_path"), "get_dependency_path", default=False),]def test_default_single_repo_surface():enabled = resolve_enabled_tools(CATALOG, is_workspace=False)- assert enabled == {"get_answer", "get_context", "list_repos"}+ assert enabled == {"get_answer", "get_context"}def test_default_workspace_adds_workspace_only():enabled = resolve_enabled_tools(CATALOG, is_workspace=True)- assert enabled == {"get_answer", "get_context", "list_repos", "get_blast_radius"}+ assert enabled == {"get_answer", "get_context", "list_repos"}def test_opt_in_tool_off_by_default():@@ -44,13 +55,13 @@ def test_delta_add_and_remove():enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="+get_dependency_path,-get_context")- assert enabled == {"get_answer", "list_repos", "get_dependency_path"}+ assert enabled == {"get_answer", "get_dependency_path"}def test_delta_string_or_list_equivalent():a = resolve_enabled_tools(CATALOG, is_workspace=False, override="+get_dependency_path")b = resolve_enabled_tools(CATALOG, is_workspace=False, override=["+get_dependency_path"])- assert a == b == {"get_answer", "get_context", "list_repos", "get_dependency_path"}+ assert a == b == {"get_answer", "get_context", "get_dependency_path"}def test_explicit_allowlist_replaces_default():@@ -68,7 +79,6 @@ def test_all_enables_everything_usable():assert resolve_enabled_tools(CATALOG, is_workspace=False, override="all") == {"get_answer","get_context",- "list_repos","get_dependency_path",}@@ -151,7 +161,7 @@ def test_workspace_only_named_explicitly_kept_in_workspace():def test_unknown_tool_ignored():enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="+does_not_exist")- assert enabled == {"get_answer", "get_context", "list_repos"}+ assert enabled == {"get_answer", "get_context"}def test_empty_override_falls_back_to_default():@@ -160,11 +170,56 @@ def test_empty_override_falls_back_to_default():)+def test_real_registry_phase_one_surfaces_are_exact():+ from repowise.core.registry import mcp_tool_registry+ from repowise.server.mcp_server import ensure_full_surface++ canonical = {+ "get_answer",+ "get_context",+ "get_symbol",+ "search_codebase",+ "get_risk",+ "get_change_risk",+ "get_why",+ "get_overview",+ "get_health",+ "get_dead_code",+ }+ ensure_full_surface()+ entries = mcp_tool_registry.entries()+ assert {entry.name for entry in entries if entry.tier == "canonical"} == canonical+ assert resolve_enabled_tools(entries, is_workspace=False) == canonical+ assert resolve_enabled_tools(entries, is_workspace=True) == canonical | {"list_repos"}+++def test_real_registry_specialist_eligibility_is_mode_specific():+ from repowise.core.registry import mcp_tool_registry+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()+ entries = mcp_tool_registry.entries()+ single_all = resolve_enabled_tools(entries, is_workspace=False, override="all")+ workspace_all = resolve_enabled_tools(entries, is_workspace=True, override="all")+ assert {+ "get_dependency_path",+ "get_execution_flows",+ "generate_refactoring_code",+ } <= single_all+ assert {+ "get_architecture",+ "get_blast_radius",+ "get_conformance",+ "list_repos",+ }.isdisjoint(single_all)+ assert {entry.name for entry in entries} == workspace_all++# --- live FastMCP trimming -------------------------------------------------@pytest.mark.asyncio-async def test_apply_trims_and_restores_live_server(tmp_path):+async def test_apply_trims_and_restores_live_server(tmp_path, monkeypatch):"""apply_tool_selection trims the real server and can rebuild the full set."""import repowise.server.mcp_server as mcp_modfrom repowise.server.mcp_server import _tool_selection@@ -172,6 +227,7 @@ async def test_apply_trims_and_restores_live_server(tmp_path):mcp = mcp_mod.mcp(tmp_path / ".repowise").mkdir()+ monkeypatch.setattr(_tool_selection, "_is_workspace", lambda _path: False)async def names() -> set[str]:return {t.name for t in await mcp.list_tools()}@@ -187,8 +243,14 @@ async def test_apply_trims_and_restores_live_server(tmp_path):# Opt in to one tool; it reappears.apply_tool_selection(mcp, repo_path=str(tmp_path), override="+get_dependency_path")assert "get_dependency_path" in await names()+ from repowise.server.mcp_server.tool_overview import _tool_surface_guide++ guide = _tool_surface_guide(is_workspace=False)+ assert set(guide["enabled"]) == await names()+ assert "get_dependency_path" in guide["enabled"]finally:# Restore the full surface so other tests see every tool, including the# workspace-only ones an "all" override on a non-workspace path omits.if _tool_selection._full_surface is not None:mcp._tool_manager._tools = dict(_tool_selection._full_surface)+ _tool_selection._selected_surface = Nonediff --git a/tests/unit/server/mcp/test_tool_table_drift.py b/tests/unit/server/mcp/test_tool_table_drift.pyindex b7dabd207..67a2cbd1d 100644--- a/tests/unit/server/mcp/test_tool_table_drift.py+++ b/tests/unit/server/mcp/test_tool_table_drift.py@@ -27,23 +27,12 @@ def test_every_table_row_names_a_registered_tool():assert not unknown, f"tool_table.py rows for unregistered tools: {unknown}"-def test_core_default_surface_is_documented():- # The single-repo default surface an agent actually sees (list_repos is- # workspace plumbing and deliberately has no row).- core = {- "get_answer",- "get_context",- "get_symbol",- "search_codebase",- "get_overview",- "get_risk",- "get_change_risk",- "get_why",- "get_dead_code",- "get_health",- }- missing = core - set(TOOL_TABLE_ROWS)- assert not missing, f"default-surface tools missing a table row: {missing}"+def test_agent_table_is_exactly_the_registry_canonical_tier():+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()+ canonical = {entry.name for entry in mcp_tool_registry.entries() if entry.tier == "canonical"}+ assert set(TOOL_TABLE_ROWS) == canonicaldef test_render_produces_one_row_per_tool():diff --git a/tests/unit/server/mcp/test_trust_contract.py b/tests/unit/server/mcp/test_trust_contract.pynew file mode 100644index 000000000..7daa52d52--- /dev/null+++ b/tests/unit/server/mcp/test_trust_contract.py@@ -0,0 +1,81 @@+"""Shared MCP trust-envelope and registry evidence contracts."""++from __future__ import annotations++from types import SimpleNamespace++from repowise.server.mcp_server import _meta+++def test_build_meta_carries_contract_and_index_identity(tmp_path, monkeypatch):+ indexed = "a" * 40+ monkeypatch.setattr(_meta, "read_live_head", lambda _path: indexed)+ repository = SimpleNamespace(+ updated_at=None,+ local_path=str(tmp_path),+ head_commit=indexed,+ )++ meta = _meta.build_meta(repository=repository, targets=["src/a.py"])++ assert meta["contract_version"] == _meta.MCP_CONTRACT_VERSION+ assert meta["indexed_commit"] == indexed[:12]+ assert meta["live_head"] == indexed[:12]+ assert meta["index_behind"] is False+++def test_shared_boundary_surfaces_degraded_partial_and_truncated_states():+ payload = {+ "degraded": "no-provider",+ "_meta": {+ "retrieval_degraded": ["vector"],+ "results_partial": True,+ "members_truncated": 2,+ },+ }++ result = _meta.finalize_trust_envelope(payload)++ assert result["_meta"]["state"] == {+ "degraded": True,+ "partial": True,+ "truncated": True,+ }+++def test_persisted_analysis_metadata_omits_unknowns_and_preserves_commits():+ assert _meta.persisted_analysis_meta(None, {}) == {}+ assert _meta.persisted_analysis_meta("2026-08-24T00:00:00Z", {"api": "abc"}) == {+ "analysis_timestamp": "2026-08-24T00:00:00Z",+ "analysis_commits": {"api": "abc"},+ }+++def test_structural_and_generated_evidence_cannot_masquerade_as_runtime_or_source():+ structural = _meta.finalize_trust_envelope({}, evidence_kind="structural")+ generated = _meta.finalize_trust_envelope({}, evidence_kind="generated")++ assert structural["_meta"]["evidence_kind"] == "structural"+ assert structural["_meta"]["runtime_breakage_proven"] is False+ assert generated["_meta"]["evidence_kind"] == "generated"+ assert generated["_meta"]["existing_verified_code"] is False+++def test_every_registered_tool_has_a_valid_tier_and_specialist_trust_kinds():+ from repowise.core.registry import TOOL_TIERS, mcp_tool_registry+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()+ entries = mcp_tool_registry.entries()+ assert entries+ assert {entry.tier for entry in entries} <= TOOL_TIERS+ trust = {entry.name: entry.trust_kind for entry in entries}+ for name in (+ "get_architecture",+ "get_blast_radius",+ "get_dependency_path",+ "get_execution_flows",+ "get_conformance",+ ):+ assert trust[name] == "structural"+ assert trust["generate_refactoring_code"] == "generated"diff --git a/tests/unit/server/test_mcp_tools_router.py b/tests/unit/server/test_mcp_tools_router.pyindex 85f6ec484..111e69e63 100644--- a/tests/unit/server/test_mcp_tools_router.py+++ b/tests/unit/server/test_mcp_tools_router.py@@ -10,7 +10,10 @@ from repowise.server.mcp_server._tool_selection import ()-def test_describe_tool_surface_single_repo(tmp_path):+def test_describe_tool_surface_single_repo(tmp_path, monkeypatch):+ from repowise.server.mcp_server import _tool_selection++ monkeypatch.setattr(_tool_selection, "_is_workspace", lambda _path: False)(tmp_path / ".repowise").mkdir()surface = describe_tool_surface(str(tmp_path))@@ -21,6 +24,10 @@ def test_describe_tool_surface_single_repo(tmp_path):assert {"get_answer", "get_context", "get_blast_radius"} <= namesby_name = {t["name"]: t for t in surface["tools"]}assert by_name["get_answer"]["enabled"] is True+ assert by_name["get_answer"]["tier"] == "canonical"+ assert by_name["list_repos"]["tier"] == "utility"+ assert by_name["list_repos"]["eligible"] is False+ assert by_name["list_repos"]["enabled"] is Falseassert by_name["get_blast_radius"]["requires_workspace"] is Trueassert by_name["get_blast_radius"]["enabled"] is False# Opt-in tools registered but off by default.diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.pyindex 21773c049..5a7c88587 100644--- a/tests/unit/workspace/test_system_graph.py+++ b/tests/unit/workspace/test_system_graph.py@@ -158,7 +158,9 @@ def test_socket_contract_becomes_socket_edge():_provider("api", "socket::/hubs/game", ctype="socket", file="api/hub.cs"),_consumer("unity", "socket::/hubs/game", ctype="socket", file="unity/net.cs"),]- links = [_link("socket::/hubs/game", "api", "api/hub.cs", "unity", "unity/net.cs", ctype="socket")]+ links = [+ _link("socket::/hubs/game", "api", "api/hub.cs", "unity", "unity/net.cs", ctype="socket")+ ]graph = build_system_graph(contracts, links, CrossRepoOverlay(), {})assert graph.edges[0].kind == "socket"@@ -273,7 +275,14 @@ def test_system_graph_json_shape_is_locked():)data = graph.to_dict()- assert set(data) == {"version", "generated_at", "nodes", "edges", "diagnostics"}+ assert set(data) == {+ "version",+ "generated_at",+ "repo_provenance",+ "nodes",+ "edges",+ "diagnostics",+ }assert set(data["nodes"][0]) == {"id","repo",diff --git a/website/mcp-server.md b/website/mcp-server.mdindex 575223533..3d04ef0d7 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -22,7 +22,7 @@ Connect repowise to Claude Code, Codex, Cursor, Cline, or any MCP-compatible edi## Overview-The MCP (Model Context Protocol) server is how repowise talks to AI coding assistants. It registers 17 tools: a curated 11-tool default surface in a single repository (ten flagship tools plus `list_repos`), two additional default tools in workspace mode, and four opt-in tools. Once connected, your editor's AI can query your codebase wiki for synthesized answers, symbols, docs, ownership, file and change-risk signals, code health, and architectural decisions.+The MCP (Model Context Protocol) server is how repowise talks to AI coding assistants. It registers 17 tools: a curated 10-tool default surface in a single repository, `list_repos` added by default in workspace mode, and six opt-in specialists subject to mode eligibility. Once connected, your editor's AI can query your codebase wiki for synthesized answers, symbols, docs, ownership, file and change-risk signals, code health, and architectural decisions.Start the server with: