From 7c43aeda93a5daf44b889ba6800c6051ee818c20 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:49:40 +0800 Subject: [PATCH 1/2] Share external knowledge source composition Bind managed CANNBot discovery and page reads to the authorized session checkout while keeping internal search independent. Agent-assisted-by: Codex (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/external-channels.md | 14 +++ docs/optimization-benchmarks.md | 14 ++- src/inferrsi/apps/cli/__init__.py | 47 +++++---- .../apps/integrations/cannbot/__init__.py | 15 ++- .../apps/integrations/cannbot/project.py | 12 +-- .../integrations/cannbot/round_knowledge.py | 26 +++-- .../apps/integrations/external_channels.py | 61 ++++++++++++ src/inferrsi/harness/optimization.py | 25 +++-- src/inferrsi/harness/optimization_session.py | 5 +- src/inferrsi/knowledge/channels.py | 4 + tests/test_cannbot_boundaries.py | 19 ++++ tests/test_knowledge_channels.py | 71 ++++++++++++++ tests/test_optimization_session.py | 98 +++++++++++++++++-- tests/test_project_optimization.py | 7 +- 14 files changed, 353 insertions(+), 65 deletions(-) create mode 100644 src/inferrsi/apps/integrations/external_channels.py diff --git a/docs/external-channels.md b/docs/external-channels.md index 4ea783757..3cb54ecaf 100644 --- a/docs/external-channels.md +++ b/docs/external-channels.md @@ -86,6 +86,20 @@ Revoke it with `inferrsi cannbot disable`. The grant lives at project's `.git` identity, so copying it to another clone does not carry the approval along. +## Using the shared registry + +Find and managed round retrieval use the same Apps registry for external +sources. Packaged knowledge is searched independently. Find uses the current +Git project and calls sources eligible for the task backend. An explicit +`--backend` takes precedence over a grant default. If available sources declare +different defaults, Find requires an explicit backend before calling any source. +`--no-external` runs Find without using the registry. + +CANNBot serves Ascend and uses its native indexed query and exact-page read +through the approved checkout's worker. Managed rounds select that source from +the registry for the Git project frozen at session start, and check the grant +again for both search and read. See [managed round retrieval](optimization-benchmarks.md#include-cannbot-in-the-round). + ## Using it Once approved, the default path searches automatically because the grant declares diff --git a/docs/optimization-benchmarks.md b/docs/optimization-benchmarks.md index dbc8cc0c8..7bb0e7e84 100644 --- a/docs/optimization-benchmarks.md +++ b/docs/optimization-benchmarks.md @@ -84,12 +84,20 @@ and access to material outside this session require their own observation. ### Include CANNBot in the round -Run from the project with an [approved CANNBot grant](external-channels.md). Add `--cannbot-platform ` at `benchmarks session start` or AB/BA -`campaign start` to freeze the external source and an explicit Ascend -platform. Omit the option for a local-only session. The paired +`campaign start` to freeze the external source and an explicit Ascend platform. +Start a benchmark session from the Git project with the +[CANNBot grant](external-channels.md). An AB/BA campaign uses the Git project of +its `--repo` target. The session records the checkout identity. Later searches +and reads check the grant for that checkout, even when invoked from a different +working directory. Omit the option for a local-only session. The paired `benchmarks compare` conditions keep their existing behavior. +A session without a verifiable project binding returns `not_enabled` for +CANNBot and still delivers local knowledge. Start a new benchmark session from +the approved Git project if your session has no binding. Use the original +frozen InferRSI release to resume sessions created with an earlier runtime. + `knowledge` queries both sources for the next round. It returns the local context and a separate `external` result, with its own ranking, channel state and `reference.path`. A CANNBot timeout still returns the local result. The diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 59ca05bec..a514ad016 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -26,22 +26,29 @@ def _print(value: object) -> None: print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)) +def _round_provider(plan): + from ..integrations.external_channels import round_provider + + return round_provider(plan) + + def _optimization_session(args, *, task_source=None, report_metadata=None): from ...harness.optimization_session import session_command settings = None - provider = None + external_project = None if getattr(args, "cannbot_platform", None): - settings = {"channel": "cannbot-knowledge", "backend": "ascend", - "platform": args.cannbot_platform} - if args.session_action in ("knowledge", "knowledge-read"): - from ..integrations.cannbot.round_knowledge import CannbotRoundKnowledge + from ..integrations.cannbot import CHANNEL_NAME + from ..integrations.external_channels import freeze_project - provider = CannbotRoundKnowledge() + settings = {"channel": CHANNEL_NAME, "backend": "ascend", + "platform": args.cannbot_platform} + external_project = freeze_project(args.repo if args.project_task else None) return session_command( args, task_source=task_source, retain_context=capture_context, knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, - external_knowledge=settings, external_provider=provider, + external_knowledge=settings, external_project=external_project, + external_provider_for=_round_provider, report_metadata=report_metadata, ) @@ -158,24 +165,9 @@ def _clip(value: str, limit: int = 160) -> str: def _channels(): - """Build the external channel registry from whatever this checkout approved. - - The grant is the second source of a declared backend, after an explicit - `--backend`. Reading it here is what makes `cannbot enable --backend ascend` - mean something: without it, an approved Ascend source would only ever run - when the caller repeated the flag, and the approval would silently do - nothing on the default path. - - Constructing a channel reads its grant, which is a cheap local file read. - An unreadable or absent grant is not fatal: the channel still exists and - reports `not_enabled` with a fix when asked, which is more useful than - dropping it from the list. - """ - from ...knowledge.channels import ChannelRegistry - from ..integrations.cannbot import CannbotChannel + from ..integrations.external_channels import external_channels - channel = CannbotChannel() - return ChannelRegistry([channel], declared_backend=channel.declared_backend) + return external_channels() def _print_external(result: dict) -> None: @@ -443,7 +435,12 @@ def main(argv: list[str] | None = None) -> int: args.query, platform=args.platform, limit=args.limit, ) else: - result = cannbot.project.read( + channel = _channels().named(cannbot.CHANNEL_NAME) + if channel is None: + raise cannbot.project.ChannelFailure( + "The CANNBot knowledge channel is unavailable", state="not_enabled", + ) + result = channel.read_page( args.locator, page=args.page, expected_sha256=args.sha256, expected_revision=args.revision, ) diff --git a/src/inferrsi/apps/integrations/cannbot/__init__.py b/src/inferrsi/apps/integrations/cannbot/__init__.py index 63224413a..9787a1862 100644 --- a/src/inferrsi/apps/integrations/cannbot/__init__.py +++ b/src/inferrsi/apps/integrations/cannbot/__init__.py @@ -16,6 +16,7 @@ __all__ = ["CannbotChannel", "project"] SCORE_SCALE = "cannbot/knowledge-search.v5" +CHANNEL_NAME = "cannbot-knowledge" class CannbotChannel: @@ -41,7 +42,7 @@ def __init__(self, *, root: Path | None = None, timeout: float = 8.0): self.hint = ChannelStatus("rejected", detail=str(exc)) self.backend = "ascend" self.declared_backend = grant.get("backend") - self.name = "cannbot-knowledge" + self.name = CHANNEL_NAME def describe(self, *, request: ChannelRequest) -> ChannelStatus: try: @@ -99,9 +100,15 @@ def search( def read(self, locator: str, *, expected_sha256: str | None = None, expected_revision: str | None = None) -> str: - payload = self._project.read( - locator, expected_sha256=expected_sha256, root=self.root, - expected_revision=expected_revision, + payload = self.read_page( + locator, expected_sha256=expected_sha256, expected_revision=expected_revision, timeout=max(self.timeout, 15.0), ) return str(payload.get("text") or "") + + def read_page(self, locator: str, *, page: int = 1, expected_sha256: str | None = None, + expected_revision: str | None = None, timeout: float = 15.0) -> dict: + return self._project.read( + locator, page=page, expected_sha256=expected_sha256, + expected_revision=expected_revision, root=self.root, timeout=timeout, + ) diff --git a/src/inferrsi/apps/integrations/cannbot/project.py b/src/inferrsi/apps/integrations/cannbot/project.py index 7386f0499..88565c91d 100644 --- a/src/inferrsi/apps/integrations/cannbot/project.py +++ b/src/inferrsi/apps/integrations/cannbot/project.py @@ -37,9 +37,9 @@ def __init__(self, message, *, state="rejected", fix="", exit_code=None): self.exit_code = exit_code -def project_root() -> Path: - cwd = Path.cwd().resolve() - for folder in (cwd, *cwd.parents): +def project_root(start: Path | None = None) -> Path: + directory = (Path.cwd() if start is None else start).resolve() + for folder in (directory, *directory.parents): if (folder / ".git").exists(): return folder raise ChannelFailure( @@ -53,7 +53,7 @@ def _grant_path(root: Path) -> Path: return Path.home() / ".config" / "inferrsi" / "cannbot-projects" / (project_id + ".json") -def _checkout_identity(root: Path) -> dict: +def checkout_identity(root: Path) -> dict: marker = root / ".git" info = marker.stat() identity = {"device": info.st_dev, "inode": info.st_ino} @@ -101,7 +101,7 @@ def load_grant(root: Path | None = None) -> dict: if len(raw) > MAX_BYTES: raise ValueError("The cannbot project grant exceeds 2 MiB") grant = _parse(raw) - checkout = _checkout_identity(root) + checkout = checkout_identity(root) except FileNotFoundError: raise ChannelFailure( "cannbot knowledge is not enabled for this project", state="not_enabled", @@ -256,7 +256,7 @@ def enable(*, upstream: Path, python: Path, backend: str = "ascend", raise ValueError("--platform takes one of " + ", ".join(PLATFORMS)) grant = { "schema": _SCHEMA, "project_root": str(root), - "checkout_identity": _checkout_identity(root), + "checkout_identity": checkout_identity(root), "upstream": str(upstream.resolve()), # Record the interpreter path as given. Resolving the symlink in a venv # bin/ lands on the base interpreter, which loses every installed diff --git a/src/inferrsi/apps/integrations/cannbot/round_knowledge.py b/src/inferrsi/apps/integrations/cannbot/round_knowledge.py index 985130bc7..6b9439d3b 100644 --- a/src/inferrsi/apps/integrations/cannbot/round_knowledge.py +++ b/src/inferrsi/apps/integrations/cannbot/round_knowledge.py @@ -4,8 +4,14 @@ import re from ....harness.records.evidence import relative_location -from ....knowledge.channels import CHANNEL_STATES, TIMEOUT, ChannelRegistry, search_channels -from . import SCORE_SCALE, CannbotChannel, project +from ....knowledge.channels import ( + CHANNEL_STATES, + NOT_ENABLED, + TIMEOUT, + ChannelRegistry, + search_channels, +) +from . import CHANNEL_NAME, SCORE_SCALE, project from .read_worker import _WORKER_CLEANUP_SECONDS SCORE_SCALES = (SCORE_SCALE, "knowledge-search.v5") @@ -30,7 +36,7 @@ def _card_identity(record): def search_metadata(record): """Validate the scalar metadata published from a retained search.""" if ( - not isinstance(record, dict) or record.get("channel") != "cannbot-knowledge" + not isinstance(record, dict) or record.get("channel") != CHANNEL_NAME or record.get("backend") != "ascend" or record.get("platform") not in project.PLATFORMS or record.get("state") not in CHANNEL_STATES or not isinstance(record.get("items"), list) ): @@ -60,7 +66,7 @@ def search_metadata(record): def read_metadata(record): """Validate the identity and page of a retained read receipt.""" card = _card_identity(record) - if (card is None or record.get("channel") != "cannbot-knowledge" + if (card is None or record.get("channel") != CHANNEL_NAME or not _hex(record.get("revision"), 40) or type(record.get("page")) is not int or record["page"] < 1): return None @@ -68,14 +74,18 @@ def read_metadata(record): class CannbotRoundKnowledge: + def __init__(self, channel): + self.channel = channel + def search(self, query, *, settings, limit, timeout): # Process cleanup runs after a timeout and must fit in the search budget too. timeout = min(8.0, timeout - _WORKER_CLEANUP_SECONDS) if timeout <= 0: return {"state": TIMEOUT, "items": [], "count": 0} - channel = CannbotChannel() + if self.channel is None: + return {"state": NOT_ENABLED, "items": [], "count": 0} results = search_channels( - ChannelRegistry([channel]), query, backend=settings["backend"], + ChannelRegistry([self.channel]), query, backend=settings["backend"], platform=settings["platform"], limit=limit, timeout=timeout, ) result, = results @@ -93,8 +103,10 @@ def read(self, locator, *, revision, card_sha256, page, timeout): timeout = min(15.0, timeout - _WORKER_CLEANUP_SECONDS) if timeout <= 0: raise ValueError("CANNBot read has insufficient time before the final reserve") + if self.channel is None: + raise ValueError("CANNBot read failed (not_enabled). Check the grant or search again") try: - result = project.read( + result = self.channel.read_page( locator, expected_revision=revision, expected_sha256=card_sha256, page=page, timeout=timeout, ) diff --git a/src/inferrsi/apps/integrations/external_channels.py b/src/inferrsi/apps/integrations/external_channels.py new file mode 100644 index 000000000..f34a710e9 --- /dev/null +++ b/src/inferrsi/apps/integrations/external_channels.py @@ -0,0 +1,61 @@ +"""Compose app-facing external knowledge for a project.""" + +from pathlib import Path + +from ...knowledge.channels import ChannelRegistry +from .cannbot import CHANNEL_NAME, CannbotChannel, project + +_SOURCES = (CannbotChannel,) + + +def external_channels(*, root: Path | None = None) -> ChannelRegistry: + channels = [source(root=root) for source in _SOURCES] + # A project grant can declare the task backend when Find has no explicit + # --backend. Conflicting grant defaults leave it undeclared. + defaults = {getattr(channel, "declared_backend", None) for channel in channels} - {None} + backend = next(iter(defaults)) if len(defaults) == 1 else None + return ChannelRegistry(channels, declared_backend=backend) + + +def freeze_project(start: Path | None = None) -> dict | None: + try: + root = project.project_root(start) + return {"root": str(root), "checkout_identity": project.checkout_identity(root)} + except (project.ChannelFailure, OSError, RuntimeError): + return None + + +def _bound_root(plan: dict) -> Path | None: + if "external_knowledge_project" not in plan and plan.get("task_source") == "project": + # Older AB/BA plans already froze the absolute editable project path. + working_candidate = plan.get("working_candidate") + if isinstance(working_candidate, str): + candidate = Path(working_candidate) + if candidate.is_absolute() and candidate.is_dir(): + binding = freeze_project(candidate) + return Path(binding["root"]) if binding else None + + binding = plan.get("external_knowledge_project") + if not isinstance(binding, dict) or not isinstance(binding.get("root"), str): + return None + root = Path(binding["root"]) + if not root.is_absolute(): + return None + try: + identity = project.checkout_identity(root) + except (OSError, ValueError): + return None + return root if identity == binding.get("checkout_identity") else None + + +def round_provider(plan: dict): + from .cannbot.round_knowledge import CannbotRoundKnowledge + + root = _bound_root(plan) + channel = None + settings = plan["external_knowledge"] + if root is not None and settings.get("channel") == CHANNEL_NAME: + candidate = external_channels(root=root).named(CHANNEL_NAME) + if candidate is not None and candidate.backend == settings.get("backend"): + channel = candidate + return CannbotRoundKnowledge(channel) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 7f86abada..4036395d3 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -355,7 +355,7 @@ def _store_knowledge(root, kind, number, record): def capture_context(root: Path, reader, *, retain_context, external_provider=None, - **request) -> dict: + external_provider_for=None, **request) -> dict: with _locked(root): plan, state = _load(root) number = _knowledge_round(plan, state) @@ -363,7 +363,7 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non if settings: if number is None: raise ValueError("Round budget consumed, run independent final evaluation") - if external_provider is None: + if external_provider is None and external_provider_for is None: raise ValueError("The frozen external knowledge provider is unavailable") request["relevance"] = sanitized_text(request["relevance"], "", limit=None) binding = _context_diagnosis(plan, state) @@ -379,11 +379,13 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non response = {"reference": reference, "context": _read_context(root, reference)} if settings: remaining = _knowledge_time(plan, state) - result = ( - external_provider.search(request["relevance"], settings=settings, - limit=request["limit"], timeout=remaining) - if remaining > 0 else {"state": "timeout", "items": [], "count": 0} - ) + if remaining > 0: + if external_provider_for is not None: + external_provider = external_provider_for(plan) + result = external_provider.search(request["relevance"], settings=settings, + limit=request["limit"], timeout=remaining) + else: + result = {"state": "timeout", "items": [], "count": 0} search = {**result, **settings, "context_ref": reference["path"]} search_ref = _store_knowledge(root, "external_search", number, search) state["contexts"].append(search_ref) @@ -392,11 +394,14 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non return response -def read_external_context(root: Path, provider, *, search_ref, locator, page): +def read_external_context(root: Path, provider, *, search_ref, locator, page, + external_provider_for=None): with _locked(root): plan, state = _load(root) number = _knowledge_round(plan, state) - if not plan.get("external_knowledge") or provider is None: + if not plan.get("external_knowledge") or ( + provider is None and external_provider_for is None + ): raise ValueError("External knowledge is disabled or unavailable for this session") if type(page) is not int or page < 1: raise ValueError("CANNBot page must be a positive integer") @@ -413,6 +418,8 @@ def read_external_context(root: Path, provider, *, search_ref, locator, page): if remaining <= 0: raise ValueError("Optimization deadline exhausted, final evaluation time is reserved") revision, card_sha256 = search["revision"], hit["card_sha256"] + if external_provider_for is not None: + provider = external_provider_for(plan) body = provider.read(locator, revision=revision, card_sha256=card_sha256, page=page, timeout=remaining) receipt = {"search_ref": search_ref, "channel": search["channel"], "locator": locator, diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index bfa5bfdf4..fa4dabe6e 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -129,6 +129,7 @@ def _runtime_identity(): def session_command(args, *, task_source: Path | None = None, knowledge_reader=None, retain_context=None, external_knowledge=None, external_provider=None, + external_project=None, external_provider_for=None, report_metadata=None) -> dict: """Run one operation; discovery and knowledge access are supplied by the caller.""" from inferrsi.harness import optimization @@ -262,6 +263,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N "runtime_identity": _runtime_identity(), **candidate, **settings} if external_knowledge: plan["external_knowledge"] = external_knowledge + plan["external_knowledge_project"] = external_project if report_metadata is not None: plan["report_metadata"] = report_metadata result = optimization.initialize(root, plan) @@ -328,6 +330,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N knowledge_reader, retain_context=retain_context, external_provider=external_provider, + external_provider_for=external_provider_for, query="", relevance=args.query, relevance_method=args.relevance_method, @@ -337,7 +340,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N if args.session_action == "knowledge-read": return optimization.read_external_context( root, external_provider, search_ref=args.search_ref, locator=args.locator, - page=args.page, + page=args.page, external_provider_for=external_provider_for, ) if args.session_action == "recover": return optimization.recover(root, _session_assess) diff --git a/src/inferrsi/knowledge/channels.py b/src/inferrsi/knowledge/channels.py index 8489b0602..033a8affd 100644 --- a/src/inferrsi/knowledge/channels.py +++ b/src/inferrsi/knowledge/channels.py @@ -189,6 +189,10 @@ class ChannelRegistry: channels: list[Channel] = field(default_factory=list) declared_backend: str | None = None + def named(self, name: str) -> Channel | None: + matches = [channel for channel in self.channels if channel.name == name] + return matches[0] if len(matches) == 1 else None + def for_backend(self, backend: str | None) -> list[Channel]: """Return channels eligible for a declared task backend. diff --git a/tests/test_cannbot_boundaries.py b/tests/test_cannbot_boundaries.py index 0db06500e..985d772e5 100644 --- a/tests/test_cannbot_boundaries.py +++ b/tests/test_cannbot_boundaries.py @@ -273,6 +273,25 @@ def test_native_fingerprint_and_raw_byte_digest_are_distinct(upstream): assert error.value.state == "index_stale" +def test_missing_native_index_keeps_local_find(upstream, capsys): + from inferrsi.apps.cli import main + + _, script, _ = upstream + script.write_text("import sys\nsys.exit('knowledge index is missing: private-index-path')\n") + args = ["find", "cache per-step masks ran out of device memory", "--json"] + assert main([*args, "--no-external"]) == 0 + local = json.loads(capsys.readouterr().out) + assert local["items"] + assert main(args) == 0 + rendered = capsys.readouterr().out + answer = json.loads(rendered) + assert answer["items"] == local["items"] + source, = answer["external"] + assert source["state"] == "index_stale" and source["count"] == 0 + assert "knowledge_index.py build" in source["fix"] + assert "private-index-path" not in rendered + + @pytest.mark.parametrize("backend", [[], ["--backend", "ascend"]]) def test_outside_git_project_reports_not_enabled(tmp_path, monkeypatch, backend): root = tmp_path.resolve() diff --git a/tests/test_knowledge_channels.py b/tests/test_knowledge_channels.py index f039b85f0..98becdfec 100644 --- a/tests/test_knowledge_channels.py +++ b/tests/test_knowledge_channels.py @@ -1,5 +1,7 @@ """External channels: gating, per-channel states, and no mixing into `items`.""" +import json + import pytest from inferrsi.knowledge.channels import ( @@ -231,6 +233,75 @@ def test_registry_declared_backend_is_what_the_task_asked_for(): assert declared.for_backend(declared.declared_backend) == [channel] +def test_apps_share_registered_sources_and_honor_entry_point_gates(tmp_path, monkeypatch, capsys): + from inferrsi.apps.cli import main + from inferrsi.apps.integrations import external_channels + from inferrsi.apps.integrations.cannbot import CHANNEL_NAME + + hit = _hit() + source = FakeChannel(name=CHANNEL_NAME, items=[hit]) + source.declared_backend = "ascend" + other = FakeChannel(name="second", items=[_hit("second/hit")]) + other.declared_backend = "cuda" + reads = [] + registrations = [] + + def register(channel): + def compose(*, root): + registrations.append((channel.name, root)) + return channel + return compose + + def read_page(locator, *, expected_revision, expected_sha256, page, timeout=None): + reads.append((locator, expected_revision, expected_sha256, page, timeout)) + return {"state": "ok", "locator": locator, "revision": expected_revision, + "card_sha256": expected_sha256, "page": page, "pages": 2, "text": "body"} + + source.read_page = read_page + monkeypatch.setattr(external_channels, "_SOURCES", (register(source), register(other))) + find_args = ["find", "cache per-step masks ran out of device memory", "--json"] + + assert main([*find_args, "--no-external"]) == 0 + local = json.loads(capsys.readouterr().out) + assert local["items"] and "external" not in local + assert not registrations + assert main(find_args) == 0 + conflict = json.loads(capsys.readouterr().out) + assert conflict["items"] == local["items"] + assert {row["state"] for row in conflict["external"]} == {BACKEND_UNKNOWN} + assert source.searched == other.searched == 0 + assert main([*find_args, "--backend", "cuda"]) == 0 + assert "external" not in json.loads(capsys.readouterr().out) + assert source.searched == other.searched == 0 + + assert main([*find_args, "--backend", "ascend", "--platform", "a3"]) == 0 + found = json.loads(capsys.readouterr().out) + assert found["items"] == local["items"] + assert [row["channel"] for row in found["external"]] == [CHANNEL_NAME, "second"] + pinned = found["external"][0]["items"][0] + revision = "deadbeef" * 5 + settings = {"channel": CHANNEL_NAME, "backend": "ascend", "platform": "a3"} + checkout = tmp_path / "approved" + nested = checkout / "component" + (checkout / ".git").mkdir(parents=True) + nested.mkdir() + registrations.clear() + provider = external_channels.round_provider({ + "external_knowledge": settings, "task_source": "project", "working_candidate": str(nested), + }) + assert registrations == [(CHANNEL_NAME, checkout.resolve()), ("second", checkout.resolve())] + result = provider.search("same query", settings=settings, limit=1, timeout=30) + assert source.searched == 2 and other.searched == 1 and source.limit_seen == 1 + assert result["items"] == [{"locator": pinned["locator"], + "card_sha256": pinned["card_sha256"], "score": hit.score}] + assert provider.read(hit.locator, revision=revision, card_sha256=hit.card_sha256, + page=2, timeout=30) == {"text": "body", "page": 2, "pages": 2} + assert main(["cannbot", "read", pinned["locator"], "--sha256", pinned["card_sha256"], + "--revision", revision, "--page", "2"]) == 0 + assert json.loads(capsys.readouterr().out)["text"] == "body" + assert [read[:4] for read in reads] == [(hit.locator, revision, hit.card_sha256, 2)] * 2 + + def test_cleanup_failure_is_visible_and_does_not_hide_other_channels(): cleaned = [] diff --git a/tests/test_optimization_session.py b/tests/test_optimization_session.py index 485fe155d..1f49ffc24 100644 --- a/tests/test_optimization_session.py +++ b/tests/test_optimization_session.py @@ -565,12 +565,19 @@ def test_cannbot_query_and_read_trace_to_candidate(tmp_path, task, capsys, monke card_text = "synthetic external body" search_query = "cache per-step masks ran out of device memory" phase = {"state": "ok", "items": [locator, uncited]} - monkeypatch.setattr(project, "describe", lambda *a, **kw: { - "state": "ok", "revision": revision, - }) + approved = tmp_path / "approved" + (approved / ".git").mkdir(parents=True) + unrelated = tmp_path / "unrelated" + (unrelated / ".git").mkdir(parents=True) + monkeypatch.chdir(approved) - def search(query, *, platform, limit, **kwargs): + def describe(root, **kwargs): + assert root == approved.resolve() + return {"state": "ok", "revision": revision} + + def search(query, *, platform, limit, root, **kwargs): assert (query, platform, limit) == (search_query, "a3", 2) + assert root == approved.resolve() if phase["state"] != "ok": raise project.ChannelFailure("private worker diagnostics", state=phase["state"]) return { @@ -581,12 +588,16 @@ def search(query, *, platform, limit, **kwargs): ], } - def read(ref, *, expected_revision, expected_sha256, page, timeout): + def read(ref, *, expected_revision, expected_sha256, page, timeout, root): assert ref in (locator, uncited) - assert (expected_revision, expected_sha256, page) == (revision, digest, 1) + assert root == approved.resolve() + assert (expected_revision, expected_sha256, page) == ( + revision, digest, 2 if ref == locator else 1, + ) return {"state": "ok", "locator": ref, "revision": revision, "card_sha256": digest, - "page": 1, "pages": 1, "text": card_text} + "page": page, "pages": 2, "text": card_text} + monkeypatch.setattr(project, "describe", describe) monkeypatch.setattr(project, "search", search) monkeypatch.setattr(project, "read", read) root = tmp_path / "with-cannbot" @@ -602,7 +613,11 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout): assert not root.exists() assert main(start_args) == 0 started = json.loads(capsys.readouterr().out) - assert started["external_knowledge"]["platform"] == "a3" + assert started["external_knowledge"] == { + "channel": "cannbot-knowledge", "backend": "ascend", "platform": "a3", + } + assert "external_knowledge_project" not in started + monkeypatch.chdir(unrelated) query_args = [*operation, "knowledge", *session_args, "--query", search_query, "--context-bytes", "8192", "--limit", "2"] @@ -632,9 +647,20 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout): capsys.readouterr() assert main([*read_args, uncited]) == 0 capsys.readouterr() - assert main([*read_args, locator]) == 0 + marker = approved / ".git" + saved_marker = approved / "saved-git" + marker.rename(saved_marker) + marker.mkdir() + with pytest.raises(SystemExit): + main([*read_args, locator, "--page", "2"]) + assert "not_enabled" in capsys.readouterr().err + marker.rmdir() + saved_marker.rename(marker) + + assert main([*read_args, locator, "--page", "2"]) == 0 delivery = json.loads(capsys.readouterr().out) assert delivery["context"]["text"] == card_text + assert delivery["receipt"]["page"] == 2 receipt_path = delivery["reference"]["path"] candidate = root / "work/candidate.py" @@ -778,6 +804,60 @@ def observe_pending(root, directory, plan, deadline): dashboard_snapshot(root) +@pytest.mark.parametrize("legacy", [False, True]) +def test_unbound_benchmark_cannot_borrow_another_checkout( + tmp_path, task, capsys, monkeypatch, legacy, +): + from inferrsi.apps.integrations import external_channels + from inferrsi.apps.views.dashboard import dashboard_snapshot + from inferrsi.harness import optimization + + origin = tmp_path / "outside-git" + origin.mkdir() + if any((path / ".git").exists() for path in origin.resolve().parents): + pytest.skip("temporary directory is inside a Git project") + unrelated = tmp_path / "other-checkout" + (unrelated / ".git").mkdir(parents=True) + monkeypatch.chdir(origin) + + def unexpected(**kwargs): + pytest.fail("an unbound session attempted to assemble a project grant") + + monkeypatch.setattr(external_channels, "_SOURCES", (unexpected,)) + if legacy: + initialize = optimization.initialize + + def legacy_plan(root, plan): + plan.pop("external_knowledge_project") + return initialize(root, plan) + + monkeypatch.setattr(optimization, "initialize", legacy_plan) + + root = tmp_path / "unbound" + args = ["benchmarks", "session"] + session_args = ["--session", str(root)] + assert main([*args, "start", task.name, *session_args, "--rounds", "1", "--max-minutes", "5", + "--evaluation-timeout-seconds", "15", "--condition", "unbound-synthetic", + "--evaluation-args", "", "--cannbot-platform", "a3"]) == 0 + capsys.readouterr() + monkeypatch.chdir(unrelated) + diagnose(root, capsys) + assert main([*args, "knowledge", *session_args, "--query", + "cache per-step masks ran out of device memory", "--context-bytes", "8192"]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["context"]["contexts"] + assert result["external"]["state"] == "not_enabled" and result["external"]["items"] == [] + + before = {path: path.read_bytes() for path in root.rglob("*.json")} + assert main([*args, "status", *session_args]) == 0 + status = json.loads(capsys.readouterr().out) + assert status["external_knowledge"]["channel"] == "cannbot-knowledge" + assert "external_knowledge_project" not in status + records = dashboard_snapshot(root)["data"]["managed_retrievals"] + assert records[0]["external"]["state"] == "not_enabled" + assert before == {path: path.read_bytes() for path in root.rglob("*.json")} + + def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor() -> None: from importlib.resources import files diff --git a/tests/test_project_optimization.py b/tests/test_project_optimization.py index 540fac993..670fcea59 100644 --- a/tests/test_project_optimization.py +++ b/tests/test_project_optimization.py @@ -255,11 +255,16 @@ def test_cannbot_timeout_keeps_local_ranking_and_final_budget(project, capsys, m from inferrsi.harness import optimization source, protocol, instructions, root = project + (source / ".git").mkdir() + unrelated = source.with_name("other-checkout") + (unrelated / ".git").mkdir(parents=True) + monkeypatch.chdir(unrelated) local_only = source, protocol, instructions, root.with_name("local-only") query = "cache per-step masks ran out of device memory" budgets = [] - def timeout_worker(*args, timeout, **kwargs): + def timeout_worker(*args, timeout, root, **kwargs): + assert root == source.resolve() budgets.append(timeout) raise channel.ChannelFailure("synthetic worker timeout", state="timeout") From 3b4fa6fba590638b10451043d3ad9eee5943ffed Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:27:43 +0800 Subject: [PATCH 2/2] Revalidate the frozen checkout inside CANNBot calls Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/apps-module-migrations.json | 5 +- docs/optimization-benchmarks.md | 5 +- .../apps/integrations/cannbot/__init__.py | 14 +++-- .../apps/integrations/cannbot/project.py | 23 ++++++-- .../apps/integrations/external_channels.py | 45 +++++++-------- .../apps/integrations/project_binding.py | 42 ++++++++++++++ tests/test_cannbot_boundaries.py | 57 +++++++++++++++++++ tests/test_knowledge_channels.py | 8 ++- tests/test_optimization_session.py | 4 +- 9 files changed, 165 insertions(+), 38 deletions(-) create mode 100644 src/inferrsi/apps/integrations/project_binding.py diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 67bff4877..92320a0b7 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -355,8 +355,10 @@ "consumers": [ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", + "src/inferrsi/apps/integrations/external_channels.py", "tests/check_installed.py", - "tests/test_apps_module_migrations.py" + "tests/test_apps_module_migrations.py", + "tests/test_knowledge_channels.py" ], "package": true, "module_exports": { @@ -385,6 +387,7 @@ "src/inferrsi/apps/cli/arguments.py", "src/inferrsi/apps/integrations/cannbot/__init__.py", "src/inferrsi/apps/integrations/cannbot/round_knowledge.py", + "src/inferrsi/apps/integrations/external_channels.py", "tests/check_installed.py", "tests/test_apps_module_migrations.py", "tests/test_cannbot_boundaries.py", diff --git a/docs/optimization-benchmarks.md b/docs/optimization-benchmarks.md index 7bb0e7e84..f3ae61ff2 100644 --- a/docs/optimization-benchmarks.md +++ b/docs/optimization-benchmarks.md @@ -88,8 +88,9 @@ Add `--cannbot-platform ` at `benchmarks session start` or AB/BA `campaign start` to freeze the external source and an explicit Ascend platform. Start a benchmark session from the Git project with the [CANNBot grant](external-channels.md). An AB/BA campaign uses the Git project of -its `--repo` target. The session records the checkout identity. Later searches -and reads check the grant for that checkout, even when invoked from a different +its `--repo` target. The session records the checkout identity, including the +Git administration directory of linked worktrees. Each search and read checks +that identity and the current grant, even when invoked from a different working directory. Omit the option for a local-only session. The paired `benchmarks compare` conditions keep their existing behavior. diff --git a/src/inferrsi/apps/integrations/cannbot/__init__.py b/src/inferrsi/apps/integrations/cannbot/__init__.py index 9787a1862..e30f47c05 100644 --- a/src/inferrsi/apps/integrations/cannbot/__init__.py +++ b/src/inferrsi/apps/integrations/cannbot/__init__.py @@ -22,12 +22,16 @@ class CannbotChannel: """Approved cannbot-knowledge checkout, queried through its own interpreter.""" - def __init__(self, *, root: Path | None = None, timeout: float = 8.0): + def __init__(self, *, root: Path | None = None, timeout: float = 8.0, + expected_checkout: dict | None = None): from . import project self._project = project self.root = root self.timeout = timeout + self._binding = ( + {"expected_checkout": expected_checkout} if expected_checkout is not None else {} + ) # `hint` records why this channel cannot answer before any search runs. # Keeping it lets `find` report "not enabled" instead of telling the # caller to declare a backend for a source that is not approved yet. @@ -46,7 +50,9 @@ def __init__(self, *, root: Path | None = None, timeout: float = 8.0): def describe(self, *, request: ChannelRequest) -> ChannelStatus: try: - info = self._project.describe(self.root, timeout=request.remaining(), request=request) + info = self._project.describe( + self.root, timeout=request.remaining(), request=request, **self._binding, + ) except self._project.ChannelFailure as exc: return ChannelStatus(exc.state, detail=str(exc), fix=exc.fix) state = info.get("state", "rejected") @@ -64,7 +70,7 @@ def search( try: payload = self._project.search( query, platform=platform, limit=limit, root=self.root, - timeout=request.remaining(), request=request, + timeout=request.remaining(), request=request, **self._binding, ) except self._project.ChannelFailure as exc: return ChannelResult( @@ -110,5 +116,5 @@ def read_page(self, locator: str, *, page: int = 1, expected_sha256: str | None expected_revision: str | None = None, timeout: float = 15.0) -> dict: return self._project.read( locator, page=page, expected_sha256=expected_sha256, - expected_revision=expected_revision, root=self.root, timeout=timeout, + expected_revision=expected_revision, root=self.root, timeout=timeout, **self._binding, ) diff --git a/src/inferrsi/apps/integrations/cannbot/project.py b/src/inferrsi/apps/integrations/cannbot/project.py index 88565c91d..250b1c749 100644 --- a/src/inferrsi/apps/integrations/cannbot/project.py +++ b/src/inferrsi/apps/integrations/cannbot/project.py @@ -15,6 +15,7 @@ import tempfile from pathlib import Path +from ..project_binding import matches_checkout from .read_worker import OutputLimitError, _finite, capture _SCHEMA = "inferrsi-cannbot-project/1" @@ -125,6 +126,15 @@ def load_grant(root: Path | None = None) -> dict: return grant +def _checked_grant(root: Path | None, expected_checkout: dict | None) -> dict: + grant = load_grant(root) + if expected_checkout is not None and ( + root is None or not matches_checkout(root, expected_checkout) + ): + raise ChannelFailure("The checkout no longer matches the external knowledge session") + return grant + + def _run(grant: dict, action: str, arguments: dict, *, timeout: float, request=None) -> dict: environment = os.environ.copy() for key in ("CANNBOT_MCP_TOKENS", "CANNBOT_KNOWLEDGE_PLATFORM"): @@ -165,9 +175,10 @@ def _run(grant: dict, action: str, arguments: dict, *, timeout: float, request=N return payload -def describe(root: Path | None = None, *, timeout: float = 15.0, request=None) -> dict: +def describe(root: Path | None = None, *, timeout: float = 15.0, request=None, + expected_checkout: dict | None = None) -> dict: try: - grant = load_grant(root) + grant = _checked_grant(root, expected_checkout) except ChannelFailure as exc: return {"state": exc.state, "detail": str(exc), "fix": exc.fix} try: @@ -186,12 +197,13 @@ def describe(root: Path | None = None, *, timeout: float = 15.0, request=None) - def search( query: str, *, platform: str | None = None, limit: int = 100, root: Path | None = None, timeout: float = 8.0, request=None, + expected_checkout: dict | None = None, ) -> dict: if not isinstance(query, str) or not query.strip(): raise ChannelFailure("cannbot search needs a non-empty query") if type(limit) is not int or not 1 <= limit <= 200: raise ChannelFailure("cannbot limit must be an integer from 1 through 200") - grant = load_grant(root) + grant = _checked_grant(root, expected_checkout) platforms = list(grant.get("platforms", [])) if platform is None: if not platforms: @@ -209,7 +221,8 @@ def search( def read(locator: str, *, page: int = 1, expected_sha256: str | None = None, expected_revision: str | None = None, - root: Path | None = None, timeout: float = 15.0) -> dict: + root: Path | None = None, timeout: float = 15.0, + expected_checkout: dict | None = None) -> dict: if not isinstance(locator, str) or not locator.strip(): raise ChannelFailure("cannbot read needs a locator from a search result") if type(page) is not int or page < 1: @@ -228,7 +241,7 @@ def read(locator: str, *, page: int = 1, expected_sha256: str | None = None, arguments["expected_sha256"] = expected_sha256 if expected_revision: arguments["expected_revision"] = expected_revision - return _run(load_grant(root), "read", arguments, timeout=timeout) + return _run(_checked_grant(root, expected_checkout), "read", arguments, timeout=timeout) def enable(*, upstream: Path, python: Path, backend: str = "ascend", diff --git a/src/inferrsi/apps/integrations/external_channels.py b/src/inferrsi/apps/integrations/external_channels.py index f34a710e9..6fcb8e959 100644 --- a/src/inferrsi/apps/integrations/external_channels.py +++ b/src/inferrsi/apps/integrations/external_channels.py @@ -4,12 +4,19 @@ from ...knowledge.channels import ChannelRegistry from .cannbot import CHANNEL_NAME, CannbotChannel, project +from .project_binding import checkout_identity, matches_checkout _SOURCES = (CannbotChannel,) -def external_channels(*, root: Path | None = None) -> ChannelRegistry: - channels = [source(root=root) for source in _SOURCES] +def external_channels( + *, root: Path | None = None, expected_checkout: dict | None = None, +) -> ChannelRegistry: + channels = [ + source(root=root, expected_checkout=expected_checkout) if expected_checkout is not None + else source(root=root) + for source in _SOURCES + ] # A project grant can declare the task backend when Find has no explicit # --backend. Conflicting grant defaults leave it undeclared. defaults = {getattr(channel, "declared_backend", None) for channel in channels} - {None} @@ -20,42 +27,34 @@ def external_channels(*, root: Path | None = None) -> ChannelRegistry: def freeze_project(start: Path | None = None) -> dict | None: try: root = project.project_root(start) - return {"root": str(root), "checkout_identity": project.checkout_identity(root)} - except (project.ChannelFailure, OSError, RuntimeError): + return {"root": str(root), "checkout_identity": checkout_identity(root)} + except (ValueError, OSError, RuntimeError): return None -def _bound_root(plan: dict) -> Path | None: - if "external_knowledge_project" not in plan and plan.get("task_source") == "project": - # Older AB/BA plans already froze the absolute editable project path. - working_candidate = plan.get("working_candidate") - if isinstance(working_candidate, str): - candidate = Path(working_candidate) - if candidate.is_absolute() and candidate.is_dir(): - binding = freeze_project(candidate) - return Path(binding["root"]) if binding else None - +def _bound_checkout(plan: dict) -> tuple[Path, dict] | None: binding = plan.get("external_knowledge_project") if not isinstance(binding, dict) or not isinstance(binding.get("root"), str): return None root = Path(binding["root"]) - if not root.is_absolute(): - return None - try: - identity = project.checkout_identity(root) - except (OSError, ValueError): + expected = binding.get("checkout_identity") + if ( + not root.is_absolute() or not isinstance(expected, dict) + or not matches_checkout(root, expected) + ): return None - return root if identity == binding.get("checkout_identity") else None + return root, expected.copy() def round_provider(plan: dict): from .cannbot.round_knowledge import CannbotRoundKnowledge - root = _bound_root(plan) + binding = _bound_checkout(plan) channel = None settings = plan["external_knowledge"] - if root is not None and settings.get("channel") == CHANNEL_NAME: - candidate = external_channels(root=root).named(CHANNEL_NAME) + if binding is not None and settings.get("channel") == CHANNEL_NAME: + root, expected = binding + candidate = external_channels(root=root, expected_checkout=expected).named(CHANNEL_NAME) if candidate is not None and candidate.backend == settings.get("backend"): channel = candidate return CannbotRoundKnowledge(channel) diff --git a/src/inferrsi/apps/integrations/project_binding.py b/src/inferrsi/apps/integrations/project_binding.py new file mode 100644 index 000000000..7071a13b2 --- /dev/null +++ b/src/inferrsi/apps/integrations/project_binding.py @@ -0,0 +1,42 @@ +"""Identify the checkout behind a frozen external knowledge session.""" + +import stat +from pathlib import Path + + +def _identity(path: Path) -> dict: + info = path.stat() + result = {"device": info.st_dev, "inode": info.st_ino} + if hasattr(info, "st_birthtime"): + result["created"] = info.st_birthtime + return result + + +def checkout_identity(root: Path) -> dict: + marker = root / ".git" + mode = marker.lstat().st_mode + if stat.S_ISDIR(mode): + git_dir = marker + elif stat.S_ISREG(mode): + with marker.open("rb") as stream: + raw = stream.read(4097) + declaration = raw.decode().strip() + prefix, _, target = declaration.partition(": ") + if len(raw) > 4096 or prefix != "gitdir" or not target or "\n" in target: + raise ValueError("Invalid worktree Git directory declaration") + git_dir = (root / target).resolve(strict=True) + else: + raise ValueError("Cannot verify the project Git marker") + if not git_dir.is_dir(): + raise ValueError("Cannot verify the worktree Git directory") + return { + "root": _identity(root), "marker": _identity(marker), + "git_dir": str(git_dir), "git_dir_identity": _identity(git_dir), + } + + +def matches_checkout(root: Path, expected: dict) -> bool: + try: + return checkout_identity(root) == expected + except (OSError, ValueError, RuntimeError): + return False diff --git a/tests/test_cannbot_boundaries.py b/tests/test_cannbot_boundaries.py index 985d772e5..aa00e6252 100644 --- a/tests/test_cannbot_boundaries.py +++ b/tests/test_cannbot_boundaries.py @@ -86,6 +86,63 @@ def set_source(script, raw): script.write_text(f"import sys\nsys.stdout.buffer.write({raw!r})\n") +@pytest.mark.parametrize("change", ["revoked", "git_marker", "git_admin"]) +def test_managed_calls_recheck_the_original_checkout(upstream, tmp_path, monkeypatch, change): + from inferrsi.apps.integrations.external_channels import freeze_project, round_provider + + root = Path.cwd().resolve() + marker = root / ".git" + grant_path = project._grant_path(root) + grant = project.load_grant(root) + if change == "git_admin": + marker.rmdir() + admin = tmp_path / "git admin" + admin.mkdir() + marker.write_text(f"gitdir: ../{admin.name}\n", encoding="utf-8") + grant["checkout_identity"] = project.checkout_identity(root) + grant_path.write_bytes(project._json(grant)) + binding = freeze_project(root) + assert binding is not None + settings = {"channel": "cannbot-knowledge", "backend": "ascend", "platform": "a2"} + provider = round_provider({ + "external_knowledge_project": binding, "external_knowledge": settings, + }) + calls = [] + card_digest = "a" * 64 + + def native(grant, action, arguments, *, timeout, request=None): + assert grant["project_root"] == str(root) + calls.append(action) + return {"state": "ok", "revision": REVISION, "items": [], "page": 1, "pages": 1, + "text": "test card", "locator": "ops/card", "card_sha256": card_digest} + + monkeypatch.setattr(project, "_run", native) + other = tmp_path / "unrelated" + (other / ".git").mkdir(parents=True) + monkeypatch.chdir(other) + assert provider.search("query", settings=settings, limit=1, timeout=5)["state"] == "ok" + provider.read("ops/card", revision=REVISION, card_sha256=card_digest, page=1, timeout=5) + assert calls == ["discover", "search", "read"] + calls.clear() + if change == "revoked": + grant_path.unlink() + elif change == "git_marker": + marker.rename(root / "previous-git") + marker.mkdir() + grant["checkout_identity"] = project.checkout_identity(root) + grant_path.write_bytes(project._json(grant)) + assert project.load_grant(root) == grant + else: + # The marker still names the same path and the ordinary grant is valid. + admin.rename(tmp_path / "previous-admin") + admin.mkdir() + assert project.load_grant(root) == grant + assert provider.search("query", settings=settings, limit=1, timeout=5)["state"] != "ok" + with pytest.raises(ValueError, match="CANNBot read failed"): + provider.read("ops/card", revision=REVISION, card_sha256=card_digest, page=1, timeout=5) + assert not calls + + @pytest.mark.parametrize("raw", [ b'{"cards": 1, "cards": 2}', b'{"x": NaN}', b'{"x": Infinity}', b'{"x": -Infinity}', b'{"x": 1e999}', b'[]', b'{"x": {"y": 1, "y": 2}}', diff --git a/tests/test_knowledge_channels.py b/tests/test_knowledge_channels.py index 98becdfec..1575f3784 100644 --- a/tests/test_knowledge_channels.py +++ b/tests/test_knowledge_channels.py @@ -247,7 +247,7 @@ def test_apps_share_registered_sources_and_honor_entry_point_gates(tmp_path, mon registrations = [] def register(channel): - def compose(*, root): + def compose(*, root, expected_checkout=None): registrations.append((channel.name, root)) return channel return compose @@ -286,8 +286,12 @@ def read_page(locator, *, expected_revision, expected_sha256, page, timeout=None (checkout / ".git").mkdir(parents=True) nested.mkdir() registrations.clear() + legacy = {"external_knowledge": settings, "task_source": "project", + "working_candidate": str(nested)} + external_channels.round_provider(legacy) + assert not registrations provider = external_channels.round_provider({ - "external_knowledge": settings, "task_source": "project", "working_candidate": str(nested), + **legacy, "external_knowledge_project": external_channels.freeze_project(nested), }) assert registrations == [(CHANNEL_NAME, checkout.resolve()), ("second", checkout.resolve())] result = provider.search("same query", settings=settings, limit=1, timeout=30) diff --git a/tests/test_optimization_session.py b/tests/test_optimization_session.py index 1f49ffc24..bd6e5d1c8 100644 --- a/tests/test_optimization_session.py +++ b/tests/test_optimization_session.py @@ -557,6 +557,7 @@ def track_read(path, limit): def test_cannbot_query_and_read_trace_to_candidate(tmp_path, task, capsys, monkeypatch): from inferrsi.apps.integrations.cannbot import project + from inferrsi.apps.integrations.project_binding import checkout_identity from inferrsi.apps.views.dashboard import dashboard_snapshot revision, digest = "a" * 40, "b" * 64 @@ -588,9 +589,10 @@ def search(query, *, platform, limit, root, **kwargs): ], } - def read(ref, *, expected_revision, expected_sha256, page, timeout, root): + def read(ref, *, expected_revision, expected_sha256, page, timeout, root, expected_checkout): assert ref in (locator, uncited) assert root == approved.resolve() + assert expected_checkout == checkout_identity(approved.resolve()) assert (expected_revision, expected_sha256, page) == ( revision, digest, 2 if ref == locator else 1, )