Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(mcp): payload precision and workflow-first CLAUDE.md (#742)

Raghav Chamadiyafe520e7845ad
diff --git a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
index 880b80228..7cab039c4 100644
--- a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
@@ -157,6 +157,35 @@ async def _generate(
# Workspace generation
# ---------------------------------------------------------------------------
+_MAX_CONTRACT_LINKS = 12
+
+
+def _curate_contract_links(links: list[dict]) -> list[dict]:
+ """Reduce raw contract links to the cross-repo rows worth a CLAUDE.md line.
+
+ Raw links include intra-repo pairs (a repo's own model/migration files
+ "providing" tables its own modules consume) and one row per provider file
+ for the same (contract, consumer) — in a real workspace that rendered 30+
+ near-duplicate ``data::repositories`` rows before the first genuinely
+ cross-repo contract. Keep provider_repo != consumer_repo only, collapse
+ duplicate (contract, consumer) pairs preferring a non-migration provider,
+ and cap the table.
+ """
+ best: dict[tuple, dict] = {}
+ for link in links:
+ if not isinstance(link, dict):
+ continue
+ if link.get("provider_repo") == link.get("consumer_repo"):
+ continue
+ key = (link.get("contract_id"), link.get("consumer_repo"), link.get("consumer_file"))
+ current = best.get(key)
+ is_migration = "alembic/versions/" in (link.get("provider_file") or "")
+ if current is None or (
+ "alembic/versions/" in (current.get("provider_file") or "") and not is_migration
+ ):
+ best[key] = link
+ return list(best.values())[:_MAX_CONTRACT_LINKS]
+
def _generate_workspace(
start_path: Path,
@@ -180,8 +209,7 @@ def _generate_workspace(
ws_root = find_workspace_root(start_path)
if ws_root is None:
raise click.ClickException(
- "No .repowise-workspace.yaml found. "
- "Run 'repowise init <workspace-dir>' first."
+ "No .repowise-workspace.yaml found. Run 'repowise init <workspace-dir>' first."
)
ws_config = WorkspaceConfig.load(ws_root)
@@ -213,7 +241,7 @@ def _generate_workspace(
if contracts_file.exists():
try:
contracts_data = json.loads(contracts_file.read_text(encoding="utf-8"))
- contract_links = contracts_data.get("contract_links", [])
+ contract_links = _curate_contract_links(contracts_data.get("contract_links", []))
# Build counts by type from raw contracts list
for contract in contracts_data.get("contracts", []):
ctype = contract.get("contract_type") or contract.get("type", "unknown")
diff --git a/packages/core/src/repowise/core/exclusion.py b/packages/core/src/repowise/core/exclusion.py
new file mode 100644
index 000000000..593b04e85
--- /dev/null
+++ b/packages/core/src/repowise/core/exclusion.py
@@ -0,0 +1,69 @@
+"""Query-time exclusion: compile a repo's exclude rules and filter rows.
+
+Excluded files are skipped at ingest time, but DB rows may predate an
+``exclude_patterns`` / gitignore change, so read paths (MCP tools, editor-file
+generation) filter again at query time. This module is the single home for
+that logic; ``repowise.server.mcp_server._helpers`` delegates here.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+
+def build_exclude_spec(repo_path: Path | str) -> Any:
+ """Compile the repo's exclusion rules into a PathSpec, or ``None``.
+
+ Unions ``.repowise/config.yaml`` ``exclude_patterns`` with the repo's
+ gitignore stack (``.gitignore`` + ``.git/info/exclude``). Indexes built
+ before the traverser honoured ``info/exclude`` still contain rows for
+ local-only scratch dirs; filtering them at query time keeps those paths
+ out of generated output without forcing a reindex.
+ """
+ import pathspec
+
+ from repowise.core.repo_config import load_repo_config
+
+ patterns = list(load_repo_config(repo_path).get("exclude_patterns") or [])
+ root = Path(repo_path)
+ for ignore_file in (root / ".gitignore", root / ".git" / "info" / "exclude"):
+ try:
+ if ignore_file.exists():
+ patterns.extend(
+ ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()
+ )
+ except OSError:
+ continue
+ if not patterns:
+ return None
+ return pathspec.PathSpec.from_lines("gitwildmatch", patterns)
+
+
+def is_excluded(path: str | None, spec: Any) -> bool:
+ """True if *path* matches *spec* (None spec or path -> not excluded)."""
+ return bool(spec is not None and path and spec.match_file(path))
+
+
+def decision_is_excluded(decision_row: Any, spec: Any) -> bool:
+ """True when a DecisionRecord is anchored entirely in excluded paths.
+
+ Decision mining can predate an exclude_patterns / info-exclude change, so
+ records anchored in vendored trees (a checked-in venv's site-packages, a
+ local-only scratch dir) survive in the DB and would surface as the repo's
+ "top decisions". A record whose affected files are ALL excluded is noise;
+ one with no affected files at all is kept (nothing to judge it by).
+ Paths are normalized to forward slashes — ``affected_files_json`` stores
+ OS-native separators.
+ """
+ if spec is None:
+ return False
+ try:
+ affected = json.loads(getattr(decision_row, "affected_files_json", None) or "[]")
+ except (ValueError, TypeError):
+ return False
+ paths = [p.replace("\\", "/") for p in affected if isinstance(p, str) and p]
+ if not paths:
+ return False
+ return all(is_excluded(p, spec) for p in paths)
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 9f707fdcd..754190cfd 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -10,6 +10,15 @@ from __future__ import annotations
from dataclasses import dataclass, field
+def _render_tool_table() -> str:
+ # Local import: tool_table is a leaf module; importing lazily keeps data.py
+ # free of import-order coupling for the many tests that build these
+ # dataclasses directly.
+ from .tool_table import render_tool_table
+
+ return render_tool_table()
+
+
@dataclass(frozen=True)
class TechStackItem:
name: str
@@ -104,6 +113,9 @@ class EditorFileData:
code_health: CodeHealthBlock | None = None
kg_layers: list[KGLayerSummary] = field(default_factory=list)
kg_tour: list[KGTourStepSummary] = field(default_factory=list)
+ # Rendered MCP tool table (single source: tool_table.py). A data field
+ # rather than a Jinja global so any environment can render the template.
+ tool_table_md: str = field(default_factory=lambda: _render_tool_table())
# ---------------------------------------------------------------------------
@@ -135,3 +147,5 @@ class WorkspaceEditorFileData:
package_deps: list[dict] = field(default_factory=list) # package dep entries
contract_links: list[dict] = field(default_factory=list) # matched contract links
contracts_by_type: dict[str, int] = field(default_factory=dict) # {"http": 5, …}
+ # Rendered MCP tool table (single source: tool_table.py).
+ tool_table_md: str = field(default_factory=lambda: _render_tool_table())
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index b129ebd57..a58f6591f 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -129,7 +129,9 @@ class EditorFileDataFetcher:
modules: list[KeyModule] = []
for page, _pagerank, symbol_count in rows:
purpose = _extract_sentences(page.content or "", max_sentences=1)
- purpose = _truncate_at_word(purpose, 80).rstrip(".") if purpose else ""
+ # 80 chars cut every purpose mid-thought ("…is the **test-layer
+ # ingestion subsystem** for…"); 140 fits one real clause.
+ purpose = _truncate_at_word(purpose, 140).rstrip(".") if purpose else ""
modules.append(
KeyModule(
name=page.target_path,
@@ -200,6 +202,8 @@ class EditorFileDataFetcher:
async def _get_decisions(self) -> list[DecisionSummary]:
"""Active decision records, least-stale first."""
+ from repowise.core.exclusion import build_exclude_spec, decision_is_excluded
+
result = await self._session.execute(
select(DecisionRecord)
.where(
@@ -207,9 +211,14 @@ class EditorFileDataFetcher:
DecisionRecord.status == "active",
)
.order_by(DecisionRecord.staleness_score.asc())
- .limit(_MAX_DECISIONS)
+ # Over-fetch: records anchored entirely in excluded paths (vendored
+ # venvs mined before exclude rules changed) are dropped below.
+ .limit(_MAX_DECISIONS * 3)
)
- records = list(result.scalars().all())
+ exclude_spec = build_exclude_spec(self._repo_path)
+ records = [r for r in result.scalars().all() if not decision_is_excluded(r, exclude_spec)][
+ :_MAX_DECISIONS
+ ]
summaries: list[DecisionSummary] = []
for rec in records:
rationale = (rec.rationale or "").strip()
@@ -489,6 +498,10 @@ def _extract_sentences(text: str, max_sentences: int) -> str:
# Drop list items, table rows, and blockquotes — prose only.
# Both "1." and "1)" enumeration styles count as list items.
text = re.sub(r"^\s*(?:[-*+]\s|\d+[.)]\s|\||>).*$", "", text, flags=re.MULTILINE)
+ # Drop colon-terminated list lead-ins ("Repowise consumes:") — their list
+ # items were just stripped, so keeping them leaves dangling fragments in
+ # the rendered CLAUDE.md.
+ text = re.sub(r"^.*:\s*$", "", text, flags=re.MULTILINE)
text = re.sub(r"`([^`]+)`", r"\1", text) # strip backticks, keep text
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) # links → text
text = re.sub(r"\n{2,}", "\n", text).strip()
diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
new file mode 100644
index 000000000..b529b677c
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
@@ -0,0 +1,85 @@
+"""Single source for the agent-facing MCP tool table.
+
+Rendered into CLAUDE.md / AGENTS.md by the editor-file templates. Keyed by
+tool name so a drift test can assert every row names a registered MCP tool
+(and every default-surface tool has a row) — the table used to be hand-edited
+prose in the template and silently drifted from the live registry.
+
+Row style: one entry per tool, 1-3 sentences, leading with when to call it.
+The load-bearing response fields (symbol_bodies, verified, continuation,
+directive, search_method) stay named — they are what the trust protocol keys
+on. Reference detail lives in docs/MCP_TOOLS.md, not here.
+"""
+
+from __future__ import annotations
+
+# Tool name -> (signature shown in the table, agent-facing row text).
+TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
+ "get_answer": (
+ "get_answer(question)",
+ 'First call for any how / where / why question. `confidence: "high"` or '
+ '`grounding: "extracted"` is content-grounded — cite it directly. When the '
+ "question names an indexed symbol, `symbol_bodies` carries its full live body "
+ "(skip the `get_symbol` follow-up). Low confidence returns `best_guesses` with "
+ "one-line justifications plus `code_rationale` (rationale comments mined live "
+ "from candidate source).",
+ ),
+ "get_context": (
+ "get_context(targets=[...])",
+ "Triage card for files/modules/symbols: summary, signatures, `symbol_id`s, "
+ "`hotspot` bit. File targets auto-serve a `verified` skeleton (every signature "
+ "at a fraction of a full Read); `mostly_full` marks files where Read costs "
+ "little more. Batch targets in one call. Opt-in blocks: "
+ '`include=["callers"|"callees"|"ownership"|"decisions"|"metrics"]`.',
+ ),
+ "get_symbol": (
+ "get_symbol(id)",
+ 'One verified body: `"path.py::Name"` (indexed symbol), `"path.py:140-180"` '
+ '(live range read), or `"repowise#<hex>"` (omission ref). `verified: true` '
+ "means no follow-up Read; `truncated` responses carry a `continuation` naming "
+ "the exact next range. Index misses fall back to live-grep `fallback_lines`.",
+ ),
+ "search_codebase": (
+ "search_codebase(query)",
+ "Hybrid search, auto-routed by query shape: identifier → symbol hits (pipe "
+ "`symbol_id` into `get_symbol`), path → file pages, prose → wiki-semantic. "
+ "Force with `mode=symbol|path|concept|hybrid`. Verify concept hits carrying "
+ '`search_method: "bm25"`.',
+ ),
+ "get_why": (
+ "get_why(query, targets?)",
+ "Why the code is shaped this way: decision records with evidence and "
+ "supersession lineage, falling back to git archaeology and `code_rationale` "
+ "comments. Call before refactors or pattern divergences.",
+ ),
+ "get_risk": (
+ "get_risk(targets, changed_files?)",
+ "What history says about touching these files: churn, owners, co-change "
+ "partners, blast radius. PR mode (`changed_files`) leads with a `directive` "
+ "block — read `will_break` / `missing_cochanges` / `missing_tests` first.",
+ ),
+ "get_health": (
+ "get_health(targets?, include?)",
+ "Health scores + findings on three dimensions (defect / maintainability / "
+ "performance). Self-check the files you touched before finishing; "
+ '`include=["biomarkers"|"refactoring"|"signals"]` for depth.',
+ ),
+ "get_dead_code": (
+ "get_dead_code()",
+ "Confidence-tiered unreachable files / unused exports / zombie packages. For "
+ "cleanup sweeps, not targeted fixes.",
+ ),
+ "get_overview": (
+ "get_overview()",
+ "Architecture map + tool recipes. Call once, first, in an unfamiliar repo; "
+ "skip it after that.",
+ ),
+}
+
+
+def render_tool_table() -> str:
+ """Markdown table of the tool rows, in the dict's curated order."""
+ lines = ["| Tool | When and why |", "|------|--------------|"]
+ for signature, row in TOOL_TABLE_ROWS.values():
+ lines.append(f"| `{signature}` | {row} |")
+ return "\n".join(lines)
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index 3ea64229e..75909c529 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -1,157 +1,85 @@
-## IMPORTANT: Codebase Intelligence Instructions for {{ data.repo_name }}
+## Codebase Intelligence for {{ data.repo_name }} (Repowise)
-> This repository is indexed by [Repowise](https://repowise.dev).
-> Use the MCP tools below for orientation, discovery, and enriched context
-> (documentation, ownership, history, decisions). **Always verify against
-> actual source files before making changes** — the index may be stale.
+Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
-Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
+The MCP tools below serve pre-verified docs, symbols, history, and health from that index. Every response carries `_meta` freshness fields; a `stale_warning` appears only when a file the response actually serves changed after indexing — silence means current.
+### How to work in this repo
+
+- **Pre-edit phase** (locate, understand, assess) is where these tools win: `get_answer` for how/where/why, `search_codebase` to find, `get_context` for a file's map, `get_risk` before touching a hotspot.
+- **Edit phase**: Claude Code requires a raw Read of any file you will Edit — that Read is correct and expected. Use the tools to decide *which* files to read and edit, not to replace the edit-target Read.
+- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first compact output. A `[repowise#<ref>: N lines omitted]` marker is fully recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.
+
+### Trust protocol
+
+- `verified: true` → the served bytes were checked against the live tree. Never follow it with a Read of the same lines.
+- `get_answer` at `confidence: "high"` or `grounding: "extracted"` is content-grounded: cite it directly. `symbol_bodies`, `quotes`, and `code_rationale` entries are live source — use them instead of opening the file.
+- The **only** re-read triggers: `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, `confidence: "low"`. `index_behind: true` alone is informational — the served content is unaffected by the drift.
+- Not valid reasons to re-read: "just to be safe", "to see full context" (use the skeleton or a range read), "the file might have changed" (`verified` already checked).
+- For exhaustive literal sweeps (rename every call site) plain `Grep` is unbeatable — use it. Reach for `get_context(include=["callers"])` when you need the `callers_total`/`callers_truncated` honesty signal instead of a maybe-incomplete grep.
+
+### Tools
+
+{{ data.tool_table_md }}
+
+**Compose them:** low-confidence `get_answer` → Read `best_guesses[0].file`; `get_context` shows `hotspot: true` → `get_risk` before editing; `decision_records` titles → `get_why(targets=[...])`; PR review → `get_risk(targets, changed_files)` and read `directive` first. A `tombstone` error means the file moved — follow `successor_paths`.
{% if data.architecture_summary %}
+
### Architecture
{{ data.architecture_summary }}
{% endif %}
{% if data.key_modules %}
-### Key Modules
-{% set module_owners = data.key_modules | selectattr("owner") | list %}
-{% if module_owners %}
-| Module | Purpose | Owner |
-|--------|---------|-------|
-{% for mod in data.key_modules %}
-| `{{ mod.name }}` | {{ mod.purpose or "—" }} | {{ mod.owner or "—" }} |
-{% endfor %}
-{% else %}
-| Module | Purpose |
-|--------|---------|
+
+### Key modules
{% for mod in data.key_modules %}
-| `{{ mod.name }}` | {{ mod.purpose or "—" }} |
+- `{{ mod.name }}`{% if mod.purpose %} — {{ mod.purpose }}{% endif %}
+
{% endfor %}
{% endif %}
-{% endif %}
{% if data.entry_points %}
-### Entry Points
-{% for ep in data.entry_points %}
-- `{{ ep }}`
-{% endfor %}
-{% endif %}
-{% if data.tech_stack %}
-### Tech Stack
-{% set langs = data.tech_stack | selectattr("category", "eq", "language") | list %}
-{% set frameworks = data.tech_stack | selectattr("category", "eq", "framework") | list %}
-{% set infra = data.tech_stack | selectattr("category", "eq", "infra") | list %}
-{% set dbs = data.tech_stack | selectattr("category", "eq", "database") | list %}
-{% if langs %}**Languages:** {{ langs | map(attribute="name") | join(", ") }}{% endif %}
-
-{% if frameworks %}**Frameworks:** {{ frameworks | map(attribute="name") | join(", ") }}{% endif %}
-
-{% if dbs %}**Databases:** {{ dbs | map(attribute="name") | join(", ") }}{% endif %}
-
-{% if infra %}**Infra:** {{ infra | map(attribute="name") | join(", ") }}{% endif %}
-{% endif %}
-{% if data.kg_layers %}
-### Architectural Layers
-| Layer | Files | Purpose |
-|-------|-------|---------|
-{% for layer in data.kg_layers[:10] %}
-| {{ layer.name }} | {{ layer.file_count }} | {{ layer.description[:80] }} |
-{% endfor %}
-{% if data.kg_tour %}
-
-### Guided Tour ({{ data.kg_tour | length }} steps)
-{% for step in data.kg_tour[:6] %}
-{{ step.order }}. `{{ step.primary_file or step.title }}`{% if step.reason %} — {{ step.reason }}{% endif %}
+### Entry points
+{% for ep in data.entry_points[:6] %}
+- `{{ ep }}`
{% endfor %}
-{% if data.kg_tour | length > 6 %}
-... and {{ data.kg_tour | length - 6 }} more steps
-{% endif %}
-{% endif %}
{% endif %}
{% if data.hotspots %}
-### Hotspots (High Churn)
-| File | Churn | 90d Commits | Owner |
-|------|-------|-------------|-------|
+
+### Hotspots (high churn — check `get_risk` before editing)
{% for h in data.hotspots %}
-| `{{ h.path }}` | {{ h.churn_percentile }}th %ile | {{ h.commit_count_90d }} | {{ h.owner or "—" }} |
+- `{{ h.path }}` — {{ h.commit_count_90d }} commits/90d ({{ h.churn_percentile }}th %ile)
{% endfor %}
{% endif %}
{% if data.code_health %}
-## Code health
-Three signals: **defect risk** (the overall score), **maintainability** (smells that hurt readability/change-cost without predicting bugs), and **performance** (static performance RISK: I/O-in-loop / N+1 shapes that waste work, high-precision/low-recall). Maintainability and performance are co-equal views, never blended into the defect headline. See `docs/CODE_HEALTH.md`.
-
-Defect risk, Hotspot health: {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}) ·
-Average: {{ data.code_health.average_health }}/10 ·
-Worst: {{ data.code_health.worst_score }}/10 (`{{ data.code_health.worst_path }}`)
-{% if data.code_health.maintainability_average is not none %}
-Maintainability, Average: {{ data.code_health.maintainability_average }}/10
-{% endif %}
-{% if data.code_health.performance_average is not none %}
-Performance risk: {{ data.code_health.performance_findings }} open finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% if data.code_health.performance_findings_density is not none %} ({{ data.code_health.performance_findings_density }} per 10K covered LOC){% endif %} · Average: {{ data.code_health.performance_average }}/10 (a bounded [9,10] summary of the findings, not a verification claim)
-{% if data.code_health.performance_coverage_pct is not none %}
-Performance coverage: perf detectors ran on {{ data.code_health.performance_coverage_pct }}% of analyzed code lines{% if data.code_health.performance_skipped_files %}; {{ data.code_health.performance_skipped_files }} file(s) skipped in unsupported languages ({% for lang, n in data.code_health.performance_unsupported_languages[:3] %}{{ lang }}×{{ n }}{% if not loop.last %}, {% endif %}{% endfor %}){% endif %}
-{% endif %}
-Performance scope: static RISK detection (I/O-in-loop / N+1, resource-in-loop, regex/defer-in-loop, blocking-in-async); high-precision, low-recall. Does NOT cover algorithmic blowups, GC/memory pressure, or ORM lazy-load N+1. Full list: `get_health(include=["biomarkers","performance"])`.
-{% endif %}
+### Code health
+Three co-equal signals: defect risk {{ data.code_health.average_health }}/10 avg, hotspot health {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}), worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
{% if data.code_health.critical_biomarkers %}
-### Critical biomarkers
+Critical files:
{% for b in data.code_health.critical_biomarkers %}
- `{{ b.path }}` — {{ b.summary }}
{% endfor %}
{% endif %}
{% if data.code_health.untested_hotspots %}
-### Untested hotspots
+Untested hotspots:
{% for h in data.code_health.untested_hotspots %}
- `{{ h.path }}` — {{ h.dependents }} dependents, {{ h.coverage_pct }}% coverage, {{ h.commits_90d }} commits/90d
{% endfor %}
{% endif %}
{% endif %}
+{% if data.decisions %}
+
+### Standing decisions (ask `get_why` before diverging)
+{% for d in data.decisions[:3] %}
+- {{ d.title }}{% if d.rationale %} — {{ d.rationale }}{% endif %}
-### Repowise MCP Tools
-
-This repo has the Repowise MCP server configured. The tools below answer questions `grep`/`Read` cannot. Every response carries an `_meta` envelope with `index_age_days`, `indexed_commit`, and a `stale_warning` only when the index has actually diverged from HEAD — silence means the index is current.
-
-**When to call which tool:**
-
-| Tool | What only this tool answers |
-|------|------------------------------|
-| `get_answer(question)` | Synthesised answer with citations and a content-grounded `confidence`. First call for "how does X work" / "where is Y" / "why is Z" — and the one-shot for "explain function/method/class X": when the question names an indexed symbol, get_answer anchors its defining file (even when fuzzy retrieval would miss it) and returns the symbol's full live body in `symbol_bodies` — read that instead of a `get_symbol` follow-up. Value questions may return `grounding: "extracted"` (verbatim source line). On low confidence returns `best_guesses` with one-line justifications, plus `code_rationale` (rationale comments mined live from the candidate source) when the "why" lives in a code comment the wiki never captured. |
-| `get_context(targets=[...])` | Triage card for files/modules/symbols — title, summary, signatures, `hotspot` bit, `decision_records` titles, `symbol_id`s. File targets auto-upgrade to a `verified` skeleton (every signature, ~37% of a full Read). `include=["callers"]` works on file targets too (import + call rollup). |
-| `get_symbol(...)` | Source bytes with live-verified bounds. Three forms: `"path.py::Name"` (indexed symbol), `"path.py:140-180"` (live range read, ≤200 lines), `"repowise#<hex>"` (omission ref). Index misses return `fallback_lines` from a live grep instead of a dead end. |
-| `search_codebase(query, mode?, kind?, symbol_kind?)` | Hybrid code search. `mode="auto"` (default) routes by query shape: an identifier → indexed symbol hits (`symbol_id`/`file`/line bounds — pipe into `get_symbol`), a path → file pages (pipe into `get_context`), prose → wiki-semantic search, mixed → hybrid (symbols first). Force a branch with `mode=symbol\|path\|concept\|hybrid`. Concept hits carry `search_method` (`embedding` vs `bm25` fallback); decision records rank below file pages unless the query is why-shaped. |
-| `get_why(query, targets?)` | Architectural decision archaeology — *why* the code is shaped this way. Call before refactors or pattern divergences. Falls back to git archaeology when no ADRs exist for a file, and to `code_rationale` (rationale comments mined from the source) when neither decisions nor git history explain it. |
-| `get_risk(targets, changed_files?)` | What history says about touching these files: churn, owners, blast radius. Pass `changed_files` for PR mode → returns a `directive` (`will_break`, `missing_cochanges`, `missing_tests`). |
-| `get_health(targets?, include?)` | Code-health scores + biomarker findings (defect / maintainability / performance pillars). Self-check before a PR — read the same signals the merge-gate judges your change on. Default is lean; opt in with `include`: `["accuracy"]` (does the score rank the buggy files first — precision@K + `lift`), `["signals"]` (per-file prior-defects / churn / owners / degree, targeted mode), `["churn_complexity"]` (volatile-and-complex danger-zone files), `["biomarkers"]` (all findings), and a dimension name `["performance"]` / `["defect"]` / `["maintainability"]` to filter findings to one pillar. |
-| `get_dead_code(...)` | Tiered unreachable / unused-export / zombie-package findings. Run before a cleanup sprint, not before a targeted fix. |
-| `get_overview(repo?)` | Architecture map + `tool_guide` recipes. One-time orientation; skip on subsequent calls in the same session. |
-
-**Trust protocol — when a response replaces reading the source:**
-- `verified: true` on any response means the served content was checked against the live working tree. **Never follow a verified response with a Read of the same lines** — you would be paying twice for identical bytes.
-- `get_answer` with `confidence: "high"` or `grounding: "extracted"` is content-grounded (asserted values were verified against retrieved source; ≥1 citation is source-backed). Cite it directly. `quotes` entries `{path, lines, quote}` are verbatim live source — quote them instead of re-reading. `symbol_bodies` entries `{path, name, lines, source}` are the full live body of a named definition — read that body, do not call `get_symbol` for the same symbol (a `continuation` token names the next range if it was truncated).
-- `code_rationale` entries `{path, lines, comment}` (on a low-confidence `get_answer` or a fallen-back `get_why`) are rationale comments read live from the source. When the "why" you asked for is a code comment rather than an ADR, the comment is right there: cite it instead of opening the file to hunt for it.
-- Reading code: `get_context` skeleton first (~37% of a full Read), then `get_symbol` for bodies, `"path.py:a-b"` range reads for anything between symbols. Raw `Read` is for files the index marks `mostly_full` or cannot serve. On a **large file** `get_symbol("path::Name")` is the win — it serves one verified body instead of pulling the whole file into context.
-- The **only** re-read triggers: `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, or `confidence: "low"`/`retrieval_quality: "weak"`.
-- Disallowed rationalizations for extra reads: "just to be safe", "to double-check the tool", "to see the full context" (use the skeleton / a range read), "the file might have changed" (that is what `verified` already checked).
-- When a plain `Grep` is the right tool, use it: an exhaustive literal-token sweep (rename every call site, find all occurrences) is one grep and unbeatable on cost. MCP's edge there is not fewer tokens — it is the `callers_total`/`callers_truncated` honesty signal that tells you whether a list is complete; reach for `get_context(include=["callers"])` when silent incompleteness would bite.
-
-**Composition tips:**
-- `get_answer` → if `confidence` is `medium`/`low`, follow `best_guesses[0].file` or `fallback_targets[0]` into `get_context`, then `get_symbol` for bytes.
-- `get_context` returns `decision_records` titles → `get_why(targets=[...])` for the rationale; `hotspot: true` → `get_risk` before editing.
-- PR review → `get_risk(targets=[...], changed_files=[...])`; read the `directive` block first.
-- A `tombstone` error means the file was deleted/renamed since indexing — follow `successor_paths`.
-
-### Output Distillation
-
-- Prefer `repowise distill <cmd>` for noisy commands — test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.
-- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved — run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.
-- Never re-run a command to see omitted output; expand the marker instead.
-- For structure-level questions about a large indexed file ("what's in here", "which function handles X"), `get_context(["path"], include=["skeleton"])` returns the file with bodies elided — every signature plus the bodies of the most central symbols — at a fraction of the cost of a full Read.
+{% endfor %}
+{% endif %}
{% if data.build_commands %}
-### Codebase Conventions
-**Commands:**
+### Commands
{% for label, cmd in data.build_commands.items() %}
- {{ label | capitalize }}: `{{ cmd }}`
{% endfor %}
diff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
index bbddcf2c9..371888adb 100644
--- a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
@@ -40,38 +40,24 @@ Files that frequently change together across repos — consider reviewing both w
{% endfor %}
{% endif %}
+{% set repos_with_eps = data.repos | selectattr("entry_points") | list %}
+{% if repos_with_eps %}
### Per-Repo Entry Points
-{% for r in data.repos %}
+{% for r in repos_with_eps %}
#### `{{ r.alias }}`{% if r.alias == data.default_repo %} (default){% elif r.is_primary %} (primary){% endif %}
-{% if r.entry_points %}
{% for ep in r.entry_points %}
- `{{ ep }}`
{% endfor %}
-{% else %}
-_No entry points indexed._
-{% endif %}
{% endfor %}
+{% endif %}
### Repowise MCP Tools
-These tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default repo. Every response carries `_meta` with `index_age_days`, `indexed_commit`, and a `stale_warning` only when the index has diverged from HEAD.
+These tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default repo. Every response carries `_meta` freshness fields; a `stale_warning` appears only when a file the response actually serves changed after indexing — silence means current.
-| Tool | What only this tool answers |
-|------|------------------------------|
-| `get_answer(question)` | Synthesised answer with verified citations and a calibrated `retrieval_quality`. First call for "how does X work" / "why is Y like this". On low confidence returns `best_guesses` with one-line justifications. |
-| `get_context(targets=[...])` | Triage card for files/modules/symbols — title, summary, signatures, `hotspot` bit, `decision_records` titles, and `symbol_id`s to pipe into `get_symbol`. Use `include=[...]` to widen. NOT for source bytes. |
-| `get_symbol("path/to/file.py::Name")` | Raw source bytes for one indexed symbol with exact line bounds. Cheaper than `Read` + offset math. |
-| `search_codebase(query, mode?, kind?, symbol_kind?)` | Hybrid code search. `mode="auto"` routes by query shape: identifier → indexed symbol hits (pipe `symbol_id` into `get_symbol`), path → file pages (`get_context`), prose → semantic search. Force with `mode=symbol\|path\|concept\|hybrid`. Concept hits tag `search_method` (`embedding` vs `bm25`). |
-| `get_why(query, targets?)` | Architectural decision archaeology — *why* the code is shaped this way. Call before refactors. Falls back to git archaeology when no ADRs exist. |
-| `get_risk(targets, changed_files?)` | What history says about touching these files. Pass `changed_files` for PR mode → returns a `directive` (`will_break`, `missing_cochanges`, `missing_tests`) plus cross-repo blast radius. |
-| `get_health(targets?, include?)` | Code-health scores + biomarker findings (defect / maintainability / performance). Self-check before a PR. Lean by default; opt in via `include`: `["accuracy"]` (precision@K + `lift`), `["signals"]` (per-file prior-defects / churn / owners / degree), `["churn_complexity"]` (danger-zone files), `["biomarkers"]` (all findings), or a dimension name `["performance"]` / `["defect"]` / `["maintainability"]` to filter findings to one pillar. |
-| `get_dead_code(...)` | Tiered unreachable / unused-export / zombie-package findings; cross-repo consumer detection lowers confidence on shared exports. |
-| `get_overview(repo?)` | Architecture map. `repo="all"` returns cross-repo topology (co-changes, package deps, API contracts). |
+{{ data.tool_table_md }}
-**Composition tips:**
-- `get_answer` → on `confidence: medium/low`, follow `best_guesses[0].file` into `get_context`, then `get_symbol` for bytes.
-- `get_context` returns `hotspot: true` → call `get_risk` before editing.
-- PR review across repos → `get_risk(changed_files=[...])` picks up cross-repo consumers automatically.
+**Workspace-specific:** `get_overview(repo="all")` returns cross-repo topology (co-changes, package deps, API contracts); `get_risk(changed_files=[...])` picks up cross-repo consumers automatically; `get_blast_radius` / `get_conformance` / `get_architecture` cover cross-repo impact, dependency-rule violations, and coupling.
-**Verify when:** `_meta.stale_warning` is present, `retrieval_quality` is `partial`/`weak`, or `search_method` is `bm25`. Otherwise trust the response.
+**Verify when:** `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"`, or `confidence: "low"`. `index_behind: true` alone is informational — the served content is unaffected. Otherwise trust the response.
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 0033f5553..b540bad89 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -496,38 +496,17 @@ def _compute_alignment(
def _get_exclude_spec(repo_path: "Path | str") -> "Any":
- """Compile the repo's exclusion rules into a PathSpec, or None.
+ """Compile the repo's exclusion rules into a PathSpec, or None."""
+ from repowise.core.exclusion import build_exclude_spec
- Unions ``.repowise/config.yaml`` ``exclude_patterns`` with the repo's
- gitignore stack (``.gitignore`` + ``.git/info/exclude``). Indexes built
- before the traverser honoured ``info/exclude`` still contain rows for
- local-only scratch dirs; filtering them at query time keeps those paths
- out of tool responses without forcing a reindex.
- """
- from pathlib import Path
-
- import pathspec
-
- from repowise.core.repo_config import load_repo_config
-
- patterns = list(load_repo_config(repo_path).get("exclude_patterns") or [])
- root = Path(repo_path)
- for ignore_file in (root / ".gitignore", root / ".git" / "info" / "exclude"):
- try:
- if ignore_file.exists():
- patterns.extend(
- ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()
- )
- except OSError:
- continue
- if not patterns:
- return None
- return pathspec.PathSpec.from_lines("gitwildmatch", patterns)
+ return build_exclude_spec(repo_path)
def is_excluded(path: "str | None", spec: "Any") -> bool:
"""True if *path* matches *spec* (None spec or path -> not excluded)."""
- return bool(spec is not None and path and spec.match_file(path))
+ from repowise.core.exclusion import is_excluded as _core_is_excluded
+
+ return _core_is_excluded(path, spec)
def filter_rows_by_attr(rows: list, attr: str, spec: "Any") -> list:
@@ -557,6 +536,13 @@ def filter_dicts_by_key(items: list, key: str, spec: "Any") -> list:
return [d for d in items if not is_excluded(d.get(key), spec)]
+def decision_is_excluded(decision_row: "Any", spec: "Any") -> bool:
+ """True when a DecisionRecord is anchored entirely in excluded paths."""
+ from repowise.core.exclusion import decision_is_excluded as _core_decision_is_excluded
+
+ return _core_decision_is_excluded(decision_row, spec)
+
+
def filter_path_list(paths: "list | None", spec: "Any") -> list:
"""Shape D: filter a list of path strings (None -> [])."""
if not paths:
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 4f8ba8b7b..2895b69e5 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -113,7 +113,88 @@ def resolve_indexed_commit(head_commit: str | None, local_path: str | None) -> s
return read_state_sync_commit(local_path) or head_commit
-def freshness_from_repo(repository: Any | None) -> dict[str, Any]:
+# (local_path, indexed_sha, live_sha) -> files changed between the two commits,
+# or None when git couldn't answer (unknown SHA after a rebase, no git, timeout).
+# One git spawn per SHA pair per process; every later response reuses the set.
+_changed_files_cache: dict[tuple[str, str, str], frozenset[str] | None] = {}
+_CHANGED_FILES_CACHE_MAX = 32
+
+
+def _changed_files_between(
+ local_path: str, indexed_full: str, live_full: str
+) -> frozenset[str] | None:
+ """Files that differ between the indexed commit and live HEAD, cached.
+
+ Returns ``None`` (not an empty set) whenever git can't answer, so callers
+ fall back to the repo-level warning instead of falsely reporting the
+ served targets as unaffected.
+ """
+ key = (local_path, indexed_full, live_full)
+ if key in _changed_files_cache:
+ return _changed_files_cache[key]
+ changed: frozenset[str] | None = None
+ try:
+ import subprocess
+
+ # stdin=DEVNULL + captured stdout/stderr: on stdio transport a child
+ # that inherits the JSON-RPC pipe handles can wedge the session (same
+ # failure mode as the get_answer git-grep hang).
+ res = subprocess.run(
+ [
+ "git",
+ "-C",
+ local_path,
+ "--no-pager",
+ "diff",
+ "--name-only",
+ indexed_full,
+ live_full,
+ ],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=3,
+ stdin=subprocess.DEVNULL,
+ )
+ if res.returncode == 0:
+ changed = frozenset(
+ line.strip().replace("\\", "/") for line in res.stdout.splitlines() if line.strip()
+ )
+ except Exception:
+ changed = None
+ if len(_changed_files_cache) >= _CHANGED_FILES_CACHE_MAX:
+ _changed_files_cache.clear()
+ _changed_files_cache[key] = changed
+ return changed
+
+
+def _normalize_target_path(target: str) -> str:
+ """Reduce a tool target to a repo-relative slash path for intersection."""
+ path = target.replace("\\", "/").strip()
+ # "path.py::Symbol" and "path.py:140-180" both reduce to the file path.
+ if "::" in path:
+ path = path.split("::", 1)[0]
+ elif ":" in path and path.rsplit(":", 1)[-1].replace("-", "").isdigit():
+ path = path.rsplit(":", 1)[0]
+ return path.removeprefix("./").rstrip("/")
+
+
+def targets_hit_by_changes(targets: list[str], changed: frozenset[str]) -> bool:
+ """True when any served target (file, symbol, or module dir) changed."""
+ for raw in targets:
+ path = _normalize_target_path(raw)
+ if not path:
+ continue
+ if path in changed:
+ return True
+ prefix = path + "/"
+ if any(f.startswith(prefix) for f in changed):
+ return True
+ return False
+
+
+def freshness_from_repo(repository: Any | None, targets: list[str] | None = None) -> dict[str, Any]:
"""Return a minimal freshness dict for the given Repository row.
Calibrated to fire ``stale_warning`` rarely so the agent keeps trusting
@@ -127,13 +208,25 @@ def freshness_from_repo(repository: Any | None) -> dict[str, Any]:
days; under that, just emit ``index_age_days`` for the agent to
consult on its own terms.
+ Pass ``targets`` (the file/symbol/module paths this response actually
+ serves) to scope the mismatch signal: when HEAD has moved but none of the
+ served targets changed between the indexed commit and live HEAD, the
+ response carries ``index_behind: true`` instead of ``stale_warning``.
+ "Silence means current" only trains trust if the warning fires only when
+ the served content is actually affected — a repo-wide warning after every
+ unrelated commit teaches the agent to ignore the field. ``targets=None``
+ (repo-level tools like get_overview) keeps the repo-level warning;
+ ``targets=[]`` means "no file content served" and never warns.
+
Always-emitted fields:
* ``index_age_days`` — informational, never a directive
* ``indexed_commit`` — short SHA the index was built against
Conditionally emitted:
* ``live_head`` — only when it differs from the indexed commit
- * ``stale_warning`` — only on a real signal (HEAD mismatch OR very old)
+ * ``stale_warning`` — only on a real signal (a served target changed,
+ HEAD mismatch on a repo-level response, OR very old with no git)
+ * ``index_behind`` — HEAD moved but no served target is affected
Defensive throughout: any missing piece is dropped rather than raised so
an upstream change to the Repository model can never poison a tool result.
@@ -163,9 +256,23 @@ def freshness_from_repo(repository: Any | None) -> dict[str, Any]:
if live_full and indexed_full:
if live_full != indexed_full:
out["live_head"] = live_full[:12]
- # The two SHAs are already in ``indexed_commit`` / ``live_head`` —
- # don't repeat them in prose. Just the directive.
- out["stale_warning"] = "Index is behind live HEAD — run `repowise update`."
+ changed = (
+ _changed_files_between(local_path, indexed_full, live_full)
+ if targets is not None and local_path
+ else None
+ )
+ if targets is not None and changed is not None:
+ if targets_hit_by_changes(targets, changed):
+ out["stale_warning"] = (
+ "A file this response serves changed after indexing — "
+ "verify against source or run `repowise update`."
+ )
+ else:
+ out["index_behind"] = True
+ else:
+ # The two SHAs are already in ``indexed_commit`` / ``live_head`` —
+ # don't repeat them in prose. Just the directive.
+ out["stale_warning"] = "Index is behind live HEAD — run `repowise update`."
# Match: deliberately emit nothing extra. Silence is the signal.
elif live_full is None and age_days is not None and age_days > _STALE_AGE_FLOOR_DAYS:
# No git signal available and the index is genuinely old.
@@ -176,6 +283,7 @@ def freshness_from_repo(repository: Any | None) -> dict[str, Any]:
return out
+
# Question patterns where narrative wiki context wins over symbol-body slicing.
# Used to suppress "use get_symbol" hints — those questions need surrounding prose.
_EXPLAIN_TOKENS = (
@@ -215,6 +323,7 @@ def build_meta(
hint: str | None = None,
cached: bool = False,
repository: Any | None = None,
+ targets: list[str] | None = None,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Construct a `_meta` envelope. All fields optional, omitted if falsy.
@@ -222,7 +331,9 @@ def build_meta(
Pass ``repository`` to auto-inject freshness fields (``index_age_days``,
``indexed_commit``, optional ``stale_warning``). Every MCP response should
carry these so an agent can detect drift between the index and live HEAD
- without an extra round-trip.
+ without an extra round-trip. Pass ``targets`` (the paths this response
+ serves) to scope ``stale_warning`` to actually-affected content — see
+ :func:`freshness_from_repo`.
Stable shape:
{
@@ -243,7 +354,7 @@ def build_meta(
if cached:
out["cached"] = True
if repository is not None:
- out.update(freshness_from_repo(repository))
+ out.update(freshness_from_repo(repository, targets=targets))
out.update(_embedder_meta())
if extra:
out.update(extra)
@@ -303,10 +414,7 @@ def answer_hint(confidence: str, retrieval_count: int) -> str | None:
"trust the answer" — that's the over-trust failure mode.
"""
if confidence == "low":
- return (
- "Low confidence — Read the listed fallback_targets to verify "
- "before answering."
- )
+ return "Low confidence — Read the listed fallback_targets to verify before answering."
if retrieval_count == 0:
return "No wiki hits — fall back to search_codebase or Grep."
return None
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.py
index e4e259511..bd18f1b82 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
@@ -209,10 +209,7 @@ def _drop_already_surfaced(rationale: list[dict], *surfaced: list[dict]) -> list
path
and isinstance(lines, (list, tuple))
and len(lines) == 2
- and any(
- p == path and not (lines[1] < s or lines[0] > e)
- for p, s, e in occupied
- )
+ and any(p == path and not (lines[1] < s or lines[0] > e) for p, s, e in occupied)
):
continue
kept.append(r)
@@ -346,6 +343,7 @@ async def get_answer(
len(payload.get("retrieval", [])),
),
repository=repository,
+ targets=[p for p in cached_paths if isinstance(p, str) and p],
)
return payload
@@ -438,6 +436,7 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint("low", 0),
repository=repository,
+ targets=[],
),
}
@@ -501,7 +500,7 @@ async def get_answer(
else "Fall back to search_codebase or Grep."
),
"fallback_targets": fallback_targets,
- "retrieval": _serialize_hits(hits, limit=_GATED_RETURN_HITS),
+ "retrieval": _serialize_hits(hits, limit=_GATED_RETURN_HITS, lean_symbols=True),
"note": (
"Multiple plausible candidates — synthesis skipped to "
"avoid anchoring on a wrong frame. Each best_guess entry "
@@ -518,6 +517,7 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint("low", len(hits)),
repository=repository,
+ targets=fallback_targets,
)
return gated
@@ -563,6 +563,7 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint("high", len(hits)),
repository=repository,
+ targets=[extraction["file"], *fallback_targets],
),
}
@@ -585,6 +586,7 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint("low", len(hits)),
repository=repository,
+ targets=fallback_targets,
),
}
@@ -632,6 +634,7 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint("low", len(hits)),
repository=repository,
+ targets=fallback_targets,
),
}
@@ -940,11 +943,7 @@ async def get_answer(
"retrieved excerpt — the 'why' may be conflated with a different "
"mechanism. Downgraded to medium; verify against "
f"{fallback_targets[0] if fallback_targets else 'the cited source'}"
- + (
- " or the code_rationale comments below."
- if code_rationale
- else "."
- )
+ + (" or the code_rationale comments below." if code_rationale else ".")
)
payload["next_action_hint"] = (
f"Verify the rationale before citing: the asserted frame term(s) "
@@ -964,15 +963,9 @@ async def get_answer(
# and the literal rationale is the comment we already mined. Surface it so
# the win is the answer AND the cited comment in one call (no re-read),
# unless a gate above already attached code_rationale.
- if "code_rationale" not in payload and any(
- h.get("_concept_anchored") for h in hits
- ):
- concept_rationale = _gather_code_rationale(
- ctx, hits, fallback_targets, question
- )
- concept_rationale = _drop_already_surfaced(
- concept_rationale, symbol_bodies, quotes
- )
+ if "code_rationale" not in payload and any(h.get("_concept_anchored") for h in hits):
+ concept_rationale = _gather_code_rationale(ctx, hits, fallback_targets, question)
+ concept_rationale = _drop_already_surfaced(concept_rationale, symbol_bodies, quotes)
if concept_rationale:
payload["code_rationale"] = concept_rationale
@@ -1014,5 +1007,6 @@ async def get_answer(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_answer_hint(confidence, len(hits)),
repository=repository,
+ targets=[*citations, *fallback_targets],
)
return payload
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
index eb17fcb1f..ff59b628d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
@@ -35,6 +35,7 @@ def serialize_hits(
limit: int | None = None,
summary_chars: int | None = None,
symbols_for_expanded: bool = True,
+ lean_symbols: bool = False,
) -> list[dict]:
"""Agent-facing view of retrieval hits — content only, no plumbing.
@@ -47,7 +48,11 @@ def serialize_hits(
``summary_chars`` truncates summaries (medium-confidence diet);
``symbols_for_expanded=False`` drops symbol enrichment from hits that
only entered via 1-hop graph expansion (they are routing material, not
- answer material).
+ answer material). ``lean_symbols=True`` keeps each symbol pipeable
+ (name/kind/signature/lines) but drops docstrings and excerpts — for the
+ gated low-confidence path, where the hits are candidates to pick between,
+ not answer material, and ``best_guesses`` + ``code_rationale`` already
+ carry the choosing signal.
"""
out: list[dict] = []
for h in hits[: limit if limit is not None else len(hits)]:
@@ -66,9 +71,15 @@ def serialize_hits(
entry["score"] = round(h["score"], 3)
expanded = "graph_expand" in (h.get("_sources") or ())
if h.get("symbols") and (symbols_for_expanded or not expanded):
- entry["key_symbols"] = [
- {k: v for k, v in s.items() if not k.startswith("_")} for s in h["symbols"]
- ]
+ if lean_symbols:
+ keep = ("name", "kind", "signature", "start_line", "end_line")
+ entry["key_symbols"] = [
+ {k: s[k] for k in keep if s.get(k) is not None} for s in h["symbols"]
+ ]
+ else:
+ entry["key_symbols"] = [
+ {k: v for k, v in s.items() if not k.startswith("_")} for s in h["symbols"]
+ ]
out.append(entry)
return out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index a70ba1c20..f081ef363 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
@@ -135,6 +135,7 @@ async def get_context(
timing_ms=(_time.perf_counter() - _t0) * 1000,
hint=_context_hint(targets, compact, include_set),
repository=repository,
+ targets=targets,
),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 17293ed8b..efc326f49 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -233,7 +233,11 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
weighted_sum = sum(m.score * max(m.nloc, 1) for m in metrics)
net_gap = HEALTHY_MIN * total_nloc - weighted_sum
below = sorted(
- (max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1) for m in metrics if m.score < HEALTHY_MIN),
+ (
+ max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1)
+ for m in metrics
+ if m.score < HEALTHY_MIN
+ ),
reverse=True,
)
if net_gap <= 0 or not below:
@@ -335,70 +339,31 @@ async def get_health(
repo: str | None = None,
limit: int = 20,
) -> dict:
- """Code-health markers and per-file scores.
-
- Dashboard mode (no ``targets``) returns repo-level KPIs + the
- lowest-scoring files. Targeted mode returns per-file findings and
- metrics for each path in ``targets``.
-
- Leverage, not just lowness: ``average_health`` is NLOC-weighted (the number
- the badge/dashboard surface), so a few large low files hold it down;
- ``kpis.average_health_unweighted`` is the plain file mean, and a gap between
- the two says "chase big files". ``gap_analysis`` reports the weighted points
- to reach an all-Healthy floor and how few files carry 50% / 90% of it;
- ``high_leverage_files`` ranks files by ``weighted_deficit`` (``(8 - score) *
- nloc``, on every metric row) — the ones that actually move the average, as
- opposed to ``worst_files`` which sorts by raw score. ``refactoring_plans``
- is capped to ``limit`` and ranked file-leverage-first (``refactoring_plans_total``
- reports the full count).
-
- Markers in v1: ``brain_method``, ``nested_complexity``,
- ``complex_method``. Phase 2 adds coverage markers; Phase 3 adds
- duplication + organizational markers.
-
- Three-signal health: every file metric carries per-dimension scores. ``score``
- is the overall, defect-calibrated number surfaced everywhere (== ``defect_score``);
- ``maintainability_score`` is a co-equal signal made of the smells the defect
- calibration floors (cohesion, brain methods, primitive obsession, duplication,
- error handling) given full weight in their own pillar; ``performance_score`` is
- the third co-equal pillar: static performance RISK (I/O-in-loop / N+1 shapes that
- waste work), high-precision / low-recall, NEVER blended into the defect headline.
- ``kpis.maintainability_average`` and ``kpis.performance_average`` are the
- NLOC-weighted repo headlines for those pillars (``None`` when unmeasured). Each
- finding carries a ``dimension`` (``defect`` / ``maintainability`` /
- ``performance``) naming the pillar it homes under, so findings can be filtered
- per dimension. A performance finding's ``details`` carry the ``boundary_kind``
- it crosses (``db`` / ``network`` / ``filesystem`` / ``subprocess`` / ``lock``),
- a ``cross_function`` flag, and, for a cross-function N+1, the ``path`` (the
- resolved ``caller -> ... -> sink`` symbol chain). Performance is a static signal:
- dynamic dispatch, ORM lazy-load, and unmodelled libraries are out of scope.
-
- Self-check before a PR: an agent can read the same signals the code-health
- merge-gate judges a change on. ``include=["accuracy"]`` returns
- ``defect_accuracy`` (does the score actually rank the buggy files first —
- precision@K of the least-healthy files vs the repo bug-fix base rate, with a
- ``lift`` headline); ``include=["signals"]`` attaches per-file process / people
- / topology ``signals`` (prior-defect count, churn, owners, in/out degree) to
- each targeted metric; ``include=["churn_complexity"]`` returns the
- churn x complexity quadrant points (volatile-and-complex files are where
- defects concentrate); and a dimension name in ``include``
- (``"performance"`` / ``"defect"`` / ``"maintainability"``) filters the
- returned findings to that pillar.
+ """Code-health scores and findings — self-check a file before/after editing.
+
+ No ``targets`` → repo dashboard (KPIs, worst files, ``high_leverage_files``
+ ranked by ``weighted_deficit`` = the files that actually move the repo
+ average). With ``targets`` → per-file scores + findings for those paths.
+
+ Three co-equal dimensions per file: ``score`` (defect risk, the headline),
+ ``maintainability_score`` (readability/change-cost smells), and
+ ``performance_score`` (static I/O-in-loop / N+1 RISK, high-precision /
+ low-recall, never blended into the defect headline). Each finding carries
+ its ``dimension``; a performance finding's ``details`` name the
+ ``boundary_kind`` (db/network/filesystem/subprocess/lock) and, for
+ cross-function N+1, the caller→sink ``path``.
Args:
- targets: List of file paths (or ``module:<name>``). Empty → dashboard mode.
- include: Optional opt-in flags (default response stays lean):
- ``"biomarkers"`` returns findings in dashboard mode;
- ``"refactoring"`` attaches a deterministic ``suggestion`` per finding;
- ``"trend"`` adds the repo trend + alert block;
- ``"coverage"`` surfaces coverage rows when ingested;
- ``"accuracy"`` adds repo-level ``defect_accuracy`` (dashboard mode);
- ``"signals"`` attaches per-file ``signals`` (targeted mode);
- ``"churn_complexity"`` adds the churn x complexity points (dashboard);
- ``"performance"`` / ``"defect"`` / ``"maintainability"`` filter
- findings to that dimension.
- repo: Repo alias / id / path.
- limit: Max rows in the lowest-scoring file list (capped at 50).
+ targets: file paths or ``module:<name>``. Empty → dashboard mode.
+ include: opt-in blocks (default stays lean): ``biomarkers`` (findings
+ in dashboard mode) | ``refactoring`` (deterministic suggestion per
+ finding) | ``trend`` | ``coverage`` | ``accuracy`` (does the score
+ rank the buggy files first) | ``signals`` (per-file churn/owners/
+ degree, targeted mode) | ``churn_complexity`` (danger-zone
+ quadrant) | ``performance``/``defect``/``maintainability``
+ (filter findings to one dimension).
+ repo: usually omitted.
+ limit: max rows in ranked lists (capped at 50).
"""
limit = min(max(limit, 1), 50)
include_set = set(include or [])
@@ -721,5 +686,7 @@ async def get_health(
r for r in rows if (r.get("dimension") or "defect") in dimension_filter
]
- result["_meta"] = _build_meta(repository=repository)
+ # Targeted mode scopes the stale signal to the asked-about files; the
+ # dashboard (no targets) keeps the repo-level warning.
+ result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index 89dbcb006..56c10ed9f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -51,6 +51,7 @@ from repowise.server.mcp_server._helpers import (
_get_repo,
_resolve_all_contexts,
_resolve_repo_context,
+ decision_is_excluded,
filter_graph_nodes,
filter_rows_by_attr,
is_excluded,
@@ -397,6 +398,12 @@ def _build_knowledge_map(all_git: list) -> dict[str, Any]:
owner_name.setdefault(email, _owner_display_name(g.primary_owner_name, email))
total_files = len(all_git) or 1
+ # Top 3 only: get_overview is orientation, and "who do I ask" is answered
+ # by the first few names. Per-file ownership questions belong to
+ # get_risk / get_context(include=["ownership"]). The old payload also
+ # carried a knowledge_silos file list here — dropped: it duplicated
+ # get_risk's per-file ownership signal and gave an orienting agent
+ # nothing actionable.
top_owners = sorted(
[
{
@@ -407,29 +414,9 @@ def _build_knowledge_map(all_git: list) -> dict[str, Any]:
for email, count in owner_file_count.items()
],
key=lambda x: -x["files_owned"],
- )[:10]
-
- # knowledge_silos: files where primary owner has > 80% ownership.
- # Filter out boilerplate (migrations, __init__.py, config, lock files).
- silo_exclude_patterns = (
- "alembic/versions/",
- "__init__.py",
- "migrations/",
- ".lock",
- "package-lock",
- "conftest.py",
- )
- knowledge_silos = [
- g.file_path
- for g in sorted(all_git, key=lambda g: -(g.primary_owner_commit_pct or 0.0))
- if (g.primary_owner_commit_pct or 0.0) > 0.8
- and not any(pat in g.file_path for pat in silo_exclude_patterns)
- ][:10]
+ )[:3]
- return {
- "top_owners": top_owners,
- "knowledge_silos": knowledge_silos,
- }
+ return {"top_owners": top_owners}
async def _load_community_nodes(
@@ -483,21 +470,20 @@ def _build_community_summary(all_nodes: list[GraphNode]) -> list[dict[str, Any]]
if len(community_summary) >= 10:
break
label = ""
- cohesion = 0.0
if members:
try:
meta = json.loads(members[0].community_meta_json or "{}")
label = meta.get("label", "")
- cohesion = meta.get("cohesion", 0.0)
except (json.JSONDecodeError, TypeError):
pass
+ # No cohesion in the payload: a 3-decimal internal clustering metric
+ # gives an agent nothing to act on. Label + size carry the map.
community_summary.append(
{
"id": cid,
"label": _community_display_label(label, members, cid, generic_labels),
"size": len(members),
- "cohesion": round(cohesion, 3),
}
)
return community_summary
@@ -636,9 +622,14 @@ async def _build_recent_reversals(session: Any, repository: Any) -> list[dict[st
return recent_reversals
-async def _build_key_decisions(session: Any, repository: Any) -> dict[str, Any]:
+async def _build_key_decisions(
+ session: Any, repository: Any, exclude_spec: Any = None
+) -> dict[str, Any]:
"""Top active decisions + recent reversals (Phase 4A)."""
try:
+ # Over-fetch, then drop records anchored entirely in excluded paths
+ # (vendored venvs, local-only scratch dirs mined before the exclude
+ # rules changed) so the repo's "top decisions" are never junk.
top_decisions_res = await session.execute(
select(DecisionRecord)
.where(
@@ -646,9 +637,13 @@ async def _build_key_decisions(session: Any, repository: Any) -> dict[str, Any]:
DecisionRecord.status == "active",
)
.order_by(DecisionRecord.confidence.desc())
- .limit(5)
+ .limit(25)
)
- top_decisions = top_decisions_res.scalars().all()
+ top_decisions = [
+ dr
+ for dr in top_decisions_res.scalars().all()
+ if not decision_is_excluded(dr, exclude_spec)
+ ][:5]
if not top_decisions:
return {}
key_decisions_list = []
@@ -783,7 +778,7 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
reading_order = await _build_reading_order(session, repository)
title = _resolve_title(overview_page, repository)
code_health = await _build_code_health(session, repository)
- key_decisions_section = await _build_key_decisions(session, repository)
+ key_decisions_section = await _build_key_decisions(session, repository, exclude_spec)
full_content = overview_page.content if overview_page else "No overview generated yet."
want_full_content = "content" in set(include or [])
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.py
index 5ee4e5380..9fccea2f2 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
@@ -167,6 +167,9 @@ async def get_risk(
# ambient awareness. Cheap (≤5 entries) and useful for orientation.
response["global_hotspots"] = global_hotspots
- response["_meta"] = _build_meta(repository=repository)
+ response["_meta"] = _build_meta(
+ repository=repository,
+ targets=[*targets, *(changed_files or [])] if targets or changed_files else None,
+ )
collector.attach(response)
return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index e0bbf043c..993f442fe 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -411,6 +411,21 @@ async def _federated_search(
return {"results": output, "_meta": _build_meta()}
+def _result_paths(results: list[dict]) -> list[str]:
+ """File paths a result set serves, for target-scoped freshness.
+
+ Symbol hits carry ``file``; concept/page hits carry ``target_path``.
+ An empty result set returns ``[]`` (meaning "no file content served",
+ which suppresses the repo-level stale warning by design).
+ """
+ paths: list[str] = []
+ for item in results:
+ p = item.get("file") or item.get("target_path")
+ if isinstance(p, str) and p:
+ paths.append(p)
+ return paths
+
+
def _grep_hint_for(query: str) -> str | None:
"""Build a Grep nudge for identifier-shaped queries, else ``None``."""
if _looks_like_exact_token(query):
@@ -533,7 +548,11 @@ async def _structured_search(
async with get_session(contexts[0].session_factory) as session:
repository = await _get_repo(session)
- response: dict = {"results": results, "mode": mode, "_meta": _build_meta(repository=repository)}
+ response: dict = {
+ "results": results,
+ "mode": mode,
+ "_meta": _build_meta(repository=repository, targets=_result_paths(results)),
+ }
if grep_hint and not results:
response["grep_hint"] = grep_hint
return response
@@ -640,7 +659,10 @@ async def search_codebase(
# Derive confidence_score from relative position in the result set.
_assign_confidence(output, "relevance_score", "confidence_score")
- response: dict = {"results": output, "_meta": _build_meta(repository=repository)}
+ response: dict = {
+ "results": output,
+ "_meta": _build_meta(repository=repository, targets=_result_paths(output)),
+ }
if grep_hint:
response["grep_hint"] = grep_hint
return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index 66ecbda0c..ed94230c9 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -226,7 +226,12 @@ async def _resolve_range_read(
"source": source,
"truncated": range_truncated,
"verified": True,
- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000, repository=repository),
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ repository=repository,
+ # A range read serves live bytes; index drift elsewhere is noise.
+ targets=[path],
+ ),
}
remainder_end = min(requested_end, total)
if range_truncated and e < remainder_end:
@@ -582,6 +587,7 @@ async def get_symbol(
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
repository=repository,
+ targets=[file_part],
),
}
return {
@@ -664,6 +670,8 @@ async def get_symbol(
timing_ms=(time.perf_counter() - t0) * 1000,
hint=_symbol_hint(row.symbol_id, check.end_line, check.start_line),
repository=repository,
+ # Served bytes are live-verified; only this file's drift matters.
+ targets=[row.file_path],
),
}
if truncated and not check.approximate and end < check.end_line:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index 7b6ae065f..8d7745251 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -28,6 +28,7 @@ from repowise.server.mcp_server._helpers import (
_resolve_all_contexts,
_resolve_repo_context,
_unsupported_repo_all,
+ decision_is_excluded,
filter_path_list,
is_excluded,
)
@@ -439,6 +440,10 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -
all_decisions = await _list_decisions(
session, repository.id, include_proposed=True, limit=200
)
+ # Records anchored entirely in excluded paths (vendored venvs mined
+ # before exclude rules changed) are noise for every mode downstream.
+ _spec = _get_exclude_spec(ctx.path)
+ all_decisions = [d for d in all_decisions if not decision_is_excluded(d, _spec)]
# Load git metadata for targets (for origin context in results)
target_git = await _load_target_git(session, repository.id, targets)
@@ -477,7 +482,7 @@ async def _why_search(query: str, targets: list[str] | None, repo: str | None) -
if rationale:
result_data["code_rationale"] = rationale
- result_data["_meta"] = _build_meta(repository=repository)
+ result_data["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
return result_data
diff --git a/tests/unit/cli/test_claude_md_contract_curation.py b/tests/unit/cli/test_claude_md_contract_curation.py
new file mode 100644
index 000000000..91e620ada
--- /dev/null
+++ b/tests/unit/cli/test_claude_md_contract_curation.py
@@ -0,0 +1,64 @@
+"""Workspace CLAUDE.md contract-table curation.
+
+Raw contract links include intra-repo rows and one row per provider file for
+the same (contract, consumer); in a real workspace that rendered 30+
+near-duplicate rows before the first genuinely cross-repo contract.
+"""
+
+from __future__ import annotations
+
+from repowise.cli.commands.claude_md_cmd import _MAX_CONTRACT_LINKS, _curate_contract_links
+
+
+def _link(
+ provider_repo,
+ consumer_repo,
+ contract_id,
+ provider_file="src/models.py",
+ consumer_file="src/client.ts",
+):
+ return {
+ "provider_repo": provider_repo,
+ "consumer_repo": consumer_repo,
+ "provider_file": provider_file,
+ "consumer_file": consumer_file,
+ "contract_id": contract_id,
+ "contract_type": "data",
+ }
+
+
+def test_intra_repo_links_are_dropped():
+ links = [
+ _link("api", "api", "data::repositories"),
+ _link("api", "web", "http::GET::/repos"),
+ ]
+ out = _curate_contract_links(links)
+ assert len(out) == 1
+ assert out[0]["consumer_repo"] == "web"
+
+
+def test_duplicate_providers_collapse_preferring_non_migration():
+ links = [
+ _link("api", "web", "data::users", provider_file="alembic/versions/0001_init.py"),
+ _link("api", "web", "data::users", provider_file="src/models.py"),
+ ]
+ out = _curate_contract_links(links)
+ assert len(out) == 1
+ assert out[0]["provider_file"] == "src/models.py"
+
+
+def test_distinct_consumers_survive():
+ links = [
+ _link("api", "web", "data::users", consumer_file="a.ts"),
+ _link("api", "web", "data::users", consumer_file="b.ts"),
+ ]
+ assert len(_curate_contract_links(links)) == 2
+
+
+def test_capped():
+ links = [_link("api", "web", f"http::GET::/x{i}") for i in range(40)]
+ assert len(_curate_contract_links(links)) == _MAX_CONTRACT_LINKS
+
+
+def test_malformed_entries_ignored():
+ assert _curate_contract_links(["nope", None]) == []
diff --git a/tests/unit/distill/test_claude_md_section.py b/tests/unit/distill/test_claude_md_section.py
index 765409794..0230d8ca5 100644
--- a/tests/unit/distill/test_claude_md_section.py
+++ b/tests/unit/distill/test_claude_md_section.py
@@ -34,9 +34,6 @@ def rendered() -> str:
class TestDistillSection:
- def test_section_present(self, rendered: str) -> None:
- assert "### Output Distillation" in rendered
-
def test_teaches_distill_command(self, rendered: str) -> None:
assert "repowise distill <cmd>" in rendered
@@ -46,4 +43,4 @@ class TestDistillSection:
assert "repowise expand <ref>" in rendered
def test_discourages_rerunning(self, rendered: str) -> None:
- assert "Never re-run" in rendered
+ assert "never re-run the command" in rendered
diff --git a/tests/unit/generation/test_editor_fetcher_helpers.py b/tests/unit/generation/test_editor_fetcher_helpers.py
index 35972b911..7d05941e6 100644
--- a/tests/unit/generation/test_editor_fetcher_helpers.py
+++ b/tests/unit/generation/test_editor_fetcher_helpers.py
@@ -52,6 +52,24 @@ class TestExtractSentences:
assert "rendered in a web UI." in out
assert "served through an API." in out
+ def test_colon_lead_ins_are_dropped_with_their_lists(self) -> None:
+ # Regression: "Repowise consumes:" survived after its list items were
+ # stripped, leaving dangling fragments in the rendered CLAUDE.md.
+ text = (
+ "Repowise is a documentation engine that produces a wiki.\n"
+ "Repowise consumes:\n"
+ "- source files\n"
+ "- git metadata\n"
+ "Think of it as a pipeline with four stages:\n"
+ "1. ingest\n"
+ "The output is served over MCP."
+ )
+ out = _extract_sentences(text, max_sentences=4)
+ assert "consumes:" not in out
+ assert "four stages:" not in out
+ assert "produces a wiki." in out
+ assert "served over MCP." in out
+
def test_empty_input(self) -> None:
assert _extract_sentences("", max_sentences=3) == ""
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 12256f9dd..f0842abb8 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -45,6 +45,17 @@ def test_render_returns_non_empty_string(gen):
assert len(result) > 0
+def test_render_never_references_repowise_repo_paths(gen):
+ # The generated file lands in USERS' repos — a `docs/CODE_HEALTH.md`-style
+ # reference points at a file that only exists in the repowise repo itself.
+ import dataclasses
+
+ data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ result = gen.render(data)
+ for repo_relative in ("docs/CODE_HEALTH.md", "docs/MCP_TOOLS.md", "docs/DISTILL.md"):
+ assert repo_relative not in result
+
+
def test_render_contains_repo_name(gen):
data = _minimal_data()
result = gen.render(data)
@@ -74,7 +85,7 @@ def test_render_surfaces_maintainability_when_present(gen):
data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
result = gen.render(data)
- assert "Maintainability, Average: 6.4/10" in result
+ assert "maintainability 6.4/10" in result
def test_render_omits_maintainability_when_unmeasured(gen):
@@ -82,9 +93,11 @@ def test_render_omits_maintainability_when_unmeasured(gen):
data = dataclasses.replace(_minimal_data(), code_health=_health_block(None))
result = gen.render(data)
- # Defect-risk block still renders; the maintainability line is suppressed.
- assert "Hotspot health" in result
- assert "Maintainability, Average" not in result
+ # Defect-risk headline still renders; the maintainability clause is
+ # suppressed (the word still appears in the static tool table, so match
+ # the clause shape, not the bare word).
+ assert "hotspot health" in result
+ assert "· maintainability" not in result
def test_render_surfaces_performance_when_present(gen):
@@ -97,10 +110,9 @@ def test_render_surfaces_performance_when_present(gen):
),
)
result = gen.render(data)
- # Leads with the finding COUNT + coverage, not the bounded /10.
- assert "Performance risk: 7 open findings" in result
- assert "Average: 9.2/10" in result
- assert "perf detectors ran on 88.0% of analyzed code lines" in result
+ # Leads with the finding COUNT; the bounded [9,10] average and coverage %
+ # are deliberately not rendered (nothing an agent can act on there).
+ assert "performance risk 7 open static I/O-in-loop / N+1 findings" in result
def test_render_omits_performance_when_unmeasured(gen):
@@ -108,9 +120,9 @@ def test_render_omits_performance_when_unmeasured(gen):
data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
result = gen.render(data)
- # Maintainability still renders; the performance line is suppressed.
- assert "Maintainability, Average: 6.4/10" in result
- assert "Performance risk:" not in result
+ # Maintainability still renders; the performance clause is suppressed.
+ assert "maintainability 6.4/10" in result
+ assert "performance risk" not in result
def test_write_creates_new_file(gen, tmp_path):
diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.py
index 4b0cd3da8..d13390685 100644
--- a/tests/unit/generation/test_kg_claude_md_onboarding.py
+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py
@@ -58,44 +58,32 @@ def onboarding_env():
class TestClaudeMdKGSection:
- def test_renders_layers_when_present(self, jinja_env):
- tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
+ """The workflow-first CLAUDE.md deliberately omits the KG layers table and
+ guided tour (onboarding material an agent doing a task never used — it
+ lives in get_overview). Key modules render as a compact list."""
+
+ def _data(self, **kwargs):
+ return EditorFileData(
repo_name="test",
indexed_at="2026-05-25",
indexed_commit="abc123",
architecture_summary="",
- kg_layers=[
- KGLayerSummary(name="CLI", file_count=10, description="Command-line interface"),
- KGLayerSummary(name="Core", file_count=25, description="Core business logic"),
- ],
+ **kwargs,
)
- rendered = tmpl.render(data=data)
- assert "### Architectural Layers" in rendered
- assert "CLI" in rendered
- assert "10" in rendered
- assert "Core" in rendered
- assert "25" in rendered
- def test_no_layers_section_without_data(self, jinja_env):
+ def test_layers_are_not_rendered(self, jinja_env):
tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
+ data = self._data(
+ kg_layers=[
+ KGLayerSummary(name="CLI", file_count=10, description="Command-line interface"),
+ ]
)
rendered = tmpl.render(data=data)
assert "Architectural Layers" not in rendered
- def test_renders_tour_when_present(self, jinja_env):
+ def test_tour_is_not_rendered(self, jinja_env):
tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
- kg_layers=[KGLayerSummary(name="Core", file_count=5, description="Core")],
+ data = self._data(
kg_tour=[
KGTourStepSummary(
order=1,
@@ -103,81 +91,40 @@ class TestClaudeMdKGSection:
primary_file="src/main.py",
reason="An entry point — execution starts here.",
),
- KGTourStepSummary(order=2, title="Graph Building", primary_file="src/graph.py"),
- ],
+ ]
)
rendered = tmpl.render(data=data)
- assert "### Guided Tour (2 steps)" in rendered
- # The package-qualified path is the step identifier; the reason follows.
- assert "`src/main.py`" in rendered
- assert "An entry point — execution starts here." in rendered
+ assert "Guided Tour" not in rendered
- def test_key_modules_owner_column_dropped_when_no_owners(self, jinja_env):
+ def test_key_modules_render_as_list(self, jinja_env):
from repowise.core.generation.editor_files.data import KeyModule
tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
+ data = self._data(
key_modules=[
KeyModule(name="src/api", purpose="API layer", file_count=4, owner=None),
- KeyModule(name="src/core", purpose="Core logic", file_count=9, owner=None),
- ],
+ KeyModule(name="src/core", purpose="", file_count=9, owner=None),
+ ]
)
rendered = tmpl.render(data=data)
- assert "| Module | Purpose |" in rendered
- assert "Owner" not in rendered
-
- def test_key_modules_owner_column_kept_when_any_owner(self, jinja_env):
- from repowise.core.generation.editor_files.data import KeyModule
+ assert "### Key modules" in rendered
+ assert "- `src/api` — API layer" in rendered
+ # No purpose → no dangling separator.
+ assert "- `src/core`\n" in rendered
+ def test_workflow_protocol_leads(self, jinja_env):
tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
- key_modules=[
- KeyModule(name="src/api", purpose="API layer", file_count=4, owner="Alice"),
- KeyModule(name="src/core", purpose="Core logic", file_count=9, owner=None),
- ],
- )
- rendered = tmpl.render(data=data)
- assert "| Module | Purpose | Owner |" in rendered
- assert "Alice" in rendered
-
- def test_no_tour_section_without_data(self, jinja_env):
- tmpl = jinja_env.get_template("claude_md.j2")
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
- kg_layers=[KGLayerSummary(name="Core", file_count=5, description="Core")],
- )
- rendered = tmpl.render(data=data)
- assert "Guided Tour" not in rendered
-
- def test_tour_truncates_at_6(self, jinja_env):
- tmpl = jinja_env.get_template("claude_md.j2")
- steps = [
- KGTourStepSummary(order=i, title=f"Step {i}", primary_file=f"f{i}.py")
- for i in range(1, 10)
- ]
- data = EditorFileData(
- repo_name="test",
- indexed_at="2026-05-25",
- indexed_commit="abc123",
- architecture_summary="",
- kg_layers=[KGLayerSummary(name="Core", file_count=5, description="Core")],
- kg_tour=steps,
- )
- rendered = tmpl.render(data=data)
- assert "`f6.py`" in rendered
- assert "`f7.py`" not in rendered
- assert "3 more steps" in rendered
+ rendered = tmpl.render(data=self._data())
+ assert "### How to work in this repo" in rendered
+ assert "### Trust protocol" in rendered
+ # Pre-edit framing: the mandatory Read of edit targets is conceded.
+ assert "raw Read of any file you will Edit" in rendered
+ # The tool table renders from the single-source module.
+ assert "| Tool | When and why |" in rendered
+ assert "`get_answer(question)`" in rendered
+ # Protocol comes before the repo-facts data blocks.
+ if "Entry points" in rendered:
+ assert rendered.index("Trust protocol") < rendered.index("Entry points")
# ---------------------------------------------------------------------------
@@ -230,7 +177,12 @@ class TestHowItWorksWithTour:
repo_name="test",
archetype="service",
kg_tour_steps=[
- {"order": 1, "title": "Entry", "description": "Start here", "nodeIds": ["file:src/main.py"]},
+ {
+ "order": 1,
+ "title": "Entry",
+ "description": "Start here",
+ "nodeIds": ["file:src/main.py"],
+ },
],
)
assert len(ctx.kg_tour_steps) == 1
@@ -242,8 +194,18 @@ class TestHowItWorksWithTour:
archetype="service",
archetype_evidence=["framework detected"],
kg_tour_steps=[
- {"order": 1, "title": "Entry Point", "description": "Start here", "nodeIds": ["file:src/main.py"]},
- {"order": 2, "title": "Processing", "description": "Core logic", "nodeIds": ["file:src/process.py"]},
+ {
+ "order": 1,
+ "title": "Entry Point",
+ "description": "Start here",
+ "nodeIds": ["file:src/main.py"],
+ },
+ {
+ "order": 2,
+ "title": "Processing",
+ "description": "Core logic",
+ "nodeIds": ["file:src/process.py"],
+ },
],
)
rendered = tmpl.render(ctx=ctx)
@@ -321,7 +283,11 @@ class TestCodebaseMapWithLayers:
total_files=10,
total_loc=500,
kg_layers=[
- {"name": "Core", "description": "Core business logic", "nodeIds": ["file:a.py", "file:b.py"]},
+ {
+ "name": "Core",
+ "description": "Core business logic",
+ "nodeIds": ["file:a.py", "file:b.py"],
+ },
{"name": "API", "description": "REST API layer", "nodeIds": ["file:c.py"]},
],
)
diff --git a/tests/unit/generation/test_workspace_claude_md.py b/tests/unit/generation/test_workspace_claude_md.py
index b7cc60caa..44d8103a4 100644
--- a/tests/unit/generation/test_workspace_claude_md.py
+++ b/tests/unit/generation/test_workspace_claude_md.py
@@ -183,6 +183,7 @@ def test_render_limits_co_changes_to_ten(gen):
assert result.count("source_repo") == 0 # field names not in output
# Count occurrences of "file_" pattern — at most 10
import re
+
matches = re.findall(r"file_\d+\.py", result)
assert len(matches) <= 10
@@ -213,10 +214,13 @@ def test_render_includes_entry_points_per_repo(gen):
assert "src/api/server.py" in result
-def test_render_shows_placeholder_when_no_entry_points(gen):
+def test_render_omits_entry_points_section_when_none_indexed(gen):
+ # A run of "_No entry points indexed._" placeholders told the agent
+ # nothing — repos without entry points are simply omitted.
repos = [_make_repo(alias="svc", entry_points=[])]
result = gen.render(_make_data(repos=repos, default_repo="svc"))
- assert "No entry points indexed" in result
+ assert "No entry points indexed" not in result
+ assert "Per-Repo Entry Points" not in result
# ---------------------------------------------------------------------------
@@ -390,8 +394,6 @@ def test_contracts_by_type_shown_when_present(gen):
"contract_id": "GET::/v1/ping",
}
]
- result = gen.render(
- _make_data(contract_links=links, contracts_by_type={"http": 3, "grpc": 1})
- )
+ result = gen.render(_make_data(contract_links=links, contracts_by_type={"http": 3, "grpc": 1}))
assert "http: 3" in result
assert "grpc: 1" in result
diff --git a/tests/unit/server/mcp/test_decision_hygiene.py b/tests/unit/server/mcp/test_decision_hygiene.py
new file mode 100644
index 000000000..2c2817ee4
--- /dev/null
+++ b/tests/unit/server/mcp/test_decision_hygiene.py
@@ -0,0 +1,53 @@
+"""Decision records anchored in excluded paths never surface as "key decisions".
+
+Decision mining can predate an exclude_patterns / info-exclude change, so the
+DB may hold records mined from vendored trees (a checked-in venv's
+site-packages). Read-time filtering heals existing indexes without a reindex.
+"""
+
+from __future__ import annotations
+
+import json
+import types
+
+import pathspec
+
+from repowise.server.mcp_server._helpers import decision_is_excluded
+
+_SPEC = pathspec.PathSpec.from_lines("gitwildmatch", ["research/", "*.lock"])
+
+
+def _decision(affected: list[str] | None):
+ return types.SimpleNamespace(
+ affected_files_json=json.dumps(affected) if affected is not None else None
+ )
+
+
+def test_all_affected_files_excluded_is_junk():
+ d = _decision(["research/.pbvenv/Lib/site-packages/charset_normalizer/api.py"])
+ assert decision_is_excluded(d, _SPEC) is True
+
+
+def test_windows_separators_normalize():
+ d = _decision(["research\\.pbvenv\\Lib\\site-packages\\api.py"])
+ assert decision_is_excluded(d, _SPEC) is True
+
+
+def test_any_real_file_keeps_the_decision():
+ d = _decision(["research/scratch.py", "packages/core/src/real.py"])
+ assert decision_is_excluded(d, _SPEC) is False
+
+
+def test_no_affected_files_is_kept():
+ assert decision_is_excluded(_decision([]), _SPEC) is False
+ assert decision_is_excluded(_decision(None), _SPEC) is False
+
+
+def test_no_spec_keeps_everything():
+ d = _decision(["research/junk.py"])
+ assert decision_is_excluded(d, None) is False
+
+
+def test_malformed_json_is_kept():
+ d = types.SimpleNamespace(affected_files_json="{not json")
+ assert decision_is_excluded(d, _SPEC) is False
diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.py
new file mode 100644
index 000000000..71f4dd9d7
--- /dev/null
+++ b/tests/unit/server/mcp/test_meta_freshness.py
@@ -0,0 +1,138 @@
+"""Target-scoped staleness in the ``_meta`` envelope.
+
+"Silence means current" only trains agent trust if ``stale_warning`` fires
+when the served content is actually affected. These tests pin the contract:
+
+ * HEAD match → silence (no warning, no ``index_behind``).
+ * HEAD mismatch + a served target changed → ``stale_warning``.
+ * HEAD mismatch + no served target changed → ``index_behind: true`` only.
+ * HEAD mismatch + no targets passed (repo-level tools) → repo-level warning.
+ * git can't diff the two SHAs → fall back to the repo-level warning
+ (fail toward warning, never toward false silence).
+"""
+
+from __future__ import annotations
+
+import subprocess
+import types
+
+import pytest
+
+from repowise.server.mcp_server import _meta
+
+_INDEXED = "a" * 40
+_LIVE = "b" * 40
+
+
[email protected](autouse=True)
+def _clear_changed_files_cache():
+ _meta._changed_files_cache.clear()
+ yield
+ _meta._changed_files_cache.clear()
+
+
+def _repo(tmp_path, head_commit: str = _INDEXED):
+ return types.SimpleNamespace(updated_at=None, local_path=str(tmp_path), head_commit=head_commit)
+
+
+def _prime(tmp_path, changed: frozenset[str] | None):
+ _meta._changed_files_cache[(str(tmp_path), _INDEXED, _LIVE)] = changed
+
+
+def test_head_match_is_silent(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _INDEXED)
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])
+ assert "stale_warning" not in out
+ assert "index_behind" not in out
+ assert "live_head" not in out
+
+
+def test_served_target_changed_warns(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, frozenset({"src/a.py"}))
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])
+ assert "stale_warning" in out
+ assert "index_behind" not in out
+
+
+def test_unaffected_targets_get_index_behind_not_warning(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, frozenset({"docs/README.md"}))
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])
+ assert "stale_warning" not in out
+ assert out.get("index_behind") is True
+ assert out.get("live_head") == _LIVE[:12]
+
+
+def test_no_targets_keeps_repo_level_warning(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)
+ assert "stale_warning" in out
+
+
+def test_empty_targets_means_nothing_served_and_never_warns(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, frozenset({"src/a.py"}))
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=[])
+ assert "stale_warning" not in out
+ assert out.get("index_behind") is True
+
+
+def test_git_diff_failure_falls_back_to_repo_level_warning(tmp_path, monkeypatch):
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, None) # git couldn't answer (rebased-away SHA, timeout)
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])
+ assert "stale_warning" in out
+
+
+ ("target", "changed", "hit"),
+ [
+ ("src/a.py::MyClass", {"src/a.py"}, True), # symbol id → file
+ ("src/a.py:10-40", {"src/a.py"}, True), # range read → file
+ ("src\\a.py", {"src/a.py"}, True), # backslashes normalize
+ ("src", {"src/a.py"}, True), # module dir → prefix
+ ("./src/a.py", {"src/a.py"}, True), # leading ./ stripped
+ ("src/a.py", {"src/other.py"}, False),
+ ("srcx", {"src/a.py"}, False), # prefix must be a dir boundary
+ ],
+)
+def test_target_intersection_shapes(target, changed, hit):
+ assert _meta.targets_hit_by_changes([target], frozenset(changed)) is hit
+
+
+def test_changed_files_between_real_git(tmp_path):
+ def git(*args):
+ subprocess.run(
+ ["git", "-C", str(tmp_path), *args],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ git("init", "-q")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ (tmp_path / "a.py").write_text("x = 1\n", encoding="utf-8")
+ git("add", ".")
+ git("commit", "-qm", "one")
+ sha1 = subprocess.run(
+ ["git", "-C", str(tmp_path), "rev-parse", "HEAD"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ (tmp_path / "b.py").write_text("y = 2\n", encoding="utf-8")
+ git("add", ".")
+ git("commit", "-qm", "two")
+ sha2 = subprocess.run(
+ ["git", "-C", str(tmp_path), "rev-parse", "HEAD"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+ changed = _meta._changed_files_between(str(tmp_path), sha1, sha2)
+ assert changed == frozenset({"b.py"})
+ # Unknown SHA → None (fail toward warning), and the miss is cached too.
+ assert _meta._changed_files_between(str(tmp_path), "f" * 40, sha2) is None
diff --git a/tests/unit/server/mcp/test_tool_docstrings.py b/tests/unit/server/mcp/test_tool_docstrings.py
new file mode 100644
index 000000000..3d57f3f83
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_docstrings.py
@@ -0,0 +1,49 @@
+"""Tool docstrings ARE the agent-facing schema — keep them lean and legible.
+
+Every registered MCP tool's docstring ships verbatim inside the tool schema
+that agent harnesses load (and may truncate). A docstring past ~400 tokens
+risks arriving cut off mid-sentence, and pushes schema-loading cost onto
+every session. The reference-manual detail belongs in docs/MCP_TOOLS.md.
+"""
+
+from __future__ import annotations
+
+from repowise.core.registry import mcp_tool_registry
+
+# ~400 tokens at the 4-chars/token estimate used across the codebase.
+_MAX_DOCSTRING_CHARS = 1600
+# The first line is what a scanning agent reads when picking a tool.
+_MAX_FIRST_LINE_CHARS = 90
+
+
+def _registered_tools():
+ # Importing the package registers every @mcp.tool with the registry.
+ import repowise.server.mcp_server # noqa: F401
+
+ tools = mcp_tool_registry.tools()
+ assert tools, "tool registry is empty — import side effect broken?"
+ return tools
+
+
+def test_every_tool_docstring_fits_the_schema_budget():
+ oversized = {
+ fn.__name__: len(fn.__doc__ or "")
+ for fn in _registered_tools()
+ if len(fn.__doc__ or "") > _MAX_DOCSTRING_CHARS
+ }
+ assert not oversized, (
+ f"Tool docstrings over {_MAX_DOCSTRING_CHARS} chars (~400 tokens): "
+ f"{oversized}. Trim the docstring; move reference detail to "
+ "docs/MCP_TOOLS.md."
+ )
+
+
+def test_every_tool_docstring_leads_with_a_task_shaped_line():
+ for fn in _registered_tools():
+ doc = (fn.__doc__ or "").strip()
+ assert doc, f"{fn.__name__} has no docstring — its schema would be blank"
+ first = doc.splitlines()[0].strip()
+ assert len(first) <= _MAX_FIRST_LINE_CHARS, (
+ f"{fn.__name__} first docstring line is {len(first)} chars; keep the "
+ "when-to-call summary scannable."
+ )
diff --git a/tests/unit/server/mcp/test_tool_table_drift.py b/tests/unit/server/mcp/test_tool_table_drift.py
new file mode 100644
index 000000000..2e1f983dc
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_table_drift.py
@@ -0,0 +1,50 @@
+"""The CLAUDE.md tool table must track the live MCP tool registry.
+
+The table used to be hand-edited prose inside claude_md.j2 and silently
+drifted from the registered surface. It now lives in
+``editor_files/tool_table.py``; this test pins it to the registry.
+"""
+
+from __future__ import annotations
+
+from repowise.core.generation.editor_files.tool_table import (
+ TOOL_TABLE_ROWS,
+ render_tool_table,
+)
+from repowise.core.registry import mcp_tool_registry
+
+
+def _registered_names() -> set[str]:
+ import repowise.server.mcp_server # noqa: F401 (registers the tools)
+
+ return {fn.__name__ for fn in mcp_tool_registry.tools()}
+
+
+def test_every_table_row_names_a_registered_tool():
+ unknown = set(TOOL_TABLE_ROWS) - _registered_names()
+ 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_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_render_produces_one_row_per_tool():
+ md = render_tool_table()
+ assert md.startswith("| Tool | When and why |")
+ # Header + separator + one line per row.
+ assert len(md.splitlines()) == 2 + len(TOOL_TABLE_ROWS)