From 56a385e5525d4553e3aceec0d04f70ecbdb267fd Mon Sep 17 00:00:00 2001 From: jiangkuaixue123 Date: Fri, 27 Nov 2026 10:43:41 +0800 Subject: [PATCH] Include opted-in MindIE navigation in ordinary Find Agent-assisted-by: Codex (author) Signed-off-by: jiangkuaixue123 --- docs/guides/knowledge/external-channels.md | 8 +- docs/guides/operations.md | 14 +- docs/guides/plugins/codex-plugin.md | 31 ++- src/inferrsi/apps/cli/__init__.py | 10 +- src/inferrsi/apps/cli/arguments.py | 15 +- .../apps/integrations/external_channels.py | 11 +- .../apps/integrations/mindie/navigation.py | 41 +++- .../apps/integrations/mindie/project.py | 25 ++- src/inferrsi/knowledge/channels.py | 14 +- src/inferrsi/knowledge/knowledge_find.py | 20 +- tests/apps/test_mindie_runtime.py | 202 ++++++++++++++++++ 11 files changed, 347 insertions(+), 44 deletions(-) diff --git a/docs/guides/knowledge/external-channels.md b/docs/guides/knowledge/external-channels.md index 8bccdede3..b1773b7c8 100644 --- a/docs/guides/knowledge/external-channels.md +++ b/docs/guides/knowledge/external-channels.md @@ -96,7 +96,9 @@ 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 +through the approved checkout's worker. Ordinary Find also includes MindIE when +the current checkout's independent grant opts in to [default navigation](../plugins/codex-plugin.md#find-navigation). +Managed rounds select CANNBot 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](../../benchmarks/optimization-benchmarks.md#include-cannbot-in-the-round). @@ -154,7 +156,7 @@ register owned resources. Python cannot forcibly stop arbitrary in-process threa | Task backend | Channels searched | | --- | --- | -| `ascend` | `cannbot-knowledge`, plus any platform-neutral channel | +| `ascend` | Eligible CANNBot and opted-in MindIE grants, plus any platform-neutral channel | | `cuda`, `mlx`, `rocm`, `cpu` | none — an Ascend source must not answer a CUDA task | | not declared, no grant | none; each channel reports `backend_unknown` | @@ -232,7 +234,7 @@ conclusion. | `cannbot enable / disable / describe / search / read` | implemented | | `find` integration with gating, budgets, per-channel states | implemented | | Managed CANNBot benchmark and AB/BA round query, read and Dashboard attribution | implemented | -| MindIE native navigation | Explicit opt-in for [standalone Find](../plugins/codex-plugin.md#find-navigation) under an approved Ascend project. Returns navigation references. | +| MindIE native navigation | Project default or per-call selection in [standalone Find](../plugins/codex-plugin.md#find-navigation) under an approved Ascend project. Returns versioned references and condition exclusion counts. | | `cannbot serve` (stdio MCP proxying `discover` / `search` / `read_card`) | not yet | | `campaign import-cannbot` (receipts into evidence) | not yet | | Automatic clone, index build or deployment | deliberately absent | diff --git a/docs/guides/operations.md b/docs/guides/operations.md index babb4499c..a2793fb83 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -312,17 +312,25 @@ to regenerate the index, then retry. searches the packaged corpus. See [fresh-install output and setup](knowledge/external-channels.md#a-fresh-install-has-no-external-channel) for the explicit per-checkout grant and source access requirements. +Ordinary Find can query CANNBot and MindIE together. MindIE requires a separate +checkout grant with `mindie enable --domain operators --default-find --backend ascend`. +Follow the [MindIE rollout and navigation guide](plugins/codex-plugin.md#find-navigation) +before enabling default queries in a project. Existing grants still support +`find --external-source mindie-agent --backend ascend` for explicit MindIE navigation. + - **Inputs:** `--backend ` declares the task backend; **without it and without an approved grant, no channel is searched** and each one reports - `backend_unknown`. `--no-external` skips all channels for CI and offline runs. + its gate status. Conflicting grant backends require an explicit `--backend`. + `--no-external` skips all channels for CI and offline runs. `--external-limit ` overrides the per-channel cap (`cannbot-knowledge` 100, `mindie-agent` 5). `--external-timeout ` bounds discovery and search - together (8s default); `--platform` overrides the upstream platform in the grant. + under one deadline (8s default). `--platform` overrides the CANNBot grant's platform. - **Output:** `external[]` sits beside `items`, never inside it. Each entry carries `state`, `revision`, `elapsed_ms`, `score_scale` and `count`. A state other than `ok` (`not_enabled`, `unreachable`, `index_stale`, `timeout`, `version_mismatch`, `rejected`, `backend_unknown`) means the channel did not - answer — it is **not** the same as answering with no hits. + answer. MindIE lists versioned matched refs and shows condition exclusions by + reason in `withheld`. These counts describe the native domain gate before ranking. - **Side effects:** none on this repository. A channel reads an external checkout that the person approved; nothing is copied into the package, a wheel or `evidence/`. diff --git a/docs/guides/plugins/codex-plugin.md b/docs/guides/plugins/codex-plugin.md index 8ecc2e943..7cb8a1a27 100644 --- a/docs/guides/plugins/codex-plugin.md +++ b/docs/guides/plugins/codex-plugin.md @@ -173,7 +173,24 @@ when the MindIE adapter is installed outside its default location. Run ### Find navigation -Select MindIE for one Find from the approved checkout. +To include MindIE in ordinary Find, opt in from the approved checkout after +the maintainer records verification of the authorized catalog in +[the rollout issue](https://github.com/InferMatrixLab/InferRSI/issues/711). + +```sh +inferrsi mindie enable --domain operators --default-find --backend ascend +inferrsi find "Ascend operator tiling" +``` + +Ordinary Find returns local results and MindIE navigation, with CANNBot cards +when its own grant is enabled and eligible. `mindie describe` shows +`default_find_backend` for an opted-in grant. Re-run `mindie enable` without +the two Find options to keep the domain grant for explicit use. `mindie disable` +revokes the grant and stops default queries. Existing grants retain per-call +selection until re-enabled with `--default-find`. + +To select only MindIE alongside the local corpus for one Find, use the explicit +form from the approved checkout. ```sh inferrsi find "Ascend operator tiling" --backend ascend --external-source mindie-agent @@ -183,9 +200,15 @@ Find keeps the local results and shows the approved domain's versioned MindIE references in native order. It includes a reference only when the native card reports `match_status="matched"`. It uses up to 8,000 native tokens and returns up to five references by default. `--external-limit` can raise the cap to 20, and -`--external-timeout` covers both the availability check and the query. -The MindIE section contains navigation metadata only. The plain Find command -selects CANNBot when eligible. Use `--no-external` for local results alone. +`--external-timeout` gives both sources a shared deadline for discovery and query. +An explicit `--backend` takes precedence. Conflicting project defaults require an +explicit `--backend`. `--platform` applies to CANNBot in ordinary Find. + +The MindIE section shows matched references and `withheld` counts for +`condition_unknown` and `mismatched`. The native condition gate counts exclusions +in the approved domain before ranking, so these counts describe domain filtering. +Use `mindie explain` with an exact versioned ref to inspect a hit. Use +`--no-external` for local results alone. ### MCP configuration and queries diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index f5b12cdf7..2010dcf56 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -197,10 +197,10 @@ def _clip(value: str, limit: int = 160) -> str: return text if len(text) <= limit else text[: limit - 1].rstrip() + "…" -def _channels(*, source: str | None = None): +def _channels(*, source: str | None = None, standalone_find: bool = False): from ..integrations.external_channels import external_channels - return external_channels(source=source) + return external_channels(source=source, standalone_find=standalone_find) def _print_external(result: dict) -> None: @@ -224,6 +224,9 @@ def _print_external(result: dict) -> None: revision = (entry.get("revision") or "")[:12] or "unpinned" heading += f" @ {revision}\t[{entry['score_scale']}]" print(f" {heading}\t{entry.get('count', 0)} hit(s)\t{entry.get('elapsed_ms', 0)} ms") + if (withheld := entry.get("withheld")) is not None: + counts = ", ".join(f"{count} {reason}" for reason, count in withheld.items()) + print(f" withheld by conditions: {counts}") for item in entry.get("items", []): score = f"{item['score']}\t" if "score" in item else "" print(f" {score}{_clip(item['title'], 60)}\t{item['locator']}") @@ -683,7 +686,8 @@ def main(argv: list[str] | None = None) -> int: args.skill_root, kinds=kinds, searchspace_index=searchspace_index, ), limit=args.limit, explain=args.explain, decision_cards=args.decision_cards, - registry=None if args.no_external else _channels(source=args.external_source), + registry=(None if args.no_external else + _channels(source=args.external_source, standalone_find=True)), backend=args.backend, platform=args.platform, external_limit=args.external_limit, external_timeout=args.external_timeout, diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index ec88af237..a908164ae 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -341,6 +341,14 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: mindie_actions = mindie.add_subparsers(dest="mindie_action", required=True) enable = mindie_actions.add_parser("enable", help="Approve a MindIE domain for this checkout") enable.add_argument("--domain", default="operators") + enable.add_argument( + "--default-find", action="store_true", + help="Include this MindIE grant in ordinary Find; requires --backend ascend", + ) + enable.add_argument( + "--backend", choices=("ascend",), + help="Declare the checkout's default task backend for --default-find", + ) enable.add_argument( "--adapter-config", type=Path, default=Path.home() / ".config/mindie-agent/codex.json", help="Installed MindIE Codex adapter configuration", @@ -791,10 +799,11 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: help="Declare the task backend once, e.g. ascend; external channels run only " "for a declared backend and are never inferred from the query", ) - find.add_argument("--platform", help="Override the grant’s upstream platform, e.g. a2") + find.add_argument("--platform", help="Override the CANNBot grant’s platform, e.g. a2") find.add_argument( "--external-source", choices=("mindie-agent",), - help="Explicitly select MindIE navigation for this Find; requires --backend ascend", + help="Select only MindIE for this Find; requires --backend ascend. Ordinary Find " + "includes project grants enabled with mindie enable --default-find", ) find.add_argument( "--no-external", action="store_true", @@ -806,7 +815,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: ) find.add_argument( "--external-timeout", type=float, default=8.0, - help="Per-channel budget in seconds; a timeout is reported, never shown as no hit", + help="Shared discovery and query deadline in seconds for the external sources", ) find.add_argument("--json", action="store_true") diff --git a/src/inferrsi/apps/integrations/external_channels.py b/src/inferrsi/apps/integrations/external_channels.py index 205c99675..41252b571 100644 --- a/src/inferrsi/apps/integrations/external_channels.py +++ b/src/inferrsi/apps/integrations/external_channels.py @@ -11,6 +11,7 @@ def external_channels( *, root: Path | None = None, expected_checkout: dict | None = None, source: str | None = None, + standalone_find: bool = False, ) -> ChannelRegistry: if source is not None: from .mindie.navigation import MindieNavigationChannel @@ -26,11 +27,19 @@ def external_channels( if expected_checkout is not None else channel_type(root=root) for channel_type in _SOURCES ] + if standalone_find: + from .mindie.navigation import MindieNavigationChannel + + mindie = MindieNavigationChannel(root=root, expected_checkout=expected_checkout) + if mindie.declared_backend is not None: + channels.append(mindie) # 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) + return ChannelRegistry( + channels, declared_backend=backend, conflicting_defaults=len(defaults) > 1, + ) def freeze_project(start: Path | None = None) -> dict | None: diff --git a/src/inferrsi/apps/integrations/mindie/navigation.py b/src/inferrsi/apps/integrations/mindie/navigation.py index 5b79e03c1..1b593ae43 100644 --- a/src/inferrsi/apps/integrations/mindie/navigation.py +++ b/src/inferrsi/apps/integrations/mindie/navigation.py @@ -1,4 +1,4 @@ -"""Explicit, project-authorized MindIE navigation for standalone Find.""" +"""Project-authorized MindIE navigation for standalone Find.""" from __future__ import annotations @@ -105,12 +105,15 @@ def read_output(): request.finish(process) -def _navigation_hits(payload: dict, *, domain: str, limit: int) -> tuple[ChannelHit, ...]: +def _navigation_results( + payload: dict, *, domain: str, limit: int, +) -> tuple[tuple[ChannelHit, ...], dict[str, int]]: # The pinned graded repository returns ordered cards in navigation mode. rows = payload.get("cards") if not isinstance(rows, list): raise _NavigationFailure(_BAD_RESPONSE) hits = {} + withheld_refs = {"condition_unknown": set(), "mismatched": set()} valid = False for row in rows: ref = row.get("ref") if isinstance(row, dict) else None @@ -125,20 +128,32 @@ def _navigation_hits(payload: dict, *, domain: str, limit: int) -> tuple[Channel if status not in ("matched", "mismatched", "condition_unknown"): continue valid = True - if status != "matched" or ref in hits: - continue - hits[ref] = ChannelHit(ref, match["id"], score=None, score_scale="", status=status) - if len(hits) == limit: - break + if status == "matched": + if ref not in hits and len(hits) < limit: + hits[ref] = ChannelHit(ref, match["id"], score=None, score_scale="", status=status) + else: + withheld_refs[status].add(ref) if rows and not valid: raise _NavigationFailure(_BAD_RESPONSE) - return tuple(hits.values()) + # v0.13.13 filters conditions before scoring. Its counts describe the + # native condition gate for this domain, not the number of lexical hits. + excluded = payload.get("excluded_conditions", {}) + if not isinstance(excluded, dict): + raise _NavigationFailure(_BAD_RESPONSE) + withheld = {} + for reason, upstream in (("condition_unknown", "unknown"), ("mismatched", "mismatch")): + count = excluded.get(upstream, len(withheld_refs[reason])) + if type(count) is not int or count < 0: + raise _NavigationFailure(_BAD_RESPONSE) + withheld[reason] = count + return tuple(hits.values()), withheld class MindieNavigationChannel: name = "mindie-agent" - backend = "ascend" + backend = project.FIND_BACKEND navigation_only = True + accepts_platform = False def __init__(self, *, root: Path | None = None, expected_checkout: dict | None = None): self._root = None @@ -154,6 +169,10 @@ def __init__(self, *, root: Path | None = None, expected_checkout: dict | None = except (OSError, ValueError, RuntimeError): pass + @property + def declared_backend(self) -> str | None: + return self._grant.get("default_find_backend") if self._grant is not None else None + def _approved(self) -> dict: if self._root is None or self._checkout is None or self._grant is None: raise _NavigationFailure(_NOT_ENABLED) @@ -228,10 +247,10 @@ def search( project._check_arguments("query", arguments, domain) payload = self._run("query", {**arguments, "include_archived": False}, request) self._approved() - hits = _navigation_hits(payload, domain=domain, limit=limit) + hits, withheld = _navigation_results(payload, domain=domain, limit=limit) except _NavigationFailure as exc: return ChannelResult(self.name, exc.status) - return ChannelResult(self.name, ChannelStatus("ok"), hits) + return ChannelResult(self.name, ChannelStatus("ok"), hits, withheld=withheld) def read(self, locator: str, *, expected_sha256: str | None = None, expected_revision: str | None = None) -> str: diff --git a/src/inferrsi/apps/integrations/mindie/project.py b/src/inferrsi/apps/integrations/mindie/project.py index 2ec6daa6f..4adb44f51 100644 --- a/src/inferrsi/apps/integrations/mindie/project.py +++ b/src/inferrsi/apps/integrations/mindie/project.py @@ -14,6 +14,7 @@ from .context import MAX_BYTES, _parse _SCHEMA = "inferrsi-mindie-project/1" +FIND_BACKEND = "ascend" _DOMAIN = re.compile(r"[a-z][a-z0-9-]{0,63}") _WORKER = Path(__file__).with_name("read_worker.py") _REF_ID = r"[A-Za-z0-9_.-]+@[1-9][0-9]*" @@ -86,6 +87,7 @@ def _load_grant(root: Path) -> dict: if (grant.get("schema") != _SCHEMA or grant.get("project_root") != str(root) or grant.get("checkout") != checkout or not isinstance(grant.get("domain"), str) or not _DOMAIN.fullmatch(grant["domain"]) + or grant.get("default_find_backend", FIND_BACKEND) != FIND_BACKEND or any(not isinstance(grant.get(key), str) or not Path(grant[key]).is_absolute() for key in ("python", "engine"))): raise ValueError("The MindIE grant does not match this project") @@ -129,8 +131,14 @@ def _worker(grant: dict, action: str, arguments: bytes) -> bytes: return result.stdout -def enable(adapter: Path, domain: str) -> dict: +def enable( + adapter: Path, domain: str, *, default_find: bool = False, backend: str | None = None, +) -> dict: """Approve this checkout for one installed, already synced MindIE domain.""" + if default_find and backend != FIND_BACKEND: + raise ValueError("--default-find requires --backend ascend") + if not default_find and backend is not None: + raise ValueError("--backend requires --default-find") root = project_root() if not _DOMAIN.fullmatch(domain): raise ValueError("Invalid MindIE domain") @@ -146,6 +154,8 @@ def enable(adapter: Path, domain: str) -> dict: schema=_SCHEMA, project_root=str(root), checkout=_checkout_identity(root), python=python, engine=str(Path(engine).resolve(strict=True)), domain=domain, ) + if default_find: + grant["default_find_backend"] = backend info = _parse(_worker(grant, "describe", b"{}")) path = _grant_path(root) path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) @@ -157,7 +167,7 @@ def enable(adapter: Path, domain: str) -> dict: pending.replace(path) finally: pending.unlink(missing_ok=True) - return {"available": True, **info} + return {"available": True, **info, **_find_setting(grant)} def disable() -> dict: @@ -171,7 +181,13 @@ def describe() -> dict: info = _parse(_worker(grant, "describe", b"{}")) except ValueError as exc: return {"available": False, "reason": str(exc)} - return {"available": True, "tools": ["knowledge_query", "knowledge_explain"], **info} + return {"available": True, "tools": ["knowledge_query", "knowledge_explain"], + **info, **_find_setting(grant)} + + +def _find_setting(grant: dict) -> dict: + backend = grant.get("default_find_backend") + return {"default_find_backend": backend} if backend is not None else {} def _check_arguments(action: str, arguments: dict, domain: str) -> None: @@ -242,7 +258,8 @@ def call(action: str, arguments: dict, *, session: str | None = None) -> dict: def dispatch(args) -> dict | None: if args.mindie_action == "enable": - return enable(args.adapter_config, args.domain) + return enable(args.adapter_config, args.domain, + default_find=args.default_find, backend=args.backend) if args.mindie_action == "disable": return disable() if args.mindie_action == "describe": diff --git a/src/inferrsi/knowledge/channels.py b/src/inferrsi/knowledge/channels.py index 19b35cb40..fa5ee6fae 100644 --- a/src/inferrsi/knowledge/channels.py +++ b/src/inferrsi/knowledge/channels.py @@ -139,6 +139,7 @@ class ChannelResult: elapsed_ms: int = 0 score_scale: str = "" read_prefix: str = "" + withheld: dict[str, int] | None = None def view(self) -> dict: record: dict[str, Any] = {"channel": self.name, **self.status.view()} @@ -146,6 +147,8 @@ def view(self) -> dict: if self.score_scale: record["score_scale"] = self.score_scale record["count"] = len(self.items) + if self.withheld is not None: + record["withheld"] = self.withheld.copy() if self.items: record["items"] = [ item.view(read_prefix=self.read_prefix, revision=self.status.revision) @@ -189,6 +192,7 @@ class ChannelRegistry: channels: list[Channel] = field(default_factory=list) declared_backend: str | None = None + conflicting_defaults: bool = False def named(self, name: str) -> Channel | None: matches = [channel for channel in self.channels if channel.name == name] @@ -327,8 +331,9 @@ def search_channels( pending = [] def work(channel, request, future): + channel_platform = platform if getattr(channel, "accepts_platform", True) else None future.set_result(_run_one( - channel, query, platform=platform, + channel, query, platform=channel_platform, limit=limit or DEFAULT_LIMITS.get(channel.name, FALLBACK_LIMIT), request=request, started=started, )) @@ -373,6 +378,11 @@ def explain_gate(registry: ChannelRegistry, backend: str | None) -> list[dict]: """ if backend is not None: return [] + detail = ( + "Project source grants declare conflicting task backends; choose --backend explicitly." + if registry.conflicting_defaults + else "No task backend was declared; external channels are not searched." + ) records = [] for channel in registry.ungated(): hint = getattr(channel, "hint", None) @@ -389,7 +399,7 @@ def explain_gate(registry: ChannelRegistry, backend: str | None) -> list[dict]: "backend": channel.backend, "state": BACKEND_UNKNOWN, "fix": f"inferrsi find --backend {channel.backend or ''}", - "detail": "No task backend was declared; external channels are not searched.", + "detail": detail, }) return records diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index e5fec6f5e..5b932bcab 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -1089,17 +1089,17 @@ def _with_channels( gated = explain_gate(registry, declared) if gated: result.setdefault("external", []).extend(gated) - if (results or gated) and all( - getattr(channel, "navigation_only", False) for channel in registry.channels - ): - result["external_notes"] = [ - "External navigation follows source order and provides references only.", - ] - elif results or gated: - result["external_notes"] = [ + navigation = [getattr(channel, "navigation_only", False) for channel in registry.channels] + notes = [] + if (results or gated) and not all(navigation): + notes.extend([ "External results are not locally verified; scores are not " "comparable across channels.", "Pin the reported revision when citing an external locator.", - "Open external cards with the channel's read command, not `read`.", - ] + "Open external cards with their emitted channel read commands.", + ]) + if (results or gated) and any(navigation): + notes.append("External navigation follows source order and provides references only.") + if notes: + result["external_notes"] = notes return result diff --git a/tests/apps/test_mindie_runtime.py b/tests/apps/test_mindie_runtime.py index 056a7d3eb..8c5825c8d 100644 --- a/tests/apps/test_mindie_runtime.py +++ b/tests/apps/test_mindie_runtime.py @@ -13,6 +13,7 @@ import pytest from inferrsi.apps.cli import main +from inferrsi.apps.integrations import external_channels from inferrsi.apps.integrations.cannbot import project as cannbot_project from inferrsi.apps.integrations.mindie import navigation from inferrsi.apps.integrations.mindie import project as mindie_project @@ -168,6 +169,21 @@ def query(self, query, *, navigation_only=False, **kwargs): "match_status": "matched"} for i in range(23) ], "results": []} prefix = "mindie://operators/units/" + if query == "navigation-no-match": + return {"cards": [], "excluded_conditions": {}} + if query == "navigation-withheld-native": + return { + "cards": [], + "excluded_conditions": { + "unknown": 3, "mismatch": 2, "archived_or_superseded": 1, + }, + "unverified_cards": [{ + "ref": prefix + "unit-unknown@1", + "match_status": "condition_unknown", + }], + } + if query == "navigation-invalid-counts": + return {"cards": [], "excluded_conditions": {"unknown": True}} if query == "navigation-unmatched": return {"cards": [ {"ref": prefix + "unit-unknown@1", @@ -332,6 +348,7 @@ def enabled_navigation(reader, tmp_path, monkeypatch): _NAVIGATION = ["--backend", "ascend", "--external-source", "mindie-agent"] +_DEFAULT_FIND = ["--default-find", "--backend", "ascend"] def _find_navigation(capsys, query, *options): @@ -458,6 +475,191 @@ def test_navigation_excludes_explicit_native_nonmatches(enabled_navigation, caps entry = _find_navigation(capsys, "navigation-unmatched") assert entry["state"] == "ok" and entry["count"] == 0 assert "items" not in entry + assert entry["withheld"] == {"condition_unknown": 1, "mismatched": 1} + + +@pytest.fixture +def project_sources(enabled_navigation, tmp_path, monkeypatch, capsys): + checkout, _, _ = enabled_navigation + upstream = tmp_path / "cannbot" + (upstream / ".git").mkdir(parents=True) + (upstream / "knowledge").mkdir() + script = upstream / ".agents/skills/knowledge-query/scripts/knowledge_query.py" + script.parent.mkdir(parents=True) + script.touch() + cannbot_calls, mindie_calls = [], [] + real_start = navigation._start + real_search = navigation.MindieNavigationChannel.search + + def cannbot_worker(grant, action, arguments, *, timeout, request=None): + cannbot_calls.append((action, arguments, request)) + if action == "discover": + return {"revision": "a" * 40, "cards": 1} + if arguments["query"] == "navigation-cannbot-error": + raise cannbot_project.ChannelFailure("fixture search failed") + return {"revision": "a" * 40, "items": [{ + "locator": "ops/fixture", "title": "CANNBot fixture", "score": 1, + "card_sha256": "a" * 64, + }]} + + def start_mindie(argv, **kwargs): + mindie_calls.append(argv[-1]) + return real_start(argv, **kwargs) + + def search_mindie(self, query, *, platform, limit, request): + assert platform is None + return real_search(self, query, platform=platform, limit=limit, request=request) + + def enable(*, mindie=False, cannbot=None): + if mindie: + assert main(["mindie", "enable", "--adapter-config", str(tmp_path / "adapter.json"), + *_DEFAULT_FIND]) == 0 + assert json.loads(capsys.readouterr().out)["default_find_backend"] == "ascend" + if cannbot is not None: + assert main(["cannbot", "enable", "--checkout", str(upstream), "--python", + sys.executable, "--backend", cannbot, "--platform", "a2"]) == 0 + capsys.readouterr() + cannbot_calls.clear() + + monkeypatch.setattr(cannbot_project, "_run", cannbot_worker) + monkeypatch.setattr(navigation, "_start", start_mindie) + monkeypatch.setattr(navigation.MindieNavigationChannel, "search", search_mindie) + return checkout, enable, cannbot_calls, mindie_calls + + +def _find_sources(capsys, query, *args): + assert main(["find", query, "--json", *args]) == 0 + found = json.loads(capsys.readouterr().out) + return found, {entry["channel"]: entry for entry in found.get("external", [])} + + +@pytest.mark.parametrize("mindie,cannbot", [(True, True), (True, False), (False, True)]) +def test_ordinary_find_uses_independently_approved_sources( + project_sources, capsys, mindie, cannbot, +): + _, enable, cannbot_calls, mindie_calls = project_sources + enable(mindie=mindie, cannbot="ascend" if cannbot else None) + query = "navigation-order" + local, entries = _find_sources(capsys, query, "--no-external") + assert not entries and not mindie_calls and not cannbot_calls + + found, entries = _find_sources(capsys, query) + assert found["items"] == local["items"] and local["items"] + assert found["backend"] == "ascend" + if cannbot: + assert entries["cannbot-knowledge"]["items"][0]["locator"] == "ops/fixture" + assert [(action, arguments) for action, arguments, _ in cannbot_calls] == [ + ("discover", {}), ("search", {"query": query, "platform": "a2", "limit": 100}), + ] + assert cannbot_calls[0][2] is cannbot_calls[1][2] + else: + assert entries["cannbot-knowledge"]["state"] == "not_enabled" + assert not cannbot_calls + if mindie: + entry = entries["mindie-agent"] + assert entry["state"] == "ok" + assert [hit["locator"] for hit in entry["items"]] == [ + "mindie://operators/units/unit-z@3", "mindie://operators/units/unit-a@2", + ] + assert mindie_calls == ["describe", "query"] + else: + assert "mindie-agent" not in entries and not mindie_calls + + +def test_ordinary_find_requires_backend_when_grants_conflict(project_sources, capsys): + _, enable, cannbot_calls, mindie_calls = project_sources + enable(mindie=True, cannbot="cuda") + _, entries = _find_sources(capsys, "navigation-order") + assert set(entries) == {"cannbot-knowledge", "mindie-agent"} + assert all(entry["state"] == "backend_unknown" for entry in entries.values()) + assert all("conflicting task backends" in entry["detail"] for entry in entries.values()) + _, entries = _find_sources(capsys, "navigation-order", "--backend", "cuda") + assert not entries and not mindie_calls and not cannbot_calls + + _, entries = _find_sources( + capsys, "navigation-order", "--backend", "ascend", "--platform", "a3", + ) + assert all(entry["state"] == "ok" for entry in entries.values()) + assert mindie_calls == ["describe", "query"] + assert cannbot_calls[-1][1]["platform"] == "a3" + + +def test_default_find_grant_revocation_and_managed_scope(project_sources, capsys): + checkout, enable, cannbot_calls, mindie_calls = project_sources + enable(mindie=True, cannbot="ascend") + assert main(["mindie", "describe"]) == 0 + assert json.loads(capsys.readouterr().out)["default_find_backend"] == "ascend" + settings = {"channel": "cannbot-knowledge", "backend": "ascend", "platform": "a2"} + provider = external_channels.round_provider({ + "external_knowledge": settings, + "external_knowledge_project": external_channels.freeze_project(checkout), + }) + assert provider.search("fixture", settings=settings, limit=1, timeout=5)["state"] == "ok" + assert [action for action, _, _ in cannbot_calls] == ["discover", "search"] + assert not mindie_calls + + assert main(["mindie", "disable"]) == 0 + capsys.readouterr() + _, entries = _find_sources(capsys, "navigation-order") + assert entries["cannbot-knowledge"]["state"] == "ok" + assert "mindie-agent" not in entries and not mindie_calls + + +def test_default_find_requires_explicit_opt_in_and_backend(project_sources, tmp_path, capsys): + _, enable, cannbot_calls, mindie_calls = project_sources + command = ["mindie", "enable", "--adapter-config", str(tmp_path / "adapter.json")] + for args, message in ( + (["--default-find"], "--default-find requires --backend ascend"), + (["--backend", "ascend"], "--backend requires --default-find"), + ): + with pytest.raises(SystemExit) as error: + main([*command, *args]) + assert error.value.code == 2 + assert message in capsys.readouterr().err + + enable(mindie=True, cannbot="ascend") + _, entries = _find_sources(capsys, "navigation-order", *_NAVIGATION) + assert set(entries) == {"mindie-agent"} and not cannbot_calls + + assert main(command) == 0 + assert "default_find_backend" not in json.loads(capsys.readouterr().out) + mindie_calls.clear() + _, entries = _find_sources(capsys, "navigation-order") + assert set(entries) == {"cannbot-knowledge"} and not mindie_calls + + +@pytest.mark.parametrize("query,failed,state", [ + ("navigation-malformed", "mindie-agent", "rejected"), + ("navigation-timeout", "mindie-agent", "timeout"), + ("navigation-cannbot-error", "cannbot-knowledge", "rejected"), +]) +def test_ordinary_find_preserves_completed_sources(project_sources, capsys, query, failed, state): + _, enable, _, _ = project_sources + enable(mindie=True, cannbot="ascend") + local, _ = _find_sources(capsys, query, "--no-external") + found, entries = _find_sources(capsys, query, "--external-timeout", "2") + assert found["items"] == local["items"] and local["items"] + assert entries.pop(failed)["state"] == state + completed, = entries.values() + assert completed["state"] == "ok" and completed["items"] + + +def test_ordinary_find_exposes_native_condition_counts(project_sources, capsys): + _, enable, _, _ = project_sources + enable(mindie=True) + for query, expected in ( + ("navigation-no-match", {"condition_unknown": 0, "mismatched": 0}), + ("navigation-withheld-native", {"condition_unknown": 3, "mismatched": 2}), + ): + _, entries = _find_sources(capsys, query) + entry = entries["mindie-agent"] + assert entry["state"] == "ok" and entry["count"] == 0 + assert entry["withheld"] == expected + assert "unit-unknown" not in json.dumps(entry) + _, entries = _find_sources(capsys, "navigation-invalid-counts") + assert entries["mindie-agent"]["state"] == "rejected" + assert main(["find", "navigation-withheld-native"]) == 0 + assert "withheld by conditions: 3 condition_unknown, 2 mismatched" in capsys.readouterr().out def test_navigation_requires_explicit_ascend_backend(enabled_navigation, monkeypatch, capsys):