test_mcp_routing.py

tests/test_mcp_routing.py

One server process, many target repositories — the target travels on the CALL.

test_a_bare_root_with_first_party_defaults_to_it

None test_mcp_routing.test_a_bare_root_with_first_party_defaults_to_it(Path tmp_path)

With a first-party sub-index present, a bare root defaults to it.

tests/test_mcp_routing.py:634

Checks

  • assert resolved.slug == first_party.slug, ("a bare root with a first-party sub-index must default to it, not refuse or guess" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-001measuredtest_a_bare_root_with_first_party_defaults_to_it → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_bare_root_with_first_party_defaults_to_it → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_a_bare_root_with_first_party_defaults_to_it → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 29 lines
def test_a_bare_root_with_first_party_defaults_to_it(tmp_path: Path) -> None:
    """OWNER RULING: first-party IS the index for a split repository, never one of several
    coequal sub-indexes guessed among. `Answering`'s docstring names the failure this module
    guards hardest against — "answering from the wrong index is this project's most expensive
    recorded defect" — and treating a repo's OWN source as just another name to disambiguate
    among was itself heading toward that shape: every plain call to a split repository would
    have had to name `sub_index='first-party'` explicitly or be refused, breaking the server's
    own served promise that omitting `target`/`sub_index` still gets an answer.

    A vendored sibling is reached only by FOLLOWING AN EDGE that names it (Phase 2), never by
    being offered as a coin-flip default alongside first-party.

    @brief A bare root with a first-party sibling resolves to it, not to a refusal.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "onlysubs"
    repo.mkdir()

    first_party = reg.register(repo, name="first-party")
    reg.register(repo, name="llama-cpp")

    resolved = state.resolve_target(str(repo.resolve()))
    assert resolved.slug == first_party.slug, (
        "a bare root with a first-party sub-index must default to it, not refuse or guess"
    )

Activity · 8 steps
lines 649–649reg = st.TargetRegistry(tmp_path / "state")lines 650–650_mcp, state = build_server(reg)lines 651–651repo = tmp_path / "onlysubs"lines 652–652repo.mkdir()lines 654–654first_party = reg.register(repo, name="first-party")lines 655–655reg.register(repo, name="llama-cpp")lines 657–657resolved = state.resolve_target(str(repo.resolve()))lines 658–660assert resolved.slug == first_party.slug, ( "a bare root with a first-party sub-index must default to it, not refuse or guess" )

test_a_bare_root_with_only_vendored_siblings_is_refused

None test_mcp_routing.test_a_bare_root_with_only_vendored_siblings_is_refused(Path tmp_path)

With only vendored sub-indexes (no first-party, no whole), a bare root is refused.

tests/test_mcp_routing.py:667

Checks

  • assert "llama-cpp" in message and "opencv" in message, message

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-MCP-001measuredtest_a_bare_root_with_only_vendored_siblings_is_refused → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_bare_root_with_only_vendored_siblings_is_refused → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_a_bare_root_with_only_vendored_siblings_is_refused → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 26 lines
def test_a_bare_root_with_only_vendored_siblings_is_refused(tmp_path: Path) -> None:
    """THE GENUINELY UNGUESSABLE CASE. Once first-party is preferred as the default, this is
    the only shape left with no principled default: a repo split with no first-party record and
    no whole-repository record either — an unconventional registry state (e.g. only a vendored
    tree was ever explicitly built), not the shape `derive_sub_indexes` produces. Refusing and
    naming the alternatives beats guessing among coequal-looking siblings for the same reason it
    always has: a caller who cannot act on the error is being told half of one.

    @brief A bare root with only vendored siblings raises and lists them.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "onlyvendored"
    repo.mkdir()

    reg.register(repo, name="llama-cpp")
    reg.register(repo, name="opencv")

    with pytest.raises(RuntimeError) as excinfo:
        state.resolve_target(str(repo.resolve()))
    message = str(excinfo.value)
    ## The names are the actionable half; without them the caller knows only that it failed.
    assert "llama-cpp" in message and "opencv" in message, message

Activity · 10 steps
lines 678–678reg = st.TargetRegistry(tmp_path / "state")lines 679–679_mcp, state = build_server(reg)lines 680–680repo = tmp_path / "onlyvendored"lines 681–681repo.mkdir()lines 683–683reg.register(repo, name="llama-cpp")lines 684–684reg.register(repo, name="opencv")lines 686–686with pytest.raises(RuntimeError) as excinfolines 687–687state.resolve_target(str(repo.resolve()))lines 688–688message = str(excinfo.value)lines 690–690assert "llama-cpp" in message and "opencv" in message, message

test_a_known_but_unbuilt_target_names_the_action_that_fixes_it

None test_mcp_routing.test_a_known_but_unbuilt_target_names_the_action_that_fixes_it(Path tmp_path)

An unbuilt routed target is refused with the remedy spelled out.

tests/test_mcp_routing.py:442

Checks

  • assert str(repo) in message
  • assert "index(action='refresh'" in message assert "target=" in message, "the remedy must be a call that names THIS target"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-MCP-001measuredtest_a_known_but_unbuilt_target_names_the_action_that_fixes_it → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_known_but_unbuilt_target_names_the_action_that_fixes_it → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_a_known_but_unbuilt_target_names_the_action_that_fixes_it → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 25 lines
async def test_a_known_but_unbuilt_target_names_the_action_that_fixes_it(
    tmp_path: Path,
) -> None:
    """ "Registered but never built" is the ordinary first state of a new target, and it
    must not surface as a bare sqlite "unable to open database file". The refusal names
    `build_or_refresh` WITH the target argument, so the advice is a call the caller can
    make rather than one that would build the wrong repository.

    @brief An unbuilt routed target is refused with the remedy spelled out.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "registered_not_built"
    repo.mkdir()
    reg.register(str(repo))

    with pytest.raises(RuntimeError) as exc:
        state.tools.graph_stats(target=str(repo))
    message = str(exc.value)
    assert str(repo) in message
    assert "index(action='refresh'" in message
    assert "target=" in message, "the remedy must be a call that names THIS target"

Activity · 11 steps
lines 453–453reg = st.TargetRegistry(tmp_path / "state")lines 454–454_mcp, state = build_server(reg)lines 455–455repo = tmp_path / "registered_not_built"lines 456–456repo.mkdir()lines 457–457reg.register(str(repo))lines 459–459with pytest.raises(RuntimeError) as exclines 460–460state.tools.graph_stats(target=str(repo))lines 461–461message = str(exc.value)lines 462–462assert str(repo) in messagelines 463–463assert "index(action='refresh'" in messagelines 464–464assert "target=" in message, "the remedy must be a call that names THIS target"

test_a_routed_build_registers_the_target_without_adopting_it

None test_mcp_routing.test_a_routed_build_registers_the_target_without_adopting_it(Path tmp_path)

A routed build registers its target and leaves the active one untouched.

tests/test_mcp_routing.py:488

Checks

  • assert result["ok"] is True and result["built"] is True
  • assert result["target"] == str(fresh)
  • assert Path(state.active.repo_path) == derived, "a routed build must not retarget"
  • assert str(fresh) in [t.repo_path for t in reg.targets()], "but must be registered"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_a_routed_build_registers_the_target_without_adopting_it → write_build_signature
REQ-DDB-CONFIG-007measuredtest_a_routed_build_registers_the_target_without_adopting_it → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_a_routed_build_registers_the_target_without_adopting_it → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_routed_build_registers_the_target_without_adopting_it → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_a_routed_build_registers_the_target_without_adopting_it → write_build_signature
REQ-DDB-WIKI-034measuredtest_a_routed_build_registers_the_target_without_adopting_it → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 41 lines
async def test_a_routed_build_registers_the_target_without_adopting_it(
    tmp_path: Path,
) -> None:
    """Building a target the server has never seen must allocate and record it — that is
    what makes `list_targets` and `cull` able to see it later — while leaving the DERIVED
    target alone. Registration is bookkeeping about a database on disk; adoption is state
    about which repository this server answers for by default, and the whole point of
    routing is that a call does not change the second.

    @brief A routed build registers its target and leaves the active one untouched.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    derived = tmp_path / "derived"
    fresh = tmp_path / "fresh"
    derived.mkdir()
    fresh.mkdir()
    state.adopt(str(derived), st.TARGET_SOURCE_FLAG)

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build leaving a current index.
        @version 1
        """
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build
    result = await state.build_or_refresh(_FakeCtx(), target=str(fresh))

    assert result["ok"] is True and result["built"] is True
    assert result["target"] == str(fresh)
    assert Path(state.active.repo_path) == derived, "a routed build must not retarget"
    assert str(fresh) in [t.repo_path for t in reg.targets()], "but must be registered"


@pytest.mark.anyio

test_a_routed_reply_reads_the_routed_INDEX_not_only_its_name

None test_mcp_routing.test_a_routed_reply_reads_the_routed_INDEX_not_only_its_name(Path tmp_path, Path rich_db)

A routed call reads the routed database, proven by content and not by label.

tests/test_mcp_routing.py:95

Show on the map →

Called by none

Calls _built_target, build_server

Checks

  • assert "found" not in hit, "the complete index must still know sensor_poll"
  • assert miss["found"] is False, ("the pruned index does not know sensor_poll — a hit here means the call read the " "DERIVED database while naming the routed one" )
  • assert miss["target"] == str(pruned)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_a_routed_reply_reads_the_routed_INDEX_not_only_its_name → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_routed_reply_reads_the_routed_INDEX_not_only_its_name → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-013measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_routed_reply_reads_the_routed_INDEX_not_only_its_name → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 37 lines
async def test_a_routed_reply_reads_the_routed_INDEX_not_only_its_name(
    tmp_path: Path, rich_db: Path
) -> None:
    """THE ASSERTION THE `target` FIELD CANNOT MAKE ON ITS OWN.

    Stamping the routed repository onto the reply and reading the DERIVED repository's
    database would satisfy every attribution check in this file while returning another
    project's answers under this project's name — the same shape as the grid that recorded
    36 cells `valid=True` because every term checked that tools were CALLED and none
    checked which index answered. So the two indexes here are made to DISAGREE, and the
    disagreement is what is asserted.

    @brief A routed call reads the routed database, proven by content and not by label.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    complete = tmp_path / "complete"
    pruned = tmp_path / "pruned"
    _built_target(state, complete, rich_db)
    thinned = _built_target(state, pruned, rich_db)
    with sqlite3.connect(thinned.db_path) as conn:
        conn.execute("DELETE FROM memberdef WHERE name = 'sensor_poll'")
    state.adopt(str(complete), st.TARGET_SOURCE_FLAG)

    hit = state.tools.dossier("sensor_poll", target=str(complete))
    miss = state.tools.dossier("sensor_poll", target=str(pruned))

    assert "found" not in hit, "the complete index must still know sensor_poll"
    assert miss["found"] is False, (
        "the pruned index does not know sensor_poll — a hit here means the call read the "
        "DERIVED database while naming the routed one"
    )
    assert miss["target"] == str(pruned)


@pytest.mark.anyio

test_a_routed_source_read_uses_the_routed_WORKING_TREE

None test_mcp_routing.test_a_routed_source_read_uses_the_routed_WORKING_TREE(Path tmp_path, Path rich_db, Path repo_root)

A routed dossier reads its body from the routed repository's files.

tests/test_mcp_routing.py:132

Show on the map →

Called by none

Calls _built_target, build_server

Checks

  • assert derived.get("found") is not False, "premise: the index knows the symbol either way"
  • assert "body" not in derived, ("premise: the derived target's working tree holds none of the indexed files, so the " "body panel must be absent rather than read from somewhere else" )
  • assert routed.get("found") is not False
  • assert "sensor_poll" in "\n".join(routed["body"]["lines"]), ("the routed tree holds the file and must be read from THERE" )
  • assert routed["target"] == str(repo_root)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_a_routed_source_read_uses_the_routed_WORKING_TREE → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_routed_source_read_uses_the_routed_WORKING_TREE → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-003measured
REQ-DDB-PIPE-005measured
REQ-DDB-PIPE-011measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_routed_source_read_uses_the_routed_WORKING_TREE → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 41 lines
async def test_a_routed_source_read_uses_the_routed_WORKING_TREE(
    tmp_path: Path, rich_db: Path, repo_root: Path
) -> None:
    """`dossier.body` reads bytes off disk using line numbers recorded in an index, so the
    call resolves TWO things from `target` — the database and the working tree — and a
    mismatch between them would quote one file's text under another's name.

    The derived target here has a database and an empty tree; the routed one has the real
    tree. Only a call that resolves the tree from `target` can read anything.

    THIS TEST GUARDED `source` AND NOW GUARDS `dossier`, which is a STRONGER shape rather
    than a port: `source` answered `found: false` on a treeless target, so index
    resolution and tree resolution failed together and one assertion covered both. A
    dossier answers from the index either way, so the tree resolution is isolated — the
    index half is asserted present on both calls and only `body` is allowed to differ.

    @brief A routed dossier reads its body from the routed repository's files.
    @version 2
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    treeless = tmp_path / "no_sources_here"
    _built_target(state, treeless, rich_db)
    _built_target(state, repo_root, rich_db)
    state.adopt(str(treeless), st.TARGET_SOURCE_FLAG)

    derived = state.tools.dossier("sensor_poll")
    assert derived.get("found") is not False, "premise: the index knows the symbol either way"
    assert "body" not in derived, (
        "premise: the derived target's working tree holds none of the indexed files, so the "
        "body panel must be absent rather than read from somewhere else"
    )

    routed = state.tools.dossier("sensor_poll", target=str(repo_root))
    assert routed.get("found") is not False
    assert "sensor_poll" in "\n".join(routed["body"]["lines"]), (
        "the routed tree holds the file and must be read from THERE"
    )
    assert routed["target"] == str(repo_root)

Activity · 13 steps
lines 151–151reg = st.TargetRegistry(tmp_path / "state")lines 152–152_mcp, state = build_server(reg)lines 153–153treeless = tmp_path / "no_sources_here"lines 154–154_built_target(state, treeless, rich_db)lines 155–155_built_target(state, repo_root, rich_db)lines 156–156state.adopt(str(treeless), st.TARGET_SOURCE_FLAG)lines 158–158derived = state.tools.dossier("sensor_poll")lines 159–159assert derived.get("found") is not False, "premise: the index knows the symbol either way"lines 160–163assert "body" not in derived, ( "premise: the derived target's working tree holds none of the indexed files, so the " "body panel must be absent rather than read from somewhere else" )lines 165–165routed = state.tools.dossier("sensor_poll", target=str(repo_root))lines 166–166assert routed.get("found") is not Falselines 167–169assert "sensor_poll" in "\n".join(routed["body"]["lines"]), ( "the routed tree holds the file and must be read from THERE" )lines 170–170assert routed["target"] == str(repo_root)

test_a_server_with_no_derived_target_still_serves_its_registered_indexes

None test_mcp_routing.test_a_server_with_no_derived_target_still_serves_its_registered_indexes(Path tmp_path, Path rich_db, pytest.MonkeyPatch monkeypatch)

Query tools are gated on having an index, not on having a derived target.

tests/test_mcp_routing.py:250

Show on the map →

Called by none

Calls _tool_names, build_server

Checks

  • assert state.resolve_startup_target(None) is None, "premise: no eager source"
  • assert state.active is None
  • assert set(TIER1_TOOLS) <= await _tool_names(mcp), ("a server with indexes but no derived target must still offer the query tools" )
  • assert state.tools.dossier("sensor_poll", target=str(repo))["target"] == str(repo)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_a_server_with_no_derived_target_still_serves_its_registered_indexes → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_server_with_no_derived_target_still_serves_its_registered_indexes → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_server_with_no_derived_target_still_serves_its_registered_indexes → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 37 lines
async def test_a_server_with_no_derived_target_still_serves_its_registered_indexes(
    tmp_path: Path, rich_db: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """THE TIER-GATE DECISION, asserted rather than described.

    The gate used to be "a target is derived". A query tool now takes the repository on
    the call, so that condition stopped correlating with "a query can be answered" — and
    the process it locks out is exactly the one routing is for: launched at no repository
    in particular, holding several indexes, serving several sessions. Under the old gate
    that server offered zero query tools.

    The honest half of the old gate survives and is asserted next door
    (`test_tier0_present_tier1_absent_at_construction`): a first-ever run with nothing
    indexed anywhere still offers only the lifecycle tools, because there genuinely is
    nothing to read.

    @brief Query tools are gated on having an index, not on having a derived target.
    @version 1
    """
    monkeypatch.delenv(st.PROJECT_DIR_ENV, raising=False)
    reg = st.TargetRegistry(tmp_path / "state")
    repo = tmp_path / "indexed_earlier"
    ## Registered and built by some earlier session, exactly the residue a restart leaves.
    repo.mkdir()
    built = reg.register(str(repo))
    Path(built.db_path).write_bytes(rich_db.read_bytes())

    mcp, state = build_server(reg)
    assert state.resolve_startup_target(None) is None, "premise: no eager source"
    assert state.active is None

    assert set(TIER1_TOOLS) <= await _tool_names(mcp), (
        "a server with indexes but no derived target must still offer the query tools"
    )
    assert state.tools.dossier("sensor_poll", target=str(repo))["target"] == str(repo)

Activity · 11 steps
lines 269–269monkeypatch.delenv(st.PROJECT_DIR_ENV, raising=False)lines 270–270reg = st.TargetRegistry(tmp_path / "state")lines 271–271repo = tmp_path / "indexed_earlier"lines 273–273repo.mkdir()lines 274–274built = reg.register(str(repo))lines 275–275Path(built.db_path).write_bytes(rich_db.read_bytes())lines 277–277mcp, state = build_server(reg)lines 278–278assert state.resolve_startup_target(None) is None, "premise: no eager source"lines 279–279assert state.active is Nonelines 281–283assert set(TIER1_TOOLS) <= await _tool_names(mcp), ( "a server with indexes but no derived target must still offer the query tools" )lines 284–284assert state.tools.dossier("sensor_poll", target=str(repo))["target"] == str(repo)

test_a_sessions_own_build_invalidates_its_stale_active_default

None test_mcp_routing.test_a_sessions_own_build_invalidates_its_stale_active_default(Path tmp_path)

A session's own stale cached default is invalidated by its own build.

tests/test_mcp_routing.py:1113

Checks

  • assert pre.name is None, "premise: nothing built yet, so the whole-repo target is cached"
  • assert result.get("ok") is True, result
  • assert state.active is not None and state.active.name == "first-party", (f"a session's own build of its active repository must re-adopt the now-preferred " f"target inline, got {state.active}" )
  • assert reply.get("target") == str(repo), reply

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → write_build_signature
REQ-DDB-CONFIG-007measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → write_build_signature
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-007measured
REQ-DDB-QUERY-014measured
REQ-DDB-WIKI-034measuredtest_a_sessions_own_build_invalidates_its_stale_active_default → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 68 lines
async def test_a_sessions_own_build_invalidates_its_stale_active_default(
    tmp_path: Path,
) -> None:
    """FIELD-REPORTED, from a real B12_single_rgb session on 1.0.25: `adopt()` was fixed
    to prefer a first-party sub-index when one is registered — but a session's OWN
    `self.active` is resolved once and cached (`ensure_target` short-circuits on it), so a
    session that connected BEFORE its first split build has no way to see one that happens
    later through an explicit `index(action='refresh', sub_index='first-party')` call.
    Reported symptom: every bare `dossier`/`search` call answered "no database has been
    built" against the never-built whole-repo target, forever, until reconnect — even
    though `index(action='targets')` correctly listed the built first-party sub-index.

    So this reproduces the exact sequence: adopt() BEFORE the split exists (caching the
    whole-repo target), THEN build first-party through `build_or_refresh` — exactly the
    call a caller makes — THEN a bare call. Not through `resolve_target`/`adopt()` in
    isolation, which the split-preference tests already cover and which cannot see a
    STALE cache populated before either existed.

    @brief A bare call after a session's own first-party build reaches the new sub-index.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "b12_repro"
    repo.mkdir()
    ## gh#40. THE SUB-INDEX NAME MUST BE ONE THE REPOSITORY ACTUALLY DERIVES. These tests are
    ## about ROUTING, and their fixture named a sub-index of a repository that vendors nothing —
    ## viable only while nothing validated the name. `_build_subject` now refuses a name no
    ## nested tree produces, so the fixture states the tree that produces it.
    (repo / "llama-cpp").mkdir()
    (repo / "llama-cpp" / ".git").write_text(
        "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8"
    )

    ## Simulate a session connecting before any split exists — caches the whole-repo target.
    pre = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)
    assert pre.name is None, "premise: nothing built yet, so the whole-repo target is cached"

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build leaving a current index for the named target.
        @version 1
        """
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    result = await state.build_or_refresh(
        _FakeCtx(), target=str(repo), sub_index="first-party", force=True
    )
    assert result.get("ok") is True, result

    ## RE-ADOPTED, not merely cleared — tier-1 query tools read `self.active_db`/
    ## `self.active_repo` directly with no lazy re-derivation of their own, so `None` here
    ## would only trade the stale-index bug for a no-default bug on the very next bare call.
    assert state.active is not None and state.active.name == "first-party", (
        f"a session's own build of its active repository must re-adopt the now-preferred "
        f"target inline, got {state.active}"
    )

    ## And the bare call that follows must reach the newly-built sub-index rather than
    ## raising "no database has been built" against the stale default.
    reply = state.tools.search("nonexistent-symbol")
    assert reply.get("target") == str(repo), reply

1 more lines, not shown

Activity · 15 steps
lines 1134–1134reg = st.TargetRegistry(tmp_path / "state")lines 1135–1135_mcp, state = build_server(reg)lines 1136–1136repo = tmp_path / "b12_repro"lines 1137–1137repo.mkdir()lines 1142–1142(repo / "llama-cpp").mkdir()lines 1143–1145(repo / "llama-cpp" / ".git").write_text( "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8" )lines 1148–1148pre = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)lines 1149–1149assert pre.name is None, "premise: nothing built yet, so the whole-repo target is cached"lines 1151–1160def _fake_build( target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False ): """@brief Stand-in build leaving a current index for the named target. @version 1 """ Path(target.db_path).parent.mkdir(parents=True, exist_ok=True) sqlite3.connect(target.db_path).close() write_build_signature(Path(target.db_path)) return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}lines 1162–1162state._run_build = _fake_buildlines 1164–1166result = await state.build_or_refresh( _FakeCtx(), target=str(repo), sub_index="first-party", force=True )lines 1167–1167assert result.get("ok") is True, resultlines 1172–1175assert state.active is not None and state.active.name == "first-party", ( f"a session's own build of its active repository must re-adopt the now-preferred " f"target inline, got {state.active}" )lines 1179–1179reply = state.tools.search("nonexistent-symbol")lines 1180–1180assert reply.get("target") == str(repo), reply

test_a_stalled_refresh_does_not_hang_a_later_query

None test_mcp_routing.test_a_stalled_refresh_does_not_hang_a_later_query(Path tmp_path, pytest.MonkeyPatch monkeypatch)

A query behind a stalled refresh answers stale instead of hanging.

tests/test_mcp_routing.py:529

Checks

  • assert waiter_returned.is_set(), ("the query behind a stalled refresh never returned. That is the hang: the build lock is " "held across the whole build, so an unbounded acquire makes one slow build block every " "later stale query in the process." )
  • assert not released.is_set(), ("the holder finished, so the waiter was never actually made to queue — this test would " "be vacuous" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-006measured
REQ-DDB-MCP-001measuredtest_a_stalled_refresh_does_not_hang_a_later_query → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_stalled_refresh_does_not_hang_a_later_query → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_a_stalled_refresh_does_not_hang_a_later_query → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 69 lines
async def test_a_stalled_refresh_does_not_hang_a_later_query(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """FIELD-OBSERVED, 2026-08-26: a single MCP call hung indefinitely. The build lock is held
    across the whole build, and the acquire was unbounded, so one stalled build queued every later
    query that found the index stale — with no way out. `_auto_refresh`'s own docstring promised
    the opposite: "a stale answer plus a warning is strictly better than an error." It honoured
    that for an exception and not for a STALL.

    THE STALL HAS TO BE DELIBERATE OR THIS CANNOT BE TESTED AT ALL. The sibling
    `test_concurrent_refreshes_of_one_target_build_it_once` passes today and always did, because
    its stand-in build returns promptly — a fast build never exercises the queue. So this one holds
    the lock for longer than the bounded wait and asserts the waiter RETURNS.

    Asserted as "returns within a bound", not on wall-clock precision: the point is termination,
    not latency.

    @brief A query behind a stalled refresh answers stale instead of hanging.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "stalled"
    repo.mkdir()
    (repo / "a.c").write_text("int main(void){return 0;}\n", encoding="utf-8")

    ## Shrink the wait so the test is fast; the production value is a backstop, not a budget.
    monkeypatch.setattr(server_module, "_LOCK_WAIT_SECONDS", 1)

    target = state.resolve_target(str(repo))
    monkeypatch.setattr(state, "_data_stale", lambda _t: True)

    released = anyio.Event()
    waiter_returned = anyio.Event()

    async def _hold_the_lock() -> None:
        """@brief Occupy the build lock far longer than the bounded wait.
        @version 1
        """
        async with state._build_lock(target.repo_path):
            await anyio.sleep(5)
            released.set()

    async def _query_behind_it() -> None:
        """@brief A second query that must not wait for the holder.
        @version 1
        """
        await state._auto_refresh(str(repo))
        waiter_returned.set()

    with anyio.move_on_after(4):
        async with anyio.create_task_group() as tg:
            tg.start_soon(_hold_the_lock)
            await anyio.sleep(0.1)  # let the holder take it
            tg.start_soon(_query_behind_it)
            await waiter_returned.wait()
            tg.cancel_scope.cancel()

    assert waiter_returned.is_set(), (
        "the query behind a stalled refresh never returned. That is the hang: the build lock is "
        "held across the whole build, so an unbounded acquire makes one slow build block every "
        "later stale query in the process."
    )
    assert not released.is_set(), (
        "the holder finished, so the waiter was never actually made to queue — this test would "
        "be vacuous"
    )

Activity · 21 steps
lines 549–549reg = st.TargetRegistry(tmp_path / "state")lines 550–550_mcp, state = build_server(reg)lines 551–551repo = tmp_path / "stalled"lines 552–552repo.mkdir()lines 553–553(repo / "a.c").write_text("int main(void){return 0;}\n", encoding="utf-8")lines 556–556monkeypatch.setattr(server_module, "_LOCK_WAIT_SECONDS", 1)lines 558–558target = state.resolve_target(str(repo))lines 559–559monkeypatch.setattr(state, "_data_stale", lambda _t: True)lines 561–561released = anyio.Event()lines 562–562waiter_returned = anyio.Event()lines 564–570async def _hold_the_lock() -> None: """@brief Occupy the build lock far longer than the bounded wait. @version 1 """ async with state._build_lock(target.repo_path): await anyio.sleep(5) released.set()lines 572–577async def _query_behind_it() -> None: """@brief A second query that must not wait for the holder. @version 1 """ await state._auto_refresh(str(repo)) waiter_returned.set()lines 579–579with anyio.move_on_after(4)lines 580–580async with anyio.create_task_group() as tglines 581–581tg.start_soon(_hold_the_lock)lines 582–582await anyio.sleep(0.1)lines 583–583tg.start_soon(_query_behind_it)lines 584–584await waiter_returned.wait()lines 585–585tg.cancel_scope.cancel()lines 587–591assert waiter_returned.is_set(), ( "the query behind a stalled refresh never returned. That is the hang: the build lock is " "held across the whole build, so an unbounded acquire makes one slow build block every " "later stale query in the process." )lines 592–595assert not released.is_set(), ( "the holder finished, so the waiter was never actually made to queue — this test would " "be vacuous" )

test_a_sub_index_resolves_by_name

None test_mcp_routing.test_a_sub_index_resolves_by_name(Path tmp_path)

A sub-index is addressed by name, and a bare root prefers the whole-repo index.

tests/test_mcp_routing.py:602

Checks

  • assert state.resolve_target(str(repo.resolve()), "llama-cpp").slug == vendor.slug
  • assert state.resolve_target(vendor.slug).slug == vendor.slug
  • assert state.resolve_target(str(repo.resolve())).slug == whole.slug, ("a bare repository path must resolve to the whole-repository index, not a sub-index" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-001measuredtest_a_sub_index_resolves_by_name → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_sub_index_resolves_by_name → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_a_sub_index_resolves_by_name → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 28 lines
def test_a_sub_index_resolves_by_name(tmp_path: Path) -> None:
    """TWO SPELLINGS, NOT THREE. `sub_index` is its own parameter rather than a suffix folded
    into `target` — a composite string a caller has to construct has no schema of its own for a
    model to read, while a second named parameter does, and `index(action='targets')` reports the
    legal values without anyone building a string. So a sub-index resolves by (`target`,
    `sub_index`) together, or by its bare slug alone.

    A BARE ROOT WITH NO `sub_index` MEANS THE WHOLE REPOSITORY when one is indexed — not
    "whichever sub-index sorted first". That distinction is the point of the next test.

    @brief Sub-indexes resolve by (target, sub_index) and by slug.
    @version 2
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "split"
    repo.mkdir()

    whole = reg.register(repo)
    vendor = reg.register(repo, name="llama-cpp")

    assert state.resolve_target(str(repo.resolve()), "llama-cpp").slug == vendor.slug
    assert state.resolve_target(vendor.slug).slug == vendor.slug
    assert state.resolve_target(str(repo.resolve())).slug == whole.slug, (
        "a bare repository path must resolve to the whole-repository index, not a sub-index"
    )

Activity · 9 steps
lines 615–615reg = st.TargetRegistry(tmp_path / "state")lines 616–616_mcp, state = build_server(reg)lines 617–617repo = tmp_path / "split"lines 618–618repo.mkdir()lines 620–620whole = reg.register(repo)lines 621–621vendor = reg.register(repo, name="llama-cpp")lines 623–623assert state.resolve_target(str(repo.resolve()), "llama-cpp").slug == vendor.sluglines 624–624assert state.resolve_target(vendor.slug).slug == vendor.sluglines 625–627assert state.resolve_target(str(repo.resolve())).slug == whole.slug, ( "a bare repository path must resolve to the whole-repository index, not a sub-index" )

test_a_tool_set_with_no_resolver_refuses_a_target_rather_than_ignoring_it

None test_mcp_routing.test_a_tool_set_with_no_resolver_refuses_a_target_rather_than_ignoring_it(Path rich_db)

A tool set with no resolver refuses an explicit target.

tests/test_mcp_routing.py:467

Show on the map →

Called by none

Calls none

Checks

  • assert tools.dossier("sensor_poll")["target"] == str(rich_db.parent), ("omitting the target must keep working on the bound shape" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-003measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
Source · 21 lines
def test_a_tool_set_with_no_resolver_refuses_a_target_rather_than_ignoring_it(
    rich_db: Path,
) -> None:
    """The bound-to-one-database shape — what a direct constructor call produces — cannot
    route. It must say so, because the alternative is answering from the repository it IS
    bound to while the reply's `target` field names that repository, which reads as a
    successful routed call and is the worst available outcome.

    @brief A tool set with no resolver refuses an explicit target.
    @version 1
    """
    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent)
    with pytest.raises(RuntimeError, match="cannot route"):
        tools.dossier("sensor_poll", target="/somewhere/else")

    assert tools.dossier("sensor_poll")["target"] == str(rich_db.parent), (
        "omitting the target must keep working on the bound shape"
    )


@pytest.mark.anyio

test_adopt_defaults_to_first_party_on_a_split_repo

None test_mcp_routing.test_adopt_defaults_to_first_party_on_a_split_repo(Path tmp_path)

adopt()'s default target prefers first-party over the whole-repo target.

tests/test_mcp_routing.py:978

Checks

  • assert active.slug == first_party.slug, (f"adopt() on a split repo must activate first-party, got {active.slug!r}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-MCP-001measuredtest_adopt_defaults_to_first_party_on_a_split_repo → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_adopt_defaults_to_first_party_on_a_split_repo → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_adopt_defaults_to_first_party_on_a_split_repo → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 28 lines
def test_adopt_defaults_to_first_party_on_a_split_repo(tmp_path: Path) -> None:
    """THE FULLY-OMITTED-TARGET PATH, distinct from and upstream of `resolve_target`. Every
    tool call that names no `target` at all goes through `ensure_target` -> `adopt`, which
    NEVER consulted the registry before this fix — it always derived the unnamed whole-repo
    Target via `target_for`, bypassing `_preferred_default` entirely. On a genuinely split
    repository (first-party + vendored registered, no whole-repo record — the shape
    `derive_sub_indexes` actually produces) every omitted-target call would have resolved to a
    database that was never built, contradicting the server's own served promise that omitting
    the argument still gets an answer.

    @brief adopt() on a split repo's root activates the first-party sub-index.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "adopt_split"
    repo.mkdir()

    first_party = reg.register(repo, name="first-party")
    reg.register(repo, name="llama-cpp")

    active = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)

    assert active.slug == first_party.slug, (
        f"adopt() on a split repo must activate first-party, got {active.slug!r}"
    )

Activity · 8 steps
lines 991–991reg = st.TargetRegistry(tmp_path / "state")lines 992–992_mcp, state = build_server(reg)lines 993–993repo = tmp_path / "adopt_split"lines 994–994repo.mkdir()lines 996–996first_party = reg.register(repo, name="first-party")lines 997–997reg.register(repo, name="llama-cpp")lines 999–999active = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)lines 1001–1003assert active.slug == first_party.slug, ( f"adopt() on a split repo must activate first-party, got {active.slug!r}" )

test_adopt_still_derives_the_whole_repo_when_unsplit

None test_mcp_routing.test_adopt_still_derives_the_whole_repo_when_unsplit(Path tmp_path)

adopt() on an unsplit repo is unaffected — still derives the whole-repo target.

tests/test_mcp_routing.py:1010

Checks

  • assert active.name is None, f"an unsplit repo must adopt the whole-repo target, got {active}"
  • assert active.repo_path == str(repo.resolve())

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-MCP-001measuredtest_adopt_still_derives_the_whole_repo_when_unsplit → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_adopt_still_derives_the_whole_repo_when_unsplit → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_adopt_still_derives_the_whole_repo_when_unsplit → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 20 lines
def test_adopt_still_derives_the_whole_repo_when_unsplit(tmp_path: Path) -> None:
    """THE COUNTER-CASE, guarding against an over-broad fix. A repository that has never been
    split — the overwhelming common case, and the shape every pre-existing `adopt` test already
    covers — must keep resolving to the whole-repo target exactly as before; nothing about
    preferring first-party should touch a repo with no sub-indexes at all.

    @brief adopt() on an unregistered/unsplit repo still derives the whole-repo Target.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "adopt_whole"
    repo.mkdir()

    active = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)

    assert active.name is None, f"an unsplit repo must adopt the whole-repo target, got {active}"
    assert active.repo_path == str(repo.resolve())

Activity · 7 steps
lines 1019–1019reg = st.TargetRegistry(tmp_path / "state")lines 1020–1020_mcp, state = build_server(reg)lines 1021–1021repo = tmp_path / "adopt_whole"lines 1022–1022repo.mkdir()lines 1024–1024active = state.adopt(str(repo), st.TARGET_SOURCE_FLAG)lines 1026–1026assert active.name is None, f"an unsplit repo must adopt the whole-repo target, got {active}"lines 1027–1027assert active.repo_path == str(repo.resolve())

test_an_unknown_target_is_refused_and_says_what_it_looked_for

None test_mcp_routing.test_an_unknown_target_is_refused_and_says_what_it_looked_for(Path tmp_path, Path rich_db)

An unresolvable target is refused by name, on every surface.

tests/test_mcp_routing.py:408

Show on the map →

Called by none

Calls _built_target, build_server

Checks

  • assert missing in message, "the refusal must name the string it could not resolve"
  • assert "index(action='targets')" in message, "and the move that would show what IS known"
  • assert str(known) in message, "and what is registered right now"
  • assert result["ok"] is False
  • assert missing in result["error"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-008measured
REQ-DDB-MCP-001measuredtest_an_unknown_target_is_refused_and_says_what_it_looked_for → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_an_unknown_target_is_refused_and_says_what_it_looked_for → build_server → _refusal_as_tool_error
REQ-DDB-QUERY-010measured
REQ-DDB-WIKI-034measuredtest_an_unknown_target_is_refused_and_says_what_it_looked_for → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 34 lines
async def test_an_unknown_target_is_refused_and_says_what_it_looked_for(
    tmp_path: Path, rich_db: Path
) -> None:
    """A target string that matches nothing must REFUSE. Building it would be worse: the
    caller most likely mistyped a path, and a mistyped path that is also a real directory
    would silently start a multi-minute doxygen run over the wrong tree.

    The message has to name the string, say what was searched, and list what is known,
    because the caller's next move — fix the spelling, or call list_targets — depends on
    which of those it was.

    @brief An unresolvable target is refused by name, on every surface.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    known = tmp_path / "known"
    _built_target(state, known, rich_db)
    missing = str(tmp_path / "never_existed")

    with pytest.raises(RuntimeError) as exc:
        state.tools.dossier("sensor_poll", target=missing)
    message = str(exc.value)
    assert missing in message, "the refusal must name the string it could not resolve"
    assert "index(action='targets')" in message, "and the move that would show what IS known"
    assert str(known) in message, "and what is registered right now"

    ## The same refusal on the build surface, which REPORTS rather than raises.
    result = await state.build_or_refresh(_FakeCtx(), target=missing)
    assert result["ok"] is False
    assert missing in result["error"]


@pytest.mark.anyio

test_an_unregistered_sub_index_derives_its_own_target

None test_mcp_routing.test_an_unregistered_sub_index_derives_its_own_target(Path tmp_path)

An unregistered repository still derives the named sub-index, not the whole repo.

tests/test_mcp_routing.py:890

Checks

  • assert named.name == "llama-cpp"
  • assert named.slug != whole.slug, ("a named sub_index on an unregistered repo must not derive the whole-repo target" )
  • assert named.db_path != whole.db_path

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-001measuredtest_an_unregistered_sub_index_derives_its_own_target → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_an_unregistered_sub_index_derives_its_own_target → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_an_unregistered_sub_index_derives_its_own_target → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 28 lines
def test_an_unregistered_sub_index_derives_its_own_target(tmp_path: Path) -> None:
    """THE FIRST BUILD OF A SUB-INDEX HAS NO REGISTRY ENTRY TO MATCH — `siblings` is empty,
    so `resolve_target(target, sub_index)` falls all the way through to the
    unregistered-directory fallback. That fallback derives via `target_for`, and `sub_index`
    has to reach that call: dropping it there silently derives the WHOLE-repo target — same
    `repo_path`, but a DIFFERENT slug and `db_path` — for a caller that named a part.

    `build_or_refresh` cannot see this mutation (it only reads `.repo_path` off the result),
    which is why this is a separate test: the QUERY path is what reads `.db_path`/`.slug`.

    @brief Resolving a named sub_index on an unregistered repo derives that sub-index's own Target.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "never_registered"
    repo.mkdir()

    whole = st.target_for(repo, reg.home)
    named = state.resolve_target(str(repo.resolve()), "llama-cpp")

    assert named.name == "llama-cpp"
    assert named.slug != whole.slug, (
        "a named sub_index on an unregistered repo must not derive the whole-repo target"
    )
    assert named.db_path != whole.db_path

Activity · 9 steps
lines 903–903reg = st.TargetRegistry(tmp_path / "state")lines 904–904_mcp, state = build_server(reg)lines 905–905repo = tmp_path / "never_registered"lines 906–906repo.mkdir()lines 908–908whole = st.target_for(repo, reg.home)lines 909–909named = state.resolve_target(str(repo.resolve()), "llama-cpp")lines 911–911assert named.name == "llama-cpp"lines 912–914assert named.slug != whole.slug, ( "a named sub_index on an unregistered repo must not derive the whole-repo target" )lines 915–915assert named.db_path != whole.db_path

test_auto_refresh_targets_the_named_sub_index_not_a_sibling

None test_mcp_routing.test_auto_refresh_targets_the_named_sub_index_not_a_sibling(Path tmp_path, pytest.MonkeyPatch monkeypatch)

Auto-refresh, triggered by a query, refreshes only the named sub-index.

tests/test_mcp_routing.py:824

Checks

  • assert builds == [(str(repo), "first-party")], (f"expected exactly one refresh of the stale, named sub-index, got {builds}" )
  • assert builds == [], f"a query naming the current sibling must not trigger a build: {builds}"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → write_build_signature
REQ-DDB-CONFIG-007measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → write_build_signature
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-006measured
REQ-DDB-MCP-001measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → write_build_signature
REQ-DDB-WIKI-034measuredtest_auto_refresh_targets_the_named_sub_index_not_a_sibling → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 62 lines
async def test_auto_refresh_targets_the_named_sub_index_not_a_sibling(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """`_answering_with_refresh` forwards `kwargs.get("sub_index")` to `_auto_refresh`, which
    resolves with it before deciding whether to build — this proves both forwards land, by
    building two sibling sub-indexes and confirming ONLY the one whose NAME the query passed
    gets rebuilt.

    `_data_stale` IS FAKED, DELIBERATELY, keyed off the resolved target's own `.name` rather
    than reproducing its real data-vs-schema-vs-code axis logic (already covered elsewhere,
    e.g. `test_a_stalled_refresh_lets_the_waiter_return`'s use of the same seam). What this
    test exists to catch is a DIFFERENT bug: `sub_index` failing to reach either the
    resolution call or the build call, so the wrong sibling — or no sibling — gets rebuilt. A
    version that dropped `sub_index` anywhere on this path would either refresh nothing
    (falling through to `self.active`, which is None here) or rebuild the wrong sibling —
    both indistinguishable from success unless the build calls are recorded.

    @brief A query naming a stale sub_index refreshes exactly that sub-index.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "auto_split"
    repo.mkdir()

    stale = reg.register(repo, name="first-party")
    current = reg.register(repo, name="llama-cpp")
    for target in (stale, current):
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))

    monkeypatch.setattr(state, "_data_stale", lambda t: t.name == "first-party")

    builds: list[tuple[str, str | None]] = []

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index.
        @version 1
        """
        builds.append((target.repo_path, target.name))
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    await state._auto_refresh(str(repo.resolve()), "first-party")

    assert builds == [(str(repo), "first-party")], (
        f"expected exactly one refresh of the stale, named sub-index, got {builds}"
    )

    ## And the counter-case in the same call: naming the CURRENT sibling triggers nothing.
    builds.clear()
    await state._auto_refresh(str(repo.resolve()), "llama-cpp")
    assert builds == [], f"a query naming the current sibling must not trigger a build: {builds}"

Activity · 19 steps
lines 844–844reg = st.TargetRegistry(tmp_path / "state")lines 845–845_mcp, state = build_server(reg)lines 846–846repo = tmp_path / "auto_split"lines 847–847repo.mkdir()lines 849–849stale = reg.register(repo, name="first-party")lines 850–850current = reg.register(repo, name="llama-cpp")lines 851–851◇ for target in (stale, current)lines 852–852Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)lines 853–853sqlite3.connect(target.db_path).close()lines 854–854write_build_signature(Path(target.db_path))lines 856–856monkeypatch.setattr(state, "_data_stale", lambda t: t.name == "first-party")lines 858–858builds: list[tuple[str, str | None]] = []lines 860–870def _fake_build( target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False ): """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index. @version 1 """ builds.append((target.repo_path, target.name)) Path(target.db_path).parent.mkdir(parents=True, exist_ok=True) sqlite3.connect(target.db_path).close() write_build_signature(Path(target.db_path)) return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}lines 872–872state._run_build = _fake_buildlines 874–874await state._auto_refresh(str(repo.resolve()), "first-party")lines 876–878assert builds == [(str(repo), "first-party")], ( f"expected exactly one refresh of the stale, named sub-index, got {builds}" )lines 881–881builds.clear()lines 882–882await state._auto_refresh(str(repo.resolve()), "llama-cpp")lines 883–883assert builds == [], f"a query naming the current sibling must not trigger a build: {builds}"

test_concurrent_refreshes_of_different_targets_are_not_serialised

None test_mcp_routing.test_concurrent_refreshes_of_different_targets_are_not_serialised(Path tmp_path)

Builds of different targets run concurrently.

tests/test_mcp_routing.py:355

Checks

  • assert (await state.build_or_refresh(_FakeCtx(), target=str(repo)))["ok"] is True
  • assert len(spans) == 2, "both targets must build"
  • assert min(a_end, b_end) > max(a_start, b_start), ("builds of different targets overlapped nowhere, so the lock is global not per-target" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → write_build_signature
REQ-DDB-CONFIG-007measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → write_build_signature
REQ-DDB-WIKI-034measuredtest_concurrent_refreshes_of_different_targets_are_not_serialised → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 53 lines
async def test_concurrent_refreshes_of_different_targets_are_not_serialised(
    tmp_path: Path,
) -> None:
    """The counter-case, and the reason the lock is keyed by TARGET rather than global.

    Two repositories are independent work; a single build lock would make five sessions
    on five repositories queue behind each other for no reason. Asserted by overlap in
    time rather than by inspecting the lock, so it survives a change of primitive.

    @brief Builds of different targets run concurrently.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repos = [tmp_path / "one", tmp_path / "two"]
    for repo in repos:
        repo.mkdir()
    spans: list[tuple[float, float]] = []

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build recording when it started and finished.
        @version 1
        """
        started = time.monotonic()
        time.sleep(0.1)
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        spans.append((started, time.monotonic()))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    async def _refresh(repo: Path) -> None:
        """@brief Refresh one of the two independent targets.
        @version 1
        """
        assert (await state.build_or_refresh(_FakeCtx(), target=str(repo)))["ok"] is True

    async with anyio.create_task_group() as tg:
        for repo in repos:
            tg.start_soon(_refresh, repo)

    assert len(spans) == 2, "both targets must build"
    (a_start, a_end), (b_start, b_end) = spans
    assert min(a_end, b_end) > max(a_start, b_start), (
        "builds of different targets overlapped nowhere, so the lock is global not per-target"
    )


@pytest.mark.anyio

test_concurrent_refreshes_of_one_target_build_it_once

None test_mcp_routing.test_concurrent_refreshes_of_one_target_build_it_once(Path tmp_path)

Concurrent refreshes of one target produce exactly one build.

tests/test_mcp_routing.py:300

Checks

  • assert result["ok"] is True, result
  • assert result["target"] == str(repo)
  • assert builds == [str(repo)], (f"four concurrent refreshes of one target must build it ONCE, got {len(builds)}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_concurrent_refreshes_of_one_target_build_it_once → write_build_signature
REQ-DDB-CONFIG-007measuredtest_concurrent_refreshes_of_one_target_build_it_once → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_concurrent_refreshes_of_one_target_build_it_once → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_concurrent_refreshes_of_one_target_build_it_once → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_concurrent_refreshes_of_one_target_build_it_once → write_build_signature
REQ-DDB-WIKI-034measuredtest_concurrent_refreshes_of_one_target_build_it_once → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 55 lines
async def test_concurrent_refreshes_of_one_target_build_it_once(tmp_path: Path) -> None:
    """FOUR SESSIONS, ONE REPOSITORY, ONE BUILD.

    The build runs on an anyio worker thread while the transport keeps serving frames, so
    the guard has to be held by the awaiting TASK across that hand-off — a threading lock
    taken on the event loop would stall the transport for every other session, which is
    the exact deployment this routing exists to serve.

    The stand-in build sleeps and then writes a currently-stamped database, because that
    is what makes the second caller's re-check meaningful: the deduplication is the lock
    PLUS the freshness re-check inside it, and a stand-in that left the index stale would
    let this pass on the lock alone.

    @brief Concurrent refreshes of one target produce exactly one build.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "contended"
    repo.mkdir()
    builds: list[str] = []

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build that records its call and leaves a current index.
        @version 1
        """
        builds.append(target.repo_path)
        time.sleep(0.05)
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    async def _refresh() -> None:
        """@brief One session's refresh of the contended target.
        @version 1
        """
        result = await state.build_or_refresh(_FakeCtx(), target=str(repo))
        assert result["ok"] is True, result
        assert result["target"] == str(repo)

    async with anyio.create_task_group() as tg:
        for _ in range(4):
            tg.start_soon(_refresh)

    assert builds == [str(repo)], (
        f"four concurrent refreshes of one target must build it ONCE, got {len(builds)}"
    )


@pytest.mark.anyio

test_dossier_and_search_route_to_the_named_sub_index

None test_mcp_routing.test_dossier_and_search_route_to_the_named_sub_index(Path tmp_path)

dossier() and search() reach the named sub-index's own database.

tests/test_mcp_routing.py:697

Checks

  • assert _table_exists(str(db_first), "FIRST_PARTY_MARK")
  • assert not _table_exists(str(db_first), "VENDOR_MARK")
  • assert _table_exists(str(db_vendor), "VENDOR_MARK")
  • assert not _table_exists(str(db_vendor), "FIRST_PARTY_MARK")
  • assert reply.get("sub_index") == "llama-cpp", (f"reply did not name which sub-index answered: {reply.get('sub_index')!r}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_dossier_and_search_route_to_the_named_sub_index → write_build_signature
REQ-DDB-CONFIG-007measuredtest_dossier_and_search_route_to_the_named_sub_index → write_build_signature
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_dossier_and_search_route_to_the_named_sub_index → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_dossier_and_search_route_to_the_named_sub_index → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_dossier_and_search_route_to_the_named_sub_index → write_build_signature
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-007measured
REQ-DDB-QUERY-014measured
REQ-DDB-WIKI-034measuredtest_dossier_and_search_route_to_the_named_sub_index → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 59 lines
def test_dossier_and_search_route_to_the_named_sub_index(tmp_path: Path) -> None:
    """END TO END THROUGH THE TOOL METHODS THEMSELVES, not through `resolve_target` alone —
    `sub_index` was threaded through `db()`, `_route()`, `_answered()` and every `_search_*`
    handler individually, and a routing-layer test cannot see a spot where one of those forwards
    stayed `None` on its way to `self.db(...)`. Each sub-index gets its own marker table, so the
    only way `dossier`/`search` can see the right marker is if `sub_index` reached the file.

    ALSO PINS THE REPLY'S OWN `sub_index` FIELD. `_target_name` reports the shared repo root for
    every sub-index of one repository, so a reply that omitted `sub_index` would make a
    first-party answer and a vendored answer read as indistinguishable — the wrong-index failure
    this module's docstring names as the project's most expensive.

    @brief dossier/search reach the sub-index's own file and label their reply with its name.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "split"
    repo.mkdir()

    first = reg.register(repo, name="first-party")
    vendor = reg.register(repo, name="llama-cpp")
    for target, marker in ((first, "FIRST_PARTY_MARK"), (vendor, "VENDOR_MARK")):
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        conn = sqlite3.connect(target.db_path)
        conn.execute(f"CREATE TABLE {marker} (x INTEGER)")
        conn.commit()
        conn.close()
        write_build_signature(Path(target.db_path))

    def _table_exists(db_path: str, name: str) -> bool:
        conn = sqlite3.connect(db_path)
        try:
            row = conn.execute(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)
            ).fetchone()
        finally:
            conn.close()
        return row is not None

    ## db() is the seam every tool method funnels through; proving it resolves to the right
    ## FILE is the load-bearing half of this test.
    db_first = state.tools.db(str(repo.resolve()), "first-party")
    db_vendor = state.tools.db(str(repo.resolve()), "llama-cpp")
    assert _table_exists(str(db_first), "FIRST_PARTY_MARK")
    assert not _table_exists(str(db_first), "VENDOR_MARK")
    assert _table_exists(str(db_vendor), "VENDOR_MARK")
    assert not _table_exists(str(db_vendor), "FIRST_PARTY_MARK")

    ## And a reply is labelled with the sub-index that actually answered it, not merely the
    ## shared repo root both would report identically.
    reply = state.tools.search(
        "nonexistent-symbol", target=str(repo.resolve()), sub_index="llama-cpp"
    )
    assert reply.get("sub_index") == "llama-cpp", (
        f"reply did not name which sub-index answered: {reply.get('sub_index')!r}"
    )

Activity · 22 steps
lines 712–712reg = st.TargetRegistry(tmp_path / "state")lines 713–713_mcp, state = build_server(reg)lines 714–714repo = tmp_path / "split"lines 715–715repo.mkdir()lines 717–717first = reg.register(repo, name="first-party")lines 718–718vendor = reg.register(repo, name="llama-cpp")lines 719–719◇ for target, marker in ((first, "FIRST_PARTY_MARK"), (vendor, "VENDOR_MARK"))lines 720–720Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)lines 721–721conn = sqlite3.connect(target.db_path)lines 722–722conn.execute(f"CREATE TABLE {marker} (x INTEGER)")lines 723–723conn.commit()lines 724–724conn.close()lines 725–725write_build_signature(Path(target.db_path))lines 727–735def _table_exists(db_path: str, name: str) -> bool: conn = sqlite3.connect(db_path) try: row = conn.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) ).fetchone() finally: conn.close() return row is not Nonelines 739–739db_first = state.tools.db(str(repo.resolve()), "first-party")lines 740–740db_vendor = state.tools.db(str(repo.resolve()), "llama-cpp")lines 741–741assert _table_exists(str(db_first), "FIRST_PARTY_MARK")lines 742–742assert not _table_exists(str(db_first), "VENDOR_MARK")lines 743–743assert _table_exists(str(db_vendor), "VENDOR_MARK")lines 744–744assert not _table_exists(str(db_vendor), "FIRST_PARTY_MARK")lines 748–750reply = state.tools.search( "nonexistent-symbol", target=str(repo.resolve()), sub_index="llama-cpp" )lines 751–753assert reply.get("sub_index") == "llama-cpp", ( f"reply did not name which sub-index answered: {reply.get('sub_index')!r}" )

test_dossier_body_survives_on_a_split_repo_with_no_whole_index

None test_mcp_routing.test_dossier_body_survives_on_a_split_repo_with_no_whole_index(Path tmp_path, Path rich_db, Path repo_root)

dossier's body panel survives on a repo with only vendored siblings registered.

tests/test_mcp_routing.py:1073

Checks

  • assert reply.get("found") is not False, "premise: the index knows the symbol"
  • assert "body" in reply, ("the body panel must be present — the sub_index-less repo() call must not have " "silently swallowed an 'ambiguous bare root' refusal" )
  • assert "sensor_poll" in "\n".join(reply["body"]["lines"])

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_dossier_body_survives_on_a_split_repo_with_no_whole_index → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_dossier_body_survives_on_a_split_repo_with_no_whole_index → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-003measured
REQ-DDB-PIPE-005measured
REQ-DDB-PIPE-011measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_dossier_body_survives_on_a_split_repo_with_no_whole_index → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 35 lines
async def test_dossier_body_survives_on_a_split_repo_with_no_whole_index(
    tmp_path: Path, rich_db: Path, repo_root: Path
) -> None:
    """`_repo_or_none` used to drop `sub_index` entirely, so `repo(target, None)` — inside a
    non-raising wrapper — hit `resolve_target`'s "ambiguous bare root" refusal for any repo whose
    registered siblings include neither a whole-repo record nor a first-party one. The exception
    was swallowed and the panel silently vanished — the database routed correctly the whole time
    (via the explicit `sub_index` given to `db()`), so this read as "this function has no
    recorded source" rather than the routing gap it was.

    REGISTERED WITH ONLY VENDORED SIBLINGS, deliberately — not first-party — because
    `resolve_target`'s bare-path branch now DEFAULTS to a first-party sibling when one exists
    (a separate, later fix in this same session), and that default would resolve the tree
    correctly even with `sub_index` dropped, masking exactly the bug this test exists to catch.
    Only the "no default to fall back on" shape isolates it.

    @brief A dossier naming a real sub_index on a split repo still carries its body panel.
    @version 2
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    vendor = state.registry.register(str(repo_root), name="llama-cpp")
    Path(vendor.db_path).write_bytes(rich_db.read_bytes())
    state.registry.register(str(repo_root), name="opencv")

    reply = state.tools.dossier("sensor_poll", target=str(repo_root), sub_index="llama-cpp")

    assert reply.get("found") is not False, "premise: the index knows the symbol"
    assert "body" in reply, (
        "the body panel must be present — the sub_index-less repo() call must not have "
        "silently swallowed an 'ambiguous bare root' refusal"
    )
    assert "sensor_poll" in "\n".join(reply["body"]["lines"])

Activity · 9 steps
lines 1092–1092reg = st.TargetRegistry(tmp_path / "state")lines 1093–1093_mcp, state = build_server(reg)lines 1094–1094vendor = state.registry.register(str(repo_root), name="llama-cpp")lines 1095–1095Path(vendor.db_path).write_bytes(rich_db.read_bytes())lines 1096–1096state.registry.register(str(repo_root), name="opencv")lines 1098–1098reply = state.tools.dossier("sensor_poll", target=str(repo_root), sub_index="llama-cpp")lines 1100–1100assert reply.get("found") is not False, "premise: the index knows the symbol"lines 1101–1104assert "body" in reply, ( "the body panel must be present — the sub_index-less repo() call must not have " "silently swallowed an 'ambiguous bare root' refusal" )lines 1105–1105assert "sensor_poll" in "\n".join(reply["body"]["lines"])

test_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one

None test_mcp_routing.test_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one(Path tmp_path, Path rich_db)

Each tier-1 tool routes when told to and falls back to the derived target.

tests/test_mcp_routing.py:192

Show on the map →

Called by none

Calls _built_target, build_server

Checks

  • assert tool(**_ARGS[name])["target"] == str(derived), (f"{name} with no target must answer from the derived repository" )
  • assert tool(**_ARGS[name], target=str(routed))["target"] == str(routed), (f"{name} must answer from the repository the CALL named" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-007measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 32 lines
async def test_every_tier1_tool_routes_and_omitting_the_target_keeps_the_derived_one(
    tmp_path: Path, rich_db: Path
) -> None:
    """THE ADDITIVE GUARANTEE, checked over the whole frozen surface rather than a sample.

    Every tier-1 tool must accept `target=` and must behave exactly as before when it is
    omitted. Driving the full `TIER1_TOOLS` set means a tool added without routing fails
    here, the same reasoning that makes the target-stamp test structural: a sampled check
    is how 36 cells were recorded valid against the wrong index.

    @brief Each tier-1 tool routes when told to and falls back to the derived target.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    derived = tmp_path / "derived"
    routed = tmp_path / "routed"
    _built_target(state, derived, rich_db)
    _built_target(state, routed, rich_db)
    state.adopt(str(derived), st.TARGET_SOURCE_FLAG)

    for name in TIER1_TOOLS:
        tool = getattr(state.tools, name)
        assert tool(**_ARGS[name])["target"] == str(derived), (
            f"{name} with no target must answer from the derived repository"
        )
        assert tool(**_ARGS[name], target=str(routed))["target"] == str(routed), (
            f"{name} must answer from the repository the CALL named"
        )


@pytest.mark.anyio

test_index_action_refuses_sub_index_alone_on_registry_wide_actions

None test_mcp_routing.test_index_action_refuses_sub_index_alone_on_registry_wide_actions(Path tmp_path)

The registry-wide refusal now also catches sub_index alone, without target.

tests/test_mcp_routing.py:1035

Checks

  • assert "sub_index" in str(excinfo.value), f"action={action!r}: {excinfo.value}"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-001measuredtest_index_action_refuses_sub_index_alone_on_registry_wide_actions → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_index_action_refuses_sub_index_alone_on_registry_wide_actions → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_index_action_refuses_sub_index_alone_on_registry_wide_actions → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 31 lines
async def test_index_action_refuses_sub_index_alone_on_registry_wide_actions(
    tmp_path: Path,
) -> None:
    """THE ACCEPTED-BUT-UNREAD KEY, this project's own most repeated defect. `_index_action`'s
    guard used to check only `target is not None`, so `sub_index='llama-cpp'` with no `target`
    on `action='status'|'targets'|'cull'` was accepted into the signature and never read —
    silently ignored rather than refused, on a registry-wide action that has no repository to
    apply it to.

    @brief sub_index alone on a non-routing action raises, naming sub_index in the message.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)

    for action in ("status", "targets"):  # 2.0.0: `cull` retired to the CLI
        with pytest.raises(ValueError) as excinfo:
            await state._index_action(
                _FakeCtx(),
                action,
                None,
                "llama-cpp",
                False,
                None,
                "from-guard",
                None,
                None,
            )
        assert "sub_index" in str(excinfo.value), f"action={action!r}: {excinfo.value}"

Activity · 6 steps
lines 1047–1047reg = st.TargetRegistry(tmp_path / "state")lines 1048–1048_mcp, state = build_server(reg)lines 1050–1050◇ for action in ("status", "targets"): # 2.0.0: `cull` retired to the CLIlines 1051–1051with pytest.raises(ValueError) as excinfolines 1052–1062await state._index_action( _FakeCtx(), action, None, "llama-cpp", False, None, "from-guard", None, None, )lines 1063–1063assert "sub_index" in str(excinfo.value), f"action={action!r}: {excinfo.value}"

test_index_refresh_tool_forwards_sub_index_through_the_dispatcher

None test_mcp_routing.test_index_refresh_tool_forwards_sub_index_through_the_dispatcher(Path tmp_path)

The registered index(action='refresh )` tool forwards sub_index end to end.

tests/test_mcp_routing.py:923

Checks

  • assert result.get("ok") is True, result
  • assert builds == [(str(repo), "llama-cpp")], (f"index(action='refresh', sub_index=...) must build exactly the named sub-index, " f"got {builds}" )
  • assert result.get("sub_index") == "llama-cpp"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → write_build_signature
REQ-DDB-CONFIG-007measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → write_build_signature
REQ-DDB-WIKI-034measuredtest_index_refresh_tool_forwards_sub_index_through_the_dispatcher → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 51 lines
async def test_index_refresh_tool_forwards_sub_index_through_the_dispatcher(
    tmp_path: Path,
) -> None:
    """ONE LAYER ABOVE `build_or_refresh` ITSELF. `sub_index` was added to `index()`'s own
    Annotated parameters and to `_index_action`'s dispatch of the `refresh` branch — a test
    against `build_or_refresh` directly cannot see either forward silently dropping back to
    `None`, because it never goes through them.

    @brief `index(action='refresh', sub_index=...)` reaches the named sub-index's own build.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "dispatch_split"
    repo.mkdir()
    ## gh#40. THE SUB-INDEX NAME MUST BE ONE THE REPOSITORY ACTUALLY DERIVES. These tests are
    ## about ROUTING, and their fixture named a sub-index of a repository that vendors nothing —
    ## viable only while nothing validated the name. `_build_subject` now refuses a name no
    ## nested tree produces, so the fixture states the tree that produces it.
    (repo / "llama-cpp").mkdir()
    (repo / "llama-cpp" / ".git").write_text(
        "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8"
    )
    builds: list[tuple[str, str | None]] = []

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index.
        @version 1
        """
        builds.append((target.repo_path, target.name))
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    result = await state.index(
        _FakeCtx(), action="refresh", target=str(repo), sub_index="llama-cpp"
    )

    assert result.get("ok") is True, result
    assert builds == [(str(repo), "llama-cpp")], (
        f"index(action='refresh', sub_index=...) must build exactly the named sub-index, "
        f"got {builds}"
    )
    assert result.get("sub_index") == "llama-cpp"

Activity · 13 steps
lines 934–934reg = st.TargetRegistry(tmp_path / "state")lines 935–935_mcp, state = build_server(reg)lines 936–936repo = tmp_path / "dispatch_split"lines 937–937repo.mkdir()lines 942–942(repo / "llama-cpp").mkdir()lines 943–945(repo / "llama-cpp" / ".git").write_text( "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8" )lines 946–946builds: list[tuple[str, str | None]] = []lines 948–958def _fake_build( target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False ): """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index. @version 1 """ builds.append((target.repo_path, target.name)) Path(target.db_path).parent.mkdir(parents=True, exist_ok=True) sqlite3.connect(target.db_path).close() write_build_signature(Path(target.db_path)) return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}lines 960–960state._run_build = _fake_buildlines 962–964result = await state.index( _FakeCtx(), action="refresh", target=str(repo), sub_index="llama-cpp" )lines 966–966assert result.get("ok") is True, resultlines 967–970assert builds == [(str(repo), "llama-cpp")], ( f"index(action='refresh', sub_index=...) must build exactly the named sub-index, " f"got {builds}" )lines 971–971assert result.get("sub_index") == "llama-cpp"

test_one_process_answers_two_targets_in_sequence

None test_mcp_routing.test_one_process_answers_two_targets_in_sequence(Path tmp_path, Path rich_db)

Two targets, one process, each reply naming its own repository.

tests/test_mcp_routing.py:64

Show on the map →

Called by none

Calls _built_target, build_server

Checks

  • assert first["target"] == str(repo_a)
  • assert second["target"] == str(repo_b)
  • assert third["target"] == str(repo_a), "a routed call must not inherit the previous one"
  • assert state.active is None, "routing must not adopt a target — the server is stateless"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_one_process_answers_two_targets_in_sequence → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_one_process_answers_two_targets_in_sequence → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_one_process_answers_two_targets_in_sequence → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 31 lines
async def test_one_process_answers_two_targets_in_sequence(tmp_path: Path, rich_db: Path) -> None:
    """THE WHOLE POINT: one server, two repositories, no restart and no retarget.

    Asserted through the `target` field because that field exists precisely so a caller
    can tell which repository answered — and because a routing bug that returned the
    right SHAPE from the wrong index is exactly the failure that voided a 36-cell grid.

    Also asserts the server stayed stateless: neither call adopts a target, so the third
    call's answer does not depend on the order of the first two.

    @brief Two targets, one process, each reply naming its own repository.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo_a = tmp_path / "alpha"
    repo_b = tmp_path / "beta"
    _built_target(state, repo_a, rich_db)
    _built_target(state, repo_b, rich_db)

    first = state.tools.dossier("sensor_poll", target=str(repo_a))
    second = state.tools.dossier("sensor_poll", target=str(repo_b))
    third = state.tools.dossier("sensor_poll", target=str(repo_a))

    assert first["target"] == str(repo_a)
    assert second["target"] == str(repo_b)
    assert third["target"] == str(repo_a), "a routed call must not inherit the previous one"
    assert state.active is None, "routing must not adopt a target — the server is stateless"


@pytest.mark.anyio

test_refresh_with_sub_index_builds_only_that_sub_index

None test_mcp_routing.test_refresh_with_sub_index_builds_only_that_sub_index(Path tmp_path)

index(action='refresh') with sub_index builds only the named sub-index.

tests/test_mcp_routing.py:761

Checks

  • assert result["ok"] is True, result
  • assert builds == [(str(repo), "llama-cpp")], (f"expected exactly one build of the named sub-index, got {builds}" )
  • assert result["target"] == str(repo)
  • assert result.get("sub_index") == "llama-cpp", (f"reply did not name which sub-index was built: {result.get('sub_index')!r}" )
  • assert resolved.name == "llama-cpp"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measuredtest_refresh_with_sub_index_builds_only_that_sub_index → write_build_signature
REQ-DDB-CONFIG-007measuredtest_refresh_with_sub_index_builds_only_that_sub_index → write_build_signature
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_refresh_with_sub_index_builds_only_that_sub_index → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_refresh_with_sub_index_builds_only_that_sub_index → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measuredtest_refresh_with_sub_index_builds_only_that_sub_index → write_build_signature
REQ-DDB-WIKI-034measuredtest_refresh_with_sub_index_builds_only_that_sub_index → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 58 lines
async def test_refresh_with_sub_index_builds_only_that_sub_index(tmp_path: Path) -> None:
    """END TO END THROUGH `build_or_refresh` ITSELF, not through `_build_subject` alone —
    `sub_index` was threaded through `build_or_refresh`'s own signature, `_index_action` and
    `index()`, and a test against `_build_subject` directly cannot see a spot where one of
    those outer forwards silently dropped back to `None` and rebuilt the whole repository.

    The repository has never been registered before this call, which is deliberately the
    harder case: `resolve_target`'s sibling match cannot help, so this also proves the
    unregistered-directory fallback carries `sub_index` through rather than deriving the
    whole-repo target for a caller that named a part.

    @brief A named sub_index reaches `_run_build` and reports itself on the reply.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(reg)
    repo = tmp_path / "fresh_split"
    repo.mkdir()
    ## gh#40. THE SUB-INDEX NAME MUST BE ONE THE REPOSITORY ACTUALLY DERIVES. These tests are
    ## about ROUTING, and their fixture named a sub-index of a repository that vendors nothing —
    ## viable only while nothing validated the name. `_build_subject` now refuses a name no
    ## nested tree produces, so the fixture states the tree that produces it.
    (repo / "llama-cpp").mkdir()
    (repo / "llama-cpp" / ".git").write_text(
        "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8"
    )
    builds: list[tuple[str, str | None]] = []

    def _fake_build(
        target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False
    ):
        """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index.
        @version 1
        """
        builds.append((target.repo_path, target.name))
        Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
        sqlite3.connect(target.db_path).close()
        write_build_signature(Path(target.db_path))
        return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}

    state._run_build = _fake_build

    result = await state.build_or_refresh(_FakeCtx(), target=str(repo), sub_index="llama-cpp")

    assert result["ok"] is True, result
    assert builds == [(str(repo), "llama-cpp")], (
        f"expected exactly one build of the named sub-index, got {builds}"
    )
    assert result["target"] == str(repo)
    assert result.get("sub_index") == "llama-cpp", (
        f"reply did not name which sub-index was built: {result.get('sub_index')!r}"
    )

    ## And the registry now knows about it by name, distinct from the (unbuilt) whole repo.
    resolved = state.resolve_target(str(repo.resolve()), "llama-cpp")
    assert resolved.name == "llama-cpp"

Activity · 16 steps
lines 775–775reg = st.TargetRegistry(tmp_path / "state")lines 776–776_mcp, state = build_server(reg)lines 777–777repo = tmp_path / "fresh_split"lines 778–778repo.mkdir()lines 783–783(repo / "llama-cpp").mkdir()lines 784–786(repo / "llama-cpp" / ".git").write_text( "gitdir: ../.git/modules/llama-cpp\n", encoding="utf-8" )lines 787–787builds: list[tuple[str, str | None]] = []lines 789–799def _fake_build( target, doxyfile, scope="from-guard", exclude=None, options=None, skip_if_fresh=False ): """@brief Stand-in build recording (repo_path, sub-index name) and leaving a current index. @version 1 """ builds.append((target.repo_path, target.name)) Path(target.db_path).parent.mkdir(parents=True, exist_ok=True) sqlite3.connect(target.db_path).close() write_build_signature(Path(target.db_path)) return {"ok": True, "built": True, "doxyfile": "(stand-in)", "output": ""}lines 801–801state._run_build = _fake_buildlines 803–803result = await state.build_or_refresh(_FakeCtx(), target=str(repo), sub_index="llama-cpp")lines 805–805assert result["ok"] is True, resultlines 806–808assert builds == [(str(repo), "llama-cpp")], ( f"expected exactly one build of the named sub-index, got {builds}" )lines 809–809assert result["target"] == str(repo)lines 810–812assert result.get("sub_index") == "llama-cpp", ( f"reply did not name which sub-index was built: {result.get('sub_index')!r}" )lines 815–815resolved = state.resolve_target(str(repo.resolve()), "llama-cpp")lines 816–816assert resolved.name == "llama-cpp"

test_target_is_an_optional_parameter_on_every_tier1_schema

None test_mcp_routing.test_target_is_an_optional_parameter_on_every_tier1_schema(Path tmp_path)

`target` is present and optional in every tier-1 tool's input schema.

tests/test_mcp_routing.py:224

Checks

  • assert name in schemas, f"{name} is not registered, so its schema cannot be checked"
  • assert "target" in schema.get("properties", {}), f"{name} does not expose `target`"
  • assert "target" not in schema.get("required", []), (f"{name} makes `target` required, which breaks every existing call" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-001measuredtest_target_is_an_optional_parameter_on_every_tier1_schema → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_target_is_an_optional_parameter_on_every_tier1_schema → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_target_is_an_optional_parameter_on_every_tier1_schema → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 26 lines
async def test_target_is_an_optional_parameter_on_every_tier1_schema(tmp_path: Path) -> None:
    """STRUCTURAL, not prose: the routing capability only exists over MCP if the argument
    reaches the wire schema, and it is only additive if it is not required.

    A Python signature that a client never sees is a capability nobody can call.

    @brief `target` is present and optional in every tier-1 tool's input schema.
    @version 1
    """
    reg = st.TargetRegistry(tmp_path / "state")
    repo = tmp_path / "anything"
    repo.mkdir()
    reg.register(str(repo))
    mcp, _state = build_server(reg)

    schemas = {t.name: t.input_schema for t in await mcp.list_tools()}
    for name in TIER1_TOOLS:
        assert name in schemas, f"{name} is not registered, so its schema cannot be checked"
        schema = schemas[name]
        assert "target" in schema.get("properties", {}), f"{name} does not expose `target`"
        assert "target" not in schema.get("required", []), (
            f"{name} makes `target` required, which breaks every existing call"
        )


@pytest.mark.anyio