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.

100 KB
Raw Blame
"""Unit tests for repowise MCP server tools.

Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
test data, mirroring the conftest pattern from the REST API tests.
"""

from __future__ import annotations

import re

import pytest

from repowise.core.persistence.search import strip_leading_headings


@pytest.mark.asyncio
async def test_search_codebase(setup_mcp):
    # Index pages in the MCP module's vector store (which is the InMemoryVectorStore)
    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server import search_codebase

    await mcp_mod._vector_store.embed_and_upsert(
        "file_page:src/auth/service.py",
        "Auth Service — Main authentication service class",
        {"title": "Auth Service", "page_type": "file_page", "target_path": "src/auth/service.py"},
    )
    await mcp_mod._vector_store.embed_and_upsert(
        "file_page:src/db/models.py",
        "DB Models — SQLAlchemy ORM models",
        {"title": "DB Models", "page_type": "file_page", "target_path": "src/db/models.py"},
    )

    result = await search_codebase("authentication service")
    assert "results" in result
    assert len(result["results"]) >= 1


def _mk_result(page_id, title, page_type, target_path, score):
    from repowise.core.persistence.search import SearchResult

    return SearchResult(
        page_id=page_id,
        title=title,
        page_type=page_type,
        target_path=target_path,
        score=score,
        snippet=title,
        search_type="vector",
    )


async def _seed_page(page_id, target_path, page_type="file_page"):
    """Insert a Page row into the setup_mcp DB so _load_page_info resolves its
    target_path. Reuses the seeded repository_id so the row is valid."""
    from datetime import UTC, datetime

    from sqlalchemy import select

    import repowise.server.mcp_server as mcp_mod
    from repowise.core.persistence.database import get_session
    from repowise.core.persistence.models import Page

    now = datetime(2026, 1, 1, tzinfo=UTC)
    async with get_session(mcp_mod._session_factory) as session:
        rid = (await session.execute(select(Page.repository_id).limit(1))).scalar()
        session.add(
            Page(
                id=page_id,
                repository_id=rid,
                page_type=page_type,
                title="Test Service",
                content="tests",
                target_path=target_path,
                source_hash="seed",
                model_name="mock",
                provider_name="mock",
                generation_level=2,
                confidence=0.5,
                freshness_status="fresh",
                metadata_json="{}",
                created_at=now,
                updated_at=now,
            )
        )
        await session.commit()


async def _seed_symbol(name):
    """Insert a WikiSymbol named ``name`` into the setup_mcp DB."""
    from datetime import UTC, datetime

    from sqlalchemy import select

    import repowise.server.mcp_server as mcp_mod
    from repowise.core.persistence.database import get_session
    from repowise.core.persistence.models import Page, WikiSymbol

    now = datetime(2026, 1, 1, tzinfo=UTC)
    async with get_session(mcp_mod._session_factory) as session:
        rid = (await session.execute(select(Page.repository_id).limit(1))).scalar()
        session.add(
            WikiSymbol(
                id=f"seed-{name}",
                repository_id=rid,
                file_path="src/net/client.py",
                symbol_id=f"src/net/client.py::{name}",
                name=name,
                qualified_name=f"net.client.{name}",
                kind="function",
                signature=f"def {name}()",
                start_line=1,
                end_line=5,
                visibility="public",
                is_async=False,
                complexity_estimate=1,
                language="python",
                created_at=now,
                updated_at=now,
            )
        )
        await session.commit()


@pytest.mark.asyncio
@pytest.mark.parametrize("glob", ["*", "?"])
async def test_path_search_accepts_trailing_glob(setup_mcp, glob):
    """A trailing glob narrows a path search without becoming a literal."""
    import types

    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server.tool_search_symbols import search_paths_single

    await _seed_page("file_page:tool_overview.py", "packages/server/tool_overview.py")
    await _seed_page("file_page:tool_answer.py", "packages/server/tool_answer.py")

    ctx = types.SimpleNamespace(
        session_factory=mcp_mod._session_factory,
        path="/tmp/test-repo",
    )
    result = await search_paths_single(ctx, f"tool_overview{glob}", limit=10)

    assert [item["file"] for item in result] == ["packages/server/tool_overview.py"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("query", "expected"),
    [
        ("tool_overview.py", ["packages/server/tool_overview.py"]),
        ("  *tool_overview?  ", ["packages/server/tool_overview.py"]),
        ("*", []),
        ("?", []),
        ("tool_*_overview", []),
    ],
)
async def test_path_search_preserves_non_trailing_glob_behavior(setup_mcp, query, expected):
    """Only boundary glob markers are supported by path-mode substring search."""
    import types

    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server.tool_search_symbols import search_paths_single

    await _seed_page("file_page:tool_overview.py", "packages/server/tool_overview.py")

    ctx = types.SimpleNamespace(
        session_factory=mcp_mod._session_factory,
        path="/tmp/test-repo",
    )
    result = await search_paths_single(ctx, query, limit=10)

    assert [item["file"] for item in result] == expected


_WORD_PATHS = [
    "src/agents/command-poll-backoff.ts",
    "lib/poll_backoff.py",
    "web/pollBackoff.js",
    "Services/PollBackoff.cs",
    "net/poll.backoff.go",
    "poll/backoff/index.ts",
    "src/agents/poll.ts",
    "src/agents/backoff-retry.ts",
]


async def _path_search(query, paths=_WORD_PATHS, limit=10):
    import types

    import repowise.server.mcp_server as mcp_mod
    from repowise.server.mcp_server.tool_search_symbols import search_paths_single

    for path in paths:
        await _seed_page(f"file_page:{path}", path)
    ctx = types.SimpleNamespace(session_factory=mcp_mod._session_factory, path="/tmp/test-repo")
    return [item["file"] for item in await search_paths_single(ctx, query, limit=limit)]


@pytest.mark.asyncio
async def test_path_words_match_every_naming_shape(setup_mcp):
    """Spaced words match kebab, snake, camel, Pascal and dotted filenames,
    filename hits above a path whose directories carry the words."""
    files = await _path_search("poll backoff")
    assert set(files[:5]) == {
        "lib/poll_backoff.py",
        "web/pollBackoff.js",
        "net/poll.backoff.go",
        "Services/PollBackoff.cs",
        "src/agents/command-poll-backoff.ts",
    }
    assert files[5:] == ["poll/backoff/index.ts"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("query", "expected"),
    [
        ("poll backof", "lib/poll_backoff.py"),  # the last word may be a prefix
        ("Poll Backoff", "lib/poll_backoff.py"),
        ("pollBackoff", "lib/poll_backoff.py"),
    ],
)
async def test_path_words_prefix_case_and_compound_queries(setup_mcp, query, expected):
    files = await _path_search(query)
    assert expected in files
    assert "src/agents/poll.ts" not in files


@pytest.mark.asyncio
@pytest.mark.parametrize("query", ["poll jitter", "pol backoff", "agents retry backoff poll"])
async def test_path_words_all_must_match(setup_mcp, query):
    assert await _path_search(query) == []


@pytest.mark.asyncio
async def test_substring_hits_rank_above_word_hits(setup_mcp):
    files = await _path_search("pollBackoff")
    assert files[:2] == ["web/pollBackoff.js", "Services/PollBackoff.cs"]
    assert "lib/poll_backoff.py" in files[2:]


@pytest.mark.asyncio
async def test_exact_path_query_is_unchanged(setup_mcp):
    assert await _path_search("src/agents/poll.ts") == ["src/agents/poll.ts"]


class TestDecisionDownweight:
    """Decision records must not crowd file pages out of the top ranks."""

    def test_why_shaped_queries(self):
        from repowise.server.mcp_server.tool_search import _is_why_shaped

        assert _is_why_shaped("why is auth using JWT?")
        assert _is_why_shaped("when did we switch to SQLite")
        assert _is_why_shaped("who decided on LanceDB")
        assert _is_why_shaped("what was the rationale for WAL mode")
        assert _is_why_shaped("show me the decision about persistence")
        assert not _is_why_shaped("where is the SQLite store for distilled output")
        assert not _is_why_shaped("authentication flow")

    def test_fetch_limit_always_overfetches(self):
        from repowise.server.mcp_server.tool_search import _fetch_limit_for

        # Down-weighting can only promote file pages that are inside the
        # fetched window, so even unfiltered queries over-fetch.
        assert _fetch_limit_for(5, None) == 15
        assert _fetch_limit_for(5, "implementation") == 30

    @pytest.mark.asyncio
    async def test_file_page_outranks_downweighted_decision(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result("decision:d1", "Use repo-local SQLite", "decision_record", "", 0.57),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.42,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("where is the SQLite store")
        types = [r["page_type"] for r in result["results"]]
        assert types[0] == "file_page"
        # The decision page survives, just demoted below the file page.
        assert "decision_record" in types

    @pytest.mark.asyncio
    async def test_why_query_keeps_decision_ranking(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result("decision:d1", "Use repo-local SQLite", "decision_record", "", 0.57),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.42,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("why did we choose SQLite for persistence?")
        assert result["results"][0]["page_type"] == "decision_record"

    @pytest.mark.asyncio
    async def test_kind_filter_survives_decision_flood(self, setup_mcp):
        # 15 decision records ahead of one file page: with the old 3x
        # over-fetch the window held only decisions and kind="implementation"
        # returned []. The 6x window must surface the file page.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        flood = [
            _mk_result(f"decision:d{i}", f"Decision {i}", "decision_record", "", 0.6 - i * 0.01)
            for i in range(15)
        ]
        flood.append(
            _mk_result(
                "file_page:src/auth/service.py",
                "Auth Service",
                "file_page",
                "src/auth/service.py",
                0.35,
            )
        )

        async def fake_search(query, limit=10):
            return flood[:limit]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("sqlite store", limit=5, kind="implementation")
        paths = [r["path"] for r in result["results"]]
        assert paths == ["src/auth/service.py"]

    @pytest.mark.asyncio
    async def test_federated_path_filters_kind_before_truncation(self, setup_mcp):
        # _search_single_repo used to truncate to ``limit`` before the
        # aggregate kind filter ran, so federated kind searches under-filled.
        import types

        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server.tool_search import _search_single_repo

        flood = [
            _mk_result(f"decision:d{i}", f"Decision {i}", "decision_record", "", 0.6 - i * 0.01)
            for i in range(15)
        ]
        flood.append(
            _mk_result(
                "file_page:src/auth/service.py",
                "Auth Service",
                "file_page",
                "src/auth/service.py",
                0.35,
            )
        )

        async def fake_search(query, limit=10):
            return flood[:limit]

        async def empty_fts(query, limit=10):
            return []

        ctx = types.SimpleNamespace(
            vector_store=types.SimpleNamespace(search=fake_search),
            # Stub FTS: this test drives ranking through the vector list, and a
            # real FTS handle on the shared in-memory engine (per-connection
            # isolation) would shadow the seeded rows for the follow-up session.
            fts=types.SimpleNamespace(search=empty_fts),
            session_factory=mcp_mod._session_factory,
            vector_store_ready=None,
            path="/tmp/test-repo",
        )
        results = await _search_single_repo(
            ctx, "sqlite store", limit=5, page_type=None, kind="implementation"
        )
        assert [r["target_path"] for r in results] == ["src/auth/service.py"]
        # Fused retrieval tags each hit with the retrievers that surfaced it.
        assert results[0]["sources"] == ["vector"]


class TestNoiseDemotion:
    """Test file pages and near-duplicate decisions must not crowd the top ranks."""

    def test_is_test_query(self):
        from repowise.server.mcp_server.tool_search import _is_test_query

        assert _is_test_query("how is the auth service tested")
        assert _is_test_query("unit test for the parser")
        assert _is_test_query("where are the pytest fixtures")
        assert not _is_test_query("how does the auth service authenticate")
        assert not _is_test_query("where is the SQLite store")

    def test_is_test_page(self):
        from repowise.server.mcp_server.tool_search import _is_test_page

        assert _is_test_page({"page_type": "file_page", "target_path": "tests/unit/test_auth.py"})
        assert _is_test_page({"page_type": "file_page", "target_path": "src/auth/service_test.py"})
        assert not _is_test_page({"page_type": "file_page", "target_path": "src/auth/service.py"})
        # Only file pages classify as test pages, never decision/concept pages.
        assert not _is_test_page({"page_type": "decision_record", "target_path": ""})

    def test_is_test_page_keeps_support_and_lookalikes_ranked(self):
        """Demotion is tests only, and only real tests (#1103).

        The substring token list this used to run on demoted every production
        file whose path merely contained "test_", and demoted the fixtures a
        "where are the shared fixtures" query is asking for.
        """
        from repowise.server.mcp_server.tool_search import _is_test_page

        def page(path: str) -> dict:
            return {"page_type": "file_page", "target_path": path}

        # Test support keeps its rank: it is often the answer. Leading segments
        # on purpose — the token list this replaced anchored on "/tests/", so a
        # root-level path would pass for the wrong reason.
        assert not _is_test_page(page("packages/core/tests/conftest.py"))
        assert not _is_test_page(page("packages/core/tests/factories/user.py"))
        # Production code that merely spells "test".
        assert not _is_test_page(page("src/analysis/missing_test_signal.py"))
        assert not _is_test_page(page("src/latest/api.py"))
        # Real tests the token list missed.
        assert _is_test_page(page("myapp/tests.py"))
        assert _is_test_page(page("src/test/java/Foo.java"))
        assert _is_test_page(page("Foo.Tests/Bar.cs"))
        assert _is_test_page(page("e2e/login.ts"))

    def test_downweight_test_pages_scales_unless_test_query(self):
        from repowise.server.mcp_server.tool_search import _downweight_test_pages

        rows = [
            {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 1.0},
            {"page_type": "file_page", "target_path": "src/x.py", "relevance_score": 1.0},
        ]
        _downweight_test_pages(rows, "how does x work")
        assert rows[0]["relevance_score"] < 1.0  # test page scaled down
        assert rows[1]["relevance_score"] == 1.0  # impl page untouched

        rows2 = [
            {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 1.0},
        ]
        _downweight_test_pages(rows2, "how is x tested")
        assert rows2[0]["relevance_score"] == 1.0  # test-focused query: no scaling

    def test_sort_demoting_noise_ranks_impl_over_test(self):
        from repowise.server.mcp_server.tool_search import _sort_demoting_noise

        rows = [
            {"page_type": "file_page", "target_path": "tests/test_x.py", "relevance_score": 0.9},
            {"page_type": "file_page", "target_path": "src/x.py", "relevance_score": 0.4},
        ]
        _sort_demoting_noise(rows, "how does x work")
        assert rows[0]["target_path"] == "src/x.py"  # impl promoted over higher-scored test
        assert rows[1]["target_path"] == "tests/test_x.py"

    def test_dedup_decisions_collapses_near_duplicates(self):
        from repowise.server.mcp_server.tool_search import _dedup_decisions

        rows = [
            {
                "page_type": "decision_record",
                "title": "CLI incremental update regenerates only affected pages",
                "page_id": "d1",
            },
            {
                "page_type": "decision_record",
                "title": "CLI incremental update regenerates only affected pages.",
                "page_id": "d2",
            },
            {
                "page_type": "decision_record",
                "title": "CLI  incremental-update regenerates only affected pages",
                "page_id": "d3",
            },
            {"page_type": "file_page", "title": "x", "page_id": "f1"},
            {"page_type": "decision_record", "title": "Use repo-local SQLite", "page_id": "d4"},
        ]
        out = _dedup_decisions(rows)
        ids = [r["page_id"] for r in out]
        assert ids == ["d1", "f1", "d4"]  # three near-dups -> one; file + distinct decision kept

    @pytest.mark.asyncio
    async def test_impl_page_outranks_its_test_page(self, setup_mcp):
        # Wiring check: demotion runs AFTER target_path is attached, so a
        # higher-scored test page still falls below the impl file page. Uses the
        # pre-seeded src/auth/service.py plus a seeded test page so both page_ids
        # resolve a target_path in _load_page_info.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("file_page:tests/unit/test_service.py", "tests/unit/test_service.py")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:tests/unit/test_service.py",
                    "Test Service",
                    "file_page",
                    "tests/unit/test_service.py",
                    0.62,
                ),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.41,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("how does the auth service work")
        paths = [r["path"] for r in result["results"]]
        assert paths[0] == "src/auth/service.py"
        assert "tests/unit/test_service.py" in paths  # demoted, not dropped

    @pytest.mark.asyncio
    async def test_test_query_keeps_test_page_ranking(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("file_page:tests/unit/test_service.py", "tests/unit/test_service.py")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:tests/unit/test_service.py",
                    "Test Service",
                    "file_page",
                    "tests/unit/test_service.py",
                    0.62,
                ),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.41,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        # Not "auth service": that spells ``AuthService``, whose file the
        # symbol leg would rightly lift on its own.
        result = await search_codebase("how is the auth flow tested")
        assert result["results"][0]["path"] == "tests/unit/test_service.py"


class TestClassifyHitKind:
    """The ``kind`` filter's path heuristic."""

    def test_decision_record_is_doc(self):
        # Regression: decision records carry an empty target_path and used
        # to fall through the path heuristics into "implementation", so
        # kind="implementation" returned decision pages instead of code.
        from repowise.server.mcp_server.tool_search import _classify_hit_kind

        assert _classify_hit_kind("", "decision_record") == "doc"

    def test_overview_and_onboarding_are_doc(self):
        from repowise.server.mcp_server.tool_search import _classify_hit_kind

        assert _classify_hit_kind("", "repo_overview") == "doc"
        assert _classify_hit_kind("onboarding/how_it_works", "onboarding") == "doc"

    def test_file_page_paths_classify_by_role(self):
        from repowise.server.mcp_server.tool_search import _classify_hit_kind

        assert _classify_hit_kind("src/auth/service.py", "file_page") == "implementation"
        assert _classify_hit_kind("tests/unit/test_auth.py", "file_page") == "test"
        assert _classify_hit_kind("pyproject.toml", "file_page") == "config"
        assert _classify_hit_kind("docs/guide.md", "file_page") == "doc"

    def test_kind_test_covers_support_unlike_the_demotion(self):
        """``kind`` splits the repo in two, so a fixture lands on the test side.

        Deliberately a different answer from ``_is_test_page``: nobody asking
        for ``kind="implementation"`` wants a conftest back, but a fixture page
        should still rank normally on an ordinary query.
        """
        from repowise.server.mcp_server.tool_search import _classify_hit_kind, _is_test_page

        for path in ("packages/core/tests/conftest.py", "packages/core/tests/factories/user.py"):
            assert _classify_hit_kind(path, "file_page") == "test"
            assert not _is_test_page({"page_type": "file_page", "target_path": path})
        # Config beats test: a workflow named for tests is still a workflow.
        assert _classify_hit_kind(".github/workflows/tests.yml", "file_page") == "config"
        # Case-sensitive rules survive: the classifier must not see a lowercased
        # path, or FooTest.java and Foo.Tests/ stop matching.
        assert _classify_hit_kind("Foo.Tests/Bar.cs", "file_page") == "test"
        assert _classify_hit_kind("src/FooTest.java", "file_page") == "test"
        assert _classify_hit_kind("src/latest/api.py", "file_page") == "implementation"

    def test_module_page_is_doc(self):
        from repowise.server.mcp_server.tool_search import _classify_hit_kind

        assert _classify_hit_kind("src/auth", "module_page") == "doc"


class TestDecisionDemotionAndRescue:
    """B4: absolute demotion of decisions on non-why queries + window rescue."""

    @pytest.mark.asyncio
    async def test_decision_outscoring_file_page_still_ranks_below(self, setup_mcp):
        # The 0.6 down-weight alone is washed out when the decision score
        # margin exceeds it (0.9 * 0.6 = 0.54 > 0.42). Demotion must be
        # absolute for non-why queries.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result("decision:d1", "Cache prompts as SWR", "decision_record", "", 0.9),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.42,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("answer cache invalidation schema version")
        types = [r["page_type"] for r in result["results"]]
        assert types[0] == "file_page"

    @pytest.mark.asyncio
    async def test_all_decision_window_is_rescued_with_file_pages(self, setup_mcp):
        # E6 live failure: 5/5 decision records, zero file pages. The wider
        # re-fetch must surface non-decision pages.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        decisions = [
            _mk_result(f"decision:d{i}", f"Decision {i}", "decision_record", "", 0.8 - i * 0.01)
            for i in range(20)
        ]
        wide = [*decisions, _mk_result("file_page:src/auth/service.py", "Auth Service", "file_page", "src/auth/service.py", 0.3)]

        async def fake_search(query, limit=10):
            # Narrow window: only decisions. Wide window: includes the file.
            return decisions[:limit] if limit <= 20 else wide[:limit]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("answer cache invalidation schema version", limit=5)
        types = [r["page_type"] for r in result["results"]]
        assert "file_page" in types, "rescue must inject non-decision pages"
        assert types[0] == "file_page", "rescued file page ranks above demoted decisions"

    @pytest.mark.asyncio
    async def test_why_query_skips_rescue_and_demotion(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result("decision:d1", "Use SQLite", "decision_record", "", 0.9),
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.42,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("why did we choose SQLite?")
        assert result["results"][0]["page_type"] == "decision_record"


class TestSymbolTestPenalty:
    """The -5 a symbol takes for living in a test file (#1103)."""

    @staticmethod
    def _score(path: str, language: str = "python", query: str = "build index") -> float:
        from repowise.core.persistence.models import WikiSymbol
        from repowise.server.mcp_server.tool_search_symbols import _score_symbol

        row = WikiSymbol(
            name="build_index",
            qualified_name="build_index",
            file_path=path,
            language=language,
        )
        # No graph node: symbol nodes never carry `is_test`, so the path rules
        # are what decide here in practice.
        return _score_symbol(row, None, {"build", "index"}, query)

    def test_tests_are_penalised_and_support_is_not(self):
        base = self._score("src/indexing/build.py")
        assert self._score("packages/core/tests/test_build.py") == base - 5.0
        # An exact match is left to the shared rank key, which puts kind first.
        exact = self._score("src/indexing/build.py", query="build_index")
        assert self._score("packages/core/tests/test_build.py", query="build_index") == exact
        assert self._score("myapp/tests.py") == base - 5.0
        # A fixture factory is often what the query was after.
        assert self._score("packages/core/tests/conftest.py") == base
        assert self._score("packages/core/tests/factories/user.py") == base
        # Production code that merely spells "test".
        assert self._score("src/analysis/missing_test_signal.py") == base

    def test_language_decides_the_ambiguous_spec_dir(self):
        base = self._score("src/indexing/build.py")
        # RSpec for Ruby, a specifications folder for anything else — the same
        # call the traverser made when it stamped the file's flag.
        assert self._score("spec/models/user.rb", language="ruby") == base - 5.0
        assert self._score("spec/openapi/users.py", language="python") == base


def test_symbol_coverage_folds_plurals_on_both_sides():
    from repowise.core.persistence.models import WikiSymbol
    from repowise.server.mcp_server.tool_search_symbols import _score_symbol, _tokens

    def score(name: str, query: str) -> float:
        row = WikiSymbol(name=name, qualified_name=name, file_path="src/a.py", language="python")
        return _score_symbol(row, None, _tokens(query), query.lower())

    # Every query word is covered once ``type`` meets ``types``, either way round.
    full = score("declared_types_in", "declared types in")
    assert score("declared_types_in", "declared type in") == full
    assert score("parseHeader", "parse headers") == score("parseHeader", "parse header")
    assert score("declared_types_in", "declared kind in") < full


@pytest.mark.parametrize(
    "name, plural, singular",
    [
        ("MyClass", "my classes", "my class"),
        ("createFactory", "create factories", "create factory"),
        ("commandNameMatch", "command name matches", "command name match"),
        ("cacheEntry", "cache entries", "cache entry"),
        ("parseResponse", "parse responses", "parse response"),
        ("statusCode", "status codes", "status code"),
    ],
)
def test_irregular_s_plurals_reach_the_singular_name(name, plural, singular):
    from repowise.core.persistence.models import WikiSymbol
    from repowise.server.mcp_server.tool_search_symbols import (
        _candidate_filter,
        _score_symbol,
        _tokens,
    )

    row = WikiSymbol(name=name, qualified_name=name, file_path="src/a.py", language="python")
    assert _score_symbol(row, None, _tokens(plural), plural) == _score_symbol(
        row, None, _tokens(singular), singular
    )
    # The candidate filter is a substring LIKE per singular form; the plural
    # word's own forms must reach the name.
    clause = _candidate_filter(_tokens(plural), plural)
    sql = str(clause.compile(compile_kwargs={"literal_binds": True})).lower()
    word = plural.split()[-1]
    likes = set(re.findall(r"'%([^%']+)%'", sql))
    assert any(like in name.lower() and like[:3] == word[:3] for like in likes)


def test_a_singular_y_word_finds_its_ies_plural():
    from repowise.server.mcp_server.tool_search_symbols import _candidate_filter, _tokens

    clause = _candidate_filter(_tokens("create factory"), "create factory")
    sql = str(clause.compile(compile_kwargs={"literal_binds": True})).lower()
    assert any(like in "createfactories" and like.startswith("fact")
               for like in re.findall(r"'%([^%']+)%'", sql))


class TestSymbolSearch:
    """mode="symbol" / "auto" routing into the structural index (issue #484)."""

    @pytest.mark.asyncio
    async def test_exact_name_returns_symbol_shape(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService", mode="symbol")
        assert result["mode"] == "symbol"
        hits = result["results"]
        assert hits, "exact name must resolve to a symbol"
        top = hits[0]
        assert top["type"] == "symbol"
        assert top["symbol_id"] == "src/auth/service.py::AuthService"
        assert top["name"] == "AuthService"
        assert top["kind"] == "class"
        assert top["path"] == "src/auth/service.py"
        assert top["start_line"] == 10
        assert top["end_line"] == 100
        assert top["next"] == "get_symbol"

    @pytest.mark.asyncio
    async def test_auto_routes_bare_identifier_to_symbol(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService")
        assert result["mode"] == "symbol"
        assert any(r["symbol_id"] == "src/auth/service.py::AuthService" for r in result["results"])

    @pytest.mark.asyncio
    async def test_camelcase_multitoken_qualified_match(self, setup_mcp):
        # "AuthService login" must surface AuthService.login via token coverage.
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService login", mode="symbol")
        ids = [r["symbol_id"] for r in result["results"]]
        assert "src/auth/service.py::login" in ids

    @pytest.mark.asyncio
    async def test_importable_module_path_finds_its_symbols(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("auth.service.AuthService.login", mode="symbol")
        assert result["results"][0]["symbol_id"] == "src/auth/service.py::login"
        assert result["results"][0]["qualified_name"] == "auth.service.AuthService.login"

    @pytest.mark.asyncio
    async def test_symbol_kind_filter(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("login", mode="symbol", symbol_kind="class")
        # login is a method, not a class — the kind filter removes it.
        assert all(r["kind"] == "class" for r in result["results"])
        assert not any(r["name"] == "login" for r in result["results"])

    @pytest.mark.asyncio
    async def test_no_match_falls_back_to_grep_hint(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("NonexistentSymbol", mode="symbol")
        assert result["results"] == []
        assert "grep_hint" in result

    @pytest.mark.asyncio
    async def test_excluded_symbol_dropped(self, setup_mcp, monkeypatch):
        # Exclude the auth file at query time; the symbol must not surface.
        import pathspec

        import repowise.server.mcp_server.tool_search_symbols as ss

        spec = pathspec.PathSpec.from_lines("gitwildmatch", ["src/auth/**"])
        monkeypatch.setattr(ss, "_get_exclude_spec", lambda _p: spec)

        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService", mode="symbol")
        assert result["results"] == []

    @pytest.mark.asyncio
    async def test_tombstoned_symbol_dropped(self, setup_mcp, factory):
        # Tombstone the auth service page; its symbols must be filtered out.
        from sqlalchemy import update

        from repowise.core.persistence.models import Page

        async with factory() as s:
            await s.execute(
                update(Page)
                .where(Page.id == "file_page:src/auth/service.py")
                .values(freshness_status="tombstone")
            )
            await s.commit()

        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService", mode="symbol")
        assert not any(r["path"] == "src/auth/service.py" for r in result["results"])


class TestPathSearch:
    """mode="path" / "auto" routing into file pages."""

    @pytest.mark.asyncio
    async def test_path_query_resolves_file(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("src/auth/service.py", mode="path")
        assert result["mode"] == "path"
        files = [r["path"] for r in result["results"]]
        assert "src/auth/service.py" in files
        top = result["results"][0]
        assert top["type"] == "file"
        assert top["next"] == "get_context"

    @pytest.mark.asyncio
    async def test_auto_routes_path_shaped_query(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("src/db/models.py")
        assert result["mode"] == "path"
        assert any(r["path"] == "src/db/models.py" for r in result["results"])


class TestHybridSearch:
    """Mixed natural-language + identifier queries run hybrid."""

    @pytest.mark.asyncio
    async def test_auto_routes_mixed_query_to_hybrid(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("where is AuthService defined")
        assert result["mode"] == "hybrid"

    @pytest.mark.asyncio
    async def test_hybrid_puts_symbols_first(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:src/auth/service.py",
                    "Auth Service",
                    "file_page",
                    "src/auth/service.py",
                    0.42,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("how does AuthService work", mode="hybrid")
        assert result["results"][0]["type"] == "symbol"

    @pytest.mark.asyncio
    async def test_hybrid_keeps_concept_page_alongside_symbol(self, setup_mcp):
        # A concept page for a DIFFERENT file (not the symbol's own file, which
        # would dedupe out) must survive the merge — hybrid is symbols AND pages.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:src/db/models.py",
                    "DB Models",
                    "file_page",
                    "src/db/models.py",
                    0.6,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("how does AuthService work", mode="hybrid", limit=5)
        types = {r["type"] for r in result["results"]}
        assert "symbol" in types, "symbol hit must be present"
        assert "page" in types, "concept page must survive the merge"


class TestHybridInterleave:
    """The hybrid block-interleave: symbol and concept scores are incomparable,
    so ordering is by block. Default symbols-lead, EXCEPT the score-scale trap -
    a mostly-prose query whose embedded identifier matches no symbol exactly must
    lead with concept pages, or fuzzy symbol hits bury the relevant page."""

    def _sym(self, name, file, score):
        return {"type": "symbol", "name": name, "file": file, "score": score}

    def _page(self, path, rel):
        return {"type": "page", "target_path": path, "relevance_score": rel}

    def test_prose_dominates(self):
        from repowise.server.mcp_server.tool_search import _prose_dominates

        # 6 prose tokens vs 1 identifier -> prose.
        assert _prose_dominates("how does retrieval feed synthesis in get_answer", ["get_answer"])
        # Balanced / symbol-heavy -> not prose-dominant.
        assert not _prose_dominates("compare FooBar and BazQux", ["FooBar", "BazQux"])
        # No embedded identifier -> never prose-dominant (nothing to demote).
        assert not _prose_dominates("plain english question here", [])

    def test_no_exact_prose_query_leads_with_concepts(self):
        from repowise.server.mcp_server.tool_search import _interleave_hybrid

        symbols = [self._sym("get", "a/registry.py", 43.8), self._sym("get", "b/store.py", 43.7)]
        concepts = [self._page("mcp/answer.py", 0.47)]
        out = _interleave_hybrid(
            "how does retrieval feed synthesis in get_answer",
            symbols,
            concepts,
            limit=5,
            exact=False,
        )
        assert out[0]["type"] == "page", "the answer.py page must lead, not fuzzy .get"
        # Nothing dropped - the fuzzy symbols still ride along at the tail.
        assert {s["file"] for s in symbols} <= {r.get("file") for r in out}

    def test_exact_match_keeps_symbols_first(self):
        from repowise.server.mcp_server.tool_search import _interleave_hybrid

        symbols = [self._sym("get_answer", "mcp/answer.py", 143.0)]
        concepts = [self._page("mcp/other.py", 0.5)]
        out = _interleave_hybrid(
            "where is get_answer defined", symbols, concepts, limit=5, exact=True
        )
        assert out[0]["type"] == "symbol"

    def test_symbol_heavy_query_keeps_symbols_first(self):
        from repowise.server.mcp_server.tool_search import _interleave_hybrid

        # Not prose-dominant, so default ordering even without an exact match.
        symbols = [self._sym("FooBar", "x.py", 40.0)]
        concepts = [self._page("y.py", 0.3)]
        out = _interleave_hybrid("compare FooBar BazQux", symbols, concepts, limit=5, exact=False)
        assert out[0]["type"] == "symbol"

    def test_no_concepts_returns_symbols(self):
        from repowise.server.mcp_server.tool_search import _interleave_hybrid

        symbols = [self._sym("get", "a.py", 43.0)]
        out = _interleave_hybrid(
            "how does retrieval feed synthesis in get_answer", symbols, [], limit=5, exact=False
        )
        assert out == symbols


class TestProtectedExactMatches:
    def test_canonical_symbol_id_routes_to_symbol_search(self):
        from repowise.server.mcp_server.tool_search import _resolve_mode

        query = "packages/server/src/repowise/server/mcp_server/tool_search.py::search_codebase"
        assert _resolve_mode(query, "auto") == "symbol"

    def test_canonical_symbol_id_is_stably_protected(self):
        from repowise.server.mcp_server.tool_search import _protect_exact_symbols

        exact_id = "src/auth/service.py::AuthService.run"
        symbols = [
            {"symbol_id": "src/jobs/runner.py::run", "name": "run", "score": 999.0},
            {"symbol_id": exact_id, "name": "run", "score": 1.0},
            {"symbol_id": "src/cli/main.py::main", "name": "main", "score": 500.0},
        ]

        out = _protect_exact_symbols(exact_id, symbols)

        assert out[0]["symbol_id"] == exact_id
        assert out[1:] == [symbols[0], symbols[2]]

    def test_exact_path_is_stably_protected(self):
        from repowise.server.mcp_server.tool_search import _protect_exact_paths

        exact_path = "src/auth/middleware.py"
        files = [
            {"file": "tests/auth/middleware.py", "score": 999.0},
            {"file": exact_path, "score": 1.0},
            {"file": "src/legacy/middleware.py", "score": 500.0},
        ]

        out = _protect_exact_paths(exact_path, files)

        assert out[0]["file"] == exact_path
        assert out[1:] == [files[0], files[2]]


class TestConceptModeUnchanged:
    """Forcing mode="concept" preserves the original semantic behavior."""

    @pytest.mark.asyncio
    async def test_concept_mode_runs_semantic(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await mcp_mod._vector_store.embed_and_upsert(
            "file_page:src/auth/service.py",
            "Auth Service — Main authentication service class",
            {
                "title": "Auth Service",
                "page_type": "file_page",
                "target_path": "src/auth/service.py",
            },
        )
        result = await search_codebase("AuthService", mode="concept")
        # Concept mode does not set the structural "mode" routing key.
        assert "results" in result
        assert all(r.get("type") != "symbol" for r in result["results"])
        assert all(
            "_coverage" not in r
            and "_coverage_multiplier" not in r
            and "_confidence_score_factor" not in r
            and "_raw_score" not in r
            for r in result["results"]
        )


class TestIdentifierGrepHint:
    @pytest.mark.asyncio
    async def test_multiword_query_with_identifier_gets_hint(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("where is _DEFAULT_CO_CHANGE_MIN_COUNT defined")
        assert "grep_hint" in result
        assert "_DEFAULT_CO_CHANGE_MIN_COUNT" in result["grep_hint"]

    @pytest.mark.asyncio
    async def test_camelcase_identifier_gets_hint(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("how does LanguageRegistryLoader resolve specs")
        assert "grep_hint" in result
        assert "LanguageRegistryLoader" in result["grep_hint"]

    @pytest.mark.asyncio
    async def test_plain_english_query_gets_no_hint(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("authentication flow for the service")
        assert "grep_hint" not in result


class TestExactMatchSignal:
    """An identifier query says whether any hit is an EXACT symbol match, so
    the agent doesn't anchor on a fuzzy neighbour that ranks first (finding 1)."""

    def test_has_exact_symbol_matches_name(self):
        from repowise.server.mcp_server.tool_search import _has_exact_symbol

        syms = [{"name": "get_answer", "qualified_name": "get_answer"}]
        assert _has_exact_symbol(["get_answer"], syms)
        assert not _has_exact_symbol(["get_answerX"], syms)
        assert not _has_exact_symbol([], syms)
        assert not _has_exact_symbol(["get_answer"], [])

    def test_has_exact_symbol_normalizes_separators(self):
        # An agent's "Class.method" must match a "Class::method" qualified_name.
        from repowise.server.mcp_server.tool_search import _has_exact_symbol

        syms = [{"name": "method", "qualified_name": "Class::method"}]
        assert _has_exact_symbol(["Class.method"], syms)

    def test_identifier_candidates_by_mode(self):
        from repowise.server.mcp_server.tool_search import _identifier_candidates

        assert _identifier_candidates("AuthService", "symbol") == ["AuthService"]
        assert _identifier_candidates("where is AuthService defined", "hybrid") == ["AuthService"]
        assert _identifier_candidates(
            "where does OmissionStore.get expand a reference", "hybrid"
        ) == ["OmissionStore.get"]
        assert _identifier_candidates("for example, e.g. retrieval flow", "hybrid") == []
        assert _identifier_candidates("rate limiting", "concept") == []

    def test_qualified_member_embedded_in_prose_is_protected(self):
        from repowise.server.mcp_server.tool_search import _protect_named_symbols

        exact = {
            "name": "get",
            "qualified_name": "repowise.core.distill.store.OmissionStore.get",
            "score": 1.0,
        }
        symbols = [
            {"name": "get_record", "qualified_name": "OmissionStore::get_record", "score": 99.0},
            exact,
            {"name": "get", "qualified_name": "LanguageRegistry::get", "score": 50.0},
        ]

        out = _protect_named_symbols(["OmissionStore.get"], symbols)

        assert out[0] is exact
        assert out[1:] == [symbols[0], symbols[2]]

    @pytest.mark.asyncio
    async def test_hybrid_scores_symbols_on_the_identifier_not_the_prose(
        self, setup_mcp, monkeypatch
    ):
        # Regression: the symbol scorer ranks on token overlap, so handing it the
        # whole question let prose tokens ("is" -> is_ci, "filter" ->
        # FilterRegistry) outrank the identifier the question asks after. The
        # identifier then never reached _has_exact_symbol and the response
        # claimed an indexed symbol was absent.
        #
        # Asserted on the query the scorer RECEIVES, not on ranking: a fixture
        # small enough to unit-test has no decoys to lose to, so an end-to-end
        # assertion here passes against the bug.
        from repowise.server.mcp_server import search_codebase, tool_search

        seen: list[str] = []
        real = tool_search.search_symbols_single

        async def spy(ctx, query, limit, **kwargs):
            seen.append(query)
            return await real(ctx, query, limit, **kwargs)

        monkeypatch.setattr(tool_search, "search_symbols_single", spy)

        await search_codebase("where is AuthService defined")
        assert seen == ["AuthService"], f"symbol scorer got prose, not the identifier: {seen}"

        # A query carrying no identifier still scores on the raw text.
        seen.clear()
        await search_codebase("AuthService", mode="symbol")
        assert seen == ["AuthService"]

    @pytest.mark.asyncio
    async def test_hybrid_without_identifier_scores_symbols_on_content_words(
        self, setup_mcp, monkeypatch
    ):
        # Regression for #3593: with no identifier in the question the scorer
        # got the raw prose, so "on" matched test_basic_auth_on_session.
        from repowise.server.mcp_server import search_codebase, tool_search

        seen: list[str] = []
        real = tool_search.search_symbols_single

        async def spy(ctx, query, limit, **kwargs):
            seen.append(query)
            return await real(ctx, query, limit, **kwargs)

        monkeypatch.setattr(tool_search, "search_symbols_single", spy)

        await search_codebase("retry on connection failure", mode="hybrid")
        assert seen, "symbol scorer was not called"
        assert "on" not in seen[0].split(), seen
        assert {"retry", "connection", "failure"} <= set(seen[0].split()), seen

    @pytest.mark.asyncio
    async def test_hybrid_stopword_does_not_outrank_the_content_match(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await _seed_symbol("test_basic_auth_on_session")
        await _seed_symbol("RetryTransport")

        result = await search_codebase("retry on connection failure", mode="hybrid", limit=10)
        names = [r.get("name") for r in result["results"] if r.get("type") == "symbol"]
        assert "RetryTransport" in names, names
        if "test_basic_auth_on_session" in names:
            assert names.index("RetryTransport") < names.index("test_basic_auth_on_session")

    @pytest.mark.asyncio
    async def test_symbol_mode_still_matches_stopword_identifiers(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await _seed_symbol("get_on_change")

        result = await search_codebase("get_on_change", mode="symbol")
        names = [r.get("name") for r in result["results"]]
        assert "get_on_change" in names, names

    @pytest.mark.asyncio
    async def test_exact_hit_sets_true_and_no_fuzzy_note(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthService", mode="symbol")
        assert result["exact_match"] is True
        assert "exactly matches" not in result.get("note", "")

    @pytest.mark.asyncio
    async def test_fuzzy_only_sets_false_with_note(self, setup_mcp):
        # "AuthServ" token-overlaps AuthService (a hit) but matches no symbol
        # exactly — the signal must fire even though results are non-empty. Two
        # humps, like a product name, so it is not read as a missing code name.
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthServ", mode="symbol")
        assert result["results"], "fuzzy neighbour should still be returned"
        assert result["exact_match"] is False
        assert "exactly matches" in result.get("note", "")

    @pytest.mark.asyncio
    @pytest.mark.parametrize(
        "query",
        [
            # Code-shaped names no symbol carries. "AuthServiceXyz" used to
            # return AuthService as a fuzzy neighbour, standing in for it.
            "AuthServiceXyz",
            "executeToolWithRetryBackoff",
            "validate_trigger_nonce",
            "AnthropicStreamingAdapter",
            "getToolkitMigrationPlan",
            "where is validate_trigger_nonce defined",
        ],
    )
    async def test_a_missing_code_name_returns_no_symbol(self, setup_mcp, query):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase
        from repowise.server.mcp_server._query_shape import NOT_THE_NAMED_SYMBOL

        async def fake_search(q, limit=10):
            return [_mk_result("file_page:src/db/models.py", "DB", "file_page", "", 0.9)]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase(query)
        assert not [r for r in result["results"] if r.get("type") == "symbol"]
        assert result["exact_match"] is False
        assert "No indexed symbol is named" in result["note"]
        if " " in query:
            assert result["results"], "the prose query should still return its page"
        for hit in result["results"]:
            assert hit["relation"] == NOT_THE_NAMED_SYMBOL
            assert hit["relevance_score"] <= 0.45

    @pytest.mark.asyncio
    async def test_pages_for_a_missing_name_are_capped_in_rank_order(self, setup_mcp):
        # relevance_score is what hybrid pages carry and clients rank on.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(q, limit=10):
            return [
                _mk_result("file_page:src/db/models.py", "DB", "file_page", "", 0.9),
                _mk_result("file_page:src/auth/service.py", "Auth", "file_page", "", 0.8),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("where is validate_trigger_nonce defined")
        scores = [hit["relevance_score"] for hit in result["results"]]
        assert len(scores) == 2
        assert scores == sorted(scores, reverse=True)
        assert scores[0] == 0.45 and scores[1] < 0.45

    @pytest.mark.asyncio
    async def test_a_missing_name_beside_an_indexed_one_is_still_named(self, setup_mcp):
        # Exactness is per name: AuthService is indexed, AuthServiceXyz is not.
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        async def fake_search(q, limit=10):
            return [_mk_result("file_page:src/db/models.py", "DB", "file_page", "", 0.9)]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("how does AuthService and AuthServiceXyz work")
        assert result["mode"] == "hybrid"
        assert result["exact_match"] is False
        assert "'AuthServiceXyz'" in result["note"]
        symbols = [r for r in result["results"] if r.get("type") == "symbol"]
        assert [s["name"] for s in symbols] == ["AuthService"]

    @pytest.mark.asyncio
    @pytest.mark.parametrize(
        "name, query",
        [
            ("proxyExecute", "how does proxyExecute retry"),
            ("HTTPClient", "how does HTTPClient send"),
        ],
    )
    async def test_an_indexed_name_routes_hybrid_through_the_symbol_table(
        self, setup_mcp, name, query
    ):
        # The shape regex alone misses both; the symbol table names them.
        from repowise.server.mcp_server import search_codebase

        await _seed_symbol(name)
        result = await search_codebase(query)
        assert result["mode"] == "hybrid"
        assert result["exact_match"] is True
        assert result["results"][0]["name"] == name

    @pytest.mark.asyncio
    async def test_a_product_word_no_symbol_carries_stays_concept(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("Is TypeScript used anywhere in this repo")
        assert result.get("mode") != "hybrid"
        assert "exact_match" not in result

    @pytest.mark.asyncio
    async def test_concept_query_gets_no_signal(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("authentication flow for the service")
        assert "exact_match" not in result

    @pytest.mark.asyncio
    async def test_path_search_gets_no_exact_symbol_signal(self, setup_mcp):
        """A path query names no identifier, so there is no symbol to be exact
        about.

        Regression: the response builder computed the query's identifiers into
        ``candidates`` and then rebound the same name with the *file*
        candidates, so this signal's gate became "there are results at all" and
        a path search was told that no symbol matched it.
        """
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("service.py", mode="path")
        assert result["results"], "the path search should have found something"
        assert "exact_match" not in result
        assert "note" not in result

    @pytest.mark.asyncio
    async def test_the_fuzzy_note_quotes_the_query_not_the_file_list(self, setup_mcp):
        """Same regression from the other side: the note names what the caller
        asked after, and the rebind made it name file paths instead."""
        from repowise.server.mcp_server import search_codebase

        result = await search_codebase("AuthServiceXyz", mode="symbol")
        assert "'AuthServiceXyz'" in result["note"]
        assert "'path'" not in result["note"]


class TestFusion:
    """search_codebase fuses FTS + vector via RRF, tagging each hit's sources.

    The prior path ran vector search and fell back to FTS only on zero vector
    results, so a page FTS ranked highly but vector missed never surfaced.
    """

    @pytest.mark.asyncio
    async def test_fts_only_and_vector_only_hits_both_fuse(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        for path in ("src/both.py", "src/vec.py", "src/fts.py"):
            await _seed_page(f"file_page:{path}", path)

        async def fake_vec(query, limit=10):
            return [
                _mk_result("file_page:src/both.py", "Both", "file_page", "src/both.py", 0.9),
                _mk_result("file_page:src/vec.py", "Vec", "file_page", "src/vec.py", 0.5),
            ]

        async def fake_fts(query, limit=10):
            return [
                _mk_result("file_page:src/both.py", "Both", "file_page", "src/both.py", 4.0),
                _mk_result("file_page:src/fts.py", "Fts", "file_page", "src/fts.py", 3.0),
            ]

        mcp_mod._vector_store.search = fake_vec
        mcp_mod._fts.search = fake_fts

        result = await search_codebase("session cache layer", limit=10)
        by_path = {r["path"]: r for r in result["results"]}
        # All three surface — including the FTS-only page the old path dropped.
        assert {"src/both.py", "src/vec.py", "src/fts.py"} <= set(by_path)
        assert by_path["src/vec.py"]["sources"] == ["vector"]
        assert by_path["src/fts.py"]["sources"] == ["fts"]
        assert by_path["src/both.py"]["sources"] == ["fts", "vector"]
        # A page both retrievers rank #1 fuses to the top.
        assert result["results"][0]["path"] == "src/both.py"

    @pytest.mark.asyncio
    async def test_vector_miss_falls_through_to_fts(self, setup_mcp):
        """Vector returning nothing must not blank the result — FTS still feeds."""
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("file_page:src/fts_rescue.py", "src/fts_rescue.py")

        async def empty_vec(query, limit=10):
            return []

        async def fake_fts(query, limit=10):
            return [
                _mk_result(
                    "file_page:src/fts_rescue.py", "Rescue", "file_page", "src/fts_rescue.py", 3.5
                )
            ]

        mcp_mod._vector_store.search = empty_vec
        mcp_mod._fts.search = fake_fts

        result = await search_codebase("session cache layer", limit=10)
        by_path = {r["path"]: r for r in result["results"]}
        assert by_path["src/fts_rescue.py"]["sources"] == ["fts"]


class TestSearchCandidates:
    """`candidates`: every slot the caller paid for resolves to an openable file.

    The unit-level rules live in ``test_search_candidates.py``. These drive the
    real tool, because the defect this fixes was not in the path logic — it was
    in which branch of ``search_codebase`` ever called it.
    """

    @pytest.mark.asyncio
    async def test_pages_that_are_not_files_do_not_cost_the_caller_a_slot(self, setup_mcp):
        """A module page and an onboarding page rank, and candidates still names
        two files, reached from below the caller's cut."""
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("module_page:pkg/cmd/release", "pkg/cmd/release", "module_page")
        await _seed_page(
            "onboarding:onboarding/how_it_works", "onboarding/how_it_works", "onboarding"
        )
        await _seed_page("file_page:pkg/cmd/release/list.go", "pkg/cmd/release/list.go")
        await _seed_page("file_page:pkg/cmd/release/http.go", "pkg/cmd/release/http.go")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "module_page:pkg/cmd/release", "Release", "module_page", "pkg/cmd/release", 0.90
                ),
                _mk_result(
                    "onboarding:onboarding/how_it_works",
                    "Guided Tour",
                    "onboarding",
                    "onboarding/how_it_works",
                    0.80,
                ),
                _mk_result(
                    "file_page:pkg/cmd/release/list.go",
                    "list.go",
                    "file_page",
                    "pkg/cmd/release/list.go",
                    0.70,
                ),
                _mk_result(
                    "file_page:pkg/cmd/release/http.go",
                    "http.go",
                    "file_page",
                    "pkg/cmd/release/http.go",
                    0.60,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("listing releases in order", limit=10)

        # The module page is still a legitimate ranked result.
        assert "module_page" in [r["page_type"] for r in result["results"]]
        # ...and candidates names only things that can be opened.
        assert result["candidates"] == [
            {"path": "pkg/cmd/release/list.go"},
            {"path": "pkg/cmd/release/http.go"},
        ]

    @pytest.mark.asyncio
    async def test_a_symbol_page_is_served_as_its_file(self, setup_mcp):
        """The half of A14 that never reached this branch.

        ``target_path`` keeps the page id, because callers pipe it into
        get_symbol. ``file`` and ``candidates`` carry the openable path.
        """
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page(
            "symbol_spotlight:api/client.go::HTTP", "api/client.go::HTTP", "symbol_spotlight"
        )

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "symbol_spotlight:api/client.go::HTTP",
                    "HTTP",
                    "symbol_spotlight",
                    "api/client.go::HTTP",
                    0.90,
                )
            ]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("how are requests issued", limit=10)

        hit = result["results"][0]
        assert hit["path"] == "api/client.go"
        assert "target_path" not in hit  # same string as path
        assert hit["path"] == "api/client.go"
        assert hit["symbol_id"] == "api/client.go::HTTP"
        assert hit["path"] == "api/client.go"
        assert result["candidates"] == [{"path": "api/client.go"}]

    @pytest.mark.asyncio
    async def test_no_block_when_nothing_openable_was_reached(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("repo_overview:cli", "cli", "repo_overview")

        async def fake_search(query, limit=10):
            return [_mk_result("repo_overview:cli", "Overview", "repo_overview", "cli", 0.90)]

        mcp_mod._vector_store.search = fake_search
        result = await search_codebase("what is this repository", limit=10)
        assert "candidates" not in result


async def test_an_exact_name_outranks_a_crowd_of_substring_neighbours(
    session, populated_db, setup_mcp
) -> None:
    """Exact-match protection is three mechanisms deep; this pins the result.

    The SQL candidate query front-loads exact name matches so the 400-row
    candidate cap cannot evict them, `_score_symbol` adds 100 for an exact name
    against a non-exact ceiling near 67, and `_protect_exact_symbols` partitions
    the survivor to the head before the cut to `limit`. Each layer is unit
    tested; none of them pins the outcome the caller actually sees when the
    fuzzy neighbours outnumber the result window several times over.

    So the crowd here is built to win if anything can: thirty substring matches,
    every one of them carrying maximal graph centrality and an entry-point flag,
    against one exact match with no graph node at all and a path that sorts
    last.
    """
    from repowise.core.persistence.models import GraphNode, WikiSymbol
    from repowise.server.mcp_server.tool_search import search_codebase

    rid = populated_db
    for i in range(30):
        name = f"load_from_source_{i:02d}"
        path = f"src/n{i:02d}.py"
        session.add(
            WikiSymbol(
                id=f"crowd-{i}",
                repository_id=rid,
                file_path=path,
                symbol_id=f"{path}::{name}",
                name=name,
                qualified_name=name,
                kind="function",
                signature=f"def {name}()",
                start_line=1,
                end_line=5,
                language="python",
            )
        )
        session.add(
            GraphNode(
                id=f"crowd-n-{i}",
                repository_id=rid,
                node_id=f"{path}::{name}",
                node_type="symbol",
                name=name,
                file_path=path,
                language="python",
                pagerank=0.9,
                betweenness=0.9,
                is_entry_point=True,
            )
        )
    session.add(
        WikiSymbol(
            id="crowd-exact",
            repository_id=rid,
            file_path="src/zzz_last.py",
            symbol_id="src/zzz_last.py::load",
            name="load",
            qualified_name="load",
            kind="function",
            signature="def load()",
            start_line=1,
            end_line=5,
            language="python",
        )
    )
    await session.commit()

    res = await search_codebase(query="load", limit=5)

    assert res["mode"] == "symbol"
    assert res["exact_match"] is True
    assert res["results"][0]["symbol_id"] == "src/zzz_last.py::load"


def test_rank_key_orders_same_named_symbols():
    from repowise.server.mcp_server._symbol_lookup import symbol_rank_key

    def key(name, kind, path, centrality=0.0):
        return symbol_rank_key(
            "Gadgets", name=name, qualified_name=name, kind=kind, path=path,
            centrality=centrality,
        )

    ranked = sorted(
        [
            ("GADGETS", "constant", "src/lib/gadgets.py"),
            ("gadgets", "function", "src/lib/gadgets.py"),
            ("Gadgets", "class", "docs/snippets/gadgets.py"),
            ("Gadgets", "method", "src/lib/core.py"),
            ("Gadgets", "class", "tests/test_gadgets.py"),
            ("Gadgets", "class", "src/lib/core.py"),
        ],
        key=lambda row: key(*row),
    )
    assert ranked == [
        ("Gadgets", "class", "src/lib/core.py"),
        ("Gadgets", "class", "tests/test_gadgets.py"),
        ("Gadgets", "class", "docs/snippets/gadgets.py"),
        ("Gadgets", "method", "src/lib/core.py"),
        ("gadgets", "function", "src/lib/gadgets.py"),
        ("GADGETS", "constant", "src/lib/gadgets.py"),
    ]
    # Centrality, then the shorter path, decide between otherwise equal hits.
    assert key("Gadgets", "class", "a/b/c/x.py", 0.5) < key("Gadgets", "class", "x.py")
    assert key("Gadgets", "class", "x.py") < key("Gadgets", "class", "a/x.py")


async def test_a_bare_name_search_leads_with_the_class_over_a_docs_constant(
    session, populated_db, setup_mcp
) -> None:
    """Case-folded, a docs constant and the core class share a name and score;
    the central docs file used to win the tie."""
    from repowise.core.persistence.models import GraphNode, WikiSymbol
    from repowise.server.mcp_server.tool_search import search_codebase

    rid = populated_db
    rows = [
        ("docs/snippets/listing.py", "GIZMOS", "constant", 0.9),
        ("src/gizmo/core.py", "Gizmos", "class", 0.01),
    ]
    for path, name, kind, pagerank in rows:
        session.add(
            WikiSymbol(
                id=f"gz-{name}", repository_id=rid, file_path=path,
                symbol_id=f"{path}::{name}", name=name, qualified_name=name,
                kind=kind, signature=name, start_line=1, end_line=5, language="python",
            )
        )
        for node_id in (path, f"{path}::{name}"):
            session.add(
                GraphNode(
                    id=f"gzn-{node_id}", repository_id=rid, node_id=node_id,
                    node_type="file" if node_id == path else "symbol", name=name,
                    file_path=path, language="python", pagerank=pagerank,
                    betweenness=pagerank,
                )
            )
    await session.commit()

    res = await search_codebase(query="Gizmos", limit=5)
    assert [r["symbol_id"] for r in res["results"][:2]] == [
        "src/gizmo/core.py::Gizmos",
        "docs/snippets/listing.py::GIZMOS",
    ]
    res = await search_codebase(query="gizmos", limit=5)
    assert res["results"][0]["symbol_id"] == "src/gizmo/core.py::Gizmos"


async def test_an_exact_test_class_outranks_an_exact_code_function(
    session, populated_db, setup_mcp
) -> None:
    """For exact matches the shared key decides, and it ranks kind before test path."""
    from repowise.core.persistence.models import WikiSymbol
    from repowise.server.mcp_server.tool_search import search_codebase

    rid = populated_db
    for path, kind in (("src/widget/core.py", "function"), ("tests/test_widget.py", "class")):
        session.add(
            WikiSymbol(
                id=f"wd-{path}", repository_id=rid, file_path=path,
                symbol_id=f"{path}::Widgets", name="Widgets", qualified_name="Widgets",
                kind=kind, signature="Widgets", start_line=1, end_line=5, language="python",
            )
        )
    await session.commit()

    res = await search_codebase(query="Widgets", limit=5)
    assert [r["symbol_id"] for r in res["results"][:2]] == [
        "tests/test_widget.py::Widgets",
        "src/widget/core.py::Widgets",
    ]


def _add_symbols(session, rid, rows):
    """Seed ``(path, name, qualified_name, line)`` WikiSymbol rows."""
    from repowise.core.persistence.models import WikiSymbol

    for path, name, qualified, line in rows:
        session.add(
            WikiSymbol(
                id=f"dw-{path}-{qualified}", repository_id=rid, file_path=path,
                symbol_id=f"{path}::{qualified}", name=name, qualified_name=qualified,
                kind="function", signature=name, start_line=line, end_line=line + 5,
                language="python",
            )
        )


_WIDGET_ROWS = [
    ("src/widget/core.py", "widget", "widget", 10),
    ("src/widget/core.py", "widget", "Box.widget", 40),
    ("src/widget/listing.py", "widget_list", "widget_list", 1),
    ("src/widget/drop.py", "widget_drop", "widget_drop", 1),
    ("src/widget/sync.py", "widget_sync", "widget_sync", 1),
]


class TestDistinctFileWindow:
    """Code-location windows spend ``limit`` on distinct files."""

    def test_collapse_folds_same_file_symbols_and_keeps_repos_apart(self):
        from repowise.server.mcp_server.tool_search import _collapse_by_file

        hits = [
            {"type": "symbol", "name": "a", "file": "x.py", "start_line": 1},
            {"type": "symbol", "name": "b", "file": "x.py", "start_line": 9},
            {"type": "symbol", "name": "c", "file": "x.py", "start_line": 5, "repo": "other"},
            {"page_type": "module_page", "target_path": "pkg"},
            {"page_type": "file_page", "target_path": "y.py"},
            {"page_type": "symbol_spotlight", "target_path": "y.py"},
        ]
        out = _collapse_by_file(hits)
        assert [h.get("name") or h["target_path"] for h in out] == ["a", "c", "pkg", "y.py"]
        assert out[0]["symbols"] == ["b:9"]
        assert "symbols" not in out[1]

    def test_a_dominant_file_counts_what_its_cap_left_out(self):
        from repowise.server.mcp_server.tool_search import _collapse_by_file

        hits = [
            {"type": "symbol", "name": f"s{i}", "file": "x.py", "start_line": i}
            for i in range(10)
        ]
        (row,) = _collapse_by_file(hits)
        assert row["symbols"] == ["s1:1", "s2:2", "s3:3", "s4:4", "s5:5", "+4 more"]

    def test_pages_are_dropped_only_for_symbols_the_window_shows(self):
        from repowise.server.mcp_server.tool_search import _hybrid_window

        def sym(f):
            return {"type": "symbol", "name": "x", "file": f}

        def page(f):
            return {"type": "page", "target_path": f, "relevance_score": 0.5}

        # Four symbol files, but limit 4 with three pages shows only two
        # symbols, so the page for d.py is the only way d.py is served.
        symbols = [sym("a.py"), sym("b.py"), sym("c.py"), sym("d.py")]
        out = _hybrid_window(
            "compare Foo Bar", symbols, [page("d.py"), page("e.py"), page("f.py")], 4, True
        )
        assert [r.get("file") or r["target_path"] for r in out] == ["a.py", "b.py", "d.py", "e.py"]
        # A page whose file a shown symbol covers gives its slot back.
        out = _hybrid_window(
            "compare Foo Bar", symbols, [page("b.py"), page("e.py"), page("f.py")], 4, True
        )
        assert [r.get("file") or r["target_path"] for r in out] == ["a.py", "b.py", "e.py", "f.py"]

    @pytest.mark.asyncio
    async def test_the_federated_page_leg_serves_one_row_per_file(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server._helpers import _resolve_repo_context
        from repowise.server.mcp_server.tool_search import _search_single_repo

        await _seed_page("file_page:api/client.go", "api/client.go")
        await _seed_page(
            "symbol_spotlight:api/client.go::HTTP", "api/client.go::HTTP", "symbol_spotlight"
        )
        await _seed_page("file_page:api/server.go", "api/server.go")

        async def fake_search(query, limit=10):
            return [
                _mk_result("file_page:api/client.go", "c", "file_page", "api/client.go", 0.9),
                _mk_result(
                    "symbol_spotlight:api/client.go::HTTP",
                    "HTTP",
                    "symbol_spotlight",
                    "api/client.go::HTTP",
                    0.8,
                ),
                _mk_result("file_page:api/server.go", "s", "file_page", "api/server.go", 0.7),
            ]

        mcp_mod._vector_store.search = fake_search
        out = await _search_single_repo(await _resolve_repo_context(None), "requests", 2, None)
        assert [r["target_path"] for r in out] == ["api/client.go", "api/server.go"]

    @pytest.mark.asyncio
    async def test_hybrid_limit_buys_distinct_files(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        _add_symbols(session, populated_db, _WIDGET_ROWS)
        await session.commit()

        res = await search_codebase("widget", mode="hybrid", limit=3)
        files = [r["path"] for r in res["results"]]
        assert len(files) == 3 and len(set(files)) == 3
        # The exact name still leads, carrying its same-file sibling.
        lead = res["results"][0]
        assert lead["symbol_id"] == "src/widget/core.py::Box.widget"
        assert lead["symbols"] == ["widget:10"]

    @pytest.mark.asyncio
    async def test_symbol_mode_still_lists_each_overload(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        _add_symbols(session, populated_db, _WIDGET_ROWS)
        await session.commit()

        res = await search_codebase("widget", mode="symbol", limit=3)
        ids = [r["symbol_id"] for r in res["results"]]
        assert ids[:2] == ["src/widget/core.py::Box.widget", "src/widget/core.py::widget"]
        assert all("symbols" not in r for r in res["results"])
        # Symbol rows serve path, with file as the transition alias.
        assert all(r["path"] == "src/widget/core.py" and "file" not in r for r in res["results"][:2])

    @pytest.mark.asyncio
    async def test_concept_window_serves_one_row_per_file(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase

        await _seed_page("file_page:api/client.go", "api/client.go")
        await _seed_page(
            "symbol_spotlight:api/client.go::HTTP", "api/client.go::HTTP", "symbol_spotlight"
        )
        await _seed_page("file_page:api/server.go", "api/server.go")

        async def fake_search(query, limit=10):
            return [
                _mk_result("file_page:api/client.go", "client.go", "file_page", "api/client.go", 0.9),
                _mk_result(
                    "symbol_spotlight:api/client.go::HTTP",
                    "HTTP",
                    "symbol_spotlight",
                    "api/client.go::HTTP",
                    0.8,
                ),
                _mk_result("file_page:api/server.go", "server.go", "file_page", "api/server.go", 0.7),
            ]

        mcp_mod._vector_store.search = fake_search
        res = await search_codebase("how are requests issued", mode="concept", limit=2)
        assert [r["path"] for r in res["results"]] == ["api/client.go", "api/server.go"]


class TestPathlessPagesInCodeLocationModes:
    """Hybrid windows drop pages naming no file; concept windows keep them."""

    async def _seed(self):
        import repowise.server.mcp_server as mcp_mod

        await _seed_page("module_page:pkg/cmd/release", "pkg/cmd/release", "module_page")
        await _seed_page(
            "onboarding:onboarding/how_it_works", "onboarding/how_it_works", "onboarding"
        )
        await _seed_page("file_page:pkg/cmd/release/list.go", "pkg/cmd/release/list.go")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "module_page:pkg/cmd/release", "Release", "module_page", "pkg/cmd/release", 0.9
                ),
                _mk_result(
                    "onboarding:onboarding/how_it_works",
                    "Guided Tour",
                    "onboarding",
                    "onboarding/how_it_works",
                    0.8,
                ),
                _mk_result(
                    "file_page:pkg/cmd/release/list.go",
                    "list.go",
                    "file_page",
                    "pkg/cmd/release/list.go",
                    0.7,
                ),
            ]

        mcp_mod._vector_store.search = fake_search

    @pytest.mark.asyncio
    async def test_hybrid_drops_module_and_onboarding_pages(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await self._seed()
        res = await search_codebase("listing releases in order", mode="hybrid", limit=5)
        pages = [r["page_type"] for r in res["results"] if r["type"] == "page"]
        assert pages == ["file_page"]

    @pytest.mark.asyncio
    async def test_concept_keeps_them(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await self._seed()
        res = await search_codebase("listing releases in order", mode="concept", limit=5)
        assert [r["page_type"] for r in res["results"]] == [
            "module_page",
            "onboarding",
            "file_page",
        ]

    @pytest.mark.asyncio
    async def test_concept_rows_carry_path_only_when_they_name_a_file(self, setup_mcp):
        """A pathless page keeps its key in target_path; a file page's moves to path."""
        from repowise.server.mcp_server import search_codebase

        await self._seed()
        res = await search_codebase("listing releases in order", mode="concept", limit=5)
        module, onboarding, file_page = res["results"]
        for pathless, key in ((module, "pkg/cmd/release"), (onboarding, "onboarding/how_it_works")):
            assert "path" not in pathless
            assert pathless["target_path"] == key
        assert file_page["path"] == "pkg/cmd/release/list.go"
        assert "target_path" not in file_page
        # page_type + path rebuild the id, so it is dropped; citations rebuild
        # it from path the same way.
        assert "page_id" not in file_page
        assert f"{file_page['page_type']}:{file_page['path']}" == "file_page:pkg/cmd/release/list.go"

    @pytest.mark.asyncio
    async def test_federated_rows_carry_path(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await self._seed()
        res = await search_codebase("listing releases in order", mode="concept", repo="all")
        by_type = {r["page_type"]: r for r in res["results"]}
        assert by_type["file_page"]["path"] == "pkg/cmd/release/list.go"
        assert "path" not in by_type["module_page"]

    @pytest.mark.asyncio
    async def test_an_empty_window_does_not_repeat_its_grep_hint(self, setup_mcp):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase
        from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT

        await _seed_page("module_page:pkg/cmd/release", "pkg/cmd/release", "module_page")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "module_page:pkg/cmd/release", "Release", "module_page", "pkg/cmd/release", 0.9
                )
            ]

        mcp_mod._vector_store.search = fake_search
        res = await search_codebase("where is validate_trigger_nonce defined", mode="hybrid")
        assert res["results"] == []
        assert "No indexed symbol is named" in res["note"]
        assert "Any page here" not in res["note"]
        assert EXHAUSTIVE_SWEEP_HINT not in res["note"]
        assert EXHAUSTIVE_SWEEP_HINT in res["grep_hint"]

    @pytest.mark.asyncio
    async def test_hybrid_keeps_them_when_pages_are_asked_for(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await self._seed()
        res = await search_codebase(
            "listing releases in order", mode="hybrid", page_type="module_page"
        )
        pages = [r["page_type"] for r in res["results"] if r["type"] == "page"]
        assert pages == ["module_page"]


class TestNamedPathBoost:
    """A query word that names a file's path lifts that file, by its rarity."""

    def _hits(self, carbon: float, pynput: float) -> list[dict]:
        return [
            {"target_path": "services/_hotkey_carbon.py", "relevance_score": carbon},
            {"target_path": "services/_hotkey_pynput.py", "relevance_score": pynput},
        ]

    def _boost(self, hits: list[dict], query: str, df: dict, total: int = 854) -> list[str]:
        from repowise.server.mcp_server._retrieval_rank import boost_named_paths

        boost_named_paths(hits, query, df, total, score_key="relevance_score")
        hits.sort(key=lambda h: -h["relevance_score"])
        return [h["target_path"] for h in hits]

    def test_a_rare_path_word_lifts_the_file_it_names(self):
        df = {"hotkey": 7, "pynput": 1, "backend": 3, "services": 120}
        order = self._boost(self._hits(2.4, 2.0), "register global hotkey pynput backend", df)
        assert order[0] == "services/_hotkey_pynput.py"

    def test_a_common_path_word_stays_neutral(self):
        hits = [{"target_path": "services/a.py", "relevance_score": 1.0}]
        self._boost(hits, "services registry", {"services": 300})
        assert hits[0]["relevance_score"] < 1.05

    def test_a_path_match_cannot_beat_a_much_stronger_content_match(self):
        order = self._boost(self._hits(9.0, 2.0), "hotkey pynput", {"hotkey": 7, "pynput": 1})
        assert order[0] == "services/_hotkey_carbon.py"

    def test_a_tiny_repo_gets_no_boost(self):
        hits = self._hits(3.0, 2.0)
        self._boost(hits, "pynput", {"pynput": 1}, total=12)
        assert [h["relevance_score"] for h in hits] == [3.0, 2.0]

    def test_extensions_stopwords_and_short_words_never_count(self):
        from repowise.server.mcp_server._retrieval_rank import path_word_counts, path_words

        assert path_words("src/the/io_utils.json") == {"src", "the", "utils"}
        assert path_word_counts(["a/models.py", "b/models.ts"])["models"] == 2
        hits = [{"target_path": "the/py/json.py", "relevance_score": 1.0}]
        self._boost(hits, "the py io", {"the": 1, "py": 1, "io": 1}, total=100)
        assert hits[0]["relevance_score"] == 1.0

    @pytest.mark.asyncio
    @pytest.mark.parametrize("leg", ["concept", "hybrid"])
    async def test_search_ranks_the_named_file_first(self, setup_mcp, leg):
        import repowise.server.mcp_server as mcp_mod
        from repowise.server.mcp_server import search_codebase
        from repowise.server.mcp_server._helpers import _resolve_repo_context
        from repowise.server.mcp_server.tool_search import _search_single_repo

        await _seed_page("file_page:services/_hotkey_carbon.py", "services/_hotkey_carbon.py")
        await _seed_page("file_page:services/_hotkey_pynput.py", "services/_hotkey_pynput.py")
        for n in range(30):  # past the tiny-repo floor
            await _seed_page(f"file_page:pkg/mod_{n}.py", f"pkg/mod_{n}.py")

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:services/_hotkey_carbon.py",
                    "Register a global hotkey backend, not pynput",
                    "file_page", "services/_hotkey_carbon.py", 0.9,
                ),
                _mk_result(
                    "file_page:services/_hotkey_pynput.py", "Register a global hotkey backend",
                    "file_page", "services/_hotkey_pynput.py", 0.8,
                ),
            ]

        mcp_mod._vector_store.search = fake_search
        mcp_mod._fts.search = fake_search
        query = "register global hotkey pynput backend"
        if leg == "concept":
            rows = (await search_codebase(query, mode="concept"))["results"]
        else:  # the page leg hybrid search runs
            rows = await _search_single_repo(await _resolve_repo_context(None), query, 5, None)
        assert (rows[0].get("path") or rows[0]["target_path"]) == "services/_hotkey_pynput.py"


class TestPathModeWithWords:
    def test_path_tokens(self):
        from repowise.server.mcp_server._query_shape import path_tokens

        assert path_tokens("services/_hotkey_pynput.py register hotkey") == [
            "services/_hotkey_pynput.py"
        ]
        assert path_tokens(r"see `src\a.py:120`, then b.ts.") == [r"src\a.py", "b.ts"]
        assert path_tokens("register hotkey") == []

    def test_path_tokens_skip_urls_prose_slashes_and_member_suffixes(self):
        from repowise.server.mcp_server._query_shape import path_tokens

        paths = ["src/client/http.py", "docs/guide.md"]
        assert path_tokens("see https://x.dev/a.py and/or client/server", paths) == []
        assert path_tokens("tests/a.py::test_x fails") == ["tests/a.py"]
        assert path_tokens("look in src/client please", paths) == ["src/client"]
        assert path_tokens("look in src/client please") == []

    @pytest.mark.asyncio
    async def test_words_around_a_path_do_not_empty_the_result(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        await _seed_page("file_page:services/_hotkey_pynput.py", "services/_hotkey_pynput.py")
        result = await search_codebase(
            "services/_hotkey_pynput.py register hotkey", mode="path"
        )
        assert [r["path"] for r in result["results"]] == ["services/_hotkey_pynput.py"]


class TestSymbolModeExactOnly:
    @pytest.mark.asyncio
    async def test_an_exact_match_is_returned_alone(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        _add_symbols(session, populated_db, _WIDGET_ROWS)
        await session.commit()

        res = await search_codebase("widget", mode="symbol", limit=5)
        assert sorted(r["symbol_id"] for r in res["results"]) == [
            "src/widget/core.py::Box.widget",
            "src/widget/core.py::widget",
        ]
        assert res["fuzzy_omitted"] == 3
        assert res["exact_match"] is True
        assert res["note"].startswith("3 other symbols contain this name")

    @pytest.mark.asyncio
    async def test_fuzzy_omitted_counts_past_the_limit(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        _add_symbols(session, populated_db, _WIDGET_ROWS)
        await session.commit()

        res = await search_codebase("widget", mode="symbol", limit=1)
        assert len(res["results"]) == 1
        assert res["results"][0]["name"] == "widget"
        assert res["fuzzy_omitted"] == 3

    @pytest.mark.asyncio
    async def test_a_shared_token_is_not_a_name_neighbour(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        _add_symbols(session, populated_db, [
            ("src/carbon.py", "CarbonRegistrar", "CarbonRegistrar", 1),
            ("src/tools.py", "carbon_tools", "carbon_tools", 1),
            ("src/reg.py", "registrar_for", "registrar_for", 1),
        ])
        await session.commit()

        res = await search_codebase("CarbonRegistrar", mode="symbol")
        assert [r["name"] for r in res["results"]] == ["CarbonRegistrar"]
        assert "fuzzy_omitted" not in res
        assert "note" not in res

    @pytest.mark.asyncio
    async def test_no_exact_match_keeps_the_fuzzy_list(self, setup_mcp):
        from repowise.server.mcp_server import search_codebase

        res = await search_codebase("AuthServ", mode="symbol")
        assert res["results"]
        assert "fuzzy_omitted" not in res
        assert "exactly matches" in res["note"]


class TestHitSymbols:
    """File rows name the symbols inside them that the query's words match."""

    @staticmethod
    async def _seed_symbols(session, rid):
        from repowise.core.persistence.models import WikiSymbol

        wav = "services/wav_metadata.py"
        rows = [
            (wav, "write_bext_chunk", 42, "public", "def write_bext_chunk(f)", "function", None),
            (wav, "_list_info_bytes", 88, "private", "def _list_info_bytes()", "function", None),
            (wav, "read_header", 10, "public", "def read_header(f)", "function", None),
            (wav, "bext_version", 3, "public", "bext_version = 2", "constant", None),
            (wav, "stamp_list_info", 120, "public", "def stamp_list_info(self)", "method", "WavWriter"),
            # No real line: never served.
            (wav, "bext_info_list", 0, "public", "def bext_info_list()", "function", None),
            ("services/mixer.py", "mix_tracks", 5, "public", "def mix_tracks()", "function", None),
        ]
        for i, (path, name, line, vis, sig, kind, parent) in enumerate(rows):
            qualified = f"services.wav_metadata.{parent}.{name}" if parent else name
            session.add(
                WikiSymbol(
                    id=f"hit-sym-{i}",
                    repository_id=rid,
                    file_path=path,
                    symbol_id=f"{path}::{name}",
                    name=name,
                    qualified_name=qualified,
                    parent_name=parent,
                    kind=kind,
                    signature=sig,
                    start_line=line,
                    end_line=line + 5,
                    visibility=vis,
                    language="python",
                )
            )
        await session.commit()

    @staticmethod
    def _fake_vector():
        import repowise.server.mcp_server as mcp_mod

        async def fake_search(query, limit=10):
            return [
                _mk_result(
                    "file_page:services/wav_metadata.py",
                    "WAV metadata",
                    "file_page",
                    "services/wav_metadata.py",
                    0.8,
                ),
                _mk_result(
                    "file_page:services/mixer.py", "Mixer", "file_page", "services/mixer.py", 0.6
                ),
            ]

        mcp_mod._vector_store.search = fake_search

    @pytest.mark.asyncio
    async def test_a_prose_query_names_the_matching_symbol_and_line(
        self, session, populated_db, setup_mcp
    ):
        from repowise.server.mcp_server import search_codebase

        await self._seed_symbols(session, populated_db)
        await _seed_page("file_page:services/wav_metadata.py", "services/wav_metadata.py")
        await _seed_page("file_page:services/mixer.py", "services/mixer.py")
        self._fake_vector()

        res = await search_codebase("which function stamps bext and LIST info into wav files")
        by_path = {r["path"]: r for r in res["results"]}
        # Most query words first; a function outranks an equally matched constant.
        assert by_path["services/wav_metadata.py"]["symbols"] == [
            "WavWriter.stamp_list_info:120",
            "_list_info_bytes:88",
            "write_bext_chunk:42",
        ]
        # No symbol in the mixer shares a word with the query.
        assert "symbols" not in by_path["services/mixer.py"]

        hybrid = await search_codebase(
            "where does wav_metadata stamp bext or mix tracks", mode="hybrid"
        )
        by_path = {r["path"]: r for r in hybrid["results"]}
        # The hybrid page leg names symbols; the symbol row standing in for
        # wav_metadata.py already names its own and gets no list.
        assert by_path["services/mixer.py"]["symbols"] == ["mix_tracks:5"]
        assert by_path["services/wav_metadata.py"]["type"] == "symbol"
        assert "symbols" not in by_path["services/wav_metadata.py"]

    @pytest.mark.asyncio
    async def test_one_symbol_query_serves_every_file_row(
        self, engine, session, populated_db, setup_mcp
    ):
        from sqlalchemy import event

        from repowise.server.mcp_server import search_codebase

        await self._seed_symbols(session, populated_db)
        await _seed_page("file_page:services/wav_metadata.py", "services/wav_metadata.py")
        await _seed_page("file_page:services/mixer.py", "services/mixer.py")
        self._fake_vector()

        statements: list[str] = []

        def record(conn, cursor, statement, *args):
            statements.append(statement)

        event.listen(engine.sync_engine, "before_cursor_execute", record)
        try:
            res = await search_codebase("which function stamps bext and mix tracks", mode="concept")
        finally:
            event.remove(engine.sync_engine, "before_cursor_execute", record)

        assert {r["path"] for r in res["results"] if r.get("symbols")} == {
            "services/wav_metadata.py",
            "services/mixer.py",
        }
        file_scoped = [s for s in statements if "wiki_symbols.file_path IN" in s]
        assert len(file_scoped) == 1

    def test_a_package_word_shared_by_most_hits_names_no_symbol(self):
        from repowise.server.mcp_server._hit_symbols import _package_terms

        paths = {"src/flask/app.py", "src/flask/cli.py", "src/flask/json/provider.py"}
        # "flask" is every hit's package; "json" is one hit's topic.
        assert _package_terms({"flask", "json", "route"}, paths) == {"flask"}
        assert _package_terms({"flask"}, {"src/flask/app.py"}) == set()

    @pytest.mark.asyncio
    async def test_a_lone_symbol_row_gets_no_list(self, session, populated_db, setup_mcp):
        from repowise.server.mcp_server._helpers import _resolve_repo_context
        from repowise.server.mcp_server._hit_symbols import attach_hit_symbols

        await self._seed_symbols(session, populated_db)
        symbol_row = {"type": "symbol", "name": "write_bext_chunk", "file": "services/wav_metadata.py"}
        page_row = {"page_type": "file_page", "target_path": "services/wav_metadata.py"}
        ctx = await _resolve_repo_context(None)
        await attach_hit_symbols(ctx, "stamp bext", [symbol_row, page_row])
        assert "symbols" not in symbol_row
        assert page_row["symbols"][0] == "write_bext_chunk:42"

    @pytest.mark.asyncio
    async def test_a_failed_lookup_leaves_the_response_intact(
        self, session, populated_db, setup_mcp, monkeypatch
    ):
        from repowise.server.mcp_server import _hit_symbols, search_codebase

        await self._seed_symbols(session, populated_db)
        await _seed_page("file_page:services/wav_metadata.py", "services/wav_metadata.py")
        await _seed_page("file_page:services/mixer.py", "services/mixer.py")
        self._fake_vector()

        async def boom(*args, **kwargs):
            raise RuntimeError("symbol table unavailable")

        monkeypatch.setattr(_hit_symbols, "_attach", boom)
        res = await search_codebase("which function stamps bext into wav files", mode="concept")
        assert [r["path"] for r in res["results"]] == [
            "services/wav_metadata.py",
            "services/mixer.py",
        ]
        assert not any("symbols" in r for r in res["results"])


_SERVED_SNIPPETS = {
    "src/session/cache.py": "# src/session/cache.py\n\n## Overview\n\nKeeps session rows warm.",
    "pkg/store.go": "# pkg/store.go\r\n\r\nSession store backed by a map.",
    "lib/layer.rb": "Cache layer with no heading. ## not a heading here",
    "docs/only.md": "# docs/only.md\n\n## Overview\n",
}


class TestServedSnippet:
    """A served snippet starts at the page text; ranking still reads the heading."""

    async def _search(self, monkeypatch, strip):
        import repowise.server.mcp_server as mcp_mod
        from repowise.core.persistence.search import SearchResult
        from repowise.server.mcp_server import search_codebase, tool_search

        monkeypatch.setattr(tool_search, "strip_leading_headings", strip)

        def hits(scale):
            return [
                SearchResult(
                    page_id=f"file_page:{path}",
                    title=path,
                    page_type="file_page",
                    target_path=path,
                    score=scale * (4 - i),
                    snippet=snippet,
                    search_type="fulltext",
                )
                for i, (path, snippet) in enumerate(_SERVED_SNIPPETS.items())
            ]

        async def fake_vec(query, limit=10):
            return hits(0.2)

        async def fake_fts(query, limit=10):
            return hits(1.0)

        monkeypatch.setattr(mcp_mod._vector_store, "search", fake_vec)
        monkeypatch.setattr(mcp_mod._fts, "search", fake_fts)
        return await search_codebase("session cache layer", limit=10, mode="concept")

    @pytest.mark.asyncio
    async def test_rows_match_the_unstripped_search_except_the_snippet(
        self, setup_mcp, monkeypatch
    ):
        for path in _SERVED_SNIPPETS:
            await _seed_page(f"file_page:{path}", path)

        raw = await self._search(monkeypatch, lambda text: text)
        served = await self._search(monkeypatch, strip_leading_headings)

        def without_snippet(rows):
            return [{k: v for k, v in row.items() if k != "snippet"} for row in rows]

        assert without_snippet(served["results"]) == without_snippet(raw["results"])
        assert served.get("candidates") == raw.get("candidates")
        snippets = {row["path"]: row["snippet"] for row in served["results"]}
        assert snippets == {
            "src/session/cache.py": "Keeps session rows warm.",
            "pkg/store.go": "Session store backed by a map.",
            "lib/layer.rb": "Cache layer with no heading. ## not a heading here",
            "docs/only.md": "# docs/only.md\n\n## Overview\n",
        }