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.

37.2 KB
Raw Blame
"""Tests for workspace-aware MCP tools.

Uses two in-memory SQLite databases (two repos) to test multi-repo routing,
``repo="all"`` federated queries, and workspace footer in get_overview.
"""

from __future__ import annotations

import asyncio
import json
import subprocess
from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace

import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool

from repowise.core.persistence.database import init_db
from repowise.core.persistence.models import (
    DeadCodeFinding,
    DecisionRecord,
    GitMetadata,
    GraphNode,
    HealthFinding,
    Page,
    Repository,
    WikiSymbol,
)
from repowise.core.persistence.search import FullTextSearch
from repowise.core.persistence.vector_store import InMemoryVectorStore
from repowise.core.providers.embedding.base import MockEmbedder
from repowise.core.workspace.registry import RepoContext

# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------

_NOW = datetime(2026, 4, 12, 10, 0, 0, tzinfo=UTC)


async def _make_repo_context(
    alias: str,
    repo_path: str,
    pages: list,
    extra_models: list | None = None,
    *,
    repo_name: str | None = None,
) -> RepoContext:
    """Create an in-memory RepoContext with test data."""
    engine = create_async_engine(
        "sqlite+aiosqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    await init_db(engine)

    factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
    async with factory() as session:
        repo = Repository(
            id=f"repo-{alias}",
            name=repo_name or alias,
            url=f"https://example.com/{alias}",
            local_path=repo_path,
            default_branch="main",
            settings_json="{}",
            created_at=_NOW,
            updated_at=_NOW,
        )
        session.add(repo)
        for p in pages:
            session.add(p)
        for m in extra_models or []:
            session.add(m)
        await session.commit()

    fts = FullTextSearch(engine)
    await fts.ensure_index()

    embedder = MockEmbedder()
    vs = InMemoryVectorStore(embedder=embedder)
    ds = InMemoryVectorStore(embedder=embedder)
    ready = asyncio.Event()
    ready.set()

    return RepoContext(
        alias=alias,
        path=__import__("pathlib").Path(repo_path),
        session_factory=factory,
        fts=fts,
        vector_store=vs,
        decision_store=ds,
        vector_store_ready=ready,
        _engine=engine,
    )


class _MockRegistry:
    """Minimal mock RepoRegistry for testing without real workspace files."""

    def __init__(
        self,
        contexts: dict[str, RepoContext],
        default_alias: str,
        workspace_root: Path,
    ):
        self._contexts = contexts
        self._default_alias = default_alias
        self.workspace_root = workspace_root
        self.ws_config = SimpleNamespace(
            repos=[
                SimpleNamespace(
                    alias=alias,
                    path=ctx.path.relative_to(self.workspace_root).as_posix(),
                    indexed_at=None,
                    last_commit_at_index=None,
                )
                for alias, ctx in contexts.items()
            ]
        )

    def get_all_aliases(self) -> list[str]:
        return list(self._contexts.keys())

    def get_default_alias(self) -> str:
        return self._default_alias

    def resolve_repo_param(self, repo):
        if repo is None:
            return self._default_alias
        if repo == "all":
            return self.get_all_aliases()
        for entry in self.ws_config.repos:
            identities = {
                entry.alias,
                entry.path,
                (self.workspace_root / entry.path).resolve().as_posix(),
            }
            if repo in identities:
                return entry.alias
        raise ValueError(f"Unknown repo '{repo}'. Available: {self.get_all_aliases()}")

    async def get(self, alias: str) -> RepoContext:
        return self._contexts[alias]

    async def get_default(self) -> RepoContext:
        return self._contexts[self._default_alias]

    async def close(self):
        for ctx in self._contexts.values():
            if ctx._engine:
                await ctx._engine.dispose()


@pytest.fixture
async def workspace_mcp(tmp_path):
    """Set up a two-repo workspace for MCP testing."""
    import repowise.server.mcp_server as mcp_mod

    workspace_root = tmp_path / "workspace"
    backend_root = workspace_root / "backend"
    frontend_root = workspace_root / "web-client"
    for root, name in (
        (backend_root, "backend_probe"),
        (frontend_root, "frontend_probe"),
    ):
        source = root / "src/probe.py"
        source.parent.mkdir(parents=True)
        source.write_text(f"def {name}():\n    return {name!r}\n", encoding="utf-8")
        for args in (
            ["git", "init", "-q"],
            ["git", "config", "user.email", "[email protected]"],
            ["git", "config", "user.name", "Workspace Fixture"],
            ["git", "add", "."],
            ["git", "commit", "-qm", f"seed {name}"],
        ):
            subprocess.run(args, cwd=root, check=True, capture_output=True)

    # Create two repo contexts with distinct data
    backend_ctx = await _make_repo_context(
        "backend",
        str(backend_root),
        pages=[
            Page(
                id="repo_overview:backend",
                repository_id="repo-backend",
                page_type="repo_overview",
                title="Backend Overview",
                content="# Backend\n\nThe API backend service.",
                target_path="backend",
                source_hash="abc",
                model_name="mock",
                provider_name="mock",
                generation_level=6,
                confidence=1.0,
                freshness_status="fresh",
                metadata_json="{}",
                created_at=_NOW,
                updated_at=_NOW,
            ),
            Page(
                id="file_page:src/probe.py",
                repository_id="repo-backend",
                page_type="file_page",
                title="Backend Probe",
                content="# Backend probe",
                target_path="src/probe.py",
                source_hash="probe-be",
                model_name="mock",
                provider_name="mock",
                generation_level=2,
                confidence=1.0,
                freshness_status="fresh",
                metadata_json="{}",
                created_at=_NOW,
                updated_at=_NOW,
            ),
        ],
        extra_models=[
            WikiSymbol(
                id="symbol-backend-probe",
                repository_id="repo-backend",
                file_path="src/probe.py",
                symbol_id="src/probe.py::backend_probe",
                name="backend_probe",
                qualified_name="backend_probe",
                kind="function",
                signature="def backend_probe()",
                start_line=1,
                end_line=2,
                language="python",
                created_at=_NOW,
                updated_at=_NOW,
            ),
            GraphNode(
                id="gn-be-probe",
                repository_id="repo-backend",
                node_id="src/probe.py",
                node_type="file",
                language="python",
                symbol_count=1,
                is_entry_point=True,
                pagerank=0.9,
                betweenness=0.1,
                community_id=1,
                created_at=_NOW,
            ),
            HealthFinding(
                id="hf-be-probe",
                repository_id="repo-backend",
                file_path="src/probe.py",
                biomarker_type="backend_probe_health",
                severity="low",
                function_name="backend_probe",
                reason="Backend fixture finding",
                health_impact=-0.1,
                status="open",
            ),
            GitMetadata(
                id="gm-be-probe",
                repository_id="repo-backend",
                file_path="src/probe.py",
                commit_count_total=2,
                churn_percentile=0.12,
            ),
            GraphNode(
                id="gn-be-1",
                repository_id="repo-backend",
                node_id="src/api/server.py",
                node_type="file",
                language="python",
                symbol_count=5,
                is_entry_point=True,
                pagerank=0.8,
                betweenness=0.5,
                community_id=1,
                created_at=_NOW,
            ),
            DeadCodeFinding(
                id="dc-be-1",
                repository_id="repo-backend",
                file_path="src/old_handler.py",
                symbol_name="old_handler",
                kind="unreachable_file",
                confidence=0.95,
                safe_to_delete=True,
                lines=42,
                reason="No imports found",
                evidence_json="[]",
            ),
            DecisionRecord(
                id="dec-be-1",
                repository_id="repo-backend",
                title="REST over GraphQL",
                decision="Use REST for all public APIs",
                rationale="Mobile client simplicity",
                status="active",
                source="cli",
                affected_files_json='["src/api/server.py"]',
                affected_modules_json='["api"]',
            ),
        ],
    )

    frontend_ctx = await _make_repo_context(
        "frontend",
        str(frontend_root),
        pages=[
            Page(
                id="repo_overview:frontend",
                repository_id="repo-frontend",
                page_type="repo_overview",
                title="Frontend Overview",
                content="# Frontend\n\nThe React web application.",
                target_path="frontend",
                source_hash="def",
                model_name="mock",
                provider_name="mock",
                generation_level=6,
                confidence=1.0,
                freshness_status="fresh",
                metadata_json="{}",
                created_at=_NOW,
                updated_at=_NOW,
            ),
            Page(
                id="file_page:src/probe.py",
                repository_id="repo-frontend",
                page_type="file_page",
                title="Frontend Probe",
                content="# Frontend probe",
                target_path="src/probe.py",
                source_hash="probe-fe",
                model_name="mock",
                provider_name="mock",
                generation_level=2,
                confidence=1.0,
                freshness_status="fresh",
                metadata_json="{}",
                created_at=_NOW,
                updated_at=_NOW,
            ),
        ],
        extra_models=[
            WikiSymbol(
                id="symbol-frontend-probe",
                repository_id="repo-frontend",
                file_path="src/probe.py",
                symbol_id="src/probe.py::frontend_probe",
                name="frontend_probe",
                qualified_name="frontend_probe",
                kind="function",
                signature="def frontend_probe()",
                start_line=1,
                end_line=2,
                language="python",
                created_at=_NOW,
                updated_at=_NOW,
            ),
            GraphNode(
                id="gn-fe-probe",
                repository_id="repo-frontend",
                node_id="src/probe.py",
                node_type="file",
                language="python",
                symbol_count=1,
                is_entry_point=True,
                pagerank=0.9,
                betweenness=0.1,
                community_id=1,
                created_at=_NOW,
            ),
            HealthFinding(
                id="hf-fe-probe",
                repository_id="repo-frontend",
                file_path="src/probe.py",
                biomarker_type="frontend_probe_health",
                severity="low",
                function_name="frontend_probe",
                reason="Frontend fixture finding",
                health_impact=-0.1,
                status="open",
            ),
            GitMetadata(
                id="gm-fe-probe",
                repository_id="repo-frontend",
                file_path="src/probe.py",
                commit_count_total=9,
                churn_percentile=0.82,
            ),
            GraphNode(
                id="gn-fe-1",
                repository_id="repo-frontend",
                node_id="src/App.tsx",
                node_type="file",
                language="typescript",
                symbol_count=3,
                is_entry_point=True,
                pagerank=0.7,
                betweenness=0.4,
                community_id=1,
                created_at=_NOW,
            ),
            DeadCodeFinding(
                id="dc-fe-1",
                repository_id="repo-frontend",
                file_path="src/legacy/utils.ts",
                symbol_name="formatLegacy",
                kind="unused_export",
                confidence=0.80,
                safe_to_delete=True,
                lines=15,
                reason="No imports found",
                evidence_json="[]",
            ),
            DecisionRecord(
                id="dec-fe-1",
                repository_id="repo-frontend",
                title="React over Vue",
                decision="Use React for all frontend work",
                rationale="Team expertise and ecosystem",
                status="active",
                source="cli",
                affected_files_json='["src/App.tsx"]',
                affected_modules_json='["src"]',
            ),
        ],
        repo_name="web-client",
    )

    registry = _MockRegistry(
        contexts={"backend": backend_ctx, "frontend": frontend_ctx},
        default_alias="backend",
        workspace_root=workspace_root,
    )

    # Set workspace state
    mcp_mod._registry = registry
    mcp_mod._workspace_root = str(workspace_root)
    mcp_mod._session_factory = backend_ctx.session_factory
    mcp_mod._fts = backend_ctx.fts
    mcp_mod._vector_store = backend_ctx.vector_store
    mcp_mod._decision_store = backend_ctx.decision_store
    mcp_mod._repo_path = str(backend_root)
    mcp_mod._vector_store_ready = backend_ctx.vector_store_ready

    yield registry

    # Cleanup
    await registry.close()
    mcp_mod._registry = None
    mcp_mod._workspace_root = None
    mcp_mod._session_factory = None
    mcp_mod._fts = None
    mcp_mod._vector_store = None
    mcp_mod._decision_store = None
    mcp_mod._repo_path = None
    mcp_mod._vector_store_ready = None
    mcp_mod._cross_repo_enricher = None


# ---------------------------------------------------------------------------
# get_health — workspace alias routing
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_get_health_resolves_alias_different_from_repo_name(workspace_mcp):
    from repowise.server.mcp_server import get_health

    result = await get_health(repo="frontend")

    assert result["mode"] == "dashboard"
    assert result["kpis"]["file_count"] == 0


@pytest.mark.asyncio
async def test_generate_refactoring_code_unknown_id_returns_error(workspace_mcp):
    from repowise.server.mcp_server import generate_refactoring_code

    result = await generate_refactoring_code(suggestion_id="does-not-exist", repo="frontend")

    assert result["error"] is not None


# ---------------------------------------------------------------------------
# generate_refactoring_code — workspace alias routing
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_generate_refactoring_code_resolves_alias_different_from_repo_name(
    workspace_mcp, monkeypatch
):
    """Regression for #880: the alias ``frontend`` maps to a repo named
    ``web-client``. ``_resolve_repo_context`` already scoped the session to that
    repo's DB, so re-filtering by the alias inside it raised
    ``LookupError: Repository not found: frontend``. Passing the ``llm.enabled``
    gate is required to reach the ``_get_repo`` call being exercised."""
    monkeypatch.setattr(
        "repowise.core.analysis.health.refactoring.llm.llm_enrichment_enabled",
        lambda config: True,
    )

    from repowise.server.mcp_server import generate_refactoring_code

    # No plan with this id exists, so a correctly-resolved repo returns
    # ``not_found`` rather than raising ``LookupError`` on alias resolution.
    result = await generate_refactoring_code(suggestion_id="nope", repo="frontend")

    assert result["error"] == "not_found"


# ---------------------------------------------------------------------------
# get_overview — workspace footer
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_get_overview_default_includes_workspace_footer(workspace_mcp):
    from repowise.server.mcp_server import get_overview

    result = await get_overview()
    assert result["title"] == "Backend Overview"
    assert "workspace" in result
    ws = result["workspace"]
    assert ws["default_repo"] == "backend"
    assert "frontend" in ws["other_repos"]
    assert "hint" in ws


@pytest.mark.asyncio
async def test_get_overview_specific_repo(workspace_mcp):
    from repowise.server.mcp_server import get_overview

    result = await get_overview(repo="frontend")
    assert result["title"] == "Frontend Overview"
    assert "workspace" in result


@pytest.mark.asyncio
async def test_get_overview_repo_all(workspace_mcp):
    from repowise.server.mcp_server import get_overview

    result = await get_overview(repo="all")
    assert result["workspace"] is True
    assert result["total_repos"] == 2
    aliases = [r["alias"] for r in result["repos"]]
    assert "backend" in aliases
    assert "frontend" in aliases
    # Default repo should be marked
    default_repos = [r for r in result["repos"] if r["is_default"]]
    assert len(default_repos) == 1
    assert default_repos[0]["alias"] == "backend"


# ---------------------------------------------------------------------------
# search_codebase — federated search
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_search_repo_all_returns_tagged_results(workspace_mcp):
    from repowise.server.mcp_server import search_codebase

    # FTS search — both repos should be queried
    result = await search_codebase(query="overview", repo="all")
    assert "results" in result
    # Results may be empty with MockEmbedder + FTS on minimal data,
    # but the function should not error


@pytest.mark.asyncio
async def test_search_specific_repo(workspace_mcp):
    from repowise.server.mcp_server import search_codebase

    result = await search_codebase(query="React", repo="frontend")
    assert "results" in result


# ---------------------------------------------------------------------------
# get_dead_code — workspace-wide
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_get_dead_code_repo_all(workspace_mcp):
    from repowise.server.mcp_server import get_dead_code

    result = await get_dead_code(repo="all")
    assert result.get("workspace") is True or "summary" in result
    # Should aggregate findings from both repos
    if "summary" in result:
        assert result["summary"]["total_findings"] >= 2


@pytest.mark.asyncio
async def test_get_dead_code_repo_all_summary_says_what_it_counts(workspace_mcp):
    from repowise.server.mcp_server import get_dead_code

    summary = (await get_dead_code(repo="all", directory="nowhere"))["summary"]
    assert summary["total_findings"] >= 2
    assert summary["filtered_findings"] == 0
    assert "filtered_findings" in summary["scope"]
    assert summary["filters"] == {"directory": "nowhere"}


@pytest.mark.asyncio
async def test_get_dead_code_specific_repo(workspace_mcp):
    from repowise.server.mcp_server import get_dead_code

    result = await get_dead_code(repo="backend")
    assert "summary" in result or "tiers" in result


# ---------------------------------------------------------------------------
# get_why — cross-repo decisions
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_get_why_repo_all(workspace_mcp):
    from repowise.server.mcp_server import get_why

    result = await get_why(query="REST", repo="all")
    # Should search across both repos
    assert isinstance(result, dict)


@pytest.mark.asyncio
async def test_get_why_specific_repo(workspace_mcp):
    from repowise.server.mcp_server import get_why

    result = await get_why(query="React", repo="frontend")
    assert isinstance(result, dict)


# ---------------------------------------------------------------------------
# Unsupported repo="all" tools
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_unsupported_repo_all_get_context(workspace_mcp):
    from repowise.server.mcp_server import get_context

    result = await get_context(targets=["src/api/server.py"], repo="all")
    assert "error" in result
    assert "not supported" in result["error"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("tool_name", "kwargs"),
    [
        ("get_health", {}),
        ("generate_refactoring_code", {"suggestion_id": "any"}),
        ("set_finding_status", {"suggestion_id": "any", "status": "acknowledged"}),
    ],
)
async def test_unsupported_repo_all_returns_error_dict(workspace_mcp, tool_name, kwargs):
    import repowise.server.mcp_server as mcp_server

    tool = getattr(mcp_server, tool_name)
    result = await tool(repo="all", **kwargs)

    assert result["error"].startswith(f"repo='all' is not supported for {tool_name}.")


# ---------------------------------------------------------------------------
# Invalid repo alias
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_invalid_repo_raises(workspace_mcp):
    from repowise.server.mcp_server import get_overview

    with pytest.raises(ValueError, match="Unknown repo"):
        await get_overview(repo="nonexistent")


# ---------------------------------------------------------------------------
# Single-repo mode — no workspace, no regression
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_single_repo_mode_no_workspace():
    """When _registry is None, tools should use _state globals directly."""
    import repowise.server.mcp_server as mcp_mod

    # Ensure no registry is set
    assert mcp_mod._registry is None

    # We can't easily call tools without DB, but verify the helper works
    from repowise.server.mcp_server._helpers import _is_workspace_mode

    assert _is_workspace_mode() is False


# ---------------------------------------------------------------------------
# Cross-repo enricher
# ---------------------------------------------------------------------------


@pytest.fixture
def enricher_data(tmp_path):
    """Write a cross_repo_edges.json and return its path."""
    data = {
        "version": 2,
        "generated_at": "2026-04-12T12:00:00Z",
        "co_changes": [
            {
                "source_repo": "backend",
                "source_file": "src/api/server.py",
                "target_repo": "frontend",
                "target_file": "src/api/client.ts",
                "strength": 4.2,
                "frequency": 6,
                "last_date": "2026-04-10",
            },
        ],
        "package_deps": [
            {
                "source_repo": "frontend",
                "target_repo": "backend",
                "source_manifest": "package.json",
                "kind": "npm_local_path",
            },
        ],
        "repo_summaries": {
            "backend": {"cross_repo_edge_count": 1},
            "frontend": {"cross_repo_edge_count": 1},
        },
    }
    path = tmp_path / "cross_repo_edges.json"
    path.write_text(json.dumps(data))
    return path


def test_enricher_loads_and_has_data(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    assert enricher.has_data is True


def test_enricher_get_cross_repo_partners(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    partners = enricher.get_cross_repo_partners("backend", "src/api/server.py")
    assert len(partners) == 1
    assert partners[0]["repo"] == "frontend"
    assert partners[0]["file"] == "src/api/client.ts"
    assert partners[0]["strength"] == 4.2


def test_enricher_bidirectional_index(enricher_data):
    """Co-change edges should be indexed from both sides."""
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    # Reverse direction
    partners = enricher.get_cross_repo_partners("frontend", "src/api/client.ts")
    assert len(partners) == 1
    assert partners[0]["repo"] == "backend"


def test_enricher_get_package_deps(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    deps = enricher.get_package_deps("frontend")
    assert len(deps) == 1
    assert deps[0]["target_repo"] == "backend"


def test_enricher_get_repos_depending_on(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    # frontend depends on backend
    depending = enricher.get_repos_depending_on("backend")
    assert "frontend" in depending


def test_enricher_get_repos_depending_on_lists_each_repo_once(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    data = json.loads(enricher_data.read_text())
    data["package_deps"].append({**data["package_deps"][0], "source_manifest": "apps/web/package.json"})
    enricher_data.write_text(json.dumps(data))
    enricher = CrossRepoEnricher(enricher_data)
    assert enricher.get_repos_depending_on("backend") == ["frontend"]


def test_enricher_has_cross_repo_consumers(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    consumers = enricher.has_cross_repo_consumers("backend", "src/api/server.py")
    assert len(consumers) == 1
    assert consumers[0]["repo"] == "frontend"


def test_enricher_get_affected_repos(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    affected = enricher.get_affected_repos("backend", "src/api/server.py")
    assert "frontend" in affected


def test_enricher_missing_file_returns_empty(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    assert enricher.get_cross_repo_partners("backend", "nonexistent.py") == []
    assert enricher.has_cross_repo_consumers("backend", "nonexistent.py") == []


def test_enricher_missing_json_has_no_data(tmp_path):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(tmp_path / "does_not_exist.json")
    assert enricher.has_data is False
    assert enricher.get_cross_repo_partners("x", "y") == []


def test_enricher_get_cross_repo_summary(enricher_data):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    enricher = CrossRepoEnricher(enricher_data)
    summary = enricher.get_cross_repo_summary()
    assert summary["co_change_count"] == 1
    assert summary["package_dep_count"] == 1
    assert len(summary["top_connections"]) >= 1


def test_enricher_serves_maven_evidence_and_bounded_diagnostics(tmp_path):
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    path = tmp_path / "cross_repo_edges.json"
    path.write_text(
        json.dumps(
            {
                "version": 2,
                "package_deps": [
                    {
                        "source_repo": "consumer",
                        "target_repo": "producer",
                        "source_manifest": "app/pom.xml",
                        "target_manifest": "shared/pom.xml",
                        "target_package": "com.acme:shared",
                        "requested_version": "1.2.0",
                        "scope": "compile",
                        "resolution_basis": "unique_workspace_coordinate",
                        "kind": "maven_coordinate",
                    }
                ],
                "package_diagnostics": [
                    {
                        "repo": "consumer",
                        "source_manifest": "pom.xml",
                        "code": "external_coordinate",
                        "detail": "org.example:outside",
                    }
                ],
                "total_package_diagnostics": 4,
            }
        ),
        encoding="utf-8",
    )

    enricher = CrossRepoEnricher(path)

    assert enricher.get_package_deps("consumer") == [
        {
            "target_repo": "producer",
            "source_manifest": "app/pom.xml",
            "kind": "maven_coordinate",
            "target_package": "com.acme:shared",
            "target_manifest": "shared/pom.xml",
            "requested_version": "1.2.0",
            "scope": "compile",
            "resolution_basis": "unique_workspace_coordinate",
        }
    ]
    summary = enricher.get_cross_repo_summary()
    assert summary["package_diagnostic_count"] == 4
    assert summary["package_diagnostics_emitted"] == 1
    assert summary["package_diagnostic_codes"] == ["external_coordinate"]


# ---------------------------------------------------------------------------
# MCP tool enrichment with cross-repo data
# ---------------------------------------------------------------------------


@pytest.fixture
async def workspace_mcp_with_enricher(workspace_mcp, enricher_data):
    """Extend workspace_mcp with a cross-repo enricher."""
    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server._enrichment import CrossRepoEnricher

    mcp_mod._cross_repo_enricher = CrossRepoEnricher(enricher_data)
    yield
    mcp_mod._cross_repo_enricher = None


@pytest.mark.asyncio
async def test_overview_footer_points_at_the_cross_repo_view(workspace_mcp_with_enricher):
    from repowise.server.mcp_server import get_overview

    result = await get_overview()
    ws = result["workspace"]
    assert "cross_repo" not in ws
    assert "repo='all'" in ws["hint"]


@pytest.mark.asyncio
async def test_overview_all_includes_cross_repo_topology(workspace_mcp_with_enricher):
    from repowise.server.mcp_server import get_overview

    result = await get_overview(repo="all")
    assert "cross_repo_topology" in result
    assert result["cross_repo_topology"]["co_change_count"] == 1


@pytest.mark.asyncio
async def test_list_repos_discovers_workspace_aliases(workspace_mcp):
    from repowise.server.mcp_server import (
        get_answer,
        get_change_risk,
        get_context,
        get_dead_code,
        get_health,
        get_overview,
        get_risk,
        get_symbol,
        get_why,
        list_repos,
        search_codebase,
    )

    result = await list_repos()

    assert result["workspace"] is True
    assert result["workspace_root"] == workspace_mcp.workspace_root.as_posix()
    assert result["default_repo"] == "backend"
    assert [repo["alias"] for repo in result["repos"]] == ["backend", "frontend"]
    assert result["repos"][0]["is_default"] is True
    repository_targets = {
        "get_answer",
        "get_change_risk",
        "get_context",
        "get_dead_code",
        "get_health",
        "get_overview",
        "get_risk",
        "get_symbol",
        "get_why",
        "search_codebase",
    }
    repository_matrix = {
        ("list_repos", "repository", target): "PASS"
        for target in repository_targets
    }
    repository_matrix.update(
        {
            ("list_repos", kind, "N/A"): "N/A"
            for kind in {
                "file",
                "symbol",
                "decision/evidence",
                "omission/continuation",
                "finding",
                "refactoring plan",
            }
        }
    )
    assert len(repository_matrix) == 16
    for emitted in result["repos"]:
        for field in ("alias", "path", "absolute_path"):
            identity = emitted[field]
            probe = f"{emitted['alias']}_probe"
            symbol_id = f"src/probe.py::{probe}"
            answer = await get_answer(f"where is {probe} defined", repo=identity)
            assert probe in json.dumps(answer)
            change = await get_change_risk("HEAD", repo=identity, baseline=0)
            assert change.get("warning") is None
            # The raw score is behind include=["diagnostics"] now; the
            # percentile is what the default payload ranks with.
            assert change["risk_percentile"] is None or change["risk_percentile"] >= 0
            expected_head = subprocess.run(
                ["git", "rev-parse", "--short=12", "HEAD"],
                cwd=workspace_mcp.workspace_root / emitted["path"],
                check=True,
                capture_output=True,
                text=True,
            ).stdout.strip()
            assert change["_meta"]["live_head"] == expected_head
            context = await get_context([symbol_id], repo=identity)
            assert context["targets"][symbol_id]["type"] == "symbol"
            assert context["targets"][symbol_id]["docs"]["name"] == probe

            overview = await get_overview(repo=identity)
            assert overview["title"] == f"{emitted['alias'].title()} Overview"
            health = await get_health(targets=["src/probe.py"], repo=identity)
            assert {
                finding["biomarker_type"]
                for finding in health["findings"]
            } == {f"{emitted['alias']}_probe_health"}
            risk = await get_risk(["src/probe.py"], repo=identity)
            assert risk["targets"]["src/probe.py"]["hotspot_score"] == (
                0.12 if emitted["alias"] == "backend" else 0.82
            )
            symbol = await get_symbol(symbol_id, repo=identity)
            assert symbol["symbol_id"] == symbol_id
            assert probe in symbol["source"]
            why = await get_why(
                id=f"dec-{'be' if emitted['alias'] == 'backend' else 'fe'}-1",
                repo=identity,
            )
            assert why["resolved"] is True
            assert why["decisions"][0]["id"].startswith(
                f"dec-{'be' if emitted['alias'] == 'backend' else 'fe'}"
            )
            dead = await get_dead_code(repo=identity, min_confidence="low")
            files = {
                finding["file_path"]
                for tier in dead["tiers"].values()
                for finding in tier["findings"]
            }
            assert files == {
                "src/old_handler.py"
                if emitted["alias"] == "backend"
                else "src/legacy/utils.ts"
            }
            search = await search_codebase(
                probe, repo=identity, mode="symbol", limit=5
            )
            assert any(row.get("symbol_id") == symbol_id for row in search["results"])
    assert "alias, path, or absolute_path" in result["hint"]


@pytest.mark.asyncio
async def test_list_repos_single_repo_mode():
    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server import list_repos

    original_registry = mcp_mod._registry
    original_repo_path = mcp_mod._repo_path
    mcp_mod._registry = None
    mcp_mod._repo_path = "/tmp/solo"

    try:
        result = await list_repos()
    finally:
        mcp_mod._registry = original_registry
        mcp_mod._repo_path = original_repo_path

    assert result["workspace"] is False
    assert result["default_repo"] == "default"
    assert result["repos"] == [
        {
            "alias": "default",
            "path": "/tmp/solo",
            "absolute_path": "/tmp/solo",
            "is_default": True,
        }
    ]


def test_list_repos_reads_the_commit_a_repo_updated_on_its_own_recorded(tmp_path):
    from repowise.core.workspace import WorkspaceConfig
    from repowise.core.workspace.config import RepoEntry
    from repowise.server.mcp_server.tool_repos import _workspace_repos

    (tmp_path / "api" / ".repowise").mkdir(parents=True)
    (tmp_path / "api" / ".repowise" / "state.json").write_text(
        json.dumps({"last_sync_commit": "b" * 40})
    )
    config = WorkspaceConfig(
        repos=[RepoEntry(path="api", alias="api", last_commit_at_index="a" * 40)]
    )
    config.save(tmp_path)
    registry = SimpleNamespace(
        workspace_root=tmp_path, ws_config=config, get_default_alias=lambda: "api"
    )

    [row] = _workspace_repos(registry)
    assert row["last_commit_at_index"] == "b" * 40
    # Read, not written: the config on disk is the CLI's to update.
    assert WorkspaceConfig.load(tmp_path).repos[0].last_commit_at_index == "a" * 40