Skip to content

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

test(server): pin the degraded and edge paths of get_context enrichment, get_overview, get_change_risk and get_symbol (#2556)

Raghav Chamadiyac7b8dfe9caf4
diff --git a/tests/unit/server/mcp/test_context_enrichment.py b/tests/unit/server/mcp/test_context_enrichment.py
new file mode 100644
index 000000000..6808c3299
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_enrichment.py
@@ -0,0 +1,568 @@
+"""Edge paths of the ``get_context`` include-block resolvers in ``tool_context/enrichment.py``.
+
+Called directly so a regression names the helper; ``test_context*.py`` covers
+the end-to-end shapes.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.persistence.models import (
+ CoverageFile,
+ GraphEdge,
+ GraphNode,
+ HealthFileMetric,
+ Repository,
+)
+from repowise.server.mcp_server import _basis
+from repowise.server.mcp_server.tool_context import enrichment
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+
[email protected](autouse=True)
+def _fresh_basis_cache():
+ # Every seed shares one repo id and updated_at, so a basis grouping cached
+ # by an earlier test would otherwise answer for this one's graph.
+ _basis.reset_cache()
+ yield
+ _basis.reset_cache()
+
+
+async def _repo(session, repo_id: str) -> Repository:
+ return await session.get(Repository, repo_id)
+
+
+def _symbol(repo_id: str, node_id: str, *, name: str | None = None) -> GraphNode:
+ file_path, _, qual = node_id.partition("::")
+ return GraphNode(
+ id=f"t_{node_id}",
+ repository_id=repo_id,
+ node_id=node_id,
+ node_type="symbol",
+ name=name or qual.split(".")[-1],
+ file_path=file_path,
+ kind="function",
+ language="python",
+ start_line=3,
+ end_line=9,
+ created_at=_NOW,
+ )
+
+
+def _call(repo_id: str, source: str, target: str, **extra) -> GraphEdge:
+ return GraphEdge(
+ id=f"t_{source}->{target}",
+ repository_id=repo_id,
+ source_node_id=source,
+ target_node_id=target,
+ edge_type="calls",
+ confidence=extra.pop("confidence", 0.9),
+ created_at=_NOW,
+ **extra,
+ )
+
+
+# ---------------------------------------------------------------------------
+# _unique_by_symbol
+# ---------------------------------------------------------------------------
+
+
+def test_unique_by_symbol_keeps_the_first_entry_per_symbol_in_order():
+ """Callers sort by confidence first, so "first" must mean "highest confidence"."""
+ rows = [
+ {"symbol_id": "a", "confidence": 0.9},
+ {"symbol_id": "b", "confidence": 0.8},
+ {"symbol_id": "a", "confidence": 0.7},
+ ]
+ assert enrichment._unique_by_symbol(rows) == [
+ {"symbol_id": "a", "confidence": 0.9},
+ {"symbol_id": "b", "confidence": 0.8},
+ ]
+
+
+# ---------------------------------------------------------------------------
+# _resolve_call_graph
+# ---------------------------------------------------------------------------
+
+
+async def test_call_graph_unknown_target_answers_empty_lists_without_a_note(
+ session, populated_db
+):
+ """A target with no graph node gets empty lists, not a misleading type note."""
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await _repo(session, populated_db),
+ "nowhere.py",
+ "file",
+ out,
+ want_callers=True,
+ want_callees=True,
+ )
+ assert out == {"callers": [], "callees": []}
+
+
+async def test_call_graph_file_target_asked_only_for_callees_explains_the_symbol_rule(
+ session, populated_db
+):
+ """Callees have no file-level rollup, so the empty list must say why it is empty."""
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await _repo(session, populated_db),
+ "src/auth/service.py",
+ "file",
+ out,
+ want_callees=True,
+ )
+ assert out["callees"] == []
+ assert "callers" not in out
+ assert "require a symbol target" in out["_call_graph_note"]
+ assert "is a file" in out["_call_graph_note"]
+
+
+async def test_call_graph_file_target_with_both_directions_rolls_up_callers_and_bases_callees(
+ session, populated_db
+):
+ """A file nothing imports: both lists empty, and each empty list carries its basis."""
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await _repo(session, populated_db),
+ "tests/test_service.py",
+ "file",
+ out,
+ want_callers=True,
+ want_callees=True,
+ )
+ assert out["callers"] == []
+ assert out["callees"] == []
+ assert "callers_basis" in out
+ assert "callees_basis" in out
+ assert out["_call_graph_note"].startswith("File-level rollup")
+
+
+async def test_call_graph_fuzzy_fallback_prefers_the_node_in_the_hinted_file(
+ session, populated_db
+):
+ """``b.py::helper`` misses the exact id ``b.py::Cls.helper`` and falls back by name.
+
+ Two symbols share the bare name; the one in the file the caller named must
+ win, or the agent is handed a different function's callers.
+ """
+ rid = populated_db
+ session.add_all(
+ [
+ _symbol(rid, "a.py::Cls.helper"),
+ _symbol(rid, "b.py::Cls.helper"),
+ _symbol(rid, "c.py::main"),
+ _symbol(rid, "d.py::other"),
+ _call(rid, "c.py::main", "b.py::Cls.helper"),
+ _call(rid, "d.py::other", "a.py::Cls.helper"),
+ ]
+ )
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await _repo(session, rid),
+ "b.py::helper",
+ "symbol",
+ out,
+ want_callers=True,
+ )
+ assert [c["symbol_id"] for c in out["callers"]] == ["c.py::main"]
+
+
+async def test_call_graph_serves_callees_and_places_a_recursive_call_on_both_sides(
+ session, populated_db
+):
+ """A self-call is one edge that matches both directions.
+
+ It must appear once under callers and once under callees; the resolution
+ origin rides along as ``via`` when the index stamped one.
+ """
+ rid = populated_db
+ session.add_all(
+ [
+ _symbol(rid, "m.py::walk"),
+ _symbol(rid, "m.py::visit"),
+ _call(rid, "m.py::walk", "m.py::walk"),
+ _call(rid, "m.py::walk", "m.py::visit", resolution_origin="import_resolved"),
+ ]
+ )
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await _repo(session, rid),
+ "m.py::walk",
+ "symbol",
+ out,
+ want_callers=True,
+ want_callees=True,
+ )
+ assert [c["symbol_id"] for c in out["callers"]] == ["m.py::walk"]
+ callees = {c["symbol_id"]: c for c in out["callees"]}
+ assert set(callees) == {"m.py::walk", "m.py::visit"}
+ assert callees["m.py::visit"]["via"] == "import_resolved"
+ assert callees["m.py::visit"]["edge_type"] == "calls"
+ assert callees["m.py::visit"]["line"] == 3
+ # Populated lists are their own evidence and earn no basis.
+ assert "callers_basis" not in out
+ assert "callees_basis" not in out
+
+
+# ---------------------------------------------------------------------------
+# _resolve_metrics
+# ---------------------------------------------------------------------------
+
+
+async def test_metrics_for_an_unknown_target_is_null(session, populated_db):
+ out: dict = {}
+ await enrichment._resolve_metrics(
+ session, await _repo(session, populated_db), "nowhere.py", out
+ )
+ assert out == {"metrics": None}
+
+
+async def test_metrics_report_measured_betweenness_with_its_percentile(session, populated_db):
+ """Once centrality has run, betweenness is a number with a peer percentile.
+
+ models.py ranks above two of the four seeded file nodes, so both percentiles are 50.
+ """
+ node = (
+ await session.execute(select(GraphNode).where(GraphNode.node_id == "src/db/models.py"))
+ ).scalar_one()
+ node.betweenness_commit = "abc1234"
+ node.community_meta_json = '{"label": "Persistence"}'
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_metrics(
+ session, await _repo(session, populated_db), "src/db/models.py", out
+ )
+ assert out["metrics"] == {
+ "pagerank": 0.6,
+ "pagerank_percentile": 50,
+ "in_degree": 1,
+ "out_degree": 0,
+ "community_id": 2,
+ "community_label": "Persistence",
+ "betweenness": 0.3,
+ "betweenness_percentile": 50,
+ }
+
+
+async def test_metrics_survive_unparseable_community_meta(session, populated_db):
+ """A corrupt meta blob costs the label only; the block still renders."""
+ node = (
+ await session.execute(select(GraphNode).where(GraphNode.node_id == "src/auth/service.py"))
+ ).scalar_one()
+ node.community_meta_json = "{not json"
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_metrics(
+ session, await _repo(session, populated_db), "src/auth/service.py", out
+ )
+ assert out["metrics"]["community_label"] is None
+ assert out["metrics"]["betweenness"] is None
+ assert "not scored yet" in out["metrics"]["betweenness_note"]
+
+
+# ---------------------------------------------------------------------------
+# _resolve_community
+# ---------------------------------------------------------------------------
+
+
+async def test_community_is_null_for_an_unknown_target(session, populated_db):
+ out: dict = {}
+ await enrichment._resolve_community(
+ session, await _repo(session, populated_db), "nowhere.py", out
+ )
+ assert out == {"community": None}
+
+
+async def test_community_names_members_by_pagerank_and_neighbours_by_crossing_edges(
+ session, populated_db
+):
+ """service.py sits in community 1 and imports models.py in community 2.
+
+ Members come back in PageRank order; the neighbour's label falls back to
+ ``cluster_<id>`` when its own meta blob does not parse.
+ """
+ rows = {
+ n.node_id: n
+ for n in (await session.execute(select(GraphNode))).scalars().all()
+ }
+ rows["src/auth/service.py"].community_meta_json = '{"label": "Auth", "cohesion": 0.4567}'
+ rows["src/db/models.py"].community_meta_json = "{not json"
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_community(
+ session, await _repo(session, populated_db), "src/auth/service.py", out
+ )
+ assert out["community"] == {
+ "id": 1,
+ "label": "Auth",
+ "cohesion": 0.457,
+ "top_members": [
+ "src/auth/service.py",
+ "src/auth/middleware.py",
+ "tests/test_service.py",
+ ],
+ "neighbors": [{"id": 2, "label": "cluster_2", "cross_edges": 1}],
+ }
+
+
+async def test_community_label_falls_back_to_cluster_id_when_unparseable(session, populated_db):
+ node = (
+ await session.execute(select(GraphNode).where(GraphNode.node_id == "src/db/models.py"))
+ ).scalar_one()
+ node.community_meta_json = "{not json"
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_community(
+ session, await _repo(session, populated_db), "src/db/models.py", out
+ )
+ assert out["community"]["label"] == "cluster_2"
+ assert out["community"]["cohesion"] == 0.0
+ # models.py only receives an edge; crossings are counted from this side.
+ assert out["community"]["neighbors"] == []
+
+
+# ---------------------------------------------------------------------------
+# _resolve_health
+# ---------------------------------------------------------------------------
+
+
+async def test_health_is_null_for_a_non_file_target_without_a_path(session, health_data):
+ out: dict = {}
+ await enrichment._resolve_health(
+ session, await _repo(session, health_data), "src/auth", "module", out
+ )
+ assert out == {"health": None}
+
+
+async def test_health_is_null_for_a_file_with_no_metric_row(session, health_data):
+ out: dict = {}
+ await enrichment._resolve_health(
+ session, await _repo(session, health_data), "src/auth/middleware.py", "file", out
+ )
+ assert out == {"health": None}
+
+
+async def test_health_for_a_symbol_target_reads_its_file_with_stored_coverage_and_signals(
+ session, health_data
+):
+ """``file::Symbol`` resolves to the file's metric row, with stored coverage,
+ the top two findings by impact, and process signals.
+ """
+ rid = health_data
+ session.add(
+ CoverageFile(
+ repository_id=rid,
+ file_path="src/auth/service.py",
+ source_format="lcov",
+ line_coverage_pct=61.5,
+ branch_coverage_pct=40.0,
+ total_coverable_lines=200,
+ )
+ )
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_health(
+ session,
+ await _repo(session, rid),
+ "src/auth/service.py::AuthService",
+ "symbol",
+ out,
+ )
+ health = out["health"]
+ assert health["score"] == 4.5
+ assert health["max_ccn"] == 15
+ assert health["has_test_file"] is False
+ assert health["module"] == "auth"
+ assert health["coverage"] == {
+ "source_format": "lcov",
+ "line_coverage_pct": 61.5,
+ "branch_coverage_pct": 40.0,
+ "total_coverable_lines": 200,
+ }
+ assert len(health["top_biomarkers"]) == 2
+ top = health["top_biomarkers"][0]
+ assert top["biomarker_type"] == "complex_method"
+ assert top["function_name"] == "authenticate"
+ assert top["impact"] == 1.2
+ assert isinstance(top["suggestion"], str) and top["suggestion"]
+ signals = health["signals"]
+ assert signals["commit_count_90d"] == 8
+ assert signals["primary_owner_name"] == "Alice"
+ # middleware.py and the test file import service.py; it imports models.py.
+ assert signals["in_degree"] == 2
+ assert signals["out_degree"] == 1
+
+
+async def test_health_falls_back_to_metric_coverage_and_omits_null_function_name(
+ session, health_data
+):
+ """No ingested coverage row: the metric's own percentages stand in.
+
+ A file-level finding carries no ``function_name`` key at all rather than a
+ null, matching get_risk's cards.
+ """
+ from repowise.core.persistence.crud import save_health_findings
+
+ rid = health_data
+ metric = (
+ await session.execute(
+ select(HealthFileMetric).where(HealthFileMetric.file_path == "src/db/models.py")
+ )
+ ).scalar_one()
+ metric.line_coverage_pct = 88.0
+ await save_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/db/models.py",
+ "biomarker_type": "low_cohesion",
+ "severity": "medium",
+ "function_name": None,
+ "line_start": None,
+ "line_end": None,
+ "details": {},
+ "health_impact": 0.5,
+ "reason": "User has low cohesion",
+ "dimension": "maintainability",
+ }
+ ],
+ )
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_health(
+ session, await _repo(session, rid), "src/db/models.py", "file", out
+ )
+ health = out["health"]
+ assert health["coverage"] == {"line_coverage_pct": 88.0, "branch_coverage_pct": None}
+ assert [b["biomarker_type"] for b in health["top_biomarkers"]] == ["low_cohesion"]
+ assert "function_name" not in health["top_biomarkers"][0]
+
+
+async def test_health_omits_signals_for_a_file_with_no_history_and_no_graph_node(
+ session, health_data
+):
+ """No git row and no graph node means no signal is known; the key is absent, not empty."""
+ from repowise.core.persistence.crud import save_health_metrics
+
+ rid = health_data
+ await save_health_metrics(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/brand_new.py",
+ "score": 9.0,
+ "max_ccn": 1,
+ "max_nesting": 1,
+ "nloc": 5,
+ "has_test_file": False,
+ "module": "src",
+ }
+ ],
+ )
+ await session.flush()
+
+ out: dict = {}
+ await enrichment._resolve_health(
+ session, await _repo(session, rid), "src/brand_new.py", "file", out
+ )
+ health = out["health"]
+ assert health["top_biomarkers"] == []
+ assert "coverage" not in health
+ assert "signals" not in health
+
+
+# ---------------------------------------------------------------------------
+# attach_doc_references / _resolve_skeleton
+# ---------------------------------------------------------------------------
+
+
+async def test_doc_references_for_a_module_target_are_null_and_the_marker_is_popped(
+ session, populated_db
+):
+ """A directory cannot be named by a reference row, so its block is null.
+
+ The private path marker must never reach the response.
+ """
+ cards = {"src/auth": {"title": "Auth", enrichment._DOC_DRIFT_PATH: None}}
+ await enrichment.attach_doc_references(session, await _repo(session, populated_db), cards)
+ assert cards == {"src/auth": {"title": "Auth", "doc_drift": None}}
+
+
+async def test_doc_references_do_nothing_when_no_card_asked(session, populated_db):
+ cards = {"src/auth/service.py": {"title": "Auth Service"}}
+ await enrichment.attach_doc_references(session, await _repo(session, populated_db), cards)
+ assert cards == {"src/auth/service.py": {"title": "Auth Service"}}
+
+
+async def test_skeleton_without_a_repo_path_is_an_error_not_a_crash(session, populated_db):
+ out: dict = {}
+ await enrichment._resolve_skeleton(
+ session, await _repo(session, populated_db), "src/auth/service.py", "file", out
+ )
+ assert out == {"skeleton": {"error": "MCP server has no repo path configured."}}
+
+
+async def test_skeleton_of_a_file_with_no_symbol_bounds_is_raw_with_a_note(
+ session, populated_db, tmp_path
+):
+ """No indexed symbols for the file: the source is served as-is and says so."""
+ (tmp_path / "notes.py").write_text("X = 1\nY = 2\n", encoding="utf-8")
+
+ out: dict = {}
+ await enrichment._resolve_skeleton(
+ session,
+ await _repo(session, populated_db),
+ "notes.py",
+ "file",
+ out,
+ repo_root=tmp_path,
+ )
+ skeleton = out["skeleton"]
+ assert skeleton["mode"] == "raw"
+ assert skeleton["verified"] is True
+ assert "X = 1" in skeleton["text"]
+ assert skeleton["note"].startswith("No usable symbol bounds")
diff --git a/tests/unit/server/mcp/test_symbol_degraded_paths.py b/tests/unit/server/mcp/test_symbol_degraded_paths.py
new file mode 100644
index 000000000..7bc7cd4bc
--- /dev/null
+++ b/tests/unit/server/mcp/test_symbol_degraded_paths.py
@@ -0,0 +1,284 @@
+"""``get_symbol`` edge paths: corrupt or empty omission refs, excluded or
+missing range reads, workspace references, vanished ambiguous candidates,
+clamped ``context_lines`` and the budget-cut ambiguity note.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.persistence.models import WikiSymbol
+from repowise.server.mcp_server import tool_symbol
+
+# ---------------------------------------------------------------------------
+# _correct_ambiguity_note
+# ---------------------------------------------------------------------------
+
+
+def _ambiguous(**extra):
+ return {"ambiguous": True, "match_count": 4, "note": "All candidate bodies are included", **extra}
+
+
+def test_ambiguity_note_is_rewritten_once_the_budget_cut_candidates():
+ """The shape promises no silent pick; a cut that leaves that note standing breaks it."""
+ result = _ambiguous(candidates_emitted=2)
+ tool_symbol._correct_ambiguity_note(result, None)
+ assert result["note"].startswith("4 symbols match this id")
+ assert "2 candidate bodies fit this response" in result["note"]
+ assert "All candidate bodies are included" not in result["note"]
+
+
+ "result",
+ [
+ {"note": "untouched", "candidates_emitted": 0, "match_count": 3},
+ _ambiguous(),
+ _ambiguous(candidates_emitted=4),
+ ],
+ ids=["not-ambiguous", "nothing-shed", "every-candidate-kept"],
+)
+def test_ambiguity_note_stands_when_nothing_was_cut(result):
+ before = result["note"]
+ tool_symbol._correct_ambiguity_note(result, None)
+ assert result["note"] == before
+
+
+# ---------------------------------------------------------------------------
+# Omission refs
+# ---------------------------------------------------------------------------
+
+
+def omission_stores(tmp_path, monkeypatch):
+ """Repo store under ``tmp_path``, "home" store under ``tmp_path/home``.
+
+ ``_resolve_omission_ref`` also consults the user-level store, so home is
+ redirected too; otherwise the test would read the developer's real one.
+ """
+ from repowise.core.distill import store as store_module
+
+ home = tmp_path / "home"
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.setattr(
+ store_module, "default_store_path", lambda start=None: Path(start) / "omit" / "o.db"
+ )
+ return {"repo": tmp_path / "omit" / "o.db", "home": home / "omit" / "o.db"}
+
+
+def _put(db_path: Path, content: str) -> str:
+ from repowise.core.distill.store import OmissionStore
+
+ store = OmissionStore(db_path)
+ try:
+ return store.put(content, source="test", original_tokens=40, kept_tokens=4)
+ finally:
+ store.close()
+
+
+async def test_omission_query_that_matches_nothing_says_how_to_get_everything(
+ setup_mcp, omission_stores
+):
+ from repowise.server.mcp_server import get_symbol
+
+ ref = _put(omission_stores["repo"], "alpha\nbeta\n")
+ result = await get_symbol(f"repowise#{ref}", query="zeta")
+ assert result["kind"] == "omission"
+ assert result["query"] == "zeta"
+ assert not result["content"]
+ assert result["note"].startswith("No lines matched the query")
+ assert "created_at" in result
+
+
+async def test_a_corrupt_repo_store_falls_through_to_the_home_store(setup_mcp, omission_stores):
+ """Recovery must never make get_symbol fail; an unreadable store is just a miss."""
+ from repowise.server.mcp_server import get_symbol
+
+ ref = _put(omission_stores["home"], "served from home\n")
+ omission_stores["repo"].parent.mkdir(parents=True, exist_ok=True)
+ omission_stores["repo"].write_bytes(b"this is not a sqlite database" * 64)
+
+ result = await get_symbol(f"repowise#{ref}")
+ assert "error" not in result
+ assert result["content"] == "served from home\n"
+
+
+# ---------------------------------------------------------------------------
+# Range reads
+# ---------------------------------------------------------------------------
+
+
+async def test_range_read_on_a_missing_file_is_a_named_error(setup_mcp):
+ from repowise.server.mcp_server import get_symbol
+
+ result = await get_symbol("pkg/ghost.py:1-3")
+ assert result["error"] == "File could not be read: 'pkg/ghost.py'"
+ assert result["symbol_id"] == "pkg/ghost.py:1-3"
+
+
+async def test_range_read_refuses_an_excluded_path(setup_mcp, tmp_path, monkeypatch):
+ """An excluded file is not served even when it exists on disk."""
+ from repowise.server.mcp_server import get_symbol
+
+ (tmp_path / "vendor").mkdir()
+ (tmp_path / "vendor" / "lib.py").write_text("x = 1\n", encoding="utf-8")
+ monkeypatch.setattr(
+ tool_symbol, "is_excluded", lambda path, _spec: str(path).startswith("vendor/")
+ )
+ result = await get_symbol("vendor/lib.py:1-1")
+ assert result["error"] == "'vendor/lib.py' is excluded from indexing."
+ assert "source" not in result
+
+
+# ---------------------------------------------------------------------------
+# Argument handling
+# ---------------------------------------------------------------------------
+
+
+async def test_repo_all_is_refused():
+ from repowise.server.mcp_server import get_symbol
+
+ result = await get_symbol("a.py::f", repo="all")
+ assert "get_symbol" in result["error"]
+
+
+async def test_a_reference_carries_its_repository_in_workspace_mode(monkeypatch):
+ """A structured reference is accepted whole: its id and its repository together."""
+ seen: dict = {}
+
+ async def _context(repo):
+ seen["repo"] = repo
+ raise LookupError("stop after resolution")
+
+ monkeypatch.setattr(tool_symbol, "_is_workspace_mode", lambda: True)
+ monkeypatch.setattr(tool_symbol, "_resolve_repo_context", _context)
+ with pytest.raises(LookupError):
+ await tool_symbol.get_symbol(reference={"id": "a.py:1-2", "repository": "web"})
+ assert seen["repo"] == "web"
+
+
+async def test_an_explicit_repo_wins_over_the_references_repository(monkeypatch):
+ seen: dict = {}
+
+ async def _context(repo):
+ seen["repo"] = repo
+ raise LookupError("stop after resolution")
+
+ monkeypatch.setattr(tool_symbol, "_is_workspace_mode", lambda: True)
+ monkeypatch.setattr(tool_symbol, "_resolve_repo_context", _context)
+ with pytest.raises(LookupError):
+ await tool_symbol.get_symbol(
+ reference={"id": "a.py:1-2", "repository": "web"}, repo="api"
+ )
+ assert seen["repo"] == "api"
+
+
+async def test_runaway_context_lines_are_clamped_to_fifty(setup_mcp, tmp_path):
+ """``login`` is indexed at 20-40; 500 lines of context is served as 50."""
+ from repowise.server.mcp_server import get_symbol
+
+ lines = [f"# line {n}" for n in range(1, 201)]
+ lines[19] = " async def login(self, username: str, password: str) -> Token:"
+ (tmp_path / "src" / "auth").mkdir(parents=True)
+ (tmp_path / "src" / "auth" / "service.py").write_text("\n".join(lines) + "\n", "utf-8")
+
+ result = await get_symbol("src/auth/service.py::login", context_lines=500)
+ assert result["start_line"] == 1
+ assert result["end_line"] == 90
+
+
+# ---------------------------------------------------------------------------
+# Helpers behind the dead-end recovery
+# ---------------------------------------------------------------------------
+
+
+def test_live_grep_caps_matches_and_handles_unreadable_or_nameless_input(tmp_path):
+ (tmp_path / "consts.py").write_text(
+ "\n".join(f"LIMIT_{i} = LIMIT" for i in range(20)) + "\n", encoding="utf-8"
+ )
+ matches = tool_symbol._live_grep_fallback(tmp_path, "consts.py", "LIMIT")
+ assert len(matches) == tool_symbol._MAX_FALLBACK_MATCHES
+ assert [m["line"] for m in matches] == list(range(1, 9))
+ assert tool_symbol._live_grep_fallback(tmp_path, "missing.py", "LIMIT") == []
+ assert tool_symbol._live_grep_fallback(tmp_path, "consts.py", "") == []
+
+
+async def test_suggestions_skip_excluded_paths_and_stop_at_five(session, repo_id, monkeypatch):
+ for i in range(8):
+ session.add(
+ WikiSymbol(
+ id=f"dup{i}",
+ repository_id=repo_id,
+ file_path=f"{'vendor' if i < 2 else 'src'}/m{i}.py",
+ symbol_id=f"{'vendor' if i < 2 else 'src'}/m{i}.py::run",
+ name="run",
+ qualified_name="run",
+ kind="function",
+ signature="def run()",
+ start_line=1,
+ end_line=2,
+ language="python",
+ )
+ )
+ await session.flush()
+ monkeypatch.setattr(
+ tool_symbol, "is_excluded", lambda path, _spec: str(path).startswith("vendor/")
+ )
+
+ out = await tool_symbol._symbol_suggestions(session, repo_id, "wrong/path.py::run", None)
+ assert len(out) == 5
+ assert all(sid.startswith("src/") for sid in out)
+ assert await tool_symbol._symbol_suggestions(session, repo_id, "wrong/path.py::", None) == []
+
+
+# ---------------------------------------------------------------------------
+# Ambiguous rendering
+# ---------------------------------------------------------------------------
+
+
+async def test_ambiguous_candidate_in_a_vanished_file_is_listed_not_dropped(tmp_path):
+ """A candidate whose file is gone is still named, with why it has no body."""
+ (tmp_path / "b.py").write_text("def run():\n return 1\n", encoding="utf-8")
+
+ def _row(path: str) -> WikiSymbol:
+ return WikiSymbol(
+ file_path=path,
+ symbol_id=f"{path}::run",
+ name="run",
+ qualified_name="run",
+ kind="function",
+ signature="def run():",
+ start_line=1,
+ end_line=2,
+ )
+
+ ctx = SimpleNamespace(path=str(tmp_path), alias="", session_factory=None)
+ result = await tool_symbol._render_ambiguous(
+ [_row("a.py"), _row("b.py")], "run", ctx, None, 0.0, 0
+ )
+ assert result["match_count"] == 2
+ assert [c["file"] for c in result["candidates"]] == ["b.py"]
+ assert result["not_rendered"] == [
+ {
+ "symbol_id": "a.py::run",
+ "file": "a.py",
+ "name": "run",
+ "kind": "function",
+ "qualified_name": "run",
+ "signature": "def run():",
+ "note": "source file could not be read",
+ }
+ ]
+ assert "not_rendered" in result["note"]
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
new file mode 100644
index 000000000..ca3d4feec
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -0,0 +1,337 @@
+"""How each ``get_change_risk`` enrichment degrades.
+
+A failed git call, health comparison, index read or changed-lines read must
+become a named state, never a crash or an empty list that reads as all-clear.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy.exc import OperationalError, SQLAlchemyError
+
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server import tool_change_risk as tool
+from repowise.server.mcp_server._budget import OmissionCollector
+
+# ---------------------------------------------------------------------------
+# get_change_risk: git failures while scoring
+# ---------------------------------------------------------------------------
+
+
+async def _score_raising(monkeypatch, exc: BaseException, revspec=None) -> dict:
+ async def _context(_repo):
+ return SimpleNamespace(path="/repo")
+
+ def _raise(*_a, **_k):
+ raise exc
+
+ monkeypatch.setattr(tool, "_resolve_repo_context", _context)
+ monkeypatch.setattr(tool, "score_live_change", _raise)
+ return await tool.get_change_risk(revspec)
+
+
+async def test_git_failure_reports_the_revspec_and_git_stderr(monkeypatch):
+ exc = subprocess.CalledProcessError(128, ["git"], stderr="fatal: bad object deadbeef\n")
+ result = await _score_raising(monkeypatch, exc, "deadbeef")
+ assert result == {"error": "Could not read change 'deadbeef': fatal: bad object deadbeef"}
+
+
+async def test_git_failure_without_stderr_falls_back_to_the_exception_text(monkeypatch):
+ exc = subprocess.CalledProcessError(1, ["git", "diff"], stderr="")
+ result = await _score_raising(monkeypatch, exc)
+ assert result["error"].startswith("Could not read change 'HEAD': ")
+ assert "returned non-zero exit status 1" in result["error"]
+
+
+async def test_git_timeout_is_an_error_naming_the_change(monkeypatch):
+ result = await _score_raising(monkeypatch, subprocess.TimeoutExpired(["git"], 30), "a..b")
+ assert result == {"error": "git timed out reading change 'a..b'."}
+
+
+# ---------------------------------------------------------------------------
+# Health comparison and its stored-finding references
+# ---------------------------------------------------------------------------
+
+
+def test_a_failed_health_comparison_degrades_to_unavailable(monkeypatch):
+ """The comparison runs in a thread beside the enrichments; it must never raise."""
+
+ def _broken(_path):
+ raise RuntimeError("worktree vanished")
+
+ monkeypatch.setattr(tool, "_delta_service", _broken)
+ delta = tool._compare_health("/repo", "HEAD", (), ())
+ assert delta.status == "unavailable"
+ assert delta.explanation == "Health comparison failed: worktree vanished"
+ assert delta.comparison_basis == "not_compared"
+ assert delta.findings == []
+
+
+def _finding(path, biomarker, symbol, start, end):
+ return SimpleNamespace(
+ path=path,
+ biomarker_type=biomarker,
+ symbol=symbol,
+ line_start=start,
+ line_end=end,
+ health_reference=None,
+ )
+
+
+async def test_only_an_exact_twin_earns_a_stored_finding_reference(factory, health_data):
+ """Same file, marker, symbol and span, or no pointer at all.
+
+ A looser match would hand the agent a ``get_health`` id for a different
+ finding. The seed stores ``complex_method`` on ``authenticate`` at 10-80.
+ """
+ exact = _finding("src/auth/service.py", "complex_method", "authenticate", 10, 80)
+ shifted = _finding("src/auth/service.py", "complex_method", "authenticate", 11, 80)
+ other_file = _finding("src/db/models.py", "complex_method", "authenticate", 10, 80)
+ ctx = SimpleNamespace(session_factory=factory, alias="")
+ await tool._attach_health_references(
+ ctx, SimpleNamespace(findings=[exact, shifted, other_file])
+ )
+
+ assert exact.health_reference["tool"] == "get_health"
+ assert exact.health_reference["arguments"]["finding_id"]
+ assert shifted.health_reference is None
+ assert other_file.health_reference is None
+
+
+async def test_health_references_skip_the_index_when_there_is_nothing_to_match():
+ finding = _finding("a.py", "complex_method", "f", 1, 2)
+ await tool._attach_health_references(
+ SimpleNamespace(session_factory=None), SimpleNamespace(findings=[finding])
+ )
+ # object() as the factory would raise if it were ever opened.
+ await tool._attach_health_references(
+ SimpleNamespace(session_factory=object()), SimpleNamespace(findings=[])
+ )
+ assert finding.health_reference is None
+
+
+async def test_repository_is_none_without_a_factory_or_a_repository_row(factory):
+ assert await tool._repository(SimpleNamespace()) is None
+ assert await tool._repository(SimpleNamespace(session_factory=factory)) is None
+
+
+# ---------------------------------------------------------------------------
+# Changed lines
+# ---------------------------------------------------------------------------
+
+
+def test_filter_changed_applies_the_scores_suffixes_and_excludes():
+ changed = {"src/a.py": {1}, "src/b.ts": {2}, "docs/c.py": {3}}
+ assert tool._filter_changed(changed, (".py",), ("docs/",)) == {"src/a.py": {1}}
+ assert tool._filter_changed(changed, (), ()) == changed
+
+
+ ("exc", "summary"),
+ [
+ (ValueError("not a ref"), "Could not read changed lines: not a ref"),
+ (subprocess.SubprocessError(), "Could not read changed lines from git."),
+ (OSError("git missing"), "Could not read changed lines from git."),
+ ],
+)
+async def test_changed_lines_failure_is_unknown_not_empty(monkeypatch, exc, summary):
+ import repowise.core.analysis.changed_lines as changed_lines_mod
+
+ def _raise(*_a, **_k):
+ raise exc
+
+ monkeypatch.setattr(changed_lines_mod, "changed_lines", _raise)
+ assert await tool._changed_in_scope("/repo", None, (), ()) == ({}, ("unknown", summary))
+
+
+async def test_changed_lines_all_filtered_out_is_named(monkeypatch):
+ import repowise.core.analysis.changed_lines as changed_lines_mod
+
+ monkeypatch.setattr(
+ changed_lines_mod, "changed_lines", lambda *_a, **_k: ({"README.md": {1}}, "HEAD")
+ )
+ assert await tool._changed_in_scope("/repo", "HEAD", (".py",), ()) == (
+ {},
+ ("no_source_line_changes", "No changed source lines to map to tests."),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Index reads that fail
+# ---------------------------------------------------------------------------
+
+
+def _get_repo_raising(monkeypatch, exc: BaseException) -> None:
+ async def _raise(_session, *_a, **_k):
+ raise exc
+
+ monkeypatch.setattr(tool, "_get_repo", _raise)
+
+
+ "exc",
+ [
+ LookupError("no repo"),
+ OperationalError("SELECT", {}, Exception("no such table: fix_events")),
+ ],
+)
+async def test_prior_fixes_stay_silent_when_there_is_no_record_to_read(
+ monkeypatch, factory, exc
+):
+ _get_repo_raising(monkeypatch, exc)
+ ctx = SimpleNamespace(session_factory=factory)
+ assert await tool._prior_fixes_block(ctx, {"a.py": {1}}) is None
+
+
+ ("exc", "cls_name"),
+ [
+ (OperationalError("SELECT", {}, Exception("database is locked")), "OperationalError"),
+ (SQLAlchemyError("boom"), "SQLAlchemyError"),
+ ],
+)
+async def test_prior_fixes_render_a_failed_read_as_unavailable(
+ monkeypatch, factory, exc, cls_name
+):
+ _get_repo_raising(monkeypatch, exc)
+ block = await tool._prior_fixes_block(
+ SimpleNamespace(session_factory=factory), {"a.py": {1}}
+ )
+ assert block["status"] == "unavailable"
+ assert cls_name in block["reason"]
+ assert "not cleared" in block["summary"]
+
+
+async def test_impacted_tests_pass_a_changed_lines_error_through(factory, tmp_path):
+ block = await tool._impacted_tests_block(
+ SimpleNamespace(session_factory=factory),
+ {},
+ ("unknown", "Could not read changed lines from git."),
+ OmissionCollector("get_change_risk", repo_root=tmp_path),
+ )
+ assert block["status"] == "unknown"
+ assert block["summary"] == "Could not read changed lines from git."
+ assert block["tests_to_run"] == []
+ assert block["map_present"] is False
+
+
+ ("exc", "status"),
+ [(LookupError("no repo"), "no_index"), (SQLAlchemyError("boom"), "unknown")],
+)
+async def test_impacted_tests_degrade_on_an_unreadable_index(
+ monkeypatch, factory, tmp_path, exc, status
+):
+ _get_repo_raising(monkeypatch, exc)
+ block = await tool._impacted_tests_block(
+ SimpleNamespace(session_factory=factory),
+ {"a.py": {1}},
+ None,
+ OmissionCollector("get_change_risk", repo_root=tmp_path),
+ )
+ assert block["status"] == status
+ assert block["total"] == 0
+
+
+async def test_inferred_tests_treat_a_failed_graph_walk_as_no_reach(
+ monkeypatch, session, repo_id, tmp_path
+):
+ """A graph walk that throws falls back to "run the full suite", never an error."""
+ import repowise.core.analysis.test_reachability as reach
+
+ async def _raise(*_a, **_k):
+ raise RuntimeError("graph unreadable")
+
+ monkeypatch.setattr(reach, "tests_reaching", _raise)
+ block = await tool._inferred_impacted(
+ session, repo_id, ["a.py"], OmissionCollector("get_change_risk", repo_root=tmp_path)
+ )
+ assert block["status"] == "no_map"
+ assert "run the full suite" in block["summary"]
+
+
+async def test_independent_changes_are_silent_for_one_file_or_an_unreadable_index(
+ monkeypatch, factory, tmp_path
+):
+ collector = OmissionCollector("get_change_risk", repo_root=tmp_path)
+ ctx = SimpleNamespace(path=str(tmp_path), session_factory=factory)
+ assert await tool._independent_changes_block(ctx, {"a.py": {1}}, collector) is None
+
+ _get_repo_raising(monkeypatch, SQLAlchemyError("boom"))
+ # revspec None is not a range, so no git call is made for commit sets.
+ assert (
+ await tool._independent_changes_block(ctx, {"a.py": {1}, "b.py": {2}}, collector)
+ is None
+ )
+
+
+async def test_branch_scan_falls_back_to_git_only_when_the_index_will_not_open(
+ monkeypatch, factory
+):
+ """Branch overlap needs only git, so an index failure costs the ranking, not the block."""
+ scan = SimpleNamespace(overlap="git-only overlap")
+ monkeypatch.setattr(tool, "_scan_from_trunk", lambda _path, _files: scan)
+ _get_repo_raising(monkeypatch, LookupError("no repo"))
+ ctx = SimpleNamespace(path="/repo", session_factory=factory)
+ assert await tool._scan_overlap(ctx, ["a.py"]) == "git-only overlap"
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo block
+# ---------------------------------------------------------------------------
+
+
+def _enricher(**overrides):
+ base = {
+ "has_contract_data": True,
+ "has_breaking_changes": True,
+ "get_contract_links_as_provider": lambda _alias, _path: [],
+ "get_breaking_changes_for_repo": lambda _alias: [],
+ "get_breaking_changes": lambda: {},
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def test_cross_repo_ignores_breaking_changes_on_files_this_change_did_not_touch(monkeypatch):
+ change = {
+ "provider_file": "api/other.py",
+ "severity": "breaking",
+ "impacted_consumers": [{"repo": "web"}],
+ }
+ monkeypatch.setattr(tool, "_is_workspace_mode", lambda: True)
+ monkeypatch.setattr(
+ _state,
+ "_cross_repo_enricher",
+ _enricher(get_breaking_changes_for_repo=lambda _alias: [change]),
+ )
+ assert tool._cross_repo_block("api", ["api/orders.py"]) is None
+
+
+def test_cross_repo_block_never_raises(monkeypatch):
+ def _boom(_alias, _path):
+ raise RuntimeError("contracts.json unreadable")
+
+ monkeypatch.setattr(tool, "_is_workspace_mode", lambda: True)
+ monkeypatch.setattr(
+ _state, "_cross_repo_enricher", _enricher(get_contract_links_as_provider=_boom)
+ )
+ assert tool._cross_repo_block("api", ["api/orders.py"]) is None
diff --git a/tests/unit/server/mcp/test_tool_overview.py b/tests/unit/server/mcp/test_tool_overview.py
new file mode 100644
index 000000000..e1cd4d12d
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_overview.py
@@ -0,0 +1,311 @@
+"""``tool_overview`` helper branches the shared ``get_overview`` seed never reaches.
+
+Legacy titles, corrupt metadata, over ten communities, a workspace registry and
+a failing health read, each pinned against the helper that owns it.
+"""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server import tool_overview as ov
+from repowise.server.mcp_server._budget import OmissionCollector
+
+# ---------------------------------------------------------------------------
+# Titles and ordering
+# ---------------------------------------------------------------------------
+
+
+def test_title_falls_back_to_the_repo_name_without_an_overview_page():
+ assert ov._resolve_title(None, SimpleNamespace(name="acme")) == "acme"
+
+
+def test_legacy_placeholder_title_gets_the_real_repo_name():
+ page = SimpleNamespace(title="Repository Overview: repo")
+ assert ov._resolve_title(page, SimpleNamespace(name="acme")) == "Repository Overview: acme"
+
+
+def test_title_substitution_is_exact_match_not_prefix():
+ """A repo whose name starts with "repo" must not be rewritten into "repowisewise"."""
+ page = SimpleNamespace(title="Repository Overview: repowise")
+ assert (
+ ov._resolve_title(page, SimpleNamespace(name="repowise"))
+ == "Repository Overview: repowise"
+ )
+
+
+def test_non_numeric_section_sorts_as_placed_but_ahead_of_every_numbered_one():
+ """A malformed section string does not raise; it sorts with the placed pages."""
+ keys = sorted(["2", "x.y", None, "1.10", "1.9"], key=ov._section_sort_key)
+ assert keys == ["x.y", "1.9", "1.10", "2", None]
+
+
+def test_entry_points_beyond_fifteen_are_capped_and_recoverable(tmp_path):
+ collector = OmissionCollector("get_overview", repo_root=tmp_path)
+ ids = [f"src/entry_{i:02d}.py" for i in range(18)]
+ assert ov._capped_entry_points(ids, collector) == ids[:15]
+ ((label, body),) = collector._chunks
+ assert "3 dropped" in label
+ assert body.splitlines() == ids[15:]
+
+
+def test_entry_points_at_the_cap_record_no_omission(tmp_path):
+ collector = OmissionCollector("get_overview", repo_root=tmp_path)
+ ids = [f"e{i}" for i in range(15)]
+ assert ov._capped_entry_points(ids, collector) == ids
+ assert collector._chunks == []
+
+
+# ---------------------------------------------------------------------------
+# Tool surface guide
+# ---------------------------------------------------------------------------
+
+
+def _row(name, *, tier="core", recipes=(), default=True, eligible=True):
+ return {
+ "name": name,
+ "tier": tier,
+ "description": f"{name} tool",
+ "recipes": list(recipes),
+ "default_single_repo": default,
+ "eligible_single_repo": eligible,
+ "default_workspace": default,
+ "eligible_workspace": eligible,
+ }
+
+
+def test_tool_surface_drops_recipes_that_need_a_disabled_tool_and_lists_opt_ins():
+ """A recipe is only advertised when every tool it names is actually served."""
+ rows = [
+ _row(
+ "get_risk",
+ recipes=[
+ {"name": "solo", "call": "get_risk()", "requires": ["get_risk"]},
+ {"name": "combo", "call": "x", "requires": ["get_risk", "get_dead_code"]},
+ ],
+ ),
+ _row("get_dead_code", tier="specialist", default=False),
+ _row("get_why", recipes=[{"name": "solo", "call": "dup", "requires": ["get_why"]}]),
+ ]
+ guide = ov._tool_surface_guide(
+ is_workspace=False, rows=rows, enabled_names={"get_risk", "get_why"}
+ )
+ assert guide["mode"] == "single_repo"
+ assert guide["enabled"] == ["get_risk", "get_why"]
+ # "combo" needs get_dead_code; the second "solo" is a duplicate name.
+ assert guide["recipes"] == [{"name": "solo", "call": "get_risk()"}]
+ assert guide["opt_in"] == [
+ {"name": "get_dead_code", "description": "get_dead_code tool", "enabled": False}
+ ]
+ assert guide["counts"] == {
+ "enabled": 2,
+ "default": 2,
+ "eligible": 3,
+ "opt_in_available": 1,
+ "tiers": {"core": 2},
+ }
+
+
+def test_tool_surface_in_workspace_mode_reads_the_workspace_columns():
+ rows = [_row("get_overview")]
+ rows[0]["default_workspace"] = False
+ guide = ov._tool_surface_guide(is_workspace=True, rows=rows, enabled_names={"get_overview"})
+ assert guide["mode"] == "workspace"
+ assert guide["tools"][0]["default"] is False
+ assert guide["counts"]["default"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Knowledge map and communities
+# ---------------------------------------------------------------------------
+
+
+def _git(path, email, name=None, pct=0.5):
+ return SimpleNamespace(
+ file_path=path,
+ primary_owner_email=email,
+ primary_owner_name=name,
+ primary_owner_commit_pct=pct,
+ )
+
+
+def test_knowledge_map_is_empty_without_git_rows():
+ assert ov._build_knowledge_map([]) == {}
+
+
+def test_knowledge_map_names_top_three_owners_and_never_surfaces_an_email():
+ rows = [
+ _git("a.py", "[email protected]", "Alice"),
+ _git("b.py", "[email protected]", "Alice"),
+ _git("c.py", "[email protected]", "Alice"),
+ _git("f.py", "[email protected]", None),
+ _git("g.py", "[email protected]", "Dave"),
+ _git("h.py", "", "Nobody"),
+ ]
+ km = ov._build_knowledge_map(rows)
+ assert [o["name"] for o in km["top_owners"]] == ["Alice", "bot", "carol"]
+ assert km["top_owners"][0] == {"name": "Alice", "files_owned": 3, "percentage": 37.5}
+ assert "@" not in json.dumps(km)
+
+
+def _node(node_id, community_id, *, node_type="file", meta="{}"):
+ return SimpleNamespace(
+ node_id=node_id,
+ node_type=node_type,
+ community_id=community_id,
+ community_meta_json=meta,
+ )
+
+
+def test_community_label_keeps_a_specific_heuristic_label():
+ assert ov._community_display_label("Billing", [], 3, {"src"}) == "Billing"
+
+
+def test_generic_community_label_falls_back_to_dominant_directory_then_cluster_id():
+ generic = {"packages", "src", "lib", "core", "app", ""}
+ members = [_node("src/payments/a.py", 1), _node("src/payments/b.py", 1), _node("x.py", 1)]
+ assert ov._community_display_label("core", members, 1, generic) == "payments"
+ assert ov._community_display_label("", [_node("top.py", 7)], 7, generic) == "cluster_7"
+
+
+def test_community_summary_caps_at_ten_by_size_and_survives_bad_meta():
+ nodes = []
+ for cid in range(12):
+ # Community `cid` has cid + 1 members, so size order is 11, 10, ... 0.
+ for m in range(cid + 1):
+ nodes.append(_node(f"pkg{cid}/deep{cid}/f{m}.py", cid, meta="{not json"))
+ nodes.append(_node("pkg0/sym::Thing", 0, node_type="symbol"))
+
+ summary = ov._build_community_summary(nodes)
+ assert [c["id"] for c in summary] == list(range(11, 1, -1))
+ assert summary[0] == {"id": 11, "label": "deep11", "size": 12}
+
+
+# ---------------------------------------------------------------------------
+# Guided tour metadata
+# ---------------------------------------------------------------------------
+
+
+def test_guided_tour_with_unparseable_metadata_adds_nothing():
+ page = SimpleNamespace(metadata_json="{not json")
+ result: dict = {}
+ ov._build_guided_tour(page, result, {}, True)
+ assert result == {}
+
+
+def test_layer_order_is_attached_under_architecture_even_without_the_tour():
+ page = SimpleNamespace(
+ metadata_json=json.dumps(
+ {"layer_order": ["api", "core"], "guided_tour": [{"kind": "k", "reason": "r"}]}
+ )
+ )
+ result: dict = {"architecture": {"layers": []}}
+ ov._build_guided_tour(page, result, {}, False)
+ assert result == {"architecture": {"layers": [], "layer_order": ["api", "core"]}}
+
+
+# ---------------------------------------------------------------------------
+# Workspace footer
+# ---------------------------------------------------------------------------
+
+
+def _registry(aliases, default="api", root="/ws"):
+ return SimpleNamespace(
+ get_default_alias=lambda: default,
+ get_all_aliases=lambda: list(aliases),
+ workspace_root=root,
+ )
+
+
+def test_workspace_footer_is_absent_outside_a_workspace_and_for_a_lone_repo(monkeypatch):
+ monkeypatch.setattr(_state, "_registry", None)
+ assert ov._build_workspace_footer() is None
+ monkeypatch.setattr(_state, "_registry", _registry(["api"]))
+ assert ov._build_workspace_footer() is None
+
+
+def test_workspace_footer_names_siblings_and_carries_cross_repo_summaries(monkeypatch):
+ enricher = SimpleNamespace(
+ has_data=True,
+ has_contract_data=True,
+ get_cross_repo_summary=lambda: {"co_changes": 4},
+ get_contract_summary=lambda: {"links": 2},
+ )
+ monkeypatch.setattr(_state, "_registry", _registry(["api", "web", "worker"]))
+ monkeypatch.setattr(_state, "_cross_repo_enricher", enricher)
+
+ footer = ov._build_workspace_footer()
+ assert 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
+
+
+# ---------------------------------------------------------------------------
+# DB-backed blocks
+# ---------------------------------------------------------------------------
+
+
+async def test_code_health_read_failure_degrades_to_an_empty_block(
+ session, populated_db, monkeypatch
+):
+ """A broken health read must cost the block, never the whole overview call."""
+
+ async def boom(*_a, **_k):
+ raise RuntimeError("health tables unreadable")
+
+ monkeypatch.setattr(ov, "_get_health_metrics", boom)
+ repo = SimpleNamespace(id=populated_db)
+ assert await ov._build_code_health(session, repo) == {}
+
+
+async def test_key_decisions_ignore_active_records_nobody_accepted(session, populated_db):
+ """The status column alone does not make a decision "settled" on the front page."""
+ from repowise.core.persistence.models import DecisionRecord
+
+ record = await session.get(DecisionRecord, "dec1")
+ record.status = "active"
+ await session.flush()
+
+ assert await ov._build_key_decisions(session, SimpleNamespace(id=populated_db)) == {}
+
+
+async def test_key_decisions_survive_corrupt_affected_files(session, populated_db):
+ from repowise.core.persistence.crud.authority import accept_decision
+ from repowise.core.persistence.models import DecisionRecord
+
+ record = await session.get(DecisionRecord, "dec1")
+ await accept_decision(session, record, accepter="test", evidence=["seed:dec1"])
+ record.status = "active"
+ record.affected_files_json = "{not json"
+ await session.flush()
+
+ block = await ov._build_key_decisions(session, SimpleNamespace(id=populated_db))
+ assert [d["id"] for d in block["top_active"]] == ["dec1"]
+ assert block["top_active"][0]["affected_files"] == []
+ assert block["recent_reversals"] == []