diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 92320a0b7..869b5905b 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -391,6 +391,7 @@ "tests/check_installed.py", "tests/test_apps_module_migrations.py", "tests/test_cannbot_boundaries.py", + "tests/test_mindie_runtime.py", "tests/test_optimization_session.py", "tests/test_project_optimization.py" ] @@ -438,6 +439,7 @@ "docs/module-layout.md", "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/mindie/mcp.py", + "src/inferrsi/apps/integrations/mindie/navigation.py", "src/inferrsi/apps/integrations/mindie/project.py", "tests/check_installed.py", "tests/test_apps_module_migrations.py", @@ -461,6 +463,7 @@ "docs/module-layout.md", "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/integrations/mindie/mcp.py", + "src/inferrsi/apps/integrations/mindie/navigation.py", "tests/check_installed.py", "tests/test_apps_module_migrations.py", "tests/test_mindie_project.py", diff --git a/docs/codex-plugin.md b/docs/codex-plugin.md index c3f8f803d..bc6821ef1 100644 --- a/docs/codex-plugin.md +++ b/docs/codex-plugin.md @@ -129,6 +129,22 @@ New sessions in that checkout reuse the grant. Use `--adapter-config ` when the MindIE adapter is installed outside its default location. Run `inferrsi mindie disable` from the same checkout to revoke the grant. +### Find navigation + +Select MindIE for one Find from the approved checkout. + +```sh +inferrsi find "Ascend operator tiling" --backend ascend --external-source mindie-agent +``` + +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. + ### MCP configuration and queries Add the following entry to the trusted checkout's `.codex/config.toml`. diff --git a/docs/external-channels.md b/docs/external-channels.md index 3cb54ecaf..95ca820ec 100644 --- a/docs/external-channels.md +++ b/docs/external-channels.md @@ -142,11 +142,13 @@ it (1–200). These are returned hits, not the total number of upstream matches. `--external-timeout` covers discovery and search together. Channels run concurrently under that deadline. On timeout the caller cancels owned worker processes and discards late results; subprocess teardown adds a short cleanup -interval. The cannbot adapter terminates its process group on POSIX; Windows -uses `taskkill /T /F` while the worker is alive. The new process-tree regression -runs on POSIX; Windows cleanup has not been qualified by that test. Generic -Python channel adapters must cooperate with the request deadline and register -owned resources; Python cannot forcibly stop arbitrary in-process threads. +interval. The CANNBot adapter terminates its process group on POSIX and uses +`taskkill /T /F` while the Windows worker is alive. Its process-tree regression +runs on POSIX. MindIE Find starts its Windows worker inside a Job Object, so +cleanup covers descendants after the launcher exits. Find reports `rejected` if +cleanup cannot confirm that the job is empty. +Generic Python channel adapters must cooperate with the request deadline and +register owned resources. Python cannot forcibly stop arbitrary in-process threads. ### The backend gate @@ -223,14 +225,14 @@ Whether CANN OSL v2.0 permits even a local read-only copy is an open question fo the organisation; see #476 Q1. This page documents the mechanism, not a legal conclusion. -## What is not implemented +## Capability status | Capability | State | | --- | --- | | `cannbot enable / disable / describe / search / read` | implemented | | `find` integration with gating, budgets, per-channel states | implemented | -| Managed benchmark and AB/BA round query, read and Dashboard attribution | implemented | -| MindIE as a second channel | not yet; `apps/integrations/mindie/` has the reader, not the adapter | +| Managed CANNBot benchmark and AB/BA round query, read and Dashboard attribution | implemented | +| MindIE native navigation | Explicit opt-in for [standalone Find](codex-plugin.md#find-navigation) under an approved Ascend project. Returns navigation references. | | `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/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index fdd9e95a1..34d4a4ca6 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -164,10 +164,10 @@ def _clip(value: str, limit: int = 160) -> str: return text if len(text) <= limit else text[: limit - 1].rstrip() + "…" -def _channels(): +def _channels(*, source: str | None = None): from ..integrations.external_channels import external_channels - return external_channels() + return external_channels(source=source) def _print_external(result: dict) -> None: @@ -186,13 +186,17 @@ def _print_external(result: dict) -> None: if entry.get("fix"): print(f" fix: {_clip(entry['fix'], 120)}") continue - revision = (entry.get("revision") or "")[:12] or "unpinned" - print(f" {entry['channel']} @ {revision}\t[{entry['score_scale']}]" - f"\t{entry.get('count', 0)} hit(s)\t{entry.get('elapsed_ms', 0)} ms") + heading = entry["channel"] + if entry.get("score_scale"): + 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") for item in entry.get("items", []): - print(f" {item['score']}\t{_clip(item['title'], 60)}\t{item['locator']}") - if entry.get("items"): - print(f" open: {entry['items'][0].get('open', '')}") + score = f"{item['score']}\t" if "score" in item else "" + print(f" {score}{_clip(item['title'], 60)}\t{item['locator']}") + first = next(iter(entry.get("items", [])), {}) + if first.get("open"): + print(f" open: {first['open']}") for note in result.get("external_notes", []): print(f" note: {_clip(note, 140)}") @@ -589,6 +593,13 @@ def main(argv: list[str] | None = None) -> int: unknown = [k for k in kinds if k not in ("case", "skill", "record")] if unknown or not kinds: raise ValueError("--kinds takes a subset of case,skill,record") + if args.external_source and not args.no_external: + if args.backend != "ascend": + raise ValueError("--external-source mindie-agent requires --backend ascend") + if args.platform: + raise ValueError( + "--platform applies to CANNBot. MindIE uses the approved domain." + ) coordinate = None if args.searchspace_coordinate is not None: from ...knowledge.searchspace_index import load_searchspace_coordinate @@ -602,7 +613,7 @@ def main(argv: list[str] | None = None) -> int: searchspace_index=coordinate.index if coordinate is not None else None, ), limit=args.limit, explain=args.explain, - registry=None if args.no_external else _channels(), + registry=None if args.no_external else _channels(source=args.external_source), 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 76ce65928..bcd25ac95 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -690,6 +690,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: "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( + "--external-source", choices=("mindie-agent",), + help="Explicitly select MindIE navigation for this Find; requires --backend ascend", + ) find.add_argument( "--no-external", action="store_true", help="Skip every external channel; use in CI and offline runs", diff --git a/src/inferrsi/apps/integrations/external_channels.py b/src/inferrsi/apps/integrations/external_channels.py index 6fcb8e959..205c99675 100644 --- a/src/inferrsi/apps/integrations/external_channels.py +++ b/src/inferrsi/apps/integrations/external_channels.py @@ -10,12 +10,21 @@ def external_channels( - *, root: Path | None = None, expected_checkout: dict | None = None, + *, root: Path | None = None, expected_checkout: dict | None = None, source: str | None = None, ) -> ChannelRegistry: + if source is not None: + from .mindie.navigation import MindieNavigationChannel + + if source != MindieNavigationChannel.name: + raise ValueError("Unknown explicit external knowledge source") + return ChannelRegistry([ + MindieNavigationChannel(root=root, expected_checkout=expected_checkout), + ]) + channels = [ - source(root=root, expected_checkout=expected_checkout) if expected_checkout is not None - else source(root=root) - for source in _SOURCES + channel_type(root=root, expected_checkout=expected_checkout) + if expected_checkout is not None else channel_type(root=root) + for channel_type in _SOURCES ] # A project grant can declare the task backend when Find has no explicit # --backend. Conflicting grant defaults leave it undeclared. diff --git a/src/inferrsi/apps/integrations/mindie/_windows_worker.py b/src/inferrsi/apps/integrations/mindie/_windows_worker.py new file mode 100644 index 000000000..c926b8be6 --- /dev/null +++ b/src/inferrsi/apps/integrations/mindie/_windows_worker.py @@ -0,0 +1,242 @@ +"""Launch the MindIE reader already contained in a Windows Job Object.""" + +import ctypes +import msvcrt +import os +import subprocess +import time +import weakref +from contextlib import ExitStack +from ctypes import wintypes as win + +_KILL_ON_JOB_CLOSE = 0x2000 +_LIMIT_ACTIVE_PROCESSES = 0x8 +_PROCESS_IDS = 3 +_EXTENDED_LIMITS = 9 +_HANDLE_LIST = 0x20002 +_JOB_LIST = 0x2000D +_USE_STD_HANDLES = 0x100 +_EXTENDED_STARTUPINFO = 0x80000 +_UNICODE_ENVIRONMENT = 0x400 +_WAIT_OBJECT_0 = 0 +_WAIT_TIMEOUT = 258 +_MAX_WAIT_MS = 0xFFFFFFFE +_SYNCHRONIZE = 0x100000 +_QUERY_LIMITED_INFORMATION = 0x1000 +_ERROR_INVALID_PARAMETER = 87 +_ERROR_MORE_DATA = 234 +_CLEANUP_SECONDS = 0.5 + + +class _BasicLimits(ctypes.Structure): + _fields_ = [ + ("per_process_time", ctypes.c_int64), ("per_job_time", ctypes.c_int64), + ("flags", win.DWORD), ("min_working_set", ctypes.c_size_t), + ("max_working_set", ctypes.c_size_t), ("process_limit", win.DWORD), + ("affinity", ctypes.c_size_t), ("priority", win.DWORD), ("scheduling", win.DWORD), + ] + + +class _ExtendedLimits(ctypes.Structure): + _fields_ = [ + ("basic", _BasicLimits), ("io_counters", ctypes.c_uint64 * 6), + ("memory_limits", ctypes.c_size_t * 4), + ] + + +class _StartupInfo(ctypes.Structure): + _fields_ = [ + ("size", win.DWORD), ("reserved", win.LPWSTR), ("desktop", win.LPWSTR), + ("title", win.LPWSTR), ("coordinates_and_fill", win.DWORD * 7), + ("flags", win.DWORD), ("show_window", win.WORD), ("reserved_bytes", win.WORD), + ("reserved_data", ctypes.c_void_p), ("stdin", win.HANDLE), ("stdout", win.HANDLE), + ("stderr", win.HANDLE), + ] + + +class _StartupInfoEx(ctypes.Structure): + _fields_ = [("startup", _StartupInfo), ("attributes", ctypes.c_void_p)] + + +class _ProcessInfo(ctypes.Structure): + _fields_ = [ + ("process", win.HANDLE), ("thread", win.HANDLE), ("pid", win.DWORD), + ("thread_id", win.DWORD), + ] + + +_KERNEL = ctypes.WinDLL("kernel32", use_last_error=True) +_SIZE = ctypes.c_size_t +_POINTER = ctypes.c_void_p + + +def _winapi(name, result, *arguments): + fn = getattr(_KERNEL, name) + fn.restype = result + fn.argtypes = arguments + return fn + + +_create_job = _winapi("CreateJobObjectW", win.HANDLE, _POINTER, win.LPCWSTR) +_set_job = _winapi("SetInformationJobObject", win.BOOL, win.HANDLE, ctypes.c_int, + _POINTER, win.DWORD) +_query_job = _winapi("QueryInformationJobObject", win.BOOL, win.HANDLE, ctypes.c_int, + _POINTER, win.DWORD, _POINTER) +_terminate_job = _winapi("TerminateJobObject", win.BOOL, win.HANDLE, win.UINT) +_close_handle = _winapi("CloseHandle", win.BOOL, win.HANDLE) +_open_process = _winapi("OpenProcess", win.HANDLE, win.DWORD, win.BOOL, win.DWORD) +_is_in_job = _winapi("IsProcessInJob", win.BOOL, win.HANDLE, win.HANDLE, ctypes.POINTER(win.BOOL)) +_init_attributes = _winapi("InitializeProcThreadAttributeList", win.BOOL, _POINTER, + win.DWORD, win.DWORD, ctypes.POINTER(_SIZE)) +_update_attributes = _winapi("UpdateProcThreadAttribute", win.BOOL, _POINTER, win.DWORD, + _SIZE, _POINTER, _SIZE, _POINTER, _POINTER) +_delete_attributes = _winapi("DeleteProcThreadAttributeList", None, _POINTER) +_create_process = _winapi("CreateProcessW", win.BOOL, win.LPCWSTR, win.LPWSTR, _POINTER, + _POINTER, win.BOOL, win.DWORD, _POINTER, win.LPCWSTR, + ctypes.POINTER(_StartupInfoEx), ctypes.POINTER(_ProcessInfo)) +_wait = _winapi("WaitForSingleObject", win.DWORD, win.HANDLE, win.DWORD) +_exit_code = _winapi("GetExitCodeProcess", win.BOOL, win.HANDLE, ctypes.POINTER(win.DWORD)) + + +def _check(success): + if not success: + raise ctypes.WinError(ctypes.get_last_error()) + return success + + +def _launch(argv, cwd, environment, job, input_handle, output_handle, stderr_handle): + size = _SIZE() + _init_attributes(None, 2, 0, ctypes.byref(size)) + attributes = ctypes.create_string_buffer(size.value) + _check(_init_attributes(attributes, 2, 0, ctypes.byref(size))) + try: + handles = (win.HANDLE * 3)(input_handle, output_handle, stderr_handle) + jobs = (win.HANDLE * 1)(job) + for attribute, value in ((_HANDLE_LIST, handles), (_JOB_LIST, jobs)): + _check(_update_attributes( + attributes, 0, attribute, value, ctypes.sizeof(value), None, None, + )) + startup = _StartupInfoEx() + startup.startup.size = ctypes.sizeof(startup) + startup.startup.flags = _USE_STD_HANDLES + startup.startup.stdin, startup.startup.stdout, startup.startup.stderr = handles + startup.attributes = ctypes.addressof(attributes) + command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv)) + env = ctypes.create_unicode_buffer("\0".join( + f"{key}={environment[key]}" for key in sorted(environment, key=str.upper) + ) + "\0") + info = _ProcessInfo() + flags = subprocess.CREATE_NO_WINDOW | _EXTENDED_STARTUPINFO | _UNICODE_ENVIRONMENT + _check(_create_process( + argv[0], command, None, None, True, flags, env, str(cwd), + ctypes.byref(startup), ctypes.byref(info), + )) + _close_handle(info.thread) + return info.process + finally: + _delete_attributes(attributes) + + +def _inheritable(stream): + handle = msvcrt.get_osfhandle(stream.fileno()) + os.set_handle_inheritable(handle, True) + return handle + + +def _set_limits(job, flags): + limits = _ExtendedLimits() + limits.basic.flags = flags + _check(_set_job(job, _EXTENDED_LIMITS, ctypes.byref(limits), ctypes.sizeof(limits))) + + +def _process_ids(job): + count = 16 + while True: + class _ProcessIds(ctypes.Structure): + _fields_ = [("assigned", win.DWORD), ("listed", win.DWORD), ("pids", _SIZE * count)] + + members = _ProcessIds() + found = _query_job(job, _PROCESS_IDS, ctypes.byref(members), ctypes.sizeof(members), None) + if found and members.assigned == members.listed: + return members.pids[:members.listed] + if not found and ctypes.get_last_error() != _ERROR_MORE_DATA: + _check(found) + if members.assigned <= count: + raise OSError("Windows returned an incomplete MindIE worker process list") + count = members.assigned + + +def _wait_for_process(handle, timeout): + milliseconds = int(min(max(0, timeout), _MAX_WAIT_MS / 1000) * 1000) + result = _wait(handle, milliseconds) + if result == _WAIT_TIMEOUT: + raise subprocess.TimeoutExpired("MindIE reader", timeout) + _check(result == _WAIT_OBJECT_0) + + +class WindowsWorker: + def __init__(self, argv, *, cwd, env): + with ExitStack() as launch, ExitStack() as owned: + job = _check(_create_job(None, None)) + owned.callback(_close_handle, job) + _set_limits(job, _KILL_ON_JOB_CLOSE) + + input_read, input_write = os.pipe() + self.stdin = owned.enter_context(os.fdopen(input_write, "wb")) + child_stdin = launch.enter_context(os.fdopen(input_read, "rb")) + output_read, output_write = os.pipe() + self.stdout = owned.enter_context(os.fdopen(output_read, "rb")) + child_stdout = launch.enter_context(os.fdopen(output_write, "wb")) + child_stderr = launch.enter_context(open(os.devnull, "wb")) + self._process = _launch( + argv, cwd, env, job, _inheritable(child_stdin), _inheritable(child_stdout), + _inheritable(child_stderr), + ) + # A waiter can still be unwinding on the channel thread during cancellation. + # Keep the process handle until the last user releases this worker object. + weakref.finalize(self, _close_handle, self._process) + self._job = job + self._confirmed_empty = False + owned.pop_all() + + def wait(self, timeout): + _wait_for_process(self._process, timeout) + code = win.DWORD() + _check(_exit_code(self._process, ctypes.byref(code))) + return code.value + + def _terminate_and_wait(self): + deadline = time.monotonic() + _CLEANUP_SECONDS + # A zero process limit prevents new job members while handles are collected. + # Job accounting can reach zero before an exiting process handle signals. + _set_limits(self._job, _KILL_ON_JOB_CLOSE | _LIMIT_ACTIVE_PROCESSES) + with ExitStack() as handles: + processes = [self._process] + for pid in _process_ids(self._job): + if time.monotonic() >= deadline: + return False + handle = _open_process(_SYNCHRONIZE | _QUERY_LIMITED_INFORMATION, False, pid) + if not handle and ctypes.get_last_error() == _ERROR_INVALID_PARAMETER: + continue # The member exited before its handle was opened. + _check(handle) + handles.callback(_close_handle, handle) + member = win.BOOL() + _check(_is_in_job(handle, self._job, ctypes.byref(member))) + if member.value: + processes.append(handle) + if len(processes) > 1: + _check(_terminate_job(self._job, 1)) + for handle in processes: + _wait_for_process(handle, deadline - time.monotonic()) + return not _process_ids(self._job) + + def stop(self): + if self._job is not None: + try: + self._confirmed_empty = self._terminate_and_wait() + finally: + # Closing the non-inheritable job is also a kill-on-close backstop. + _check(_close_handle(self._job)) + self._job = None + if not self._confirmed_empty: + raise OSError("MindIE worker tree cleanup could not be confirmed") diff --git a/src/inferrsi/apps/integrations/mindie/navigation.py b/src/inferrsi/apps/integrations/mindie/navigation.py new file mode 100644 index 000000000..5b79e03c1 --- /dev/null +++ b/src/inferrsi/apps/integrations/mindie/navigation.py @@ -0,0 +1,238 @@ +"""Explicit, project-authorized MindIE navigation for standalone Find.""" + +from __future__ import annotations + +import os +import queue +import re +import signal +import subprocess +import threading +from contextlib import ExitStack, suppress +from pathlib import Path + +from ....knowledge.channels import ChannelHit, ChannelRequest, ChannelResult, ChannelStatus +from ..project_binding import checkout_identity, matches_checkout +from . import project +from .context import MAX_BYTES, _parse + +_TOKEN_BUDGET = 8000 +_NATIVE_LIMIT = 20 +_REF = re.compile( + r"mindie://(?P[a-z][a-z0-9-]{0,63})/units/" + r"(?P[A-Za-z0-9][A-Za-z0-9_.-]{0,127})@(?P[1-9][0-9]*)" +) +_NOT_ENABLED = ChannelStatus( + "not_enabled", detail="No active MindIE grant matches the captured project checkout.", + fix="Enable MindIE knowledge for the current project.", +) +_WORKER_ERRORS = { + "The project reader supports mindie-knowledge 0.13.13": ChannelStatus( + "version_mismatch", detail="MindIE navigation requires mindie-knowledge 0.13.13.", + ), + "The installed MindIE domain differs from the project grant": ChannelStatus( + "rejected", detail="The installed MindIE domain differs from the project grant.", + ), + "The approved MindIE domain has no synced graded catalog": ChannelStatus( + "unreachable", detail="The approved MindIE domain has no synced graded catalog.", + ), +} +_UNREACHABLE = ChannelStatus("unreachable", detail="The approved MindIE reader is unavailable.") +_BAD_RESPONSE = ChannelStatus("rejected", detail="MindIE returned invalid navigation data.") + + +class _NavigationFailure(ValueError): + def __init__(self, status: ChannelStatus): + super().__init__(status.detail) + self.status = status + + +def _start(argv, *, cwd, env): + if os.name == "nt": + from ._windows_worker import WindowsWorker + + return WindowsWorker(argv, cwd=cwd, env=env) + return subprocess.Popen( + argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + cwd=cwd, env=env, start_new_session=os.name == "posix", + ) + + +def _stop(process) -> None: + if os.name == "nt": + process.stop() + return + try: + if os.name == "posix": + with suppress(ProcessLookupError): + os.killpg(process.pid, signal.SIGKILL) + finally: + if process.poll() is None: + with suppress(ProcessLookupError): + process.kill() + process.wait(timeout=2) + + +def _exchange(start, stop, arguments: bytes, request: ChannelRequest) -> tuple[int, bytes]: + """Read a bounded pipe and reap the worker on deadline or excess output.""" + process = request.start(start, stop) + output: queue.Queue[bytes] = queue.Queue(maxsize=1) + + def write_input(): + with suppress(OSError), process.stdin as stream: + stream.write(arguments) + + def read_output(): + try: + with process.stdout as stream: + raw = stream.read(MAX_BYTES + 1) + except OSError: + raw = b"" + output.put(raw) + + try: + threading.Thread(target=write_input, daemon=True).start() + threading.Thread(target=read_output, daemon=True).start() + raw = output.get(timeout=request.remaining()) + if len(raw) > MAX_BYTES: + raise _NavigationFailure( + ChannelStatus("rejected", detail="MindIE navigation output exceeded 2 MiB.") + ) + return process.wait(timeout=request.remaining()), raw + except (queue.Empty, subprocess.TimeoutExpired): + raise TimeoutError from None + finally: + request.finish(process) + + +def _navigation_hits(payload: dict, *, domain: str, limit: int) -> tuple[ChannelHit, ...]: + # The pinned graded repository returns ordered cards in navigation mode. + rows = payload.get("cards") + if not isinstance(rows, list): + raise _NavigationFailure(_BAD_RESPONSE) + hits = {} + valid = False + for row in rows: + ref = row.get("ref") if isinstance(row, dict) else None + match = _REF.fullmatch(ref) if isinstance(ref, str) and len(ref) <= 256 else None + if match is None or match["domain"] != domain: + continue + revision = row.get("revision") + if ("revision" in row and (type(revision) is not int or str(revision) != match["revision"]) + or "id" in row and row["id"] != match["id"]): + continue + status = row.get("match_status") + 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 rows and not valid: + raise _NavigationFailure(_BAD_RESPONSE) + return tuple(hits.values()) + + +class MindieNavigationChannel: + name = "mindie-agent" + backend = "ascend" + navigation_only = True + + def __init__(self, *, root: Path | None = None, expected_checkout: dict | None = None): + self._root = None + self._checkout = None + self._grant = None + try: + self._root = project.project_root(root) + self._checkout = ( + expected_checkout.copy() if expected_checkout is not None + else checkout_identity(self._root) + ) + self._grant = project._load_grant(self._root) + except (OSError, ValueError, RuntimeError): + pass + + def _approved(self) -> dict: + if self._root is None or self._checkout is None or self._grant is None: + raise _NavigationFailure(_NOT_ENABLED) + try: + current = project._load_grant(self._root) + except (OSError, ValueError, RuntimeError): + raise _NavigationFailure(_NOT_ENABLED) from None + if current != self._grant or not matches_checkout(self._root, self._checkout): + raise _NavigationFailure(_NOT_ENABLED) + return self._grant + + def _run(self, action: str, arguments: dict, request: ChannelRequest) -> dict: + request.remaining() + grant = self._approved() + workspace = ExitStack() + + def start(): + with ExitStack() as preparing: + argv, cwd, environment = preparing.enter_context( + project._worker_context(grant, action), + ) + self._approved() + request.remaining() + process = _start(argv, cwd=cwd, env=environment) + # Only the request's serialized cleanup owns the workspace after launch. + workspace.enter_context(preparing.pop_all()) + return process + + def stop(process): + try: + _stop(process) + finally: + workspace.close() + + try: + code, raw = _exchange(start, stop, project._json(arguments), request) + except TimeoutError: + raise + except (OSError, subprocess.SubprocessError): + raise _NavigationFailure(_UNREACHABLE) from None + request.remaining() + try: + payload = _parse(raw) + except ValueError: + raise _NavigationFailure(_BAD_RESPONSE) from None + if (code or payload.get("isError") or payload.get("error") + or payload.get("status") in ("error", "failed", "inactive", "denied")): + error = payload.get("error") + status = _WORKER_ERRORS.get(error) if isinstance(error, str) else None + raise _NavigationFailure(status or _UNREACHABLE) + return payload + + def describe(self, *, request: ChannelRequest) -> ChannelStatus: + try: + payload = self._run("describe", {}, request) + if payload.get("domain") != self._approved()["domain"]: + return _BAD_RESPONSE + except _NavigationFailure as exc: + return exc.status + return ChannelStatus("ok") + + def search( + self, query: str, *, platform: str | None, limit: int, request: ChannelRequest, + ) -> ChannelResult: + try: + domain = self._approved()["domain"] + limit = min(limit, _NATIVE_LIMIT) + arguments = { + "query": query, "limit": limit, "token_budget": _TOKEN_BUDGET, + "conditions": {}, "include_unknown": False, + } + 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) + except _NavigationFailure as exc: + return ChannelResult(self.name, exc.status) + return ChannelResult(self.name, ChannelStatus("ok"), hits) + + def read(self, locator: str, *, expected_sha256: str | None = None, + expected_revision: str | None = None) -> str: + raise ValueError("Standalone Find provides MindIE navigation only") diff --git a/src/inferrsi/apps/integrations/mindie/project.py b/src/inferrsi/apps/integrations/mindie/project.py index 8a7fb091a..2ec6daa6f 100644 --- a/src/inferrsi/apps/integrations/mindie/project.py +++ b/src/inferrsi/apps/integrations/mindie/project.py @@ -8,6 +8,7 @@ import re import subprocess import tempfile +from contextlib import contextmanager from pathlib import Path from .context import MAX_BYTES, _parse @@ -27,8 +28,8 @@ def __init__(self, message, *, exit_code=None, response=None): self.response = response -def project_root() -> Path: - cwd = Path.cwd().resolve() +def project_root(start: Path | None = None) -> Path: + cwd = (Path.cwd() if start is None else start).resolve() for folder in (cwd, *cwd.parents): if (folder / ".git").exists(): return folder @@ -91,19 +92,25 @@ def _load_grant(root: Path) -> dict: return grant -def _worker(grant: dict, action: str, arguments: bytes) -> bytes: +@contextmanager +def _worker_context(grant: dict, action: str): environment = os.environ.copy() environment.pop("MINDIE_BENCH_WORKSPACE", None) + with tempfile.TemporaryDirectory(prefix="inferrsi-mindie-read-") as temporary: + # Upstream also probes cwd.parent/workspace and cwd.parent/work. + # Keep that parent private and empty, not the shared temp directory. + cwd = Path(temporary) / "reader" + cwd.mkdir(mode=0o700) + argv = [grant["python"], "-I", "-B", str(_WORKER), + grant["engine"], grant["domain"], action] + yield argv, cwd, environment + + +def _worker(grant: dict, action: str, arguments: bytes) -> bytes: try: - with tempfile.TemporaryDirectory(prefix="inferrsi-mindie-read-") as temporary: - # Upstream also probes cwd.parent/workspace and cwd.parent/work. - # Keep that parent private and empty, not the shared temp directory. - cwd = Path(temporary) / "reader" - cwd.mkdir(mode=0o700) + with _worker_context(grant, action) as (argv, cwd, environment): result = subprocess.run( - [grant["python"], "-I", "-B", str(_WORKER), - grant["engine"], grant["domain"], action], - input=arguments, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + argv, input=arguments, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=cwd, env=environment, timeout=20, check=False, ) except (OSError, subprocess.TimeoutExpired): diff --git a/src/inferrsi/apps/integrations/mindie/read_worker.py b/src/inferrsi/apps/integrations/mindie/read_worker.py index 54b1adfa3..51ca9d4d9 100644 --- a/src/inferrsi/apps/integrations/mindie/read_worker.py +++ b/src/inferrsi/apps/integrations/mindie/read_worker.py @@ -13,6 +13,7 @@ from threading import RLock from time import perf_counter from types import SimpleNamespace +from urllib.parse import quote def read(engine_path, domain, action, arguments): @@ -40,8 +41,15 @@ def _rebuild_index(self, catalog, started): if engine.get("domain") != domain: raise ValueError("The installed MindIE domain differs from the project grant") root = state_root(engine["root"], domain) - database = (root / "state-v4.sqlite3").as_uri() + "?mode=ro" - with closing(sqlite3.connect(database, uri=True, timeout=3)) as db: + database = root / "state-v4.sqlite3" + drive = database.drive + if drive.startswith("\\\\?\\") and len(drive) == 6 and drive.endswith(":"): + # Keep the Windows extended-length drive prefix in the SQLite path. + # Path.as_uri() treats it as an authority, which SQLite rejects. + uri = "file:" + quote(str(database), safe="") + else: + uri = database.as_uri() + with closing(sqlite3.connect(uri + "?mode=ro", uri=True, timeout=3)) as db: db.row_factory = sqlite3.Row db.execute("BEGIN") store = SimpleNamespace(db=db, root=root, domain=domain, lock=RLock()) diff --git a/src/inferrsi/knowledge/channels.py b/src/inferrsi/knowledge/channels.py index 033a8affd..19b35cb40 100644 --- a/src/inferrsi/knowledge/channels.py +++ b/src/inferrsi/knowledge/channels.py @@ -93,7 +93,7 @@ class ChannelHit: locator: str title: str - score: float + score: float | None score_scale: str summary: str = "" status: str = "" @@ -105,9 +105,10 @@ def view(self, *, read_prefix: str, revision: str | None = None) -> dict: record: dict[str, Any] = { "locator": self.locator, "title": self.title, - "score": round(self.score, 2), - "score_scale": self.score_scale, } + if self.score is not None: + record["score"] = round(self.score, 2) + record["score_scale"] = self.score_scale if self.summary: record["summary"] = self.summary if self.status: diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index 97f810f12..99bb03164 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -966,7 +966,13 @@ def _with_channels( gated = explain_gate(registry, declared) if gated: result.setdefault("external", []).extend(gated) - if results or 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"] = [ "External results are not locally verified; scores are not " "comparable across channels.", diff --git a/tests/test_mindie_runtime.py b/tests/test_mindie_runtime.py index 5eb9ec854..6044e559c 100644 --- a/tests/test_mindie_runtime.py +++ b/tests/test_mindie_runtime.py @@ -6,13 +6,20 @@ import subprocess import sys import textwrap +import time import venv from pathlib import Path import pytest +from inferrsi.apps.cli import main +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 from inferrsi.apps.integrations.mindie.context import MAX_BYTES +from inferrsi.knowledge import knowledge_find +from inferrsi.knowledge.knowledge_find import load_corpus +from inferrsi.knowledge.searchspace_index import LIBRARY @pytest.fixture @@ -45,6 +52,9 @@ def __init__(self, units): "graded/repository.py": ''' import os import sqlite3 + import subprocess + import sys + import time from pathlib import Path class GradedRepository: @@ -79,6 +89,9 @@ def query(self, query, *, navigation_only=False, **kwargs): root = ledger.parent.parent if ledger else roots[0] if (root / "logs").is_dir(): (root / "logs/knowledge_query_audit.jsonl").write_text(query) + if "include_archived" in kwargs: + assert bench is None and ledger is None and cwd.name == "reader" + return {"cards": [], "results": []} return {"cwd": str(cwd), "bench_workspace": bench, "ledger": ledger.read_text() if ledger else None} if query == "value-error": @@ -99,6 +112,101 @@ def query(self, query, *, navigation_only=False, **kwargs): "value": self.store.db.execute( "SELECT value FROM sentinel").fetchone()["value"]} self.observe_delivered(index, payload, delivery="query") + if query.startswith("navigation-") or query == "graph mode": + assert navigation_only + assert kwargs == { + "conditions": {}, "token_budget": 8000, + "include_unknown": False, "include_archived": False, + "limit": 20 if query == "navigation-limit" else 5, + } + if query == "navigation-timeout": + time.sleep(30) + if query in ("navigation-detached-output", "navigation-parent-exit"): + marker = Path(__file__).with_name("reader-child.pid") + program = ( + "import os, sys, time; from pathlib import Path; " + "Path(sys.argv[1]).write_text(str(os.getpid())); time.sleep(15)" + ) + holds_stdout = query == "navigation-parent-exit" + child = subprocess.Popen( + [sys._base_executable, "-I", "-c", program, str(marker)], + stdout=sys.stdout if holds_stdout else subprocess.DEVNULL, + ) + while not marker.is_file() and child.poll() is None: + time.sleep(0.01) + assert marker.is_file() + if holds_stdout: + os._exit(0) + if query == "navigation-oversized": + sys.stdout.write("X" * (2 * 1024 * 1024 + 1)) + sys.stdout.flush() + time.sleep(30) + if query == "navigation-malformed": + return {"cards": {"private": "FIXTURE_PRIVATE_PATH"}, "results": []} + if query in ("navigation-missing-status", "navigation-empty-status"): + item = {"ref": "mindie://operators/units/unit-1@1"} + if query == "navigation-empty-status": + item["match_status"] = "" + return {"cards": [item], "results": [item]} + if query == "navigation-native-cards": + item = {"ref": "mindie://operators/units/unit-z@3", + "id": "unit-z", "revision": 3, "match_status": "matched"} + return {"cards": [item], "results": []} + if query == "navigation-foreign": + return {"cards": [{"ref": "mindie://foreign/units/unit-1@1", + "match_status": "matched"}], "results": []} + if query == "navigation-denied": + return { + "status": "denied", + "cards": [{"ref": "mindie://operators/units/unit-1@1", + "match_status": "matched"}], + "results": [], + } + if query == "navigation-limit": + return {"cards": [ + {"ref": f"mindie://operators/units/unit-{i}@1", + "match_status": "matched"} for i in range(23) + ], "results": []} + prefix = "mindie://operators/units/" + if query == "navigation-unmatched": + return {"cards": [ + {"ref": prefix + "unit-unknown@1", + "match_status": "condition_unknown"}, + {"ref": prefix + "unit-mismatched@1", "match_status": "mismatched"}, + ], "results": []} + return { + "results": [ + {"ref": prefix + "unit-legacy@1", "match_status": "matched"}, + ], + "foundation_cards": [ + {"ref": prefix + "unit-foundation@1", "match_status": "matched"}, + ], + "unverified_cards": [ + {"ref": prefix + "unit-unverified@1", + "match_status": "condition_unknown"}, + ], + "cards": [ + {"ref": prefix + "unit-z@3"}, + {"ref": prefix + "unit-z@3", "match_status": "matched", + "excerpt": "FIXTURE_PRIVATE_PATH", "body": "fixture body", + "score": 42, "card_sha256": "fake", "revision": 3}, + {"ref": prefix + "unit-z@3", "match_status": "matched"}, + {"ref": prefix + "unit-empty@1", "match_status": ""}, + {"ref": prefix + "unit-invalid@1", "match_status": ["matched"]}, + {"ref": prefix + "unit-unknown@1", + "match_status": "condition_unknown"}, + {"ref": prefix + "unit-mismatched@1", "match_status": "mismatched"}, + {"ref": "mindie://foreign/units/unit-1@1", + "match_status": "matched"}, + {"ref": prefix + "unit-unpinned", "match_status": "matched"}, + {"ref": prefix + "unit-revision-conflict@3", + "revision": 4, "match_status": "matched"}, + {"ref": prefix + "unit-id-conflict@1", + "id": "unit-other", "match_status": "matched"}, + {"ref": prefix + "unit-a@2", "match_status": "matched"}, + ], + "revision": "fixture-generation", "raw_response": "fixture body", + } return payload def explain(self, refs, **kwargs): @@ -125,8 +233,17 @@ def explain(self, refs, **kwargs): return {"python": str(python), "engine": str(engine), "domain": "operators"}, metadata -def test_worker_query_and_explain_are_read_only(reader): +@pytest.mark.parametrize("extended_path", [ + False, + pytest.param(True, marks=pytest.mark.skipif(os.name != "nt", reason="Windows extended path")), +]) +def test_worker_query_and_explain_are_read_only(reader, extended_path): grant, _ = reader + if extended_path: + engine_path = Path(grant["engine"]) + engine = json.loads(engine_path.read_text(encoding="utf-8")) + engine["root"] = "\\\\?\\" + engine["root"] + engine_path.write_text(json.dumps(engine), encoding="utf-8") query = json.loads(mindie_project._worker(grant, "query", b'{"query":"fixture"}')) assert query == {"results": [{"ref": "mindie://operators/units/fixture@1"}], "navigation_only": True, "value": "original"} @@ -193,6 +310,392 @@ def test_worker_masks_private_library_errors(reader, query, message): assert b"FIXTURE_PRIVATE_PATH" not in error.value.response +@pytest.fixture +def enabled_navigation(reader, tmp_path, monkeypatch): + grant, metadata = reader + home = tmp_path / "home" + home.mkdir() + monkeypatch.setattr(Path, "home", lambda: home) + checkout = tmp_path / "checkout" + (checkout / ".git").mkdir(parents=True) + monkeypatch.chdir(checkout) + adapter = tmp_path / "adapter.json" + adapter.write_text(json.dumps({"python": grant["python"], "engine_config": grant["engine"]}), + encoding="utf-8") + assert mindie_project.enable(adapter, "operators")["available"] + corpus = knowledge_find.Corpus([knowledge_find.Document( + "fixture-nav", "skill", "active", None, "Local navigation", "navigation", + {"title": "Local navigation"}, + )]) + monkeypatch.setattr(knowledge_find, "load_corpus", lambda *args, **kwargs: corpus) + return checkout, metadata, Path(grant["engine"]) + + +_NAVIGATION = ["--backend", "ascend", "--external-source", "mindie-agent"] + + +def _find_navigation(capsys, query, *options): + assert main(["find", query, *_NAVIGATION, *options, "--json"]) == 0 + raw = capsys.readouterr().out + assert "FIXTURE_PRIVATE_PATH" not in raw and "fixture body" not in raw + return json.loads(raw)["external"][0] + + +def test_explicit_navigation_preserves_native_order_and_local_results( + enabled_navigation, tmp_path, monkeypatch, capsys, +): + checkout, _, _ = enabled_navigation + real_exchange = navigation._exchange + started = [] + processes = [] + request_path = mindie_project._grant_path(checkout).parent + protected = [request_path, tmp_path / "knowledge"] + before = {path: path.read_bytes() for root in protected + for path in root.rglob("*") if path.is_file()} + + def observe(start, stop, arguments, request): + def observed_start(): + process = start() + processes.append(process) + started.append(request) + return process + + return real_exchange(observed_start, stop, arguments, request) + + monkeypatch.setattr(navigation, "_exchange", observe) + monkeypatch.setattr(cannbot_project, "load_grant", lambda root: {"backend": "ascend"}) + monkeypatch.setattr(cannbot_project, "describe", lambda *args, **kwargs: {"state": "ok"}) + monkeypatch.setattr(cannbot_project, "search", lambda *args, **kwargs: {"items": [ + {"locator": "fixture", "score": 42, "title": "CANNBot fixture"}, + ]}) + command = ["find", "navigation-order", "--json"] + assert main([*command, "--no-external"]) == 0 + local = json.loads(capsys.readouterr().out) + assert main(command) == 0 + default = json.loads(capsys.readouterr().out) + cannbot, = default["external"] + assert cannbot["channel"] == "cannbot-knowledge" and cannbot["state"] == "ok" + assert default["backend"] == "ascend" and cannbot["items"][0]["score"] == 42 + assert default["items"] == local["items"] + assert local["items"] + assert not started + + assert main([*command, *_NAVIGATION]) == 0 + raw = capsys.readouterr().out + assert "fixture body" not in raw and "FIXTURE_PRIVATE_PATH" not in raw + found = json.loads(raw) + assert found["items"] == local["items"] + entry, = found["external"] + assert entry["state"] == "ok" + assert not {"revision", "score_scale"} & entry.keys() + assert entry["items"] == [ + {"locator": "mindie://operators/units/unit-z@3", "title": "unit-z", "status": "matched"}, + {"locator": "mindie://operators/units/unit-a@2", "title": "unit-a", "status": "matched"}, + ] + assert len(started) == 2 and started[0] is started[1] + assert all(process.wait(timeout=1) == 0 for process in processes) + assert {path: path.read_bytes() for root in protected + for path in root.rglob("*") if path.is_file()} == before + + assert main(["find", "navigation-order", *_NAVIGATION]) == 0 + rendered = capsys.readouterr().out + assert "mindie://operators/units/unit-z@3" in rendered + assert "open:" not in rendered and "fixture-generation" not in rendered + assert _find_navigation(capsys, "navigation-limit", "--external-limit", "30")["count"] == 20 + + +@pytest.mark.parametrize("query", ["navigation-missing-status", "navigation-empty-status"]) +def test_navigation_rejects_unclassified_refs(enabled_navigation, capsys, query): + entry = _find_navigation(capsys, query) + assert entry["state"] == "rejected" and entry["count"] == 0 + assert entry["detail"] == "MindIE returned invalid navigation data." + + +def test_navigation_reads_pinned_native_cards(enabled_navigation, capsys): + entry = _find_navigation(capsys, "navigation-native-cards") + assert entry["state"] == "ok" and entry["count"] == 1 + assert entry["items"] == [ + {"locator": "mindie://operators/units/unit-z@3", "title": "unit-z", "status": "matched"}, + ] + + +def test_navigation_leaves_native_results_independent_of_local_coordinate( + enabled_navigation, monkeypatch, capsys, +): + monkeypatch.setattr(knowledge_find, "load_corpus", load_corpus) + root = Path(__file__).resolve().parents[1] / LIBRARY + command = [ + "find", "graph mode", *_NAVIGATION, "--skill-root", str(root), + "--kinds", "skill", "--limit", "1", "--json", + ] + assert main(command) == 0 + baseline = json.loads(capsys.readouterr().out) + assert baseline["items"][0]["id"] == "ascend-graph-mode" + assert baseline["external"][0]["count"] == 2 + + assert main([*command, "--searchspace-coordinate", "SSD", "Configure"]) == 0 + filtered = json.loads(capsys.readouterr().out) + assert filtered["items"][0]["id"] == "ascend-model-adaptation" + assert filtered["searchspace_filter"]["stage"] == "Configure" + before, = baseline["external"] + after, = filtered["external"] + assert after["channel"] == before["channel"] == "mindie-agent" + assert after["state"] == before["state"] == "ok" + assert after["items"] == before["items"] + + +def test_navigation_excludes_explicit_native_nonmatches(enabled_navigation, capsys): + entry = _find_navigation(capsys, "navigation-unmatched") + assert entry["state"] == "ok" and entry["count"] == 0 + assert "items" not in entry + + +def test_navigation_requires_explicit_ascend_backend(enabled_navigation, monkeypatch, capsys): + def never(*args): + pytest.fail("MindIE must be gated before starting its worker") + + monkeypatch.setattr(navigation, "_exchange", never) + selected = ["find", "navigation-order", "--external-source", "mindie-agent"] + for arguments, message in ( + ([], "requires --backend ascend"), + (["--backend", "cuda"], "requires --backend ascend"), + (["--backend", "ascend", "--platform", "a3"], "--platform applies to CANNBot"), + ): + with pytest.raises(SystemExit) as error: + main([*selected, *arguments]) + assert error.value.code == 2 + assert message in capsys.readouterr().err + assert main([*selected, "--no-external", "--json"]) == 0 + assert "external" not in json.loads(capsys.readouterr().out) + + +@pytest.mark.parametrize( + "change", ["revoke", "revoke-at-launch", "replace-checkout", "change-grant"], +) +def test_navigation_rejects_grant_changes_before_query_launch( + enabled_navigation, monkeypatch, capsys, change, +): + checkout, _, _ = enabled_navigation + real_discover = navigation.MindieNavigationChannel.describe + real_exchange = navigation._exchange + real_start = navigation._start + actions = [] + + def observe_start(argv, **kwargs): + actions.append(argv[-1]) + return real_start(argv, **kwargs) + + def discover_and_change(channel, *, request): + status = real_discover(channel, request=request) + assert status.state == "ok" + if change == "revoke": + mindie_project.disable() + elif change == "replace-checkout": + (checkout / ".git").rename(checkout / "replaced-git") + (checkout / ".git").mkdir() + elif change == "change-grant": + payload = mindie_project._load_grant(checkout) + mindie_project._grant_path(checkout).write_bytes( + mindie_project._json({**payload, "domain": "different"}) + ) + return status + + def exchange_and_change(start, stop, arguments, request): + if change == "revoke-at-launch" and json.loads(arguments).get("query"): + mindie_project.disable() + return real_exchange(start, stop, arguments, request) + + monkeypatch.setattr(navigation, "_start", observe_start) + monkeypatch.setattr(navigation.MindieNavigationChannel, "describe", discover_and_change) + monkeypatch.setattr(navigation, "_exchange", exchange_and_change) + assert _find_navigation(capsys, "navigation-order")["state"] == "not_enabled" + assert actions == ["describe"] + + +def test_navigation_uses_captured_checkout_after_cwd_changes( + enabled_navigation, tmp_path, monkeypatch, capsys, +): + unrelated = tmp_path / "unapproved-checkout" + (unrelated / ".git").mkdir(parents=True) + real_discover = navigation.MindieNavigationChannel.describe + + def discover_and_change_cwd(channel, *, request): + status = real_discover(channel, request=request) + monkeypatch.chdir(unrelated) + return status + + monkeypatch.setattr(navigation.MindieNavigationChannel, "describe", discover_and_change_cwd) + result = _find_navigation(capsys, "navigation-order") + assert result["state"] == "ok" and result["count"] == 2 + + +@pytest.mark.parametrize("failure, state, action", [ + ("no-grant", "not_enabled", None), + ("no-dependency", "unreachable", "describe"), + ("wrong-version", "version_mismatch", "describe"), + ("wrong-domain", "rejected", "describe"), +]) +def test_navigation_unavailable_without_approved_catalog( + enabled_navigation, monkeypatch, capsys, failure, state, action, +): + _, metadata, engine = enabled_navigation + if failure == "no-grant": + mindie_project.disable() + elif failure == "no-dependency": + metadata.unlink() + metadata.parent.rmdir() + elif failure == "wrong-version": + metadata.write_text("Name: mindie-knowledge\nVersion: 0.13.12\n", encoding="utf-8") + else: + source = json.loads(engine.read_text(encoding="utf-8")) + engine.write_text(json.dumps({**source, "domain": "foreign"}), encoding="utf-8") + real_start = navigation._start + actions = [] + + def observe_start(argv, **kwargs): + actions.append(argv[-1]) + return real_start(argv, **kwargs) + + monkeypatch.setattr(navigation, "_start", observe_start) + assert _find_navigation(capsys, "navigation-order")["state"] == state + assert actions == ([action] if action else []) + + +@pytest.mark.parametrize("query, state", [ + ("navigation-malformed", "rejected"), + ("navigation-foreign", "rejected"), + ("navigation-denied", "unreachable"), + ("navigation-oversized", "rejected"), + ("navigation-timeout", "timeout"), +]) +def test_navigation_bounds_output_and_reaps_worker( + enabled_navigation, monkeypatch, capsys, query, state, +): + real_start = navigation._start + children = [] + workdirs = [] + + def observe_start(argv, **kwargs): + process = real_start(argv, **kwargs) + children.append((argv[-1], process)) + workdirs.append(kwargs["cwd"]) + return process + + monkeypatch.setattr(navigation, "_start", observe_start) + started = time.monotonic() + timeout = "2" if state == "timeout" else "8" + entry = _find_navigation(capsys, query, "--external-timeout", timeout) + assert entry["state"] == state and entry["count"] == 0 + if query == "navigation-oversized": + assert "output exceeded 2 MiB" in entry["detail"] + assert time.monotonic() - started < 10 + assert [action for action, _ in children] == ["describe", "query"] + assert all(process.wait(timeout=1) is not None for _, process in children) + assert all(not directory.exists() for directory in workdirs) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows Job Object integration") +@pytest.mark.parametrize("query, state", [ + ("navigation-detached-output", "ok"), + ("navigation-parent-exit", "timeout"), +]) +def test_windows_navigation_reaps_descendant_even_after_launcher_exits( + enabled_navigation, monkeypatch, capsys, query, state, +): + import ctypes + from ctypes import wintypes as win + + _, metadata, _ = enabled_navigation + marker = metadata.parent.parent / "mindie_knowledge/graded/reader-child.pid" + real_stop = navigation._stop + exited_before_cleanup = [] + + def observe_stop(process): + if marker.exists(): + try: + process.wait(timeout=0) + except subprocess.TimeoutExpired: + exited_before_cleanup.append(False) + else: + exited_before_cleanup.append(True) + return real_stop(process) + + monkeypatch.setattr(navigation, "_stop", observe_stop) + started = time.monotonic() + entry = _find_navigation(capsys, query, "--external-timeout", "3") + assert entry["state"] == state + assert time.monotonic() - started < 5 + assert exited_before_cleanup == [True] + pid = int(marker.read_text()) + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.OpenProcess.argtypes = (win.DWORD, win.BOOL, win.DWORD) + kernel.OpenProcess.restype = win.HANDLE + kernel.WaitForSingleObject.argtypes = (win.HANDLE, win.DWORD) + kernel.WaitForSingleObject.restype = win.DWORD + kernel.CloseHandle.argtypes = (win.HANDLE,) + handle = kernel.OpenProcess(0x100000, False, pid) # SYNCHRONIZE + if handle: + try: + assert kernel.WaitForSingleObject(handle, 0) == 0 + finally: + kernel.CloseHandle(handle) + else: + assert ctypes.get_last_error() == 87 # ERROR_INVALID_PARAMETER: PID already gone + + +@pytest.mark.skipif(os.name != "nt", reason="Windows Job Object integration") +@pytest.mark.parametrize("failing_api, query", [ + ("_query_job", "navigation-order"), + ("_terminate_job", "navigation-detached-output"), +]) +def test_windows_navigation_rejects_unconfirmed_job_cleanup( + enabled_navigation, monkeypatch, capsys, failing_api, query, +): + from inferrsi.apps.integrations.mindie import _windows_worker + + monkeypatch.setattr(_windows_worker, failing_api, lambda *args: False) + entry = _find_navigation(capsys, query, "--external-timeout", "3") + assert entry["state"] == "rejected" and entry["count"] == 0 + assert entry["detail"] == "channel resource cleanup failed" + + +@pytest.mark.skipif(os.name != "nt", reason="Windows Job Object integration") +def test_windows_navigation_refuses_uncontained_worker(enabled_navigation, monkeypatch, capsys): + from inferrsi.apps.integrations.mindie import _windows_worker + + update = _windows_worker._update_attributes + + def reject_job_attribute(attributes, flags, attribute, *args): + if attribute == _windows_worker._JOB_LIST: + return False + return update(attributes, flags, attribute, *args) + + def unexpected_launch(*args): + pytest.fail("MindIE must not start without its Job Object") + + monkeypatch.setattr(_windows_worker, "_update_attributes", reject_job_attribute) + monkeypatch.setattr(_windows_worker, "_create_process", unexpected_launch) + assert _find_navigation(capsys, "navigation-order")["state"] == "unreachable" + + +def test_navigation_uses_isolated_working_directory( + enabled_navigation, tmp_path, monkeypatch, capsys, +): + checkout, _, _ = enabled_navigation + unrelated, temporary = tmp_path / "unrelated", tmp_path / "temporary" + roots = [checkout, unrelated, temporary / "workspace", temporary / "work"] + for root in roots: + (root / "logs").mkdir(parents=True) + (root / "logs/experiment-ledger.jsonl").write_text("fixture ledger\n") + monkeypatch.setenv("MINDIE_BENCH_WORKSPACE", str(unrelated)) + monkeypatch.setattr(mindie_project.tempfile, "tempdir", str(temporary)) + result = _find_navigation(capsys, "workspace-probe") + assert result["state"] == "ok" and result["count"] == 0 + assert all(list((root / "logs").iterdir()) == [root / "logs/experiment-ledger.jsonl"] + for root in roots) + assert {path.name for path in temporary.iterdir()} == {"workspace", "work"} + + @pytest.mark.parametrize("oversized_line", ["newline", "eof", "boundary-newline"]) def test_mcp_stdio_round_trip(reader, tmp_path, monkeypatch, oversized_line): grant, _ = reader