Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): overhaul tools — get_symbol exposed, get_answer reworked, page leads tuned (#210)
Raghav Chamadiyaee1b71f4f9ba
diff --git a/README.md b/README.mdindex f7188e10d..81300b97c 100644--- a/README.md+++ b/README.md@@ -3,7 +3,7 @@<img src=".github/assets/logo.png" width="280" alt="repowise" /><br />**The codebase intelligence layer for your AI coding agent.**-Four intelligence layers. Seven MCP tools. Multi-repo workspaces. Auto-sync hooks. One `pip install`.+Four intelligence layers. Eight MCP tools. Multi-repo workspaces. Auto-sync hooks. One `pip install`.[](https://pypi.org/project/repowise/)[](https://www.gnu.org/licenses/agpl-3.0)@@ -23,7 +23,7 @@ Four intelligence layers. Seven MCP tools. Multi-repo workspaces. Auto-sync hookYour AI coding agent reads files. It doesn't know which ones change together, which ones are dead, or why they were built the way they were. It has the source code and no memory of how the codebase got there.-repowise fixes that. It indexes your codebase into four intelligence layers — dependency graph, git history, auto-generated documentation, and architectural decisions — and exposes them to Claude Code (and any MCP-compatible AI agent) through seven precisely designed tools. Multi-repo? Initialize a workspace and get cross-repo co-change detection, API contract extraction, and federated MCP queries across all your services. **27× fewer tokens per query. 36% cheaper. Same answer quality.**+repowise fixes that. It indexes your codebase into four intelligence layers — dependency graph, git history, auto-generated documentation, and architectural decisions — and exposes them to Claude Code (and any MCP-compatible AI agent) through eight precisely designed tools. Multi-repo? Initialize a workspace and get cross-repo co-change detection, API contract extraction, and federated MCP queries across all your services. **27× fewer tokens per query. 36% cheaper. Same answer quality.**The result: your agent answers *"why does auth work this way?"* instead of *"here is what auth.ts contains."*@@ -175,19 +175,20 @@ Full guide: [docs/WORKSPACES.md](docs/WORKSPACES.md)----## Seven MCP tools+## Eight MCP tools-Most tools are designed around data entities — one module, one file, one symbol — which forces AI agents into long chains of sequential calls. repowise tools are designed around **tasks**. Pass multiple targets in one call. Get complete context back. Full reference: [docs/MCP_TOOLS.md](docs/MCP_TOOLS.md)+Most tools are designed around data entities — one module, one file, one symbol — which forces AI agents into long chains of sequential calls. repowise tools are designed around **tasks**. Pass multiple targets in one call. Get complete context back. Every response carries an `_meta` envelope with `index_age_days`, `indexed_commit`, and a `stale_warning` that fires only when the indexed HEAD diverges from live `.git/HEAD` — silence means the index is current. Full reference: [docs/MCP_TOOLS.md](docs/MCP_TOOLS.md)-| Tool | What it answers | When Claude Code calls it |+| Tool | What only this tool answers | When Claude Code calls it ||---|---|---|| `get_overview()` | Architecture summary, module map, entry points, git health, community summary | First call on any unfamiliar codebase |-| `get_answer(question)` | One-call RAG: retrieves over the wiki, gates on confidence, and synthesizes a cited 2–5 sentence answer. High-confidence answers cite directly; ambiguous queries return ranked excerpts. | First call on any code question — collapses search → read → reason into one round-trip |-| `get_context(targets, include?)` | The workhorse. Docs, symbols, ownership, freshness, community membership for any targets. `include` options: `"source"` (symbol body), `"callers"`/`"callees"` (call graph), `"metrics"` (PageRank, centrality), `"community"` (cluster membership). Batch multiple targets. In workspace mode, pass `repo` to target a specific repo. | Before reading or modifying code. Pass all relevant targets in one call. |-| `search_codebase(query)` | Semantic search over the full wiki. Natural language. In workspace mode, searches across all repos. | When `get_answer` returned low confidence and you need to discover candidate pages by topic |-| `get_risk(targets?, changed_files?)` | Hotspot scores, dependents, co-change partners, blast radius, recommended reviewers, test gaps, security signals, 0–10 risk score | Before modifying files — understand what could break |-| `get_why(query?)` | Three modes: NL search over decisions · path-based decisions for a file · no-arg health dashboard | Before architectural changes — understand existing intent |-| `get_dead_code(min_confidence?, include_internals?)` | Unreachable code sorted by confidence tier with cleanup impact estimates | Cleanup tasks |+| `get_answer(question)` | Hybrid retrieval (FTS + vector merged via RRF) plus PageRank bias and 1-hop graph expansion, synthesised into a cited answer with a calibrated `retrieval_quality` reported separately from `confidence`. On low confidence returns a structured `best_guesses` list with one-line per-file justifications instead of an empty answer. Decision records are fused in for "why"-shaped questions. | First call on any code question — collapses search → read → reason into one round-trip |+| `get_context(targets, include?)` | Triage card for files / modules / symbols: title, summary, signatures, `hotspot` bit, `decision_records` titles, and `symbol_id`s the agent pipes into `get_symbol`. NOT source bytes. `include` opens richer data: `"callers"`/`"callees"`, `"ownership"`, `"last_change"`, `"metrics"`, `"community"`, `"decisions"`, `"full_doc"`. Batch multiple targets. | Before reading or modifying code. Pass all relevant targets in one call. |+| `get_symbol("path/to/file.py::Name")` | Raw source bytes for one indexed symbol with exact line bounds — cheaper and safer than `Read` + offset math. Bounded at ~400 lines, normalises `::` / `.` / `/` separators across languages, deterministic resolution on overloads. | When you need the body of one function or class. Use the `symbol_id` returned by `get_context`. |+| `search_codebase(query, kind?)` | Semantic search over the wiki. Each result tags its `search_method` (`"embedding"` vs `"bm25"` fallback) and is filterable by `kind` (`implementation` / `test` / `config` / `doc`). Surfaces a Grep hint when the query is a bareword identifier. | When `get_answer` returned low confidence and you need to discover candidate pages by topic |+| `get_risk(targets, changed_files?)` | Hotspot scores, dependents, co-change partners, ownership, test gaps, security signals. Pass `changed_files` for PR mode → response carries a `directive` block (`will_break`, `missing_cochanges`, `missing_tests`) for one-glance review plus cross-repo blast radius. | Before modifying files — understand what could break |+| `get_why(query?, targets?)` | Architectural decision records, their status (active / proposed / deprecated / superseded), and the commits that are evidence for them. Falls back to git archaeology when no ADRs exist for a file. | Before architectural changes — understand existing intent |+| `get_dead_code(min_confidence?, include_internals?)` | Unreachable code sorted by confidence tier with cleanup impact estimates. In workspace mode, cross-repo consumer detection lowers confidence on findings that other repos import. | Cleanup tasks |### Tool call comparison — a real task@@ -196,7 +197,7 @@ Most tools are designed around data entities — one module, one file, one symbo| Approach | Tool calls | Time to first change | What it misses ||---|---|---|---|| Claude Code alone (no MCP) | grep + read ~30 files | ~8 min | Ownership, prior decisions, hidden coupling |-| **repowise (7 tools)** | **5 calls** | **~2 min** | **Nothing** |+| **repowise (8 tools)** | **5 calls** | **~2 min** | **Nothing** |The 5 calls for that task:@@ -460,7 +461,7 @@ The "why" usually walks out the door — when a teammate leaves, or when you reo| Bus factor analysis | ✅ | ❌ | ❌ | ❌ | ✅ || Architectural decision records | ✅ | ❌ | ❌ | ❌ | ❌ || Multi-repo workspace intelligence | ✅ co-changes, contracts, federated MCP | ❌ | ❌ | ❌ | ❌ |-| MCP server for AI agents | ✅ 7 tools | ❌ | ✅ 3 tools | ✅ | ✅ |+| MCP server for AI agents | ✅ 8 tools | ❌ | ✅ 3 tools | ✅ | ✅ || Proactive agent hooks | ✅ PreToolUse + PostToolUse | ❌ | ❌ | ❌ | ❌ || Auto-generated CLAUDE.md | ✅ | ❌ | ❌ | ❌ | ❌ || Doc freshness scoring | ✅ | ❌ | ❌ | ⚠️ staleness only | ❌ |diff --git a/packages/core/src/repowise/core/generation/page_generator.py b/packages/core/src/repowise/core/generation/page_generator.pyindex 6bfb8683d..7007282f2 100644--- a/packages/core/src/repowise/core/generation/page_generator.py+++ b/packages/core/src/repowise/core/generation/page_generator.py@@ -86,6 +86,18 @@ SYSTEM_PROMPTS: dict[str, str] = {"You are repowise, an expert technical documentation generator. ""Your task is to produce comprehensive, accurate wiki pages from source code. ""Output markdown only. Do not include preamble or apologies. "+ "\n"+ "CRITICAL — lead-with-role rule: the FIRST sentence under ## Overview must "+ "state this file's job in one line. Use concrete architectural vocabulary "+ "(orchestrator, entry point, parser, adapter, dispatcher, factory, resolver, "+ "persistence layer, indexer, analyzer, etc.) and name what it produces or "+ "consumes. This sentence is what semantic search and grep both anchor on, "+ "so role keywords must appear at the very front — not buried in paragraph 3. "+ "Bad: 'This file contains the X class which is used by Y.' "+ "Good: 'X is the orchestrator for the indexing pipeline — it sequences "+ "traversal, parsing, graph analysis, git enrichment, and persistence.' "+ "If the user prompt lists Architectural signals (entry point, high PageRank, "+ "bridge), weave them into that first sentence rather than restating them. ""Required sections: ## Overview, ## Public API, ## Dependencies, ## Usage Notes."),"symbol_spotlight": (@@ -98,6 +110,15 @@ SYSTEM_PROMPTS: dict[str, str] = {"You are repowise, an expert technical documentation generator. ""Write a module-level overview page summarising all files in the module. ""Output markdown only. "+ "\n"+ "CRITICAL — lead-with-role rule: the FIRST sentence under ## Overview must "+ "state the module's job in the larger system. Use architectural vocabulary "+ "(ingestion subsystem, generation pipeline, persistence layer, transport "+ "adapter, etc.) and name the inputs it consumes and the outputs it produces. "+ "Bad: 'The X module contains 15 files responsible for...' "+ "Good: 'The ingestion module is the entry stage of repowise's indexing "+ "pipeline — it traverses a repository, parses files into ASTs, extracts "+ "symbols, and yields ParsedFile objects for downstream analysis.' ""Required sections: ## Overview, ## Public API Summary, ## Architecture Notes."),"scc_page": (@@ -111,6 +132,15 @@ SYSTEM_PROMPTS: dict[str, str] = {"You are repowise, an expert technical documentation generator. ""Write a high-level repository overview suitable for onboarding new developers. ""Output markdown only. "+ "\n"+ "CRITICAL — lead-with-purpose rule: the FIRST sentence under ## Project "+ "Summary must answer 'what does this repository do, end-to-end?' in one "+ "concrete sentence. Name the inputs, the pipeline, and the outputs in "+ "architectural vocabulary. "+ "Bad: 'This repository implements a documentation tool with 15 packages.' "+ "Good: 'Repowise is a codebase documentation engine: it indexes a repository "+ "by traversing files, parsing code into ASTs, analyzing dependencies, and "+ "generating LLM-synthesised wiki pages served via MCP and a web UI.' ""Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture."),"architecture_diagram": (diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index 0f870a752..d046dcf78 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -50,33 +50,28 @@ Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.### Repowise MCP Tools-This project has a Repowise MCP server configured. These tools provide documentation, ownership, architectural decisions, and risk signals. Use them for orientation and discovery — then read actual source to verify before editing.+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.-**Recommended workflow:**+**When to call which tool:**-1. Start with `get_overview()` on a new task to orient yourself.-2. Call `get_context(targets=["path/to/file.py"])` for enriched context on unfamiliar files — but always read the source before editing.-3. Call `get_risk(targets=["path/to/file.py"])` before changing hotspot files.-4. Don't know where something lives? Call `search_codebase(query="authentication flow")`.-5. Need to understand why code is structured a certain way? Call `get_why(query="why JWT over sessions")` before architectural changes.-6. After **architectural changes**, consider calling `update_decision_records(action="create", ...)` to record the rationale.-7. Need to understand how two modules connect? Call `get_dependency_path(source="src/auth", target="src/db")`.-8. Before cleanup tasks, call `get_dead_code()` to find confirmed unused code.-9. For documentation or diagrams, call `get_architecture_diagram(scope="src/auth")`.+| 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 instead of an empty answer. |+| `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=["callers","ownership",...]` 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 and safer than `Read` + offset math. Use the `symbol_id` returned by `get_context`. |+| `search_codebase(query, kind?)` | Find pages by concept when you don't know the file. Each result carries `search_method` (`embedding` vs `bm25` fallback). For exact identifiers use Grep — the tool will hint when it sees one. |+| `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. |+| `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_dead_code(...)` | Tiered unreachable / unused-export / zombie-package findings. Run before a cleanup sprint, not before a targeted fix. |+| `get_overview(repo?)` | Architecture map for an unfamiliar repo. One-time orientation; skip on subsequent calls in the same session. |-**Note:** MCP tool responses reflect the last index run. If the index is stale, verify against source files.+**Composition tips:**+- `get_answer` → if `confidence` is `medium`/`low`, follow the `best_guesses[0].file` or `fallback_targets[0]` into `get_context`, then `get_symbol` for bytes.+- `get_context` returns `decision_records` titles → call `get_why(targets=[...])` for the rationale.+- `get_context` returns `hotspot: true` → call `get_risk` before editing.+- PR review → `get_risk(targets=[...], changed_files=[...])`; read the `directive` block first.-| Tool | When to use |-|------|-------------|-| `get_overview()` | Orient yourself on a new task |-| `get_context(targets=[...])` | Enriched context on unfamiliar files |-| `get_risk(targets=[...])` | Before changing hotspot files |-| `get_why(query="...")` | Before architectural changes |-| `update_decision_records(action=...)` | After architectural changes — record decisions |-| `search_codebase(query="...")` | When locating code |-| `get_dependency_path(source=..., target=...)` | When tracing module connections |-| `get_dead_code()` | Before any cleanup or removal |-| `get_architecture_diagram(scope=...)` | For visual structure or documentation |+**Verify when:** `_meta.stale_warning` is present, or `retrieval_quality` is `partial`/`weak`, or `search_method` is `bm25`. Otherwise trust the response and act on it.{% if data.build_commands %}### Codebase Conventionsdiff --git a/packages/core/src/repowise/core/generation/templates/file_page.j2 b/packages/core/src/repowise/core/generation/templates/file_page.j2index c5f9a5a88..59aece45f 100644--- a/packages/core/src/repowise/core/generation/templates/file_page.j2+++ b/packages/core/src/repowise/core/generation/templates/file_page.j2@@ -1,17 +1,32 @@You are documenting the file `{{ ctx.file_path }}` (language: {{ ctx.language }}).## File Overview-{% if ctx.docstring %}-Module docstring: {{ ctx.docstring }}-{% endif %}-- **Path**: `{{ ctx.file_path }}`-- **Language**: {{ ctx.language }}-- **PageRank score**: {{ "%.4f"|format(ctx.pagerank_score) }}-- **Betweenness centrality**: {{ "%.4f"|format(ctx.betweenness_score) }}-- **Community**: {{ ctx.community_id }}-- **Is API contract**: {{ ctx.is_api_contract }}-- **Is entry point**: {{ ctx.is_entry_point }}-- **Is test file**: {{ ctx.is_test }}++**Path:** `{{ ctx.file_path }}` | **Language:** {{ ctx.language }}{% if ctx.is_test %} | test file{% endif %}{% if ctx.is_api_contract %} | API contract{% endif %}++{% if ctx.docstring %}**Module docstring:** {{ ctx.docstring }}++{% endif %}+{# Surface architectural signals in plain prose so the LLM weaves them into the+ opening sentence. Raw numeric metrics (pagerank=0.0234) carry no semantic+ weight in the generated page — embeddings see digits, not meaning. Stating+ the same fact in role vocabulary ("entry point", "central in dependency+ graph", "bridge between modules") puts retrieval-relevant terms into the+ page text where both FTS and vector search can anchor on them. #}+{%- set _signals = [] -%}+{%- if ctx.is_entry_point -%}{%- set _ = _signals.append("entry point into this subsystem") -%}{%- endif -%}+{%- if ctx.pagerank_score is defined and ctx.pagerank_score >= 0.01 -%}{%- set _ = _signals.append("central in the dependency graph (high PageRank)") -%}{%- endif -%}+{%- if ctx.betweenness_score is defined and ctx.betweenness_score >= 0.005 -%}{%- set _ = _signals.append("frequent bridge between modules (high betweenness)") -%}{%- endif -%}+{%- if ctx.community_label -%}{%- set _ = _signals.append("part of the " ~ ctx.community_label ~ " community") -%}{%- endif -%}+{% if _signals %}+**Architectural signals:** {{ _signals | join("; ") }}.++Weave these into the role-leading first sentence of ## Overview. They are the+shape of the file's job, not decoration.+{% endif %}++**Raw metrics** (for reference, do NOT recite verbatim in the page):+PageRank {{ "%.4f"|format(ctx.pagerank_score) }} · betweenness {{ "%.4f"|format(ctx.betweenness_score) }} · community {{ ctx.community_id }}## Symbols ({{ ctx.symbols | length }}){% for sym in ctx.symbols %}diff --git a/packages/core/src/repowise/core/generation/templates/module_page.j2 b/packages/core/src/repowise/core/generation/templates/module_page.j2index 4c5349452..55d931cdc 100644--- a/packages/core/src/repowise/core/generation/templates/module_page.j2+++ b/packages/core/src/repowise/core/generation/templates/module_page.j2@@ -1,13 +1,20 @@You are documenting the module **{{ ctx.module_path }}** (language: {{ ctx.language }}).## Module Overview-- **Label**: {{ ctx.module_path }}-- **Language**: {{ ctx.language }}-- **Files in module**: {{ ctx.files | length }}-- **Total symbols**: {{ ctx.total_symbols }} ({{ ctx.public_symbols }} public)-- **Mean PageRank**: {{ "%.4f"|format(ctx.pagerank_mean) }}-{% if ctx.community_label %}-- **Community label**: {{ ctx.community_label }}{% if ctx.community_cohesion > 0 %} (cohesion {{ "%.2f"|format(ctx.community_cohesion) }}){% endif %}++**Module:** `{{ ctx.module_path }}` | **Language:** {{ ctx.language }} | **Files:** {{ ctx.files | length }} | **Public symbols:** {{ ctx.public_symbols }} / {{ ctx.total_symbols }}{% if ctx.community_label %} | **Community:** {{ ctx.community_label }}{% if ctx.community_cohesion > 0 %} (cohesion {{ "%.2f"|format(ctx.community_cohesion) }}){% endif %}{% endif %}++{# The role-leading sentence is the highest-leverage signal a module page+ carries. Surface the module's position in the system so the LLM can frame+ the Overview correctly — high-PageRank modules are usually orchestrators+ or shared infrastructure, low-PageRank modules are leaf consumers. #}+{%- set _mod_signals = [] -%}+{%- if ctx.entry_points -%}{%- set _ = _mod_signals.append("hosts entry points into this subsystem") -%}{%- endif -%}+{%- if ctx.pagerank_mean is defined and ctx.pagerank_mean >= 0.005 -%}{%- set _ = _mod_signals.append("architecturally central (high mean PageRank across its files)") -%}{%- endif -%}+{% if _mod_signals %}+**Architectural signals:** {{ _mod_signals | join("; ") }}.++Lead the ## Overview's first sentence with the module's role in repowise's pipeline; weave the signals above into that opening rather than re-listing them.{% endif %}{% if ctx.entry_points %}diff --git a/packages/core/src/repowise/core/generation/templates/repo_overview.j2 b/packages/core/src/repowise/core/generation/templates/repo_overview.j2index 6de4ded94..ea98b76c4 100644--- a/packages/core/src/repowise/core/generation/templates/repo_overview.j2+++ b/packages/core/src/repowise/core/generation/templates/repo_overview.j2@@ -1,11 +1,14 @@You are generating a high-level overview for the repository `{{ ctx.repo_name }}`.## Repository Summary-- **Name**: {{ ctx.repo_name }}-- **Is monorepo**: {{ ctx.is_monorepo }}-- **Total files**: {{ ctx.total_files }}-- **Total lines of code**: {{ ctx.total_loc }}-- **Circular dependency count**: {{ ctx.circular_dependency_count }}++**Name:** `{{ ctx.repo_name }}`{% if ctx.is_monorepo %} (monorepo){% endif %} | **Files:** {{ ctx.total_files }} | **LOC:** {{ ctx.total_loc }}{% if ctx.circular_dependency_count > 0 %} | **Circular deps:** {{ ctx.circular_dependency_count }}{% endif %}++The first sentence of your ## Project Summary section is what every downstream+agent (RAG, semantic search, onboarding) anchors on. Make it answer "what does+this repository do, end-to-end?" using concrete pipeline vocabulary — name the+inputs the repo consumes, the transformation stages, and the artifacts produced.+Do NOT open with stats or package counts; those belong further down.## Packages{% for pkg in ctx.packages %}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.j2index 855109179..ecf9bf68a 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@@ -55,30 +55,22 @@ _No entry points indexed._### Repowise MCP Tools-These tools work across all repos in this workspace. Pass `repo="alias"` to scope queries, or omit for the default repo.+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.-**Recommended workflow:**+| 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, kind?)` | Find pages by concept when you don't know the file. Each result tags its `search_method` (`embedding` vs `bm25`). For exact identifiers use Grep. |+| `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_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). |-1. Start with `get_overview()` on a new task to orient yourself.-2. Call `get_context(targets=["path/to/file.py"])` for enriched context on unfamiliar files — but always read the source before editing.-3. Call `get_risk(targets=["path/to/file.py"])` before changing hotspot files.-4. Don't know where something lives? Call `search_codebase(query="authentication flow")`.-5. Need to understand why code is structured a certain way? Call `get_why(query="why JWT over sessions")` before architectural changes.-6. After **architectural changes**, consider calling `update_decision_records(action="create", ...)` to record the rationale.-7. Need to understand how two modules connect? Call `get_dependency_path(source="src/auth", target="src/db")`.-8. Before cleanup tasks, call `get_dead_code()` to find confirmed unused code.-9. For documentation or diagrams, call `get_architecture_diagram(scope="src/auth")`.+**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.-**Note:** MCP tool responses reflect the last index run. If the index is stale, verify against source files.--| Tool | When to use |-|------|-------------|-| `get_overview()` | Orient yourself on a new task |-| `get_context(targets=[...])` | Enriched context on unfamiliar files |-| `get_risk(targets=[...])` | Before changing hotspot files |-| `get_why(query="...")` | Before architectural changes |-| `update_decision_records(action=...)` | After architectural changes — record decisions |-| `search_codebase(query="...")` | When locating code |-| `get_dependency_path(source=..., target=...)` | When tracing module connections |-| `get_dead_code()` | Before any cleanup or removal |-| `get_architecture_diagram(scope=...)` | For visual structure or documentation |+**Verify when:** `_meta.stale_warning` is present, `retrieval_quality` is `partial`/`weak`, or `search_method` is `bm25`. Otherwise trust the response.diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 438e98266..cc4405f3c 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -1,4 +1,4 @@-"""repowise MCP Server — 7 tools for AI coding assistants.+"""repowise MCP Server — 8 tools for AI coding assistants.Exposes the full repowise wiki as queryable tools via the MCP protocol.Supports both stdio transport (Claude Code, Cursor, Cline) and SSE transport@@ -36,6 +36,7 @@ from repowise.server.mcp_server.tool_dead_code import get_dead_codefrom repowise.server.mcp_server.tool_overview import get_overviewfrom repowise.server.mcp_server.tool_risk import get_riskfrom repowise.server.mcp_server.tool_search import search_codebase+from repowise.server.mcp_server.tool_symbol import get_symbolfrom repowise.server.mcp_server.tool_why import get_why# ---------------------------------------------------------------------------@@ -96,6 +97,7 @@ __all__ = ["get_dead_code","get_overview","get_risk",+ "get_symbol","get_why","mcp","run_mcp",diff --git a/packages/server/src/repowise/server/mcp_server/_answer_context.py b/packages/server/src/repowise/server/mcp_server/_answer_context.pynew file mode 100644index 000000000..32a530d14--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_answer_context.py@@ -0,0 +1,332 @@+"""LLM context construction for ``get_answer``.++The LLM only ever sees what we put in its prompt. This module owns *that*+text — and only that. Three responsibilities, each in its own function so+the orchestrator can swap individual layers without re-deriving the rest:++ 1. ``fetch_relevant_decisions`` — for "why"-shaped questions, pull+ DecisionRecord rows that touch the top hits. Architectural rationale+ lives in ADRs, not file summaries — without this layer the LLM hedges+ on every "why" question even when ``get_why`` would have the answer.++ 2. ``build_structured_prelude`` — a short scaffolding block placed BEFORE+ the file excerpts: top symbols by PageRank, recent significant commits,+ decision titles, co-change partners. Gives the LLM a frame to interpret+ the excerpts against, rather than reading them cold.++ 3. ``build_context_block`` — assembles the final prompt body: prelude+ followed by per-hit excerpts with their hydrated symbols. Lives here+ so the formatting is colocated with the data sources that feed it.+"""++from __future__ import annotations++import json+import re+from typing import Any++from sqlalchemy import select++from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import DecisionRecord, GitMetadata++# Heuristic for "why"-shaped questions. Cheap — first-word check plus+# "why" appearing as a whole word. Conservative so we don't mistakenly+# fuse ADRs into a "how does X work" question (which has its own grounding+# needs and doesn't want ADR-driven hedging).+_WHY_PATTERN = re.compile(r"\bwhy\b", re.IGNORECASE)++# How many decision records to inject, and per-record truncation. Three is+# usually enough — most files are governed by 0–2 active ADRs; 3 gives room+# for one tangential overlap without blowing the context budget.+_MAX_DECISIONS_INJECTED = 3+_DECISION_RATIONALE_CHARS = 400++# How many significant commits to surface in the prelude. Recent + filtered+# already by the indexer — we just take the head of the list per hit.+_MAX_PRELUDE_COMMITS_PER_HIT = 2++# Per-symbol truncation in the context block. Matches the existing+# get_answer behavior — separate constants here so future tuning doesn't+# have to thread through the orchestrator.+_MAX_SYMBOL_DOC_CHARS = 120+_MATCHED_SYMBOL_DOC_CHARS = 400+_MAX_CHARS_PER_HIT_SUMMARY = 800+++def is_why_question(question: str) -> bool:+ """True when the question is about rationale, not mechanism.++ "why" present as a whole word is the signal. We avoid substring matches+ ("typewriter" contains "why" — no, but the principle holds for less+ obvious cases) by anchoring to word boundaries.+ """+ return bool(question and _WHY_PATTERN.search(question))+++# ---------------------------------------------------------------------------+# Decision-record fusion+# ---------------------------------------------------------------------------+++async def fetch_relevant_decisions(+ ctx: Any,+ repo_id: str,+ target_paths: list[str],+ *,+ limit: int = _MAX_DECISIONS_INJECTED,+) -> list[dict]:+ """Return up to ``limit`` decisions touching any of ``target_paths``.++ Scans active+proposed decisions (skips deprecated/superseded — those are+ historical and shouldn't drive a current answer). Ranks by overlap with+ target_paths: a decision touching three of the top hits is more relevant+ than one touching only the fifth. Ties broken by status preference+ (active > proposed) and confidence.+ """+ if not target_paths:+ return []+ targets_set = set(target_paths)+ async with get_session(ctx.session_factory) as session:+ res = await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repo_id,+ DecisionRecord.status.in_(("active", "proposed")),+ )+ )+ all_decisions = list(res.scalars().all())++ scored: list[tuple[int, float, DecisionRecord]] = []+ for d in all_decisions:+ try:+ affected = set(json.loads(d.affected_files_json or "[]"))+ except (json.JSONDecodeError, TypeError):+ affected = set()+ overlap = len(affected & targets_set)+ if overlap == 0:+ continue+ # Active outranks proposed at the same overlap; confidence breaks+ # ties within a status. Negative tuple element so higher = better+ # after ascending sort.+ status_rank = 0 if d.status == "active" else 1+ scored.append((-overlap, status_rank, d))++ scored.sort(key=lambda t: (t[0], t[1], -(t[2].confidence or 0.0)))+ selected = [d for _, _, d in scored[:limit]]+ return [_decision_to_dict(d) for d in selected]+++def _decision_to_dict(d: DecisionRecord) -> dict:+ """Compact projection — only fields the LLM needs to ground rationale."""+ rationale = (d.rationale or "").strip()+ if len(rationale) > _DECISION_RATIONALE_CHARS:+ rationale = rationale[:_DECISION_RATIONALE_CHARS].rstrip() + "…"+ return {+ "title": d.title,+ "status": d.status,+ "decision": (d.decision or "").strip(),+ "rationale": rationale,+ }+++# ---------------------------------------------------------------------------+# Structured prelude+# ---------------------------------------------------------------------------+++async def build_structured_prelude(+ hits: list[dict],+ decisions: list[dict],+ ctx: Any,+ repo_id: str,+) -> str:+ """Build the scaffolding block placed before file excerpts.++ Layout (each section omitted when empty so the prelude is never just+ section headers):++ Top symbols by relevance: ...+ Recent significant commits: ...+ Decision records: ...++ Designed to fit in roughly 400-800 chars regardless of how many hits we+ pass in. The point is *frame*, not coverage — the file excerpts that+ follow carry the actual material.+ """+ sections: list[str] = []++ top_symbols = _top_symbols_summary(hits)+ if top_symbols:+ sections.append(f"Top symbols by relevance: {top_symbols}")++ commits_line = await _recent_commits_summary(hits, ctx, repo_id)+ if commits_line:+ sections.append(f"Recent significant commits: {commits_line}")++ if decisions:+ titles = "; ".join(+ f"{d['title']} ({d['status']})" for d in decisions+ )+ sections.append(f"Decision records touching these files: {titles}")++ if not sections:+ return ""+ return "## Context scaffolding\n\n" + "\n".join(f"- {s}" for s in sections) + "\n"+++def _top_symbols_summary(hits: list[dict]) -> str:+ """One-line summary of the top question-matched symbols across hits.++ Prefers symbols flagged ``_matched`` by upstream symbol hydration —+ those are the ones the question explicitly named. Falls back to the+ first symbol of the top hit when no matches are present.+ """+ matched: list[str] = []+ for h in hits[:3]:+ for s in h.get("symbols") or []:+ if s.get("_matched"):+ name = s.get("name") or s.get("signature") or ""+ kind = s.get("kind") or "?"+ if name:+ matched.append(f"{name} ({kind}) in {h.get('target_path','')}")+ if len(matched) >= 4:+ break+ if len(matched) >= 4:+ break+ if matched:+ return "; ".join(matched)++ # No matched symbols — surface the head symbol of the top hit so the+ # LLM at least knows what's in the most relevant file.+ if hits and hits[0].get("symbols"):+ s = hits[0]["symbols"][0]+ name = s.get("name") or ""+ kind = s.get("kind") or ""+ path = hits[0].get("target_path", "")+ if name:+ return f"{name} ({kind}) in {path}"+ return ""+++async def _recent_commits_summary(+ hits: list[dict], ctx: Any, repo_id: str+) -> str:+ """Short summary of significant commits across the top hits.++ GitMetadata.significant_commits_json is already filtered by the indexer+ for noise (style/chore commits dropped). We surface the most recent+ couple per hit, deduplicated by SHA — enough to anchor "what changed+ recently" follow-ups without rebuilding the git log.+ """+ paths = [h.get("target_path") for h in hits[:3] if h.get("target_path")]+ if not paths:+ return ""+ async with get_session(ctx.session_factory) as session:+ res = await session.execute(+ select(GitMetadata.file_path, GitMetadata.significant_commits_json).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.file_path.in_(paths),+ )+ )+ rows = list(res.all())++ seen_shas: set[str] = set()+ lines: list[str] = []+ for _path, sig_json in rows:+ try:+ commits = json.loads(sig_json or "[]")+ except (json.JSONDecodeError, TypeError):+ continue+ for c in commits[:_MAX_PRELUDE_COMMITS_PER_HIT]:+ sha = (c.get("sha") or "")[:7]+ if sha in seen_shas or not sha:+ continue+ seen_shas.add(sha)+ msg = (c.get("message") or "").split("\n")[0][:80]+ date = (c.get("date") or "")[:10]+ lines.append(f"{sha} {date} {msg}")+ if len(lines) >= 4:+ break+ if len(lines) >= 4:+ break+ return "; ".join(lines)+++# ---------------------------------------------------------------------------+# Context block assembly+# ---------------------------------------------------------------------------+++def build_context_block(+ hits: list[dict],+ prelude: str = "",+ decisions: list[dict] | None = None,+ *,+ max_chars_per_hit: int = _MAX_CHARS_PER_HIT_SUMMARY,+) -> str:+ """Format the LLM prompt body: prelude + decisions block + per-hit excerpts.++ Replaces the inline ``_build_context_block`` in tool_answer. Behavior+ parity for the per-hit part (file summary, symbol signatures, matched-+ symbol source bodies); additions are the prelude and the optional+ decisions block, each gated on having content.+ """+ parts: list[str] = []+ if prelude:+ parts.append(prelude.rstrip())+ if decisions:+ parts.append(_format_decisions_block(decisions))+ parts.append(_format_hits_block(hits, max_chars_per_hit))+ return "\n\n".join(p for p in parts if p)+++def _format_decisions_block(decisions: list[dict]) -> str:+ """Pull the ADRs to the front of the prompt where the LLM grounds intent."""+ lines = ["## Architectural decisions touching these files"]+ for i, d in enumerate(decisions, start=1):+ lines.append(f"[D{i}] {d['title']} ({d['status']})")+ if d.get("decision"):+ lines.append(f" decision: {d['decision']}")+ if d.get("rationale"):+ lines.append(f" rationale: {d['rationale']}")+ return "\n".join(lines)+++def _format_hits_block(hits: list[dict], max_chars_per_hit: int) -> str:+ """Format the per-hit excerpts. Mirrors the prior tool_answer behaviour."""+ parts: list[str] = []+ for i, h in enumerate(hits, start=1):+ body_src = h.get("summary") or h.get("snippet") or ""+ body = body_src[:max_chars_per_hit]+ # Tag expanded hits so the LLM knows they didn't surface in retrieval+ # directly — useful context when deciding how much weight to put on+ # them in the answer.+ tag = " [graph-expanded]" if h.get("_expanded_from") else ""+ sources = h.get("_sources") or set()+ src_tag = f" [{'+'.join(sorted(sources))}]" if sources else ""+ block = [+ f"[{i}] {h.get('target_path','')} (score={h.get('score', 0.0):.3f}){tag}{src_tag}",+ f" title: {h.get('title','')}",+ f" summary: {body}",+ ]+ symbols = h.get("symbols") or []+ if symbols:+ block.append(" symbols:")+ for s in symbols:+ sig = s.get("signature") or s.get("name") or ""+ kind = s.get("kind") or "?"+ matched = bool(s.get("_matched"))+ doc = (s.get("docstring") or "").strip()+ doc_cap = _MATCHED_SYMBOL_DOC_CHARS if matched else _MAX_SYMBOL_DOC_CHARS+ match_tag = " [question-match]" if matched else ""+ block.append(f" - [{kind}]{match_tag} {sig}")+ if doc:+ trimmed = " ".join(doc.split())[:doc_cap]+ block.append(f" docstring: {trimmed}")+ src = s.get("source_excerpt")+ if src:+ block.append(" source:")+ for line in src.splitlines():+ block.append(f" {line}")+ parts.append("\n".join(block))+ return "\n\n".join(parts)diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pynew file mode 100644index 000000000..6ae453f54--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -0,0 +1,374 @@+"""Retrieval pipeline for ``get_answer``.++This module owns everything that turns a developer question into a ranked+list of candidate wiki hits — but emphatically not the LLM step, the cache,+or the response shape (those live in ``tool_answer``). Separation of concerns+lets us iterate on retrieval quality without rereading the orchestrator and+vice versa.++Pipeline (each stage is a pure function over hit dicts):++ 1. ``hybrid_retrieve`` — FTS + vector store in parallel, merged via+ Reciprocal Rank Fusion. Single retrieval+ modes systematically miss either token+ matches (vectors drift) or conceptual+ matches (FTS is literal). Two modes catch+ both classes of failure for the cost of one+ extra coroutine.+ 2. ``hydrate_hits`` — attach target_path, summary, page_type from+ the Page table to each hit.+ 3. ``apply_pagerank_bias`` — multiply scores by a damped PageRank factor+ so architecturally central files outrank+ peripheral ones at similar retrieval score.+ This is what rescues "how does X work"+ questions from peripheral consumers of X.+ 4. ``expand_via_graph`` — for top-N hits, walk 1 hop through imports+ and pull in neighbors that have a wiki+ page. Rescues near-misses where retrieval+ landed in the right module but on a wrong+ file (consumer vs. orchestrator).++Stages downstream of this module (term coverage, intersection boost, domain+penalty) live in ``tool_answer`` for now — they're tightly coupled to the+existing question-aware symbol promotion code and not worth duplicating.+"""++from __future__ import annotations++import asyncio+import contextlib+from typing import Any++from sqlalchemy import select++from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import GraphEdge, GraphNode, Page++# How many candidates each retriever fetches before merging. Both modes+# tend to put the right answer in their top ~10, so 15 gives RRF room to+# resolve ties without dragging weak tail hits into the merge.+_RETRIEVAL_FETCH_LIMIT = 15++# RRF constant. The standard k=60 from the original RRF paper — large enough+# that rank-1 (1/61) and rank-2 (1/62) are close, small enough that rank-10+# (1/70) still contributes meaningfully when a hit only shows up in one mode.+_RRF_K = 60++# Multiplier applied to RRF scores so they land in roughly the same numeric+# range as the BM25 raw scores the downstream gates/thresholds (dominance+# ratio, high-confidence score floor, absolute-gap branch) were tuned for.+#+# Top-1 RRF with both modes hitting at rank 0 is 1/60 + 1/60 ≈ 0.033.+# Scaling by 180 puts it at ~6, matching the upper end of observed BM25+# scores on this corpus. Pure ordering preservation — never changes+# *which* hit ranks where, only the absolute numbers the gates compare.+_RRF_SCORE_SCALE = 180.0++# Cap how many extra files graph expansion can add. Without a cap, a hub+# file (many importers) would flood the candidate set and dilute the LLM's+# context budget on tangential neighbors.+_GRAPH_EXPAND_TOP_N = 2+_GRAPH_EXPAND_MAX_NEW = 3++# PageRank bias is multiplicative and capped. We don't want a marginally+# more central file to outrank a strong text match — only to break ties.+# Empirically PageRank values on this corpus span ~0 to ~0.01; we normalise+# to the max in the candidate set and scale to a [1.0, 1.3] multiplier.+_PAGERANK_BIAS_MAX = 0.3++# Damping factor for graph-expanded hits. They didn't surface in retrieval,+# so we trust them less than direct hits — but enough to outrank the bottom+# of the top-5 if the parent was strong. 0.7 keeps a strong parent's child+# (e.g. parent at 4.5, expanded child at 3.15) competitive with a real+# rank-3/4 hit (~3.0-3.5).+_GRAPH_EXPAND_DAMPING = 0.7+++# ---------------------------------------------------------------------------+# Stage 1: Hybrid retrieval (FTS + vector → RRF merge)+# ---------------------------------------------------------------------------+++async def hybrid_retrieve(question: str, ctx: Any) -> list[dict]:+ """Run FTS and vector retrieval in parallel and merge via RRF.++ Returns a list of dicts shaped ``{page_id, title, score, snippet,+ page_type, _sources: set[str]}``. ``_sources`` names which retrievers+ found the hit — useful for ranking signal ("hit by both modes" is a+ stronger ground-truth signal than "hit by one"). Score is the RRF-fused+ score; downstream stages may multiply it further.++ Both retrievers are best-effort with timeouts so one slow path can never+ block the call. An empty result from one mode just means the other mode+ fully drives ranking, which matches the pre-hybrid behaviour.+ """+ fts_task = _safe_fts_search(ctx, question)+ vec_task = _safe_vector_search(ctx, question)+ fts_results, vec_results = await asyncio.gather(fts_task, vec_task)++ # RRF merge. Each hit's contribution from a source is 1/(rank + k);+ # hits appearing in both sources sum their contributions naturally.+ fused: dict[str, dict] = {}+ for rank, h in enumerate(fts_results):+ entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))+ entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _RRF_K)+ entry["_sources"].add("fts")+ for rank, h in enumerate(vec_results):+ entry = fused.setdefault(h.page_id, _hit_dict_from_result(h))+ entry["score"] = entry.get("score", 0.0) + 1.0 / (rank + _RRF_K)+ entry["_sources"].add("vector")++ # Scale to BM25-range so downstream confidence/dominance gates (tuned+ # against the prior single-mode BM25 retrieval) keep behaving sanely.+ # Ordering is unchanged — multiplying by a positive constant is a+ # no-op for ranking.+ for entry in fused.values():+ entry["score"] = entry["score"] * _RRF_SCORE_SCALE++ merged = list(fused.values())+ merged.sort(key=lambda h: h["score"], reverse=True)+ return merged+++async def _safe_fts_search(ctx: Any, question: str) -> list[Any]:+ """FTS search wrapped in timeout + suppression. Returns [] on any failure."""+ if ctx.fts is None:+ return []+ try:+ return await asyncio.wait_for(+ ctx.fts.search(question, limit=_RETRIEVAL_FETCH_LIMIT), timeout=5.0+ )+ except Exception:+ return []+++async def _safe_vector_search(ctx: Any, question: str) -> list[Any]:+ """Vector search wrapped in timeout + suppression. Returns [] on any failure.++ Also waits for vector-store readiness when the lifespan event is set —+ skipping the wait would race a background-loading store on cold start.+ """+ if ctx.vector_store is None:+ return []+ ready = getattr(ctx, "vector_store_ready", None)+ if ready is not None:+ with contextlib.suppress(TimeoutError):+ await asyncio.wait_for(ready.wait(), timeout=30.0)+ try:+ return await asyncio.wait_for(+ ctx.vector_store.search(question, limit=_RETRIEVAL_FETCH_LIMIT),+ timeout=8.0,+ )+ except Exception:+ return []+++def _hit_dict_from_result(result: Any) -> dict:+ """Convert a retriever result object to the pipeline's dict shape."""+ return {+ "page_id": result.page_id,+ "title": getattr(result, "title", ""),+ "snippet": getattr(result, "snippet", ""),+ "page_type": getattr(result, "page_type", ""),+ "score": 0.0,+ "_sources": set(),+ }+++# ---------------------------------------------------------------------------+# Stage 2: Hydrate hits with Page metadata (target_path, summary)+# ---------------------------------------------------------------------------+++async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None) -> list[dict]:+ """Attach target_path, summary, and page_type from the Page table.++ Mutates each hit in place. Applies the ``scope`` filter (path prefix) at+ this stage rather than during retrieval — retrievers don't know about+ paths, and post-filtering keeps the merge logic source-agnostic.+ """+ if not hits:+ return hits+ page_ids = [h["page_id"] for h in hits]+ async with get_session(ctx.session_factory) as session:+ res = await session.execute(+ select(Page.id, Page.target_path, Page.summary, Page.page_type).where(+ Page.id.in_(page_ids)+ )+ )+ meta_by_id = {+ row[0]: {+ "target_path": row[1] or "",+ "summary": row[2] or "",+ "page_type": row[3] or "",+ }+ for row in res.all()+ }++ out: list[dict] = []+ for h in hits:+ meta = meta_by_id.get(h["page_id"], {})+ target_path = meta.get("target_path", "")+ if scope and target_path and not target_path.startswith(scope):+ continue+ h["target_path"] = target_path+ h["summary"] = meta.get("summary", "")+ # Prefer the Page table's page_type when present — it's the source+ # of truth; retrievers sometimes carry stale or empty types.+ h["page_type"] = meta.get("page_type") or h.get("page_type", "")+ out.append(h)+ return out+++# ---------------------------------------------------------------------------+# Stage 3: PageRank bias+# ---------------------------------------------------------------------------+++async def apply_pagerank_bias(hits: list[dict], ctx: Any) -> None:+ """Multiply each hit's score by a damped PageRank factor (in place).++ Looks up the GraphNode row for each hit's target_path and pulls its+ PageRank. We normalise within the candidate set rather than against the+ whole graph: a candidate with the highest PageRank among its peers gets+ the full bias, the lowest gets none. This avoids the failure mode where+ an absolute scale would over-reward famous-but-irrelevant files.+ """+ if not hits:+ return+ paths = [h.get("target_path") for h in hits if h.get("target_path")]+ if not paths:+ return+ async with get_session(ctx.session_factory) as session:+ # Look up GraphNodes by node_id — file nodes are keyed by their path.+ res = await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.node_id.in_(paths),+ GraphNode.node_type == "file",+ )+ )+ pr_by_path = {row[0]: float(row[1] or 0.0) for row in res.all()}++ if not pr_by_path:+ return+ max_pr = max(pr_by_path.values(), default=0.0)+ if max_pr <= 0:+ return++ for h in hits:+ pr = pr_by_path.get(h.get("target_path"), 0.0)+ # Normalised in [0, 1] then scaled to a multiplicative bias in+ # [1.0, 1 + _PAGERANK_BIAS_MAX].+ bias = 1.0 + _PAGERANK_BIAS_MAX * (pr / max_pr)+ h["_pagerank"] = pr+ h["_pagerank_bias"] = round(bias, 3)+ h["score"] = h.get("score", 0.0) * bias++ hits.sort(key=lambda h: h["score"], reverse=True)+++# ---------------------------------------------------------------------------+# Stage 4: Graph expansion (1-hop neighbors of top hits)+# ---------------------------------------------------------------------------+++async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:+ """Add up to ``_GRAPH_EXPAND_MAX_NEW`` graph-neighbor files to ``hits``.++ Rescues near-misses where the top retrieved file is in the right+ neighborhood but isn't the actual answer (a consumer instead of the+ orchestrator, a wrapper instead of the implementation). Expansion walks+ one hop through GraphEdges in both directions from the top-N candidates,+ then folds in any neighbor that:+ * has a wiki page (otherwise the LLM has nothing to read)+ * is not already in the candidate set++ Expanded hits carry an ``_expanded_from`` marker and a damped score so+ the gate / confidence calibration knows they're indirect.+ """+ if not hits:+ return hits+ seed_paths = [+ h.get("target_path") for h in hits[:_GRAPH_EXPAND_TOP_N] if h.get("target_path")+ ]+ if not seed_paths:+ return hits+ existing = {h.get("target_path") for h in hits}++ async with get_session(ctx.session_factory) as session:+ # Importers (someone → seed) and importees (seed → someone) in one+ # query each. Two queries are fine — both hit the same indexed edge+ # table and run in <10ms on the corpus this is tuned for.+ importer_res = await session.execute(+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ GraphEdge.target_node_id.in_(seed_paths),+ )+ )+ importee_res = await session.execute(+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ GraphEdge.source_node_id.in_(seed_paths),+ )+ )++ neighbors: set[str] = set()+ for src, tgt in importer_res.all():+ if src and src not in existing:+ neighbors.add(src)+ for src, tgt in importee_res.all():+ if tgt and tgt not in existing:+ neighbors.add(tgt)++ if not neighbors:+ return hits++ # Only fold in neighbors that have a wiki page — otherwise the LLM+ # context block can't carry a useful excerpt for them.+ page_res = await session.execute(+ select(Page.target_path, Page.summary, Page.page_type).where(+ Page.target_path.in_(neighbors),+ Page.page_type == "file_page",+ )+ )+ page_rows = list(page_res.all())++ # Also load PageRank for the neighbors so we can rank them.+ pr_res = await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.node_id.in_(neighbors),+ GraphNode.node_type == "file",+ )+ )+ pr_by_path = {row[0]: float(row[1] or 0.0) for row in pr_res.all()}++ if not page_rows:+ return hits++ # Damp parent score by _GRAPH_EXPAND_DAMPING for child candidates; pick+ # the strongest parent each child connects to (taking the max parent+ # score is conservative — favors well-connected neighbors).+ parent_score = max((h.get("score", 0.0) for h in hits[:_GRAPH_EXPAND_TOP_N]), default=0.0)+ candidates: list[dict] = []+ for path, summary, page_type in page_rows:+ candidates.append({+ "page_id": f"file_page:{path}",+ "target_path": path,+ "title": f"File: {path}",+ "summary": summary or "",+ "snippet": (summary or "")[:200],+ "page_type": page_type or "file_page",+ "score": parent_score * _GRAPH_EXPAND_DAMPING,+ "_sources": {"graph_expand"},+ "_expanded_from": "graph",+ "_pagerank": pr_by_path.get(path, 0.0),+ })++ # Rank candidates by PageRank within the expansion set so we pick the+ # most central neighbor first when we have multiple plausible ones.+ candidates.sort(key=lambda c: -c.get("_pagerank", 0.0))+ additions = candidates[:_GRAPH_EXPAND_MAX_NEW]+ if not additions:+ return hits++ combined = hits + additions+ combined.sort(key=lambda h: h["score"], reverse=True)+ return combineddiff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex b83cd7e10..a16e4cfc4 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -18,8 +18,124 @@ Rules of thumb baked into the hint generators:from __future__ import annotations+from datetime import datetime, timezone+from pathlib import Pathfrom typing import Any+# Only warn about age when we have no other signal AND the index is genuinely+# old. A short threshold here would nag on every call and train the agent to+# ignore the field — defeating the point. 90 days is a deliberate floor: by+# then even quiet repos have likely drifted enough that a re-index matters.+# The preferred path is the git-HEAD comparison below, which fires only on a+# real mismatch and gives a single, calibrated stale signal.+_STALE_AGE_FLOOR_DAYS = 90+++def _read_live_head(local_path: str | None) -> str | None:+ """Read the repo's current git HEAD SHA via plain file I/O.++ Returns a full 40-char SHA, or ``None`` when the repo isn't a git checkout+ on disk (hosted indexes, ephemeral clones). Avoids spawning ``git``: we+ parse ``.git/HEAD`` and follow at most one ref — fast enough to call on+ every MCP tool response without caching, and never blocks the event loop.++ Detached HEADs are handled (the HEAD file contains the SHA directly).+ Unknown ref formats just return ``None`` rather than guessing — staleness+ semantics should fail closed (no warning) rather than open (false alarms).+ """+ if not local_path:+ return None+ git_dir = Path(local_path) / ".git"+ if not git_dir.is_dir():+ return None+ try:+ head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()+ except OSError:+ return None+ if head.startswith("ref: "):+ ref_rel = head[5:].strip()+ # Try the loose ref first, then packed-refs as a fallback. Packed-refs+ # is common right after `git gc` or on freshly cloned repos.+ ref_file = git_dir / ref_rel+ try:+ return ref_file.read_text(encoding="utf-8").strip() or None+ except OSError:+ pass+ packed = git_dir / "packed-refs"+ try:+ for raw in packed.read_text(encoding="utf-8").splitlines():+ if raw.startswith("#") or raw.startswith("^"):+ continue+ sha, _, name = raw.partition(" ")+ if name.strip() == ref_rel:+ return sha.strip() or None+ except OSError:+ return None+ return None+ # Detached HEAD: the file contains the SHA verbatim.+ return head or None+++def freshness_from_repo(repository: Any | 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+ the tools. Two signals, in order of preference:++ 1. **Git HEAD comparison** (preferred). If the repo is a checkout on+ disk, compare ``repository.head_commit`` to the live HEAD. They+ match → silence. They differ → ``stale_warning`` plus the live SHA+ so the agent can decide whether to call ``repowise update``.+ 2. **Age fallback** (only when git is unreachable). Warn only past 90+ days; under that, just emit ``index_age_days`` for the agent to+ consult on its own terms.++ 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)++ Defensive throughout: any missing piece is dropped rather than raised so+ an upstream change to the Repository model can never poison a tool result.+ """+ if repository is None:+ return {}+ out: dict[str, Any] = {}++ updated_at = getattr(repository, "updated_at", None)+ age_days: int | None = None+ if isinstance(updated_at, datetime):+ ua = updated_at if updated_at.tzinfo else updated_at.replace(tzinfo=timezone.utc)+ age_days = max(0, (datetime.now(timezone.utc) - ua).days)+ out["index_age_days"] = age_days++ indexed_full = getattr(repository, "head_commit", None) or None+ if indexed_full:+ out["indexed_commit"] = indexed_full[:12] if isinstance(indexed_full, str) else indexed_full++ local_path = getattr(repository, "local_path", None)+ live_full = _read_live_head(local_path)++ if live_full and indexed_full:+ if live_full != indexed_full:+ out["live_head"] = live_full[:12]+ out["stale_warning"] = (+ f"Index built at {indexed_full[:12]} but HEAD is at "+ f"{live_full[:12]} — code has moved on. 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.+ out["stale_warning"] = (+ f"Index is {age_days} days old and live HEAD is unreachable — "+ "results may be stale. Run `repowise update`."+ )++ 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 = (@@ -58,15 +174,24 @@ def build_meta(timing_ms: float | None = None,hint: str | None = None,cached: bool = False,+ repository: Any | None = None,extra: dict[str, Any] | None = None,) -> dict[str, Any]:"""Construct a `_meta` envelope. All fields optional, omitted if falsy.+ 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.+Stable shape:{- "timing_ms": float, # tool wall-time (omitted if None)- "hint": str, # short follow-up suggestion (omitted if None)- "cached": bool, # only included when True+ "timing_ms": float, # tool wall-time (omitted if None)+ "hint": str, # short follow-up suggestion (omitted if None)+ "cached": bool, # only included when True+ "index_age_days": int, # days since last `repowise update`+ "indexed_commit": str, # short SHA the index was built against+ "stale_warning": str, # only when age > threshold...extras}"""@@ -77,6 +202,8 @@ def build_meta(out["hint"] = hintif cached:out["cached"] = True+ if repository is not None:+ out.update(freshness_from_repo(repository))if extra:out.update(extra)return outdiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer.pyindex a4ce5fef2..1c48918c9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer.py@@ -32,6 +32,26 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import AnswerCache, Page, WikiSymbol+from repowise.server.mcp_server._answer_context import (+ build_context_block as _build_context_block_v2,+)+from repowise.server.mcp_server._answer_context import (+ build_structured_prelude as _build_structured_prelude,+)+from repowise.server.mcp_server._answer_context import (+ fetch_relevant_decisions as _fetch_relevant_decisions,+)+from repowise.server.mcp_server._answer_context import is_why_question as _is_why_question+from repowise.server.mcp_server._answer_pipeline import (+ apply_pagerank_bias as _apply_pagerank_bias,+)+from repowise.server.mcp_server._answer_pipeline import (+ expand_via_graph as _expand_via_graph,+)+from repowise.server.mcp_server._answer_pipeline import (+ hybrid_retrieve as _hybrid_retrieve,+)+from repowise.server.mcp_server._answer_pipeline import hydrate_hits as _hydrate_hitsfrom repowise.server.mcp_server._helpers import (_get_repo,_resolve_repo_context,@@ -209,6 +229,62 @@ def _answer_is_hedged(answer_text: str) -> bool:_GATED_EXCERPT_CHARS = 600_GATED_RETURN_HITS = 3+# Path-prefix domain heuristics — down-weight cross-domain retrievals so a+# clearly backend question doesn't anchor on a same-vocabulary UI file (and+# vice versa). The penalty is multiplicative, not absolute, so a strongly+# matching cross-domain file can still survive on raw signal; the goal is+# to break ties when retrieval is otherwise ambiguous, not to censor results.+_UI_PATH_PREFIXES = (+ "packages/ui/",+ "packages/web/",+ "frontend/",+ "website/",+)+_BACKEND_PATH_PREFIXES = (+ "packages/server/",+ "packages/core/",+ "packages/cli/",+ "backend/",+ "modal_app/",+)+# Tokens that flag a question as being about a specific domain. Kept small+# and conservative — ambiguous questions (both lists hit, or neither) fall+# through to no penalty rather than misclassify.+_UI_QUESTION_TOKENS = frozenset({+ "ui", "frontend", "component", "react", "tsx", "jsx", "render",+ "css", "tailwind", "view", "dashboard", "button", "modal", "page",+ "browser", "client-side",+})+_BACKEND_QUESTION_TOKENS = frozenset({+ "backend", "server", "api", "endpoint", "route", "indexer", "ingest",+ "ingestion", "pipeline", "database", "db", "schema", "migration",+ "orchestrat", "mcp", "fastapi", "sqlalchemy", "subprocess", "worker",+ "cli", "command", "sql",+})+# Penalty factor applied to cross-domain hits. 0.5 is strong enough to+# overtake a same-domain near-tie but small enough that a dominant cross-+# domain hit (real top score outlier) still survives.+_DOMAIN_PENALTY = 0.5++# Floor on raw top-hit score for "high" confidence. Below this the answer+# may be technically dominant but built on weak retrieval — downgrade to+# "medium" so the agent verifies. Tuned against observed BM25 ranges on+# the wiki corpus where useful hits routinely score >1.5.+_HIGH_CONFIDENCE_SCORE_FLOOR = 1.5++# Schema version stamped on every cached payload. Bump whenever the response+# shape changes in a way that would mislead a consumer reading an old cached+# entry (new top-level fields, semantics of existing fields). On cache reads+# we treat any payload at a lower version as a miss and re-synthesise — the+# alternative (returning stale-shape payloads) silently bypasses every+# improvement to the tool and was the failure mode that hid the entire+# get_answer rework behind a cache hit during testing.+# v3: retrieval pipeline overhaul (hybrid FTS+vector, PageRank bias, graph+# expansion, structured prelude, decision fusion). Cached v2 payloads were+# synthesised over weaker retrieval — bumping forces re-synthesis so the+# upgrade actually reaches callers without waiting for cache expiry.+_ANSWER_SCHEMA_VERSION = 3+# Intersection-retrieval connectives. If a question contains any of these# (case-insensitive whole-word), it's likely a relational/multi-entity# question. We split the question on the connective, run two FTS passes,@@ -732,6 +808,77 @@ async def _enrich_gated_excerpts(hits: list[dict], ctx: Any = None) -> None:h["excerpt"] = body[:_GATED_EXCERPT_CHARS]+def _detect_question_domain(question: str) -> str | None:+ """Return ``"ui"``, ``"backend"``, or ``None`` when the question is ambiguous.++ Used to break ties on retrievals where vocabulary overlaps across domains+ (e.g. "how does indexing work" could plausibly retrieve a UI status-pill+ component or the actual ingestion pipeline). The classifier is intentionally+ conservative: if both domain token sets fire, or neither does, we return+ ``None`` and apply no penalty — better to leave ranking alone than to+ miscategorise a cross-cutting question.+ """+ qlow = question.lower()+ has_ui = any(tok in qlow for tok in _UI_QUESTION_TOKENS)+ has_backend = any(tok in qlow for tok in _BACKEND_QUESTION_TOKENS)+ if has_ui and not has_backend:+ return "ui"+ if has_backend and not has_ui:+ return "backend"+ return None+++def _apply_domain_penalty(hits: list[dict], question: str) -> None:+ """Multiplicatively penalise cross-domain hits in place.++ Mutates ``hits`` and re-sorts by adjusted score. No-op when the question+ domain is ambiguous (see ``_detect_question_domain``). Hits that take the+ penalty get a ``_domain_penalty`` marker so the gated-return path can+ surface the reason to the caller.+ """+ domain = _detect_question_domain(question)+ if domain is None or not hits:+ return+ if domain == "backend":+ bad_prefixes = _UI_PATH_PREFIXES+ else:+ bad_prefixes = _BACKEND_PATH_PREFIXES+ touched = False+ for h in hits:+ tp = h.get("target_path") or ""+ if tp and any(tp.startswith(p) for p in bad_prefixes):+ h["score"] = h.get("score", 0.0) * _DOMAIN_PENALTY+ h["_domain_penalty"] = f"{domain} question; cross-domain path"+ touched = True+ if touched:+ hits.sort(key=lambda h: h["score"], reverse=True)+++def _candidate_justification(h: dict) -> str:+ """One-line reason this hit might answer the question.++ Used on the low-confidence return path so the agent sees something+ decision-shaped ("Read file X because it implements Y") instead of a+ flat list of paths it has to scan into. Prefers the matched-symbol name+ over the file summary because the matched symbol is what tied this hit+ to the question in the first place.+ """+ syms = h.get("symbols") or []+ matched = next((s for s in syms if s.get("_matched")), None)+ if matched:+ name = matched.get("name") or matched.get("signature") or "matched symbol"+ kind = matched.get("kind") or "symbol"+ return f"Implements {kind} {name}."+ summary = (h.get("summary") or h.get("snippet") or "").strip()+ if summary:+ # First sentence only; trailing prose is mostly cache-write cost on+ # the consumer side.+ first = summary.split(". ")[0]+ return (first[:160].rstrip() + ".") if first else ""+ title = h.get("title") or ""+ return title[:160]++def _question_terms(question: str) -> list[str]:"""Extract content terms from a question. Lowercase, alnum-tokenized,stopwords + length<3 dropped. Used by the term-coverage re-ranker."""@@ -782,12 +929,19 @@ async def get_answer(scope: str | None = None,repo: str | None = None,) -> dict:- """One-call RAG: answer a code question. Always your first call.+ """Synthesised answer to a code question with verified citations and a calibrated trust signal.++ The only tool that pairs RAG retrieval over the wiki with an LLM-written+ answer plus a separately-reported retrieval_quality. Use it as the first+ call on "how does X work" / "where is Y" / "why is Z structured this way"+ questions — it eliminates the search → context → read loop when retrieval+ is dominant. On low confidence it returns a structured ``best_guesses``+ list (one-line justifications per candidate) instead of an empty answer,+ so the caller always has somewhere concrete to Read next.- Returns {answer, citations, confidence, fallback_targets}. High-confidence- answers name concrete files/symbols and can be used with less verification.- For medium/low confidence, cross-reference with search_codebase + get_context.- Always verify cited file paths exist before acting on them.+ Returns ``{answer, citations, confidence, retrieval_quality,+ fallback_targets, best_guesses?, next_action_hint?}``. Always verify cited+ paths exist if you intend to act on them.Args:question: developer question.@@ -831,11 +985,24 @@ async def get_answer(if cached is not None:with contextlib.suppress(Exception):payload = _json.loads(cached.payload_json)+ # Schema bypass: payloads from a pre-rework code path don't carry+ # the fields the current consumer expects (retrieval_quality,+ # best_guesses, calibrated confidence). Returning them masks every+ # subsequent improvement until the cache happens to expire. Bypass+ # silently so the next write upgrades the row.+ cached_version = payload.get("_schema_version", 1)+ schema_stale = cached_version < _ANSWER_SCHEMA_VERSION# Bypass-on-hedged: if the cached answer hedged, the retrieval +# symbol pipeline has since been upgraded (question-aware symbol# promotion, source-body excerpts). Give synthesis another shot# with the new context rather than pinning the bad answer.- if _answer_is_hedged(payload.get("answer", "")):+ hedged_cache = _answer_is_hedged(payload.get("answer", ""))+ if schema_stale:+ _log.info(+ "Bypassing cache entry at schema v%s (current v%s)",+ cached_version, _ANSWER_SCHEMA_VERSION,+ )+ elif hedged_cache:_log.info("Bypassing hedged cache entry for re-synthesis")else:payload["_meta"] = _build_meta(@@ -845,63 +1012,40 @@ async def get_answer(payload.get("confidence", "low"),len(payload.get("retrieval", [])),),+ repository=repository,)return payload- # --- Retrieval (FTS) ---------------------------------------------------- raw_hits: list[Any] = []- if ctx.fts is not None:- with contextlib.suppress(Exception):- # Pull a wider candidate set so the term-coverage re-ranker has- # room to push conjunctive matches up the list before we cap to 5.- raw_hits = await asyncio.wait_for(- ctx.fts.search(question, limit=15), timeout=5.0- )-- # Hydrate hits with target_path + summary from the Page table.- hits: list[dict] = []- if raw_hits:- page_ids = [h.page_id for h in raw_hits]- async with get_session(ctx.session_factory) as session:- res = await session.execute(- select(- Page.id,- Page.target_path,- Page.summary,- Page.page_type,- ).where(Page.id.in_(page_ids))- )- meta_by_id = {- row[0]: {- "target_path": row[1],- "summary": row[2] or "",- "page_type": row[3],- }- for row in res.all()- }- for h in raw_hits:- meta = meta_by_id.get(h.page_id, {})- target_path = meta.get("target_path", "")- if scope and target_path and not target_path.startswith(scope):- continue- hits.append(- {- "page_id": h.page_id,- "title": h.title,- "target_path": target_path,- "page_type": meta.get("page_type", h.page_type),- "snippet": h.snippet,- "summary": meta.get("summary", ""),- "score": float(h.score or 0.0),- }- )-- # Term-coverage re-rank before the cap so conjunctive matches survive.+ # --- Retrieval pipeline ------------------------------------------------+ # Stages live in ``_answer_pipeline`` so each can evolve without+ # rereading the orchestrator: hybrid retrieval (FTS + vector + RRF) →+ # hydration → coverage rerank → domain penalty → intersection boost →+ # PageRank bias → 1-hop graph expansion. The orchestrator only sequences+ # them and decides when to stop (cap at 5 for the response payload).+ hits = await _hybrid_retrieve(question, ctx)+ hits = await _hydrate_hits(hits, ctx, scope=scope)++ # Term-coverage re-rank before any graph-aware bias so conjunctive+ # matches survive the merge.hits = _rerank_by_coverage(hits, question)+ # Domain heuristic: down-weight cross-domain hits (e.g. UI files for a+ # clearly backend question). Cheap tie-breaker, never a hard filter.+ _apply_domain_penalty(hits, question)# Intersection-retrieval boost for relational questions (multi-entity).# Pages at the intersection of two split-FTS halves get a 2× bonus.with contextlib.suppress(Exception):await _intersection_boost(question, hits, ctx)+ # PageRank bias: nudge architecturally central files above peripheral+ # ones at the same retrieval score. Damped + normalised within the+ # candidate set so it's a tie-breaker, not a wholesale reordering.+ with contextlib.suppress(Exception):+ await _apply_pagerank_bias(hits, ctx)+ # Graph expansion: 1-hop walk from the top hits to rescue near-misses+ # where retrieval landed in the right module but on the wrong file+ # (consumer instead of orchestrator). Adds up to 3 neighbors with a+ # damped score, then re-sorts.+ with contextlib.suppress(Exception):+ hits = await _expand_via_graph(hits, ctx)# Always cap retrieval hits at 5 for the response payload.hits = hits[:5]@@ -935,6 +1079,7 @@ async def get_answer("_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint("low", 0),+ repository=repository,),}@@ -968,21 +1113,43 @@ async def get_answer(# Enrich top hits with substantive excerpts so the agent has# real material to ground in (not one-line summaries).await _enrich_gated_excerpts(hits, ctx)+ # Structured candidate set: a decision-shaped list with a+ # one-line justification per file. Beats the prior flat+ # ``fallback_targets`` list because the agent can pick ONE file+ # to Read first instead of skimming five.+ best_guesses = [+ {+ "file": h.get("target_path"),+ "why_relevant": _candidate_justification(h),+ "score": round(h.get("score", 0.0), 3),+ "domain_penalty": h.get("_domain_penalty"),+ }+ for h in hits[:_GATED_RETURN_HITS]+ if h.get("target_path")+ ]return {"answer": "","citations": [],"confidence": "low",+ "retrieval_quality": "weak",+ "best_guesses": best_guesses,+ "next_action_hint": (+ f"Read {best_guesses[0]['file']} first — it scored highest "+ "but retrieval was ambiguous, so verify before answering."+ if best_guesses+ else "Fall back to search_codebase or Grep."+ ),"fallback_targets": fallback_targets,"retrieval": hits[:_GATED_RETURN_HITS],"note": ("Multiple plausible candidates — synthesis skipped to "- "avoid anchoring on a wrong frame. Each retrieval entry "- "includes an excerpt from the page; read them and pick "- "the one that actually answers the question."+ "avoid anchoring on a wrong frame. Each best_guess entry "+ "names why that file is in the running."),"_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint("low", len(hits)),+ repository=repository,),}@@ -1013,13 +1180,27 @@ async def get_answer("_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint("low", len(hits)),+ repository=repository,),}+ # Decision fusion (why-shaped questions only) + structured prelude. Both+ # layers are gated on signal: no ADRs for the top hits → no decisions+ # block, no symbols / commits / decisions → no prelude. Empty layers are+ # dropped before formatting, so the prompt never carries hollow scaffolding.+ top_paths = [h["target_path"] for h in hits if h.get("target_path")]+ decisions: list[dict] = []+ if _is_why_question(question) and top_paths:+ with contextlib.suppress(Exception):+ decisions = await _fetch_relevant_decisions(ctx, repo_id, top_paths)+ prelude = ""+ with contextlib.suppress(Exception):+ prelude = await _build_structured_prelude(hits, decisions, ctx, repo_id)+user_prompt = _USER_TEMPLATE.format(question=question.strip(),n=len(hits),- context=_build_context_block(hits),+ context=_build_context_block_v2(hits, prelude=prelude, decisions=decisions),)answer_text = ""@@ -1046,6 +1227,7 @@ async def get_answer("_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint("low", len(hits)),+ repository=repository,),}@@ -1065,8 +1247,14 @@ async def get_answer(_ratio = _top / _secondelse:_ratio = float("inf") if hits else 0.0- if _ratio >= _DOMINANCE_RATIO:+ _top_score = hits[0].get("score", 0.0) if hits else 0.0+ if _ratio >= _DOMINANCE_RATIO and _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR:confidence = "high"+ elif _ratio >= _DOMINANCE_RATIO:+ # Dominant but weak — the right file relative to its siblings, but+ # the signal isn't strong enough to trust the synthesised answer+ # without verification. Downgrade so the consumer Reads the source.+ confidence = "medium"else:confidence = "medium"@@ -1095,15 +1283,29 @@ async def get_answer(if not has_match:confidence = "medium"+ # retrieval_quality is a separate signal from confidence. Where confidence+ # says "how much should you trust the synthesised text", retrieval_quality+ # says "how good was the retrieval that fed it". The agent uses confidence+ # to decide whether to re-read; retrieval_quality to decide whether to+ # call search_codebase again with a refined query.+ if _top_score >= _HIGH_CONFIDENCE_SCORE_FLOOR and _ratio >= _DOMINANCE_RATIO:+ retrieval_quality = "high"+ elif _ratio >= _DOMINANCE_RATIO:+ retrieval_quality = "partial"+ else:+ retrieval_quality = "weak"+if hedged:# Hedged answers: drop the retrieval payload. The consumer has been# told to read the source — the symbol-docstring blob that helped# synthesis doesn't help them, and keeping it in the response bloats# every follow-up turn's prompt cache.payload = {+ "_schema_version": _ANSWER_SCHEMA_VERSION,"answer": answer_text,"citations": citations,"confidence": "low",+ "retrieval_quality": retrieval_quality,"fallback_targets": fallback_targets[:3],"retrieval": [],"note": (@@ -1113,18 +1315,21 @@ async def get_answer(}else:payload = {+ "_schema_version": _ANSWER_SCHEMA_VERSION,"answer": answer_text,"citations": citations,"confidence": confidence,+ "retrieval_quality": retrieval_quality,"fallback_targets": fallback_targets,"retrieval": hits,}if confidence == "high":payload["note"] = ("High confidence: top retrieval result clearly dominates "- f"(dominance ratio {_ratio:.2f}x) AND the synthesized answer "- "is direct (no hedging). Cite this answer; do not re-read the "- "source unless a specific detail is missing."+ f"(dominance ratio {_ratio:.2f}x, top score {_top_score:.2f}) "+ "AND the synthesised answer is direct (no hedging). Cite this "+ "answer; do not re-read the source unless a specific detail "+ "is missing.")# Persist to cache. Best-effort: cache failures must NEVER block the@@ -1146,5 +1351,6 @@ async def get_answer(payload["_meta"] = _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_answer_hint(confidence, len(hits)),+ repository=repository,)return payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_context.py b/packages/server/src/repowise/server/mcp_server/tool_context.pyindex 76551bf6d..c26857755 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context.py@@ -1,12 +1,21 @@-"""MCP Tool: get_context — the workhorse tool for files, modules, or symbols.--Absorbs functionality from the former get_symbol, get_callers_callees,-get_graph_metrics, and get_community tools via the ``include`` parameter:- - include=["source"] → symbol source body (replaces get_symbol)- - include=["callers"] → who calls this symbol (replaces get_callers_callees)- - include=["callees"] → what this symbol calls- - include=["metrics"] → PageRank, betweenness, percentiles (replaces get_graph_metrics)- - include=["community"]→ community membership + neighbors (replaces get_community)+"""MCP Tool: get_context — relationships and triage signals for files / modules / symbols.++Workhorse for "what is this and what touches it" questions. Returns a triage+card by default (title, summary, signatures, hotspot bit, top callers, pointers+to risk / why / symbol). NOT a source-body tool — for raw bytes call+``get_symbol("path::Name")`` instead. The split keeps the cached prompt prefix+small on multi-turn agent sessions: ``get_context`` stays under ~2k tokens for+common targets, while ``get_symbol`` returns bounded bytes for one symbol.++Optional ``include`` parameter widens the response:+ - include=["full_doc"] → full wiki markdown content+ - include=["callers"] → who calls this symbol (symbol targets only)+ - include=["callees"] → what this symbol calls (symbol targets only)+ - include=["ownership"] → primary owner, bus factor, contributor count+ - include=["last_change"]→ last commit date and author+ - include=["metrics"] → PageRank, betweenness, percentile ranks+ - include=["community"] → community membership + neighbors+ - include=["decisions"] → full decision records (default returns titles only)"""from __future__ import annotations@@ -14,7 +23,6 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-from pathlib import Pathfrom typing import Anylogger = logging.getLogger(__name__)@@ -68,8 +76,6 @@ from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import context_hint as _context_hintfrom repowise.server.mcp_server._server import mcp-# Safety cap for source retrieval (from former get_symbol)-_MAX_SOURCE_LINES = 400# Minimum confidence for call edges to filter false positives_MIN_CALL_CONFIDENCE = 0.7@@ -104,8 +110,6 @@ async def _resolve_one_target(target: str,include: set[str] | None,compact: bool = False,- *,- repo_path: str | None = None,) -> dict:"""Resolve a single target and return its full context."""repo_id = repository.id@@ -288,19 +292,35 @@ async def _resolve_one_target(classes = [s.name for s in symbols if s.kind == "class"]functions = [s.name for s in symbols if s.kind in ("function", "method")]if compact:- # Compact mode: name+kind+signature+line only. Drop docstring,- # start_line/end_line range, structure block, and imported_by.- # Used by agents that already know the file and just want a- # cheap signature index.+ # Compact mode: name+kind+signature+line+symbol_id only. Drops+ # docstrings, line ranges, structure, and imported_by — those+ # live behind compact=False or include= flags. The symbol_id+ # is the canonical handle the caller pipes straight into+ # get_symbol when it wants bytes.+ #+ # Cap at 40 symbols so a dense generated file (protobuf+ # wrappers, vendored libs) can't blow the triage card past+ # the agent's budget. Order matches WikiSymbol.start_line+ # (assigned at index time), so the head is the navigationally+ # useful slice.+ symbol_cap = 40+ visible = list(symbols)[:symbol_cap]docs["symbols"] = [{"name": s.name,"kind": s.kind,"signature": s.signature,"line": s.start_line,+ "symbol_id": s.symbol_id,}- for s in symbols+ for s in visible]+ if len(symbols) > symbol_cap:+ docs["symbols_truncated"] = {+ "shown": symbol_cap,+ "total": len(symbols),+ "hint": "Call with compact=False or include=['full_doc'] for the full list.",+ }if not docs.get("summary"):docs["summary"] = _synthesize_structural_summary(target, classes, functions@@ -422,6 +442,51 @@ async def _resolve_one_target(result_data["docs"] = docs+ # --- Triage signals (always on) ---------------------------------------+ # Two single-bit-ish pointers the agent uses to decide its next move:+ # * ``hotspot``: lights the way to ``get_risk`` for files in the 95th++ # churn percentile. Just the boolean — the full risk dossier stays+ # in ``get_risk`` so the triage card doesn't grow.+ # * ``decision_records``: titles only, no body. Lights the way to+ # ``get_why``. We deliberately don't inline the rationale here;+ # duplicating it across every ``get_context`` response bloats the+ # cached prompt prefix and defeats the split between the two tools.+ #+ # Cheap: two short queries piggybacking on the session we already opened.+ triage_path = file_path_for_git+ if target_type == "module" and page:+ triage_path = page.target_path+ if triage_path:+ triage_meta_res = await session.execute(+ select(GitMetadata.is_hotspot).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.file_path == triage_path,+ )+ )+ triage_meta = triage_meta_res.scalar_one_or_none()+ result_data["hotspot"] = bool(triage_meta) if triage_meta is not None else False++ decision_titles_res = await session.execute(+ select(DecisionRecord.title, DecisionRecord.affected_files_json).where(+ DecisionRecord.repository_id == repo_id,+ )+ )+ titles: list[str] = []+ for title, affected_json in decision_titles_res.all():+ try:+ affected = json.loads(affected_json or "[]")+ except (json.JSONDecodeError, TypeError):+ affected = []+ if triage_path in affected or target in affected:+ titles.append(title)+ if len(titles) >= 5:+ break+ if titles:+ result_data["decision_records"] = titles+ result_data["decision_records_hint"] = (+ "Decisions touch this file. Call get_why(targets=[...]) for rationale."+ )+# --- Ownership ---if include is None or "ownership" in include:ownership: dict[str, Any] = {}@@ -543,13 +608,6 @@ async def _resolve_one_target(freshness["is_stale"] = Noneresult_data["freshness"] = freshness- # --- Source (replaces get_symbol) ---- if include and "source" in include:- await _resolve_source(- session, repository, target, target_type, result_data,- repo_path=repo_path,- )-# --- Callers / Callees (replaces get_callers_callees) ---want_callers = bool(include and "callers" in include)want_callees = bool(include and "callees" in include)@@ -575,100 +633,6 @@ async def _resolve_one_target(# ----------------------------------------------------------------------------async def _resolve_source(- session: AsyncSession,- repository: Repository,- target: str,- target_type: str | None,- result_data: dict[str, Any],- *,- repo_path: str | None = None,-) -> None:- """Resolve symbol source body and attach to result_data["source"]."""- repo_id = repository.id-- # Find the symbol — target could be "path::Name" or a bare name- file_path, name = None, None- if "::" in target:- file_path, _, name = target.partition("::")- else:- name = target-- # Try exact symbol_id match first- res = await session.execute(- select(WikiSymbol).where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.symbol_id == target,- )- )- row = res.scalar_one_or_none()-- if row is None and file_path and name:- # Try (file_path, qualified_name)- res = await session.execute(- select(WikiSymbol).where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.file_path == file_path,- WikiSymbol.qualified_name == name,- )- )- row = res.scalar_one_or_none()-- if row is None and file_path and name:- # Try (file_path, name) — bare name- bare = name.split("::")[-1] if "::" in name else name- res = await session.execute(- select(WikiSymbol).where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.file_path == file_path,- WikiSymbol.name == bare,- )- )- row = res.scalar_one_or_none()-- if row is None:- result_data["source"] = {"error": f"Symbol not found: {target!r}"}- return-- if not repo_path:- result_data["source"] = {"error": "MCP server has no repo path configured"}- return-- repo_root = Path(repo_path)- abs_path = (repo_root / row.file_path).resolve()- try:- abs_path.relative_to(repo_root.resolve())- except ValueError:- result_data["source"] = {"error": "Path escape attempt blocked"}- return-- try:- text = abs_path.read_text(encoding="utf-8", errors="replace")- except OSError:- result_data["source"] = {"error": "Source file could not be read"}- return-- lines = text.splitlines()- total = len(lines)- s = max(1, min(row.start_line, total))- e = max(s, min(row.end_line, total))-- span = e - s + 1- truncated = False- if span > _MAX_SOURCE_LINES:- e = s + _MAX_SOURCE_LINES - 1- truncated = True-- sliced = "\n".join(lines[s - 1 : e])- result_data["source"] = {- "body": sliced,- "start_line": s,- "end_line": e,- "language": row.language,- "truncated": truncated,- }--async def _resolve_call_graph(session: AsyncSession,repository: Repository,@@ -1061,32 +1025,33 @@ async def get_context(compact: bool = True,repo: str | None = None,) -> dict:- """Compact context for files, modules, or symbols. Batch multiple targets.-- Default returns title + summary + symbol signatures. Add include options- for richer data. Pass all relevant targets in one call.-- In workspace mode, responses are automatically enriched with cross-repo- signals: co-change partners, and API contract links (HTTP routes, gRPC- services, message topics consumed/provided by this file).-- Include options:- - "docs" (default): wiki summary + symbol signatures- - "full_doc": full wiki markdown content- - "ownership": primary owner, bus factor, contributor count- - "last_change": last commit date and author- - "source": symbol source body (for symbol targets like "path::Name")- - "callers": who calls this symbol (symbol targets only)- - "callees": what this symbol calls (symbol targets only)- - "metrics": PageRank, betweenness centrality, percentile ranks- - "community": architectural community membership + neighbors+ """Triage card for files / modules / symbols — relationships, not source bytes.++ Returns a compact card the agent can use to decide its next move: title,+ summary, signatures, hotspot bit, top callers, and pointers (decision_record+ titles, symbol_ids) into the deeper tools. For the actual source body of a+ symbol, call ``get_symbol("path/to/file.py::Name")`` — it is cheaper than+ Read and returns bounded bytes with exact line numbers.++ Batch multiple targets in one call. In workspace mode responses are+ auto-enriched with cross-repo co-change partners and API contract links.++ Include options (everything outside defaults is opt-in):+ - "full_doc": full wiki markdown content for the target+ - "ownership": primary owner, bus factor, contributor count+ - "last_change":last commit date and author+ - "callers": who calls this symbol (symbol targets only)+ - "callees": what this symbol calls (symbol targets only)+ - "metrics": PageRank, betweenness centrality, percentile ranks+ - "community": architectural community membership + neighbors+ - "decisions": full decision records (default returns titles only)Example: get_context(["src/auth/service.py", "src/auth/middleware.py"])- Example: get_context(["src/auth/service.py::verify_token"], include=["source","callers"])+ Example: get_context(["src/auth/service.py::verify_token"], include=["callers"])Args:targets: file paths, module paths, or qualified symbol IDs.- include: list of data blocks to include (default: ["docs","freshness"]).+ include: list of optional data blocks (defaults are always returned).compact: default True (signatures only). False adds structure+imports+docstrings.repo: usually omitted."""@@ -1110,7 +1075,6 @@ async def get_context(*[_resolve_one_target(session, repository, t, include_set, compact,- repo_path=str(ctx.path),)for t in targets]@@ -1121,6 +1085,7 @@ async def get_context("_meta": _build_meta(timing_ms=(_time.perf_counter() - _t0) * 1000,hint=_context_hint(targets, compact, include_set),+ repository=repository,),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex b82c8eeba..8fe35d762 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -19,6 +19,7 @@ from repowise.server.mcp_server._helpers import (_resolve_all_contexts,_resolve_repo_context,)+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._server import mcp@@ -38,11 +39,13 @@ async def get_dead_code(no_unreachable: bool = False,no_unused_exports: bool = False,) -> dict:- """Get a tiered refactor plan for dead and unused code.+ """Unused exports, unreachable files, zombie packages — what grep cannot tell you.- Returns findings organized into confidence tiers (high/medium/low),- with per-directory rollups, ownership hotspots, and impact estimates- so you can prioritize cleanup.+ Static reachability analysis the agent cannot derive from imports alone.+ Returns findings tiered by confidence (high = zero refs; medium = likely+ unused; low = check first) with per-directory and per-owner rollups so a+ cleanup sprint can prioritise. In workspace mode, cross-repo consumer+ detection lowers confidence on findings that other repos import.Use group_by="directory" for a directory-level overview, orgroup_by="owner" to see who owns the most dead code. Use tier@@ -224,6 +227,7 @@ async def get_dead_code(f"and was clamped to {_MAX_PER_TIER}. Use tier/directory/owner filters ""or paginate to see more findings.")+ result_ws["_meta"] = _build_meta()return result_ws# --- Single repo path ---@@ -318,6 +322,7 @@ async def get_dead_code("or paginate to see more findings.")+ result["_meta"] = _build_meta(repository=repository)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 5b3c73aaf..f6f6be8fc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -21,6 +21,7 @@ from repowise.server.mcp_server._helpers import (_resolve_all_contexts,_resolve_repo_context,)+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._server import mcp@@ -167,16 +168,19 @@ def _build_workspace_footer() -> dict | None:@mcp.tool()async def get_overview(repo: str | None = None) -> dict:- """Get the repository overview: architecture summary, module map, key entry points.+ """Architecture map for an unfamiliar repo — first call when you don't know your way around.- Best first call when starting to explore an unfamiliar codebase.+ Returns the synthesised overview plus key modules, entry points, repo-wide+ git health (hotspot count, churn trend, bus-factor distribution), the+ knowledge map (top owners, knowledge silos), and the community summary.+ Skip this on subsequent calls — once you have the map, jump straight to+ ``get_context`` / ``get_answer``.In workspace mode:- - Omit ``repo`` for the default repo overview (includes workspace context,- cross-repo co-changes, package dependencies, and API contract links).- - Use ``repo="all"`` for a workspace-level summary of all repos including- cross-repo topology and contract links (HTTP routes, gRPC services, topics).- - Use ``repo="<alias>"`` to query a specific repo.+ - Omit ``repo`` for the default repo's overview plus a workspace footer.+ - ``repo="all"`` returns the cross-repo topology (co-changes, package deps,+ API contracts) — no single-repo detail.+ - ``repo="<alias>"`` targets one specific repo.Args:repo: Repository alias, path, or ID. Use ``"all"`` for workspace overview.@@ -424,4 +428,5 @@ async def get_overview(repo: str | None = None) -> dict:if ws_footer:result["workspace"] = ws_footer+ result["_meta"] = _build_meta(repository=repository)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex 968253b68..7b0f01cb9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -27,6 +27,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._server import mcp_FIX_PATTERN = re.compile(@@ -349,31 +350,27 @@ async def get_risk(repo: str | None = None,changed_files: list[str] | None = None,) -> dict:- """Assess modification risk for one or more files before making changes.-- Pass ALL files you plan to modify in a single call. Returns per-file:- - hotspot_score and trend ("increasing"/"stable"/"decreasing")- - risk_type ("churn-heavy"/"bug-prone"/"high-coupling"/"stable")- - impact_surface: top 3 critical modules that would break- - dependents, co-change partners, ownership- - test_gap: bool — True if no test file exists for this file- - security_signals: list of {kind, severity, snippet} from static analysis-- In workspace mode, includes cross-repo impact: co-change partners from- other repos, affected repos, and API contract links (files in other repos- that consume HTTP/gRPC/topic contracts provided by this file, or providers- this file depends on). Cross-repo consumers increase the dependents count.-- Plus the top 5 global hotspots for ambient awareness.-- Pass ``changed_files`` for PR review / blast radius analysis. When provided,- the response includes an additional ``pr_blast_radius`` key containing:- - direct_risks: per-file risk score (centrality × temporal hotspot)- - transitive_affected: files that import any changed file (up to depth 3)- - cochange_warnings: historical co-change partners missing from the PR- - recommended_reviewers: top 5 owners of affected files- - test_gaps: changed/affected files lacking a corresponding test- - overall_risk_score: 0-10 composite score+ """What history says about touching these files — hotspot, churn, owners, blast radius.++ The only tool that fuses git temporal signals (churn percentile, trend,+ bus factor) with graph topology (dependents, co-changes, impact surface)+ and security findings into one decision-shaped payload. Consult before+ editing any file in the 95th+ churn percentile or before merging a+ multi-file PR.++ Per-file fields: ``hotspot_score``, ``trend``, ``risk_type``,+ ``impact_surface`` (top 3), ``dependents_count``, ``co_change_partners``,+ ``primary_owner``, ``bus_factor``, ``test_gap``, ``security_signals``.++ Pass ``changed_files`` for PR-blast-radius mode. The response then carries+ a ``directive`` block — three short lists the caller can read in one+ glance (``will_break``, ``missing_cochanges``, ``missing_tests``) — plus+ the trimmed full ``pr_blast_radius`` dossier for deeper review. Global+ hotspots are omitted in PR mode (irrelevant to the diff) and re-included+ when ``changed_files`` is absent.++ In workspace mode, cross-repo consumers and API contract links bump the+ dependents count and appear in ``cross_repo_impact``.Example: get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])@@ -526,8 +523,73 @@ async def get_risk(response: dict = {"targets": {r["target"]: r for r in results},- "global_hotspots": global_hotspots,}+if pr_blast_radius is not None:- response["pr_blast_radius"] = pr_blast_radius+ # PR mode — drop global_hotspots (irrelevant to a specific diff), trim+ # per-target co-change lists, and synthesize a tight directive the+ # agent can act on without parsing the whole blast-radius dossier.+ for r in response["targets"].values():+ partners = r.get("co_change_partners") or []+ if len(partners) > 3:+ r["co_change_partners"] = partners[:3]++ # ``pr_blast_radius`` is the analyzer's own payload — preserve it for+ # callers that want the full picture, but truncate the noisy lists so+ # we stay well under the 25k-token transport ceiling on PRs that touch+ # many files. The directive below is what the agent should read first.+ trimmed_blast: dict[str, Any] = dict(pr_blast_radius)+ for key, cap in (+ ("transitive_affected", 15),+ ("cochange_warnings", 10),+ ("test_gaps", 10),+ ("recommended_reviewers", 5),+ ):+ value = trimmed_blast.get(key)+ if isinstance(value, list) and len(value) > cap:+ trimmed_blast[key] = value[:cap]+ trimmed_blast[f"{key}_truncated_total"] = len(value)+ response["pr_blast_radius"] = trimmed_blast++ # Directive: 3 short lists the agent can read in one glance. Each+ # entry is a file path (string), never a dossier. Designed to answer+ # "what should I do about this PR" in three lines.+ def _as_path(entry: Any) -> str | None:+ if isinstance(entry, str):+ return entry+ if isinstance(entry, dict):+ return entry.get("file_path") or entry.get("path") or entry.get("file")+ return None++ will_break = [+ p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", []))+ if p+ ][:5]+ missing_cochanges = [+ p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", []))+ if p+ ][:3]+ missing_tests = [+ p for p in (_as_path(e) for e in trimmed_blast.get("test_gaps", []))+ if p+ ][:3]++ response["directive"] = {+ "will_break": will_break,+ "missing_cochanges": missing_cochanges,+ "missing_tests": missing_tests,+ "overall_risk_score": trimmed_blast.get("overall_risk_score"),+ "summary": (+ f"PR touches {len(changed_files)} file(s). "+ f"~{len(will_break)} downstream file(s) likely affected, "+ f"{len(missing_cochanges)} historical co-changer(s) missing, "+ f"{len(missing_tests)} file(s) without tests."+ ),+ }+ else:+ # Standard per-file risk request (no diff) — keep global hotspots as+ # ambient awareness. Cheap (≤5 entries) and useful for orientation.+ response["global_hotspots"] = global_hotspots++ response["_meta"] = _build_meta(repository=repository)return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 8aa9a5e12..16d2494ca 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import refrom sqlalchemy import select@@ -18,15 +19,65 @@ from repowise.server.mcp_server._helpers import (_resolve_all_contexts,_resolve_repo_context,)+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._server import mcp# Minimum relevance score below which results are dropped. Prevents# returning semantically unrelated pages when the corpus has no real match._MIN_RELEVANCE_SCORE = 0.03+# Pure-identifier pattern: a single bareword that looks like a code symbol+# (no spaces, no punctuation other than _/.). These are almost always+# better handled by Grep than by semantic search — vector embeddings of a+# bare ``getCurrentUser`` quickly drift to thematically-similar but+# textually-distant pages, while Grep would have found the literal usage+# in milliseconds. We hint to Grep but still run the search so callers+# that genuinely want fuzzy symbol search are not blocked.+_IDENT_QUERY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]{1,29}$")+++def _looks_like_exact_token(query: str) -> bool:+ """True when the query is a single identifier-shaped token best served by Grep."""+ stripped = query.strip()+ if not stripped or " " in stripped:+ return False+ return bool(_IDENT_QUERY_RE.match(stripped))+++# Path-prefix heuristics for the ``kind`` filter. We classify a hit's+# target_path against these prefixes; if none match, the hit falls into+# ``other`` and is dropped only when the caller asked for a specific kind.+_TEST_PATH_TOKENS = ("/test/", "/tests/", "/__tests__/", "test_", "_test.", ".spec.", ".test.")+_CONFIG_PATH_TOKENS = (+ "pyproject.toml", "package.json", "tsconfig", "setup.py", "setup.cfg",+ "/.github/", "dockerfile", ".yml", ".yaml", ".toml", ".ini", ".cfg",+ "lockfile", "package-lock", "uv.lock", "poetry.lock",+)+-async def _search_single_repo(ctx, query: str, limit: int, page_type: str | None):- """Run search against a single repo context. Returns list of result dicts."""+def _classify_hit_kind(target_path: str, page_type: str) -> str:+ """Bucket a hit into implementation / test / config / doc."""+ tp = (target_path or "").lower()+ if page_type == "module_page" or page_type == "symbol_spotlight" or tp.endswith(".md"):+ return "doc"+ if any(tok in tp for tok in _TEST_PATH_TOKENS):+ return "test"+ if any(tok in tp for tok in _CONFIG_PATH_TOKENS):+ return "config"+ return "implementation"+++async def _search_single_repo(+ ctx, query: str, limit: int, page_type: str | None+) -> tuple[list[dict], str]:+ """Run search against a single repo context.++ Returns ``(results, method)`` where ``method`` is ``"embedding"`` or+ ``"bm25"`` so the caller can surface which retrieval backend produced+ the list — embedding misses fall through to FTS silently in the existing+ code, and the agent has no way to distinguish a strong embedding hit+ from a fallback BM25 hit otherwise.+ """# Wait for vector store readinessif ctx.vector_store_ready is not None:with contextlib.suppress(TimeoutError):@@ -34,12 +85,14 @@ async def _search_single_repo(ctx, query: str, limit: int, page_type: str | Nonefetch_limit = limit * 3 if page_type else limitresults = []+ method = "embedding"with contextlib.suppress(TimeoutError, Exception):results = await asyncio.wait_for(ctx.vector_store.search(query, limit=fetch_limit),timeout=8.0,)if not results:+ method = "bm25"with contextlib.suppress(Exception):results = await ctx.fts.search(query, limit=fetch_limit)@@ -57,7 +110,7 @@ async def _search_single_repo(ctx, query: str, limit: int, page_type: str | None"relevance_score": r.score,})- return output[:limit]+ return output[:limit], methodasync def _federated_search(query: str, limit: int, page_type: str | None) -> dict:@@ -66,10 +119,11 @@ async def _federated_search(query: str, limit: int, page_type: str | None) -> diall_results = []for ctx in contexts:- repo_results = await _search_single_repo(ctx, query, limit, page_type)+ repo_results, repo_method = await _search_single_repo(ctx, query, limit, page_type)for rank, item in enumerate(repo_results):item["repo"] = ctx.aliasitem["rrf_score"] = 1.0 / (rank + 60) # RRF constant k=60+ item["search_method"] = repo_methodall_results.extend(repo_results)# Sort by RRF score and take top N@@ -83,7 +137,7 @@ async def _federated_search(query: str, limit: int, page_type: str | None) -> diraw = item.get("rrf_score", 0)item["confidence_score"] = round(raw / max_rrf, 2) if max_rrf > 0 else 0.0- return {"results": output}+ return {"results": output, "_meta": _build_meta()}@mcp.tool()@@ -91,43 +145,74 @@ async def search_codebase(query: str,limit: int = 5,page_type: str | None = None,+ kind: str | None = None,repo: str | None = None,) -> dict:- """Semantic search over the wiki. Use when ``get_answer`` did not return- a confident result and you need to discover candidate pages by topic.+ """Find pages by concept — semantic search across the wiki.++ The right tool when ``get_answer`` punted and you need candidate files for+ a conceptual query ("authentication flow", "rate limiting", "where do we+ handle webhooks"). For exact identifiers or token matches, use Grep — it+ is faster and never drifts thematically. This tool will surface a Grep+ hint when the query looks like a bare identifier.- In workspace mode, use ``repo="all"`` to search across all repos.+ Each result carries ``search_method`` (``"embedding"`` or ``"bm25"``) so+ the caller can tell whether semantic retrieval succeeded or fell back to+ keyword scoring; BM25 hits warrant more verification than embedding hits.Args:query: natural-language search query.limit: maximum number of results to return (default 5).- page_type: optional filter on page kind (e.g. ``file_page``,- ``module_page``, ``symbol_spotlight``).+ page_type: filter on page kind (``file_page``, ``module_page``,+ ``symbol_spotlight``).+ kind: filter by file role: ``"implementation"`` | ``"test"`` |+ ``"config"`` | ``"doc"``. Path-prefix heuristic; trims the result+ list rather than rewriting the query.repo: repository alias, or ``"all"`` for workspace-wide search."""+ grep_hint: str | None = None+ if _looks_like_exact_token(query):+ grep_hint = (+ f"Query {query!r} looks like an exact identifier. Grep will find "+ "literal usages faster and without thematic drift. This tool ran "+ "the search anyway — verify before relying on the results."+ )+if repo == "all":- return await _federated_search(query, limit, page_type)+ federated = await _federated_search(query, limit, page_type)+ if kind:+ federated["results"] = [+ r for r in federated["results"]+ if _classify_hit_kind(r.get("target_path", ""), r.get("page_type", "")) == kind+ ]+ if grep_hint:+ federated["grep_hint"] = grep_hint+ return federatedctx = await _resolve_repo_context(repo)async with get_session(ctx.session_factory) as session:# Validate repo exists in DB- await _get_repo(session)+ repository = await _get_repo(session)# Wait for vector store readinessif ctx.vector_store_ready is not None:with contextlib.suppress(TimeoutError):await asyncio.wait_for(ctx.vector_store_ready.wait(), timeout=30.0)- # Try semantic search, fall back to FTS.+ # Try semantic search, fall back to FTS. Track which backend supplied the+ # hits so the response can surface it per-result — silent fallback hides+ # a quality cliff that the agent should weigh into its trust budget.fetch_limit = limit * 3 if page_type else limitresults = []+ search_method = "embedding"with contextlib.suppress(TimeoutError, Exception):results = await asyncio.wait_for(ctx.vector_store.search(query, limit=fetch_limit),timeout=8.0,)if not results:+ search_method = "bm25"with contextlib.suppress(Exception):results = await ctx.fts.search(query, limit=fetch_limit)@@ -144,6 +229,7 @@ async def search_codebase("page_type": r.page_type,"snippet": r.snippet,"relevance_score": r.score,+ "search_method": search_method,})@@ -157,6 +243,10 @@ async def search_codebase(select(Page.id, Page.target_path).where(Page.id.in_(page_ids)))page_info = {row[0]: row[1] for row in res.all()}+ # Attach target_path to each item so the kind filter (path-prefix+ # heuristic) and downstream get_context callers can act on it.+ for item in output:+ item["target_path"] = page_info.get(item["page_id"], "")# Build git freshness map for result file pathstarget_paths = [tp for tp in page_info.values() if tp]@@ -192,4 +282,13 @@ async def search_codebase(raw = item.get("relevance_score") or 0item["confidence_score"] = round(raw / max_score, 2) if max_score > 0 else 0.0- return {"results": output}+ if kind:+ output = [+ item for item in output+ if _classify_hit_kind(item.get("target_path", ""), item.get("page_type", "")) == kind+ ]++ response: dict = {"results": output, "_meta": _build_meta(repository=repository)}+ if grep_hint:+ response["grep_hint"] = grep_hint+ return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 49bc29425..8e5a575f5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -282,11 +282,16 @@ async def get_symbol(context_lines: int = 0,repo: str | None = None,) -> dict:- """Return the exact source body of one symbol by ID. Trust the result.+ """Read one function/class with exact line bounds — cheaper and safer than Read+math.- Cheaper than Read for "show me X" / "what does Y do" questions.- Returns {file, name, kind, signature, start_line, end_line, source}.- On miss returns {error: "Symbol not found"}.+ The only tool that returns the raw source bytes of a single indexed symbol+ without the agent having to compute offsets or guess at file structure.+ Bounded to ~400 lines (hard cap) so a misconfigured row can never blow up+ the context window. Pass the canonical ``"path/to/file.py::Name"`` that+ appears in ``get_context``'s symbol list.++ Returns {file, name, kind, signature, start_line, end_line, source,+ truncated}. On miss returns {error: "Symbol not found …"}.Args:symbol_id: "path/to/file.py::SymbolName" (canonical id from get_context).@@ -304,6 +309,7 @@ async def get_symbol("error": "symbol_id is required","_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),}+ repository = Noneif context_lines < 0 or context_lines > 50:# Bound context_lines to a sane range — runaway values would# defeat the whole point of symbol-level retrieval.@@ -321,14 +327,20 @@ async def get_symbol("available symbols in the file, then try again with the ""exact symbol_id from that response."),- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),+ "_meta": _build_meta(+ timing_ms=(time.perf_counter() - t0) * 1000,+ repository=repository,+ ),}if not ctx.path:return {"symbol_id": symbol_id,"error": "MCP server has no repo path configured",- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),+ "_meta": _build_meta(+ timing_ms=(time.perf_counter() - t0) * 1000,+ repository=repository,+ ),}repo_root = Path(str(ctx.path))@@ -347,7 +359,10 @@ async def get_symbol("Symbol metadata exists but source file could not be read. ""The file may have been moved or deleted since indexing."),- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),+ "_meta": _build_meta(+ timing_ms=(time.perf_counter() - t0) * 1000,+ repository=repository,+ ),}truncated = (end - start + 1) >= _MAX_SOURCE_LINES and (@@ -371,5 +386,6 @@ async def get_symbol("_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000,hint=_symbol_hint(row.symbol_id, row.end_line, row.start_line),+ repository=repository,),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 7467a4710..dd53f094f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -24,6 +24,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._server import mcp@@ -33,22 +34,28 @@ async def get_why(targets: list[str] | None = None,repo: str | None = None,) -> dict:- """Understand why code is built the way it is — intent archaeology.+ """Why this code looks the way it does — decision archaeology git log cannot answer.++ The only tool that surfaces architectural decision records, their status+ (active / proposed / deprecated / superseded), and the commits that are+ evidence for them. ``git log`` tells you *what* changed; this tells you+ *why we chose this design* — call it before any architectural change,+ refactor of an owned module, or pattern divergence in a community.Four modes:- 1. get_why("why is auth using JWT?") — semantic + keyword search over decisions- 2. get_why("src/auth/service.py") — all decisions governing a specific file,- plus origin story and alignment score- 3. get_why("why was caching added?", targets=["src/auth/cache.py"]) —- target-aware search: prioritizes decisions governing the target files- 4. get_why() — decision health dashboard+ 1. ``get_why("why is auth using JWT?")`` — keyword + semantic decision search.+ 2. ``get_why("src/auth/service.py")`` — decisions governing the file plus+ origin story and an alignment score (does this file follow its own ADRs?).+ 3. ``get_why("why was caching added?", targets=["src/auth/cache.py"])`` —+ target-anchored search; decisions touching the targets get boosted.+ 4. ``get_why()`` — health dashboard (stale, proposed, ungoverned hotspots).- Always call this before making architectural changes.+ When no decisions exist for a path, falls back to git archaeology+ (significant commits + cross-file references) so the call is never empty.Args:query: Natural language question, file/module path, or omit for health dashboard.- targets: Optional file paths to anchor the search. Decisions governing- these files are prioritized in results.+ targets: Optional file paths to anchor the search.repo: Repository path, name, or ID."""# --- repo="all": search decisions across ALL repos ---@@ -84,6 +91,7 @@ async def get_why("query": query,"workspace": True,"decisions": merged[:15],+ "_meta": _build_meta(),}# --- Mode 1: No query → health dashboard ---@@ -127,6 +135,7 @@ async def get_why(for d in proposed[:10]],"ungoverned_hotspots": ungoverned[:15],+ "_meta": _build_meta(repository=repository),}# --- Mode 2: Path → decisions, origin story, alignment ---@@ -197,6 +206,7 @@ async def get_why(repository,)+ result_data["_meta"] = _build_meta(repository=repository)return result_data# --- Mode 3: Natural language → target-aware search ---@@ -362,6 +372,7 @@ async def get_why(target_context[t] = ctx_entryresult_data["target_context"] = target_context+ result_data["_meta"] = _build_meta(repository=repository)return result_data