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): a lean get_overview default with the tool surface, quarter and full scope on request (#4207)
Raghav Chamadiyab423538c6ca6
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex cc3aff7cd..d44a8e252 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -307,14 +307,14 @@ get_why()### `get_overview`-The architecture map: summary, key modules, entry points, layers, code and git health, and the next actions for the week and quarter. Call it once, first, in an unfamiliar repo. Skip it afterwards; it does not change within a session.+Orientation for an unfamiliar repo: summary, key modules, entry points, layers, code health, the riskiest files and this week's top actions. Call it once, first. Skip it afterwards; it does not change within a session.| Parameter | Type | Default | Meaning ||-----------|------|---------|---------|-| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners), `components` (declared and derived components with file counts), `changes` (Change Records by category and week, and the agent share of changes with coverage) |+| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners), `components` (declared and derived components with file counts), `changes` (Change Records by category and week, and the agent share of changes with coverage), `actions` (the quarter's actions too, with `done_when`), `tools` (`tool_surface`: enabled tools, opt-ins and recipes), `scope` (the whole `_meta.index_scope`) || `repo` | string | default repo | Workspace repo alias, or `"all"` for the cross-repo topology |-**Key return fields:** `title`, `content_md` (summary section by default), `key_modules`, `entry_points`, `architecture` (layers in stack order, plus `dependencies`: the ten heaviest package-to-package edges with `from`, `to`, `verb` and `weight`, and `edges_total` when more exist; absent in a single-package repo), `code_health`, `git_health`, `next_actions`, `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.+**Key return fields:** `title`, `content_md` (summary section by default), `key_modules`, `entry_points`, `architecture` (layers in stack order, plus `dependencies`: the ten heaviest package-to-package edges with `from`, `to`, `verb` and `weight`, and `edges_total` when more exist; absent in a single-package repo), `code_health`, `git_health` (`riskiest_files`), `next_actions` (top three for the week, or the quarter when the week is empty), `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.```get_overview()diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex fc571d535..69e962c4b 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -1072,7 +1072,7 @@ Defined in `tool_health/tool.py`, which dispatches to one module per mode and bl2 markers (each with a `suggestion` string), a coverage block, and anull-dropped `signals` block (process/people/topology, see §8).- `get_overview()`: adds a `code_health` block: avg, repo `band`, hotspot,- worst performer, open finding count, and the NLOC-weighted `distribution`.+ worst performer, open finding count, and the file count per band.Every response carries the standard `_meta` envelope via `build_meta()`.diff --git a/docs/layers/OWNERSHIP.md b/docs/layers/OWNERSHIP.mdindex 2c097f3d7..6cfc595c4 100644--- a/docs/layers/OWNERSHIP.md+++ b/docs/layers/OWNERSHIP.md@@ -115,7 +115,6 @@ add "informational: small team" to the reason.| Truck factor | Stats page | Fewest primary owners who together own more than half the owned files. Bot authors are left out || Single-owner files | Stats page | Files with bus factor 1 || Silo count | Stats page | Modules where one person owns more than 80% of files |-| `git_health.avg_bus_factor`, `git_health.files_with_bus_factor_1` | `get_overview` | Average bus factor and count of bus-factor-1 files || `knowledge_map.top_owners` | `get_overview(include=["ownership"])` | The three people owning the most files, by display name only |### Contributor profilesdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 58aa31a1d..b6a0fbd67 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -289,7 +289,7 @@ See [WORKTREES.md](../scale/WORKTREES.md).`state.json:index_scope` is the canonical machine-readable description used by `status --format json`, `/api/repos`, generated agent guidance, and MCP `_meta.index_scope`. It separately records run mode, content provenance (`none`, `template`, or `model`), Git tier, configured commit cap, achieved Git-history coverage, configured/effective file-page caps, eligible/generated/omitted file-page counts, unavailable/skipped analysis, search availability, provider choices, and upgrade state. Older indexes project missing facts as `unknown`/`null`; a configured cap is never reported as achieved coverage and a missing analysis result is never reported as a clean result.-Over MCP, an ordinary tool response carries a **compact projection** of this object rather than all of it: the run mode, content provenance, Git tier, a `status` of `complete`, `partial`, `degraded`, `upgrading` or `unknown`, the names of any degraded analyses, and a `fingerprint` identifying the canonical object. `get_overview` carries the canonical object in full, with the same `fingerprint` beside it, so a held copy can be checked against a later digest without either side resending it. `status` reaches `complete` only when the evidence exists and is clean; an index whose coverage was never recorded reports `unknown`. Since `_meta` contract 3 an ordinary response leaves a `complete` digest out, so only a gap rides on it. Set `REPOWISE_MCP_INDEX_SCOPE=full` to put the canonical object on every MCP response, as builds before `_meta.contract_version` 2 did.+Over MCP, an ordinary tool response carries a **compact projection** of this object rather than all of it: the run mode, content provenance, Git tier, a `status` of `complete`, `partial`, `degraded`, `upgrading` or `unknown`, the names of any degraded analyses, and a `fingerprint` identifying the canonical object. `get_overview(include=["scope"])` carries the canonical object in full, with the same `fingerprint` beside it, so a held copy can be checked against a later digest without either side resending it. `status` reaches `complete` only when the evidence exists and is clean; an index whose coverage was never recorded reports `unknown`. Since `_meta` contract 3 an ordinary response leaves a `complete` digest out, so only a gap rides on it. Set `REPOWISE_MCP_INDEX_SCOPE=full` to put the canonical object on every MCP response, as builds before `_meta.contract_version` 2 did.**Examples:**diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex e19e1c307..39733bf84 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -18,7 +18,7 @@ The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../ageEvery response carries `_meta`. Fields are present only when they carry a signal, so read absence as "nothing to report", never as an error.-Routine responses carry a lean envelope. `get_overview`, called once per session, keeps the full one: `contract_version`, `timing_ms`, `response_budget` and `completeness` on every call, and the whole `index_scope`. Setting `REPOWISE_MCP_DEBUG_META=1` in the server's environment restores the diagnostic fields on every tool (`contract_version`, `timing_ms`, `response_budget`, `completeness`, `tokens_saved`, `replaced_tokens`) for diagnosis; it is read per call, so no restart is needed.+Routine responses carry a lean envelope. `get_overview`, called once per session, keeps the full one: `contract_version`, `timing_ms`, `response_budget` and `completeness` on every call. Its `index_scope` is the same digest as elsewhere (left out when `complete`); `include=["scope"]` adds the whole object. Setting `REPOWISE_MCP_DEBUG_META=1` in the server's environment restores the diagnostic fields on every tool (`contract_version`, `timing_ms`, `response_budget`, `completeness`, `tokens_saved`, `replaced_tokens`) for diagnosis; it is read per call, so no restart is needed.| Field | When present | Meaning ||-------|--------------|---------|@@ -32,7 +32,7 @@ Routine responses carry a lean envelope. `get_overview`, called once per session| `index_behind` | When the live-versus-indexed comparison ran | `true` if HEAD moved, `false` if it matches. Absent means the comparison could not run || `stale_warning` | Only on a real signal | HEAD moved and the move changed files this response serves, a file this response serves has uncommitted edits the index has not seen or was indexed from uncommitted edits since reverted, or the index is very old and git is unreachable. Two commits with identical trees set `index_behind` with no warning || `working_tree_dirty` | Only when above zero | How many served targets have uncommitted edits no `repowise update --working-tree` has indexed. Source reads are live; graph and index facts for those files predate the edit. A dirty tree elsewhere never sets it |-| `index_scope` | When the index records it and its `status` is not `complete` (whole object on `get_overview`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`) | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole |+| `index_scope` | When the index records it and its `status` is not `complete` (whole object on `get_overview(include=["scope"])`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`) | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole || `embedder_degraded` | When an embedder is resolved | `true` or `false` || `embedder`, `embedder_warning` | Only when the embedder fell back to a mock or degraded mode, or the semantic index on disk could not be opened | Which embedder, and why || `newer_release` | Once per server process | A newer repowise is published; restart the MCP server after upgrading |@@ -328,12 +328,13 @@ The `candidates` and `history` lanes shed first under budget pressure, so an abs| `key_modules` | Name, path, and outline section || `entry_points` | Detected entry points || `architecture` | Layer names and file counts in stack order, test layer left out |-| `code_health`, `git_health` | Repo-level health and history summaries |-| `next_actions` | Per horizon (week, quarter): the first three stored actions (`id`, `tier`, `title`, `impact`, `done_when`, `target`) with `total` and `by_tier`. `get_health(fix_id="act_...")` opens one in full |+| `code_health` | Headline score and band, `production_average` (non-test files, when the reading holds tests), hotspot health, worst file, open findings, `code_files` (every code file health read; `files_scored` when some carry no score) and `files_by_band` |+| `git_health` | Hotspot count, churn trend and `riskiest_files`: five paths, bug magnets first, then fix mass, then churn |+| `next_actions` | The first three stored actions (`id`, `tier`, `title`, a one-line `impact`, `target`) for the week, or the quarter when the week is empty, with each horizon's `total`. `include=["actions"]` serves both horizons with `done_when` and `by_tier`. `get_health(fix_id="act_...")` opens one in full || `more` | Names the opt-in blocks || `workspace` | Workspace mode footer |-Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`), `components`, `changes`. They are not computed unless named.+Opt-in blocks: `outline` (wiki page tree, two levels), `tour` (`guided_tour`, `reading_order`), `decisions` (`key_decisions`), `graph` (`community_summary`), `ownership` (`knowledge_map`), `components`, `changes`, `actions`, `tools` (`tool_surface`), `scope` (the whole `_meta.index_scope`). They are not computed unless named.**changes.** Change Records over a 90-day `window` ending at the newest merged change (`since`, `until`): `total`, `by_category` (largest first), `by_week` (`{week, changes}` per week starting Monday, zero weeks included) and `provenance` over changes: `agent_changes`, `human_attested_changes`, `unknown_changes`, `coverage`, `agent_share` and `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason`, and the agent and human-attested counts are left out. A change stored without a label counts as unknown, never human. `{"total": 0}` when no Change Records are stored; `provenance` is `{"unavailable": "attribution_off"}` with attribution off. Grouped by change and category only, never by person.diff --git a/packages/core/src/repowise/core/index_scope.py b/packages/core/src/repowise/core/index_scope.pyindex 899b09847..7b65cd8ea 100644--- a/packages/core/src/repowise/core/index_scope.py+++ b/packages/core/src/repowise/core/index_scope.py@@ -369,7 +369,7 @@ def index_scope_fingerprint(scope: Mapping[str, Any]) -> str:def compact_index_scope(- scope: Mapping[str, Any] | None, *, full_hint: str = "get_overview()"+ scope: Mapping[str, Any] | None, *, full_hint: str = 'get_overview(include=["scope"])') -> dict[str, Any] | None:"""The routine-response projection of a canonical scope.diff --git a/packages/server/src/repowise/server/chat_view_builders.py b/packages/server/src/repowise/server/chat_view_builders.pyindex 1811b285d..bc613ba9f 100644--- a/packages/server/src/repowise/server/chat_view_builders.py+++ b/packages/server/src/repowise/server/chat_view_builders.py@@ -302,14 +302,19 @@ _HEALTH_BANDS = ("at_risk", "needs_work", "fair", "good", "excellent"))def health_bands_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:data = artifact.data- distribution = data.get("distribution") or (data.get("code_health") or {}).get("distribution")+ distribution = data.get("distribution")bands = distribution.get("bands") if isinstance(distribution, Mapping) else None- if not isinstance(bands, Mapping):+ if isinstance(bands, Mapping):+ files = {b: v.get("files") for b, v in bands.items() if isinstance(v, Mapping)}+ else:+ # The overview carries the per-band file counts alone.+ files = (data.get("code_health") or {}).get("files_by_band")+ if not isinstance(files, Mapping):raise ViewError("this result has no health distribution; call get_health with no targets")rows = [- {"band": band.replace("_", " "), "files": bands[band]["files"]}+ {"band": band.replace("_", " "), "files": files[band]}for band in _HEALTH_BANDS- if isinstance(bands.get(band), Mapping) and isinstance(bands[band].get("files"), int)+ if isinstance(files.get(band), int)]total = sum(row["files"] for row in rows)return _chart(diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 86ac6b44f..3493ce2ab 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -303,6 +303,9 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {("graph", ("community_summary",)),("ownership", ("knowledge_map",)),("content", ("content_md",)),+ ("tools", ("tool_surface.opt_in", "tool_surface.tools[]",+ "tool_surface.recipes[]", "tool_surface")),+ ("actions", ("next_actions.quarter.actions[]",)),),),"get_health": ResponseBudgetContract(diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex c7887b259..d6570bcbd 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -142,8 +142,9 @@ def _canonical_scope_requested() -> bool:def _full_scope_hint() -> str:"""The call that returns the whole scope, as this server is running.- In workspace mode ``get_overview()`` returns the repo listing and carries- no scope at all, so a digest pointing there would send an agent somewhere+ The overview carries the whole scope only when asked for it. In workspace+ mode ``get_overview(repo="all")`` returns the repo listing and carries no+ scope at all, so a digest pointing there would send an agent somewherethe rest of the answer is not. The argument is named rather than filled inbecause the alias belongs to the caller's own request, not to therepository row this envelope was built from.@@ -151,8 +152,8 @@ def _full_scope_hint() -> str:from repowise.server.mcp_server import _stateif getattr(_state, "_registry", None) is not None:- return "get_overview(repo=...)"- return "get_overview()"+ return 'get_overview(repo=..., include=["scope"])'+ return 'get_overview(include=["scope"])'def index_scope_for_response(local_path: str | None) -> dict[str, Any] | None:diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.pyindex 9b2a4ad96..58a554f20 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py@@ -16,29 +16,60 @@ _PER_HORIZON = NEXT_ACTIONS_HEAD_FIELDS = ("id", "tier", "title", "impact", "done_when")+#: The default row: what to do and where, with the impact cut to one line.+#: ``include=["actions"]`` restores ``done_when``, ``by_tier`` and the quarter.+_LEAN_FIELDS = ("id", "tier", "title", "impact")+_IMPACT_CHARS = 140-def _compact(action: dict[str, Any]) -> dict[str, Any]:- row = {k: action.get(k) for k in _FIELDS}++def _one_line(text: Any) -> Any:+ """The first sentence of *text*, cut at a word boundary to ``_IMPACT_CHARS``."""+ if not isinstance(text, str):+ return text+ flat = " ".join(text.split())+ head, dot, _ = flat.partition(". ")+ line = head + "." if dot else flat+ if len(line) <= _IMPACT_CHARS:+ return line+ return line[: _IMPACT_CHARS - 1].rsplit(" ", 1)[0].rstrip(";,") + "…"+++def _compact(action: dict[str, Any], *, full: bool) -> dict[str, Any]:+ row = {k: action.get(k) for k in (_FIELDS if full else _LEAN_FIELDS)}+ if not full:+ row["impact"] = _one_line(row["impact"])row["target"] = {k: v for k, v in (action.get("target") or {}).items() if v is not None}return row-def compact_actions_view(view: dict[str, Any]) -> dict[str, Any]:- """The head of each horizon plus its totals, from a ``load_actions_view`` result."""- block: dict[str, Any] = {"anchor": view.get("anchor")}- for name, horizon in (view.get("horizons") or {}).items():- block[name] = {- "total": horizon.get("total", 0),- "by_tier": horizon.get("by_tier", {}),- "actions": [_compact(a) for a in horizon.get("actions", [])[:_PER_HORIZON]],- }+def compact_actions_view(view: dict[str, Any], *, full: bool = True) -> dict[str, Any]:+ """The head of each horizon plus its totals, from a ``load_actions_view`` result.++ ``full=False`` is the default overview's cut: rows for the nearest+ non-empty horizon only (the week, else the quarter, as ``repowise next``+ picks), and a bare total for the other.+ """+ horizons = view.get("horizons") or {}+ block: dict[str, Any] = {"anchor": view.get("anchor")} if full else {}+ lead = next((n for n, h in horizons.items() if h.get("actions")), None)+ for name, horizon in horizons.items():+ row: dict[str, Any] = {"total": horizon.get("total", 0)}+ if full:+ row["by_tier"] = horizon.get("by_tier", {})+ if full or name == lead:+ row["actions"] = [+ _compact(a, full=full) for a in horizon.get("actions", [])[:_PER_HORIZON]+ ]+ block[name] = rowunavailable = sorted(view.get("unavailable") or {})if unavailable:block["unavailable"] = unavailablereturn block-async def _build_next_actions(session: Any, repository: Any) -> tuple[dict[str, Any], str | None]:+async def _build_next_actions(+ session: Any, repository: Any, *, full: bool = False+) -> tuple[dict[str, Any], str | None]:"""``(block, None)``, or ``({}, reason)`` when the actions could not be read.The loader already tolerates a store missing from an older index; this@@ -49,7 +80,7 @@ async def _build_next_actions(session: Any, repository: Any) -> tuple[dict[str,try:async with session.begin_nested():view = await load_actions_view(session, repository.id)- return compact_actions_view(view), None+ return compact_actions_view(view, full=full), Noneexcept Exception as exc:logger.warning("get_overview: next actions unavailable: %s", exc)return {}, f"Next actions could not be read from this index ({type(exc).__name__})."diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py b/packages/server/src/repowise/server/mcp_server/tool_overview/health.pyindex bcc0d74f1..c7d2a9ee7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/health.py@@ -9,7 +9,8 @@ from repowise.core.analysis.health.grading import (distribution as health_distribution,)from repowise.core.analysis.health.grading import headline_band-from repowise.core.analysis.health.scoring import hotspot_health+from repowise.core.analysis.health.rows import scored_rows, split_tests+from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_scorefrom repowise.core.persistence.crud import (get_health_metrics as _get_health_metrics,)@@ -19,25 +20,38 @@ from repowise.core.persistence.crud import (from repowise.core.persistence.crud import get_hotspot_file_paths+def _production_average(metrics_rows: list[Any]) -> float | None:+ """The headline over non-test files, as ``compute_kpis`` weighs it; ``None``+ when the reading holds no tests, since it would only repeat the headline."""+ production, tests = split_tests(scored_rows(metrics_rows))+ if not production or not tests:+ return None+ return round(nloc_weighted_score(production), 2)++async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:- """Headline code-health KPIs; empty when health hasn't been run on this repo."""+ """Headline code-health KPIs; empty when health hasn't been run on this repo.++ ``code_files`` is every code file health read, scored or not.+ """try:# Metrics first, handed to the summary so the shared table is read once.metrics_rows = await _get_health_metrics(session, repository.id)if not metrics_rows:return {}health_summary = await _get_health_summary(session, repository.id, metrics=metrics_rows)+ scored = health_summary["file_count"]+ code_files = scored + health_summary["unanalysed_file_count"]if health_summary["average_health"] is None:# Every file is in a language health has no dialect for.- return {- "analysis_status": NO_DIALECT_STATUS,- "unanalysed_file_count": health_summary["unanalysed_file_count"],- }+ return {"analysis_status": NO_DIALECT_STATUS, "code_files": code_files}# Hotspot health from its one owner, over the rows already loaded.hotspot_paths = await get_hotspot_file_paths(session, repository.id)- unanalysed = health_summary["unanalysed_file_count"]+ production = _production_average(metrics_rows)+ bands = health_distribution(metrics_rows)["bands"]return {"average_health": health_summary["average_health"],+ **({"production_average": production} if production is not None else {}),# ``None`` when too few code files were analysed to grade the repo."band": headline_band(health_summary["average_health"], health_summary["analysed_share"]@@ -46,17 +60,11 @@ async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:"worst_performer_path": health_summary["worst_performer_path"],"worst_performer_score": health_summary["worst_performer_score"],"open_findings": health_summary["open_findings"],- "file_count": health_summary["file_count"],- # Only said when there are some, as the health dashboard does.- **(- {- "unanalysed_file_count": unanalysed,- "analysed_share": health_summary["analysed_share"],- }- if unanalysed- else {}- ),- "distribution": health_distribution(metrics_rows),+ "code_files": code_files,+ # Only said when some code files carry no score.+ **({"files_scored": scored} if scored != code_files else {}),+ # File counts only; get_health carries the NLOC-weighted split.+ "files_by_band": {band: row["files"] for band, row in bands.items()},}except Exception:return {}diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/history.py b/packages/server/src/repowise/server/mcp_server/tool_overview/history.pyindex 1593b6608..cb3bfc76f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/history.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/history.py@@ -2,30 +2,51 @@from __future__ import annotations-from collections import Counter, defaultdict+from collections import defaultdict+from pathlib import Pathfrom typing import Any-from repowise.core.analysis.health.aggregation import module_label+#: Riskiest files the overview names; get_risk / get_health carry the rest.+_RISKIEST_FILES = 5-def _build_git_health(all_git: list) -> dict[str, Any]:- """Repo-wide git health summary (hotspots, bus factor, churn trend, top modules)."""+def _build_git_health(all_git: list, repo_root: Path | str | None = None) -> dict[str, Any]:+ """Repo-wide git health: hotspot count, churn trend and the riskiest files."""if not all_git:return {}-- bus_factors = [getattr(g, "bus_factor", 0) or 0 for g in all_git]return {- # Files with git history, not the parsed total: vendored, generated- # and new files have none, so the two counts can differ.- "files_git_attributed": len(all_git),"hotspot_count": sum(1 for g in all_git if g.is_hotspot),- "avg_bus_factor": round(sum(bus_factors) / len(bus_factors), 1),- "files_with_bus_factor_1": sum(1 for b in bus_factors if b == 1),"churn_trend": _churn_trend(all_git),- "top_churn_modules": _top_churn_modules(all_git),+ "riskiest_files": _riskiest_files(all_git, repo_root),}+def _riskiest_files(all_git: list, repo_root: Path | str | None) -> list[str]:+ """Hotspots and bug magnets in the order the generated CLAUDE.md lists them.++ Bug magnets first, then fix mass, then churn, as ``files that need care``+ ranks them in the editor files. A row can outlive its file when the+ deleted-file prune skips a run, so with *repo_root* only live files count.+ """+ candidates = sorted(+ (g for g in all_git if g.is_hotspot or getattr(g, "bug_magnet", False)),+ key=lambda g: (+ not getattr(g, "bug_magnet", False),+ -(getattr(g, "fix_mass", 0) or 0),+ -(getattr(g, "churn_percentile", 0) or 0),+ g.file_path,+ ),+ )+ root = Path(repo_root) if repo_root else None+ out: list[str] = []+ for g in candidates:+ if len(out) >= _RISKIEST_FILES:+ break+ if root is None or (root / g.file_path).exists():+ out.append(g.file_path)+ return out++def _churn_trend(all_git: list) -> str:"""Last-30-day commit rate against the 60 days before it."""c30_total = sum(g.commit_count_30d or 0 for g in all_git)@@ -38,14 +59,6 @@ def _churn_trend(all_git: list) -> str:return "decreasing" if ratio < 0.5 else "stable"-def _top_churn_modules(all_git: list) -> list[str]:- """Five busiest modules by 90-day commits, on the module axis every count uses."""- module_churn: Counter = Counter()- for g in all_git:- module_churn[module_label(g.file_path)] += g.commit_count_90d or 0- return [m for m, _ in module_churn.most_common(5) if module_churn[m] > 0]--def _owner_display_name(name: str | None, email: str) -> str:"""A privacy-safe display name for a contributor — never the raw email.diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.pyindex a7446ff75..1fa066f37 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import functoolsfrom collections.abc import Awaitablefrom typing import Any@@ -26,6 +27,8 @@ from repowise.server.mcp_server._helpers import (filter_rows_by_attr,resolve_enum_argument,)+from repowise.server.mcp_server._meta import MCP_CONTRACT_VERSION+from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import (build_meta_with_full_scope as _build_meta_with_full_scope,)@@ -63,31 +66,37 @@ from repowise.server.mcp_server.tool_overview.workspace import (#: The ``include`` values get_overview serves; anything else is named, not applied._INCLUDE_BLOCKS = frozenset(- {"content", "outline", "tour", "decisions", "graph", "ownership", "components", "changes"}+ {+ "content",+ "outline",+ "tour",+ "decisions",+ "graph",+ "ownership",+ "components",+ "changes",+ "tools",+ "actions",+ "scope",+ })@mcp.tool(surface_order=80, artifact_type="overview", presentation="overview")async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:- """Architecture map for an unfamiliar repo — first call when you don't know your way around.-- Returns the overview summary, key modules, entry points, architecture- layers and package dependencies, code health, repo-wide git health, and- ``next_actions`` (top work for the week and quarter).- Skip it on later calls; go straight to ``get_context`` / ``get_answer``.+ """Orientation for an unfamiliar repo: packages, entry points, riskiest files, top actions.- Compact by default: ``content_md`` carries only the essay's summary- section; other blocks ship on request, named in ``more``.+ Once per session; then use ``get_context`` or ``get_answer``.+ Compact by default: ``content_md`` is the essay's summary section and+ ``next_actions`` the week's top three; other blocks ship on request,+ named in ``more``.Defaults fit 24,000 chars; nonempty ``include`` uses 32,000. Reductionscarry counts and recovery status in ``_meta``.Include-gated blocks are projections, not omissions.- In workspace mode:- - 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.+ In a workspace, omit ``repo`` for the default repo, ``repo='<alias>'`` for+ another, ``repo='all'`` for cross-repo links.Args:repo: Repository alias, path, or ID, or ``"all"``.@@ -100,9 +109,22 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None``"ownership"`` — ``knowledge_map``: top 3 owners by files owned.``"components"`` — component list with file counts.``"changes"`` — changes by category, week and source, with coverage.+ ``"tools"`` — ``tool_surface``: enabled tools, opt-ins, recipes.+ ``"actions"`` — ``next_actions`` for the quarter too, with ``done_when``.+ ``"scope"`` — the whole ``_meta.index_scope`` (provider, coverage)."""+ ignored: list[dict[str, Any]] = []+ want = {+ k+ for k in include or []+ if resolve_enum_argument(k, _INCLUDE_BLOCKS, argument="include", ignored=ignored)+ }if repo == "all":- return await _workspace_overview()+ result = await _workspace_overview(tools="tools" in want)+ for k in sorted(want - {"tools"}): # single-repo blocks+ resolve_enum_argument(k, {"tools"}, argument="include", ignored=ignored)+ attach_ignored_arguments(result, ignored)+ return resultctx = await _resolve_repo_context(repo)exclude_spec = _get_exclude_spec(ctx.path)@@ -111,14 +133,8 @@ async def get_overview(repo: str | None = None, include: list[str] | None = Nonecollector = OmissionCollector("get_overview", repo_root=ctx.path)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)- ignored: list[dict[str, Any]] = []- want = {- k- for k in include or []- if resolve_enum_argument(k, _INCLUDE_BLOCKS, argument="include", ignored=ignored)- }result = await _repo_overview(- session, ctx.session_factory, repository, exclude_spec, want, collector+ session, ctx.session_factory, repository, exclude_spec, want, collector, ctx.path)if "components" in want:result["components"] = await component_list(@@ -132,9 +148,15 @@ async def get_overview(repo: str | None = None, include: list[str] | None = Noneif "changes" in want:result["changes"] = await overview_changes(session, repository)- # Made once per session, so this is where the full scope that every- # other response's compact projection points at is worth its bytes.- result["_meta"] = _build_meta_with_full_scope(repository=repository)+ # The whole scope that every compact projection points at ships on+ # request; by default the overview carries the same digest as the rest.+ if "scope" in want:+ result["_meta"] = _build_meta_with_full_scope(repository=repository)+ else:+ result["_meta"] = {+ "contract_version": MCP_CONTRACT_VERSION,+ **_build_meta(repository=repository),+ }collector.attach(result)attach_ignored_arguments(result, ignored)return result@@ -147,13 +169,14 @@ async def _repo_overview(exclude_spec: Any,want: set[str],collector: OmissionCollector,+ repo_root: Any = None,) -> dict[str, Any]:"""Every single-repo block, in payload order; empty optional blocks are left out.Code health and the next actions are the slow reads and need nothing elsehere, so each runs on its own read session while the rest is read."""- slow = _slow_reads(session, session_factory, repository)+ slow = _slow_reads(session, session_factory, repository, full_actions="actions" in want)try:overview_page = await _load_overview_page(session, repository)module_pages = await _load_module_pages(session, repository, collector)@@ -186,12 +209,13 @@ async def _repo_overview(for p in module_pages],"entry_points": _capped_entry_points(entry_point_ids, collector),- "git_health": _build_git_health(all_git),+ "git_health": _build_git_health(all_git, repo_root),"more": ('get_overview(include=[...]) also serves: "outline" (the wiki ''page tree), "tour" (guided_tour + reading_order), "decisions", ''"graph" (code communities), "ownership" (top owners, silos), '- '"content" (the full essay).'+ '"content" (the full essay), "actions" (the quarter), "tools" '+ '(the tool surface), "scope" (the whole index scope).'),}optional = {@@ -216,27 +240,31 @@ async def _repo_overview(if ws_footer:result["workspace"] = ws_footer- result["tool_surface"] = _tool_surface_guide(is_workspace=_state._registry is not None)+ if "tools" in want:+ result["tool_surface"] = _tool_surface_guide(is_workspace=_state._registry is not None)return result-def _slow_reads(session: Any, session_factory: Any, repository: Any) -> Awaitable[Any]:+def _slow_reads(+ session: Any, session_factory: Any, repository: Any, *, full_actions: bool = False+) -> Awaitable[Any]:"""``(code health, next actions)``: started now on their own sessions, or,on a store whose sessions share one connection, read later on *session*."""+ actions = functools.partial(_build_next_actions, full=full_actions)if not _own_connections(session_factory):- return _in_turn(session, repository)+ return _in_turn(session, repository, actions)async def apart(build: Any) -> Any:async with get_session(session_factory) as own:return await build(own, repository)- return asyncio.gather(apart(_build_code_health), apart(_build_next_actions))+ return asyncio.gather(apart(_build_code_health), apart(actions))-async def _in_turn(session: Any, repository: Any) -> tuple[Any, Any]:+async def _in_turn(session: Any, repository: Any, actions: Any) -> tuple[Any, Any]:return (await _build_code_health(session, repository),- await _build_next_actions(session, repository),+ await actions(session, repository),)@@ -279,12 +307,14 @@ _READING_ORDER_HINT = (#: most of a warm overview on a large repository._GIT_ROW_COLUMNS = (GitMetadata.file_path,- GitMetadata.bus_factor,GitMetadata.is_hotspot,GitMetadata.commit_count_30d,GitMetadata.commit_count_90d,GitMetadata.primary_owner_email,GitMetadata.primary_owner_name,+ GitMetadata.bug_magnet,+ GitMetadata.fix_mass,+ GitMetadata.churn_percentile,)diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py b/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.pyindex 3d0f52a5a..7ef4c7495 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py@@ -18,7 +18,7 @@ from repowise.server.mcp_server.tool_overview.pages import _load_overview_pagefrom repowise.server.mcp_server.tool_overview.surface import _tool_surface_guide-async def _workspace_overview() -> dict:+async def _workspace_overview(*, tools: bool = False) -> dict:"""Build a concise workspace-level overview across all repos."""registry = _state._registryfed = Federation()@@ -34,9 +34,10 @@ async def _workspace_overview() -> dict:"total_symbols": totals["symbol_count"],"repos": repos_info,"hint": ("Use repo='<alias>' to query a specific repo. Omit repo to use the default."),- "tool_surface": _tool_surface_guide(is_workspace=True),"_meta": _build_meta(),}+ if tools:+ result["tool_surface"] = _tool_surface_guide(is_workspace=True)if cross_repo_topology:result["cross_repo_topology"] = cross_repo_topology@@ -107,22 +108,14 @@ def _build_workspace_footer() -> dict | None:if not other_repos:return None- footer: dict[str, Any] = {+ # Names only: the cross-repo links are what repo="all" serves, so the+ # footer points there rather than restating them.+ return {"workspace_root": str(registry.workspace_root),"default_repo": default_alias,"other_repos": other_repos,"hint": (- "This repo is part of a workspace. "- f"Other repos: {', '.join(other_repos)}. "- "Use repo='<alias>' to query another repo, "- "or repo='all' for workspace-wide results."+ "Use repo='<alias>' for another repo, "+ "or repo='all' for cross-repo links and contracts."),}-- enricher = _enricher_with_data()- if enricher is not None:- footer["cross_repo"] = enricher.get_cross_repo_summary()- if enricher.has_contract_data:- footer["contract_links"] = enricher.get_contract_summary()-- return footerdiff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.jsonindex b84120c6d..0b2c00437 100644--- a/tests/fixtures/mcp/tool_response_shapes.json+++ b/tests/fixtures/mcp/tool_response_shapes.json@@ -1244,40 +1244,18 @@"code_health": {"average_health": null,"band": null,- "distribution": {- "bands": {- "at_risk": {- "files": null,- "nloc": null,- "pct": null- },- "excellent": {- "files": null,- "nloc": null,- "pct": null- },- "fair": {- "files": null,- "nloc": null,- "pct": null- },- "good": {- "files": null,- "nloc": null,- "pct": null- },- "needs_work": {- "files": null,- "nloc": null,- "pct": null- }- },- "total_files": null,- "total_nloc": null+ "code_files": null,+ "files_by_band": {+ "at_risk": null,+ "excellent": null,+ "fair": null,+ "good": null,+ "needs_work": null},- "file_count": null,+ "files_scored": null,"hotspot_health": null,"open_findings": null,+ "production_average": null,"worst_performer_path": null,"worst_performer_score": null},@@ -1287,12 +1265,9 @@null],"git_health": {- "avg_bus_factor": null,"churn_trend": null,- "files_git_attributed": null,- "files_with_bus_factor_1": null,"hotspot_count": null,- "top_churn_modules": [+ "riskiest_files": [null]},diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex cc3add5a1..684d8c8bd 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -568,12 +568,12 @@ async def test_get_overview_stays_under_a_narrowed_host_cap(mcp_mod._repo_path = str(repo_root)budgeted = tool_middleware(get_overview)- full = await budgeted()+ full = await budgeted(include=["tools"])assert "truncated" not in full # normal cap: nothing shedsassert full["tool_surface"]["recipes"]monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "700")- trimmed = await budgeted()+ trimmed = await budgeted(include=["tools"])assert trimmed["truncated"] is Trueassert not trimmed.get("tool_surface", {}).get("recipes")diff --git a/tests/unit/server/mcp/test_federation.py b/tests/unit/server/mcp/test_federation.pyindex b42da07dd..d697f2218 100644--- a/tests/unit/server/mcp/test_federation.py+++ b/tests/unit/server/mcp/test_federation.py@@ -258,8 +258,9 @@ async def test_happy_path_shapes_unchanged(workspace_mcp): # noqa: F811overview = await get_overview(repo="all")assert set(overview) == {"workspace", "workspace_root", "total_repos", "total_files", "total_symbols",- "repos", "hint", "tool_surface", "_meta",+ "repos", "hint", "_meta",}+ assert "tool_surface" in await get_overview(repo="all", include=["tools"])assert overview["total_repos"] == 2assert all("stale" not in r for r in overview["repos"])@@ -301,3 +302,13 @@ async def test_stale_repo_is_named_and_its_rows_marked(workspace_mcp): # noqa:assert stale["live_head"] == git("rev-parse", "HEAD")[:12]rows = [f for t in result["tiers"].values() for f in t["findings"]]assert {f["repo"]: f.get("stale", False) for f in rows} == {"backend": True, "frontend": False}+++async def test_all_names_the_single_repo_includes_it_does_not_serve(workspace_mcp): # noqa: F811+ from repowise.server.mcp_server import get_overview++ overview = await get_overview(repo="all", include=["tools", "content"])+ assert "tool_surface" in overview+ assert overview["ignored_arguments"] == [+ {"argument": "include", "values": ["content"], "valid": ["tools"]}+ ]diff --git a/tests/unit/server/mcp/test_ff_mcp_payload_overview.py b/tests/unit/server/mcp/test_ff_mcp_payload_overview.pyindex 1131e891d..def338da8 100644--- a/tests/unit/server/mcp/test_ff_mcp_payload_overview.py+++ b/tests/unit/server/mcp/test_ff_mcp_payload_overview.py@@ -1,6 +1,6 @@"""Regression tests for get_overview payload quality:-- the git-attributed file count is labelled distinctly (not "total_files"),+- git health names the riskiest files in the editor files' order,- the knowledge map emits a contributor display name, never the raw email."""@@ -30,15 +30,26 @@ def _git_row(**kw) -> SimpleNamespace:return SimpleNamespace(**base)-# --- file-count labelling --------------------------------------------------+# --- riskiest files ---------------------------------------------------------def test_git_health_labels_git_attributed_count():- rows = [_git_row(file_path="a.py"), _git_row(file_path="b.py")]- out = _build_git_health(rows)- assert out["files_git_attributed"] == 2- # The ambiguous name is gone so it can't read as a parsed-file total.- assert "total_files_indexed" not in out+def test_git_health_names_the_riskiest_files_bug_magnets_first(tmp_path):+ rows = [+ _git_row(file_path="churny.py", is_hotspot=True, churn_percentile=0.99),+ _git_row(file_path="fixed.py", is_hotspot=True, fix_mass=4.0, churn_percentile=0.5),+ _git_row(file_path="magnet.py", bug_magnet=True, fix_mass=1.0),+ _git_row(file_path="gone.py", bug_magnet=True, fix_mass=9.0),+ _git_row(file_path="quiet.py"),+ ]+ for name in ("churny.py", "fixed.py", "magnet.py", "quiet.py"):+ (tmp_path / name).write_text("")++ out = _build_git_health(rows, tmp_path)++ # A row that outlived its file is not named.+ assert out["riskiest_files"] == ["magnet.py", "fixed.py", "churny.py"]+ assert out["hotspot_count"] == 2+ assert "files_git_attributed" not in out# --- contributor-email privacy ---------------------------------------------diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex b9b7c9498..7676abd79 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -2868,8 +2868,8 @@ async def test_overview_states_both_counts_and_withholds_the_band(setup_mcp, hearepo = SimpleNamespace(id=health_data)full = await _build_code_health(session, repo)assert full["band"] is not None- assert "unanalysed_file_count" not in full- assert "analysed_share" not in full+ assert full["code_files"] == 2+ assert "files_scored" not in fullfor i in range(3):session.add(@@ -2884,9 +2884,8 @@ async def test_overview_states_both_counts_and_withholds_the_band(setup_mcp, heaawait session.flush()partial = await _build_code_health(session, repo)- assert partial["file_count"] == 2- assert partial["unanalysed_file_count"] == 3- assert partial["analysed_share"] == 0.4+ assert partial["code_files"] == 5+ assert partial["files_scored"] == 2assert partial["band"] is Nonediff --git a/tests/unit/server/mcp/test_index_scope_projection.py b/tests/unit/server/mcp/test_index_scope_projection.pyindex 626228bf1..58e19ac3d 100644--- a/tests/unit/server/mcp/test_index_scope_projection.py+++ b/tests/unit/server/mcp/test_index_scope_projection.py@@ -89,7 +89,7 @@ def test_the_digest_keeps_what_changes_how_an_answer_reads() -> None:assert compact["git_tier"] == "full"assert compact["projection"] == "compact"# Says outright that it is not the whole thing, and where the rest is.- assert compact["full"] == "get_overview()"+ assert compact["full"] == 'get_overview(include=["scope"])'def test_the_digest_is_a_fraction_of_the_scope_it_stands_for() -> None:@@ -372,14 +372,14 @@ def test_the_fingerprint_refuses_what_it_cannot_canonicalise() -> None:def test_the_pointer_names_the_repo_argument_in_workspace_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """get_overview() with no repo returns the listing, which carries no scope."""+ """The digest names the repo argument: in a workspace it picks the repo."""from repowise.server.mcp_server import _statemonkeypatch.setattr(_state, "_registry", object(), raising=False)out = _meta.build_meta(repository=_write_state(tmp_path, _FULL_STATE))- assert out["index_scope"]["full"] == "get_overview(repo=...)"+ assert out["index_scope"]["full"] == 'get_overview(repo=..., include=["scope"])'def test_the_pointer_is_a_plain_call_for_a_single_repo(@@ -391,7 +391,7 @@ def test_the_pointer_is_a_plain_call_for_a_single_repo(out = _meta.build_meta(repository=_write_state(tmp_path, _FULL_STATE))- assert out["index_scope"]["full"] == "get_overview()"+ assert out["index_scope"]["full"] == 'get_overview(include=["scope"])'def test_the_window_opens_without_a_restart(diff --git a/tests/unit/server/mcp/test_overview_next_actions.py b/tests/unit/server/mcp/test_overview_next_actions.pyindex a26e364f7..b48a2c907 100644--- a/tests/unit/server/mcp/test_overview_next_actions.py+++ b/tests/unit/server/mcp/test_overview_next_actions.py@@ -35,24 +35,29 @@ async def test_overview_carries_the_stored_actions(setup_mcp, session):from repowise.server.mcp_server import get_overviewawait _seed(session, setup_mcp)- result = await get_overview()+ view = await load_actions_view(session, setup_mcp)+ lead = next(h for h in ("week", "quarter") if view["horizons"][h]["actions"])- block = result["next_actions"]+ result = await get_overview()assert "next_actions_reason" not in result- view = await load_actions_view(session, setup_mcp)+ block = result["next_actions"]for horizon in ("week", "quarter"):- full = view["horizons"][horizon]- assert block[horizon]["total"] == full["total"]- assert block[horizon]["by_tier"] == full["by_tier"]- # Same rows, same order, as the UI reads.- assert [a["id"] for a in block[horizon]["actions"]] == [- a["id"] for a in full["actions"][:3]- ]- assert block["quarter"]["actions"], "the seed should produce actions"- for row in block["quarter"]["actions"]:- assert set(row) == {"id", "tier", "title", "impact", "done_when", "target"}+ assert block[horizon]["total"] == view["horizons"][horizon]["total"]+ # Rows for the nearest horizon only, in the order the UI reads them.+ assert [a["id"] for a in block[lead]["actions"]] == [+ a["id"] for a in view["horizons"][lead]["actions"][:3]+ ]+ for row in block[lead]["actions"]:+ assert set(row) == {"id", "tier", "title", "impact", "target"}assert None not in row["target"].values()+ full = (await get_overview(include=["actions"]))["next_actions"]+ for horizon in ("week", "quarter"):+ assert full[horizon]["by_tier"] == view["horizons"][horizon]["by_tier"]+ assert full["quarter"]["actions"], "the seed should produce actions"+ for row in full["quarter"]["actions"]:+ assert set(row) == {"id", "tier", "title", "impact", "done_when", "target"}+@pytest.mark.asyncioasync def test_every_handed_out_action_id_opens_in_get_health(setup_mcp, session):@@ -61,7 +66,7 @@ async def test_every_handed_out_action_id_opens_in_get_health(setup_mcp, sessionfrom repowise.server.mcp_server import get_health, get_overviewawait _seed(session, setup_mcp)- block = (await get_overview())["next_actions"]+ block = (await get_overview(include=["actions"]))["next_actions"]ids = {a["id"] for h in ("week", "quarter") for a in block[h]["actions"]}assert ids, "the seed should produce actions"for action_id in ids:@@ -124,6 +129,28 @@ def test_compact_view_keeps_three_rows_and_names_unavailable_stores():assert block["unavailable"] == ["performance", "security"]+def test_the_default_cut_is_one_horizon_with_one_line_impacts():+ long = "Changed often; " * 20+ row = {"id": "act_0", "tier": "plan", "title": "T", "impact": f"First. {long}",+ "done_when": "d", "target": {"kind": "file", "path": "a.py"}}+ wordy = {**row, "id": "act_1", "impact": long}+ view = {+ "horizons": {+ "week": {"actions": [], "total": 0, "by_tier": {}},+ "quarter": {"actions": [row, wordy], "total": 2, "by_tier": {"plan": 2}},+ },+ } # fmt: skip++ block = compact_actions_view(view, full=False)++ # An empty week hands the rows to the quarter, as `repowise next` does.+ assert block["week"] == {"total": 0}+ first, second = block["quarter"]["actions"]+ assert set(first) == {"id", "tier", "title", "impact", "target"}+ assert first["impact"] == "First."+ assert len(second["impact"]) <= 140 and second["impact"].endswith("…")++def test_budget_sheds_the_block_before_the_protected_ones():from repowise.server.mcp_server._budget.contracts import _CONTRACTS@@ -154,7 +181,7 @@ def _record(monkeypatch, gate=None):await gate.wait() # finishes only if next_actions runs meanwhilereturn {"average_health": 7.0}- async def next_actions(session, _repo):+ async def next_actions(session, _repo, full=False):seen["next_actions"] = sessionif gate is not None:gate.set()@@ -204,7 +231,7 @@ async def test_a_failed_overview_leaves_no_slow_read_running(tmp_path, monkeypat_record(monkeypatch, gate=asyncio.Event())from repowise.server.mcp_server.tool_overview import tool- async def stuck(session, _repo):+ async def stuck(session, _repo, full=False):await asyncio.Event().wait()monkeypatch.setattr(tool, "_build_next_actions", stuck)diff --git a/tests/unit/server/mcp/test_overview_surface.py b/tests/unit/server/mcp/test_overview_surface.pyindex d9467598b..52b34af8b 100644--- a/tests/unit/server/mcp/test_overview_surface.py+++ b/tests/unit/server/mcp/test_overview_surface.py@@ -155,8 +155,10 @@ async def test_default_and_combined_overview_payloads_fit(setup_mcp):assert len(json.dumps(default, separators=(",", ":"), default=str)) <= 24_000assert len(json.dumps(combined, separators=(",", ":"), default=str)) <= 32_000- assert default["tool_surface"]["recipes"]+ # The agent already holds its tool list; the guide ships on request.+ assert "tool_surface" not in defaultassert "tool_guide" not in default+ assert (await call(include=["tools"]))["tool_surface"]["recipes"]@pytest.mark.asyncio@@ -164,7 +166,7 @@ async def test_live_registry_recipe_calls_bind_to_current_tool_signatures(setup_from repowise.core.registry import mcp_tool_registryfrom repowise.server.mcp_server import get_overview, tool_middleware- result = await tool_middleware(get_overview)()+ result = await tool_middleware(get_overview)(include=["tools"])entries = {entry.name: entry for entry in mcp_tool_registry.entries()}recipe_requirements = {recipe.name: set(recipe.requires)diff --git a/tests/unit/server/mcp/test_tool_overview.py b/tests/unit/server/mcp/test_tool_overview.pyindex d46340e45..26695b879 100644--- a/tests/unit/server/mcp/test_tool_overview.py+++ b/tests/unit/server/mcp/test_tool_overview.py@@ -254,7 +254,7 @@ def test_workspace_footer_is_absent_outside_a_workspace_and_for_a_lone_repo(monkassert ov._build_workspace_footer() is None-def test_workspace_footer_names_siblings_and_carries_cross_repo_summaries(monkeypatch):+def test_workspace_footer_names_siblings_and_points_at_the_cross_repo_view(monkeypatch):enricher = SimpleNamespace(has_data=True,has_contract_data=True,@@ -268,23 +268,9 @@ def test_workspace_footer_names_siblings_and_carries_cross_repo_summaries(monkeyassert footer["default_repo"] == "api"assert footer["other_repos"] == ["web", "worker"]assert footer["workspace_root"] == "/ws"- assert "web, worker" in footer["hint"]- assert footer["cross_repo"] == {"co_changes": 4}- assert footer["contract_links"] == {"links": 2}---def test_workspace_footer_omits_contract_links_without_contract_data(monkeypatch):- enricher = SimpleNamespace(- has_data=True,- has_contract_data=False,- get_cross_repo_summary=lambda: {"co_changes": 1},- )- monkeypatch.setattr(_state, "_registry", _registry(["api", "web"]))- monkeypatch.setattr(_state, "_cross_repo_enricher", enricher)-- footer = ov._build_workspace_footer()- assert footer["cross_repo"] == {"co_changes": 1}- assert "contract_links" not in footer+ assert "repo='all'" in footer["hint"]+ # The links themselves are what repo="all" serves.+ assert "cross_repo" not in footer and "contract_links" not in footer# ---------------------------------------------------------------------------@@ -333,3 +319,14 @@ async def test_key_decisions_survive_corrupt_affected_files(session, populated_dassert [d["id"] for d in block["top_active"]] == ["dec1"]assert block["top_active"][0]["affected_files"] == []assert block["recent_reversals"] == []+++def test_production_average_needs_tests_in_the_reading():+ from repowise.server.mcp_server.tool_overview.health import _production_average++ prod = SimpleNamespace(file_path="a.py", score=6.0, nloc=10, is_test=False)+ test = SimpleNamespace(file_path="t.py", score=10.0, nloc=10, is_test=True)++ assert _production_average([prod, test]) == 6.0+ # With no tests it would only repeat the headline.+ assert _production_average([prod]) is Nonediff --git a/tests/unit/server/test_chat_views.py b/tests/unit/server/test_chat_views.pyindex 60668dd3b..58958db6c 100644--- a/tests/unit/server/test_chat_views.py+++ b/tests/unit/server/test_chat_views.py@@ -142,8 +142,9 @@ def test_health_bands_plots_each_band_file_count():assert part["as_of"] == "4c1e31fe3a9b"-def test_health_bands_reads_the_overview_distribution_too():- overview = {"code_health": {"distribution": HEALTH["distribution"]}}+def test_health_bands_reads_the_overview_band_counts_too():+ bands = HEALTH["distribution"]["bands"]+ overview = {"code_health": {"files_by_band": {b: v["files"] for b, v in bands.items()}}}part = _build(overview, "overview", "get_overview", "health.bands")assert sum(_series(part, "files")) == 5034assert part["as_of"] is Nonediff --git a/tests/unit/server/test_mcp_workspace.py b/tests/unit/server/test_mcp_workspace.pyindex 51435eb02..27b0ed104 100644--- a/tests/unit/server/test_mcp_workspace.py+++ b/tests/unit/server/test_mcp_workspace.py@@ -912,14 +912,13 @@ async def workspace_mcp_with_enricher(workspace_mcp, enricher_data):@pytest.mark.asyncio-async def test_overview_footer_includes_cross_repo(workspace_mcp_with_enricher):+async def test_overview_footer_points_at_the_cross_repo_view(workspace_mcp_with_enricher):from repowise.server.mcp_server import get_overviewresult = await get_overview()- assert "workspace" in resultws = result["workspace"]- assert "cross_repo" in ws- assert ws["cross_repo"]["co_change_count"] == 1+ assert "cross_repo" not in ws+ assert "repo='all'" in ws["hint"]@pytest.mark.asyncio