diff --git a/docs/contributing.md b/docs/contributing.md index 08948aac8..1f079eb79 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -60,6 +60,21 @@ qualifies entries by Skill root, id and path. Coordinate verification reads checkout Skill metadata with PyYAML. If your interpreter lacks PyYAML, install it from the checkout with `python -m pip install '.[skills]'`. +To filter Find by a matrix coordinate, supply the checkout's Skill root explicitly: + +```sh +inferrsi find "graph mode" --skill-root src/inferrsi/knowledge/data/skill_library --searchspace-coordinate SSD Diagnose +``` + +Find ranks the chosen corpus and applies the coordinate before the result limit. +The filter ranks the Skill inputs verified with the index and checks for source +changes before returning matches. In Python, pass `coordinate.index` to +`load_corpus(searchspace_index=...)` and the coordinate to `find`. External +channels receive the original query. JSON reports the selected pair and matrix, +registry and Skill source fingerprints. A wheel install can use the filter with +an explicit matching source checkout because the wheel does not include the +matrix or its generated index. + Protected changes also require a current-head [knowledge authorship declaration](knowledge-model-policy.md). Every material AI author must use an approved model at `xhigh` or `max`; human-only work is declared diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index a514ad016..fdd9e95a1 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -199,6 +199,10 @@ def _print_external(result: dict) -> None: def _print_find(result: dict) -> None: """Lead with what was tried and how far the evidence goes, then the path.""" + if coordinate := result.get("searchspace_filter"): + source = coordinate["source"] + print(f"SearchSpace\t{coordinate['resource']} × {coordinate['stage']}\t" + f"{source['matrix_path']} (sha256 {source['matrix_sha256']})") if result["no_match"]: print(f"no_match\t{result['corpus_size']} entries searched; " f"rephrase, or search the corpus directly with rg") @@ -585,13 +589,24 @@ 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") + coordinate = None + if args.searchspace_coordinate is not None: + from ...knowledge.searchspace_index import load_searchspace_coordinate + + coordinate = load_searchspace_coordinate( + args.skill_root, *args.searchspace_coordinate, + ) result = find( - args.query, load_corpus(args.skill_root, kinds=kinds), + args.query, load_corpus( + args.skill_root, kinds=kinds, + 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(), backend=args.backend, platform=args.platform, external_limit=args.external_limit, external_timeout=args.external_timeout, + searchspace_coordinate=coordinate, ) if args.json: _print(result) diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index edf0446db..76ce65928 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -677,6 +677,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: "--skill-root", type=Path, help="Root for case and skill searches, defaulting to the installed library", ) + find.add_argument( + "--searchspace-coordinate", nargs=2, metavar=("RESOURCE", "STAGE"), + help="Filter ranked local Skills by a matrix pair using an explicit checkout --skill-root", + ) find.add_argument( "--explain", action="store_true", help="Report each query term's contribution" ) diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index dce4793bc..97f810f12 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -38,6 +38,7 @@ if TYPE_CHECKING: from .channels import ChannelRegistry + from .searchspace_index import SearchspaceCoordinate, SearchspaceIndex from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends @@ -470,7 +471,9 @@ def _skill_description(body: str) -> str: return description.strip() if isinstance(description, str) else "" -def _skill_documents(root: Path, *, source_location: str) -> list[Document]: +def _skill_documents( + root: Path, *, source_location: str, searchspace_index: SearchspaceIndex | None = None, +) -> list[Document]: """Skills registered by this root, resolved the way `skills` and `read` do. Reading skill-index.json directly assumed every root is a generated library. @@ -481,19 +484,43 @@ def _skill_documents(root: Path, *, source_location: str) -> list[Document]: from .skill_catalog import _sidecar, _skill_search_source, skill_registrations documents = [] - for name, (directory, backend) in sorted(skill_registrations(root).items()): + if searchspace_index is None: + inputs = ( + (name, directory, backend, None) + for name, (directory, backend) in sorted(skill_registrations(root).items()) + ) + else: + inputs = ( + (name, source.directory, source.backend, source) + for name, source in searchspace_index.ranking_skills() + ) + for name, directory, backend, source in inputs: core = directory / "SKILL.md" - body = _body_text(core) + if source is None: + body = _body_text(core) + else: + # Match the default text reader's universal newlines and decoding fallback. + try: + body = source.body.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") + except UnicodeError: + body = "" try: body, metadata = _skill_search_source(body) except ValueError: # Malformed structured data is neither evidence nor instruction text. continue - if metadata is not None and (directory / "metadata.json").exists(): + has_sidecar = ( + (directory / "metadata.json").exists() if source is None else source.sidecar_present + ) + if metadata is not None and has_sidecar: continue try: if metadata is None: - metadata = _sidecar(directory) or {} + if source is None: + metadata = _sidecar(directory) or {} + else: + # Coordinate validation already checked the captured legacy sidecar's schema. + metadata = json.loads(source.sidecar) if source.sidecar is not None else {} except (ValueError, OSError): metadata = {} # Task entrypoints remain addressable through the registry. Counting @@ -576,8 +603,11 @@ def _record_documents(records: Iterable[dict]) -> list[Document]: class Corpus: """Documents plus their inverse document frequencies, read once.""" - def __init__(self, documents: list[Document]): + def __init__( + self, documents: list[Document], *, _searchspace_index: SearchspaceIndex | None = None, + ): self.documents = documents + self._searchspace_index = _searchspace_index total = len(documents) appearances = Counter() self._counts = [ @@ -657,6 +687,7 @@ def load_documents( *, kinds: tuple[str, ...] = ("case", "skill", "record"), records: Iterable[dict] | None = None, + _searchspace_index: SearchspaceIndex | None = None, ) -> list[Document]: documents: list[Document] = [] if "case" in kinds or "skill" in kinds: @@ -668,7 +699,9 @@ def load_documents( if "case" in kinds: documents.extend(_case_documents(root, source_location=source_location)) if "skill" in kinds: - documents.extend(_skill_documents(root, source_location=source_location)) + documents.extend(_skill_documents( + root, source_location=source_location, searchspace_index=_searchspace_index, + )) if "record" in kinds: from .catalog import knowledge_records @@ -683,9 +716,18 @@ def load_documents( def load_corpus( - skill_root: Path | None = None, *, kinds: tuple[str, ...] = ("case", "skill", "record") + skill_root: Path | None = None, *, kinds: tuple[str, ...] = ("case", "skill", "record"), + searchspace_index: SearchspaceIndex | None = None, ) -> Corpus: - return Corpus(load_documents(skill_root, kinds=kinds)) + """Build a rankable corpus, using the verified Skill inputs if explicitly supplied.""" + if searchspace_index is None: + return Corpus(load_documents(skill_root, kinds=kinds)) + if skill_root is not None and Path(skill_root).resolve() != searchspace_index.skill_root: + raise ValueError("SearchSpace coordinate and Find corpus require the same Skill root") + documents = load_documents( + searchspace_index.skill_root, kinds=kinds, _searchspace_index=searchspace_index, + ) + return Corpus(documents, _searchspace_index=searchspace_index) @lru_cache(maxsize=1) @@ -808,6 +850,15 @@ def rank(query: str, corpus: Corpus) -> tuple[ return query_tokens, applied, scored +def _matches_coordinate(document: Document, coordinate: SearchspaceCoordinate) -> bool: + return ( + document.kind == "skill" and document.root is not None and document.path is not None + and coordinate.matches( + skill_root=document.root, skill_id=document.identity, path=document.path, + ) + ) + + def find( query: str, corpus: Corpus, @@ -819,10 +870,22 @@ def find( platform: str | None = None, external_limit: int | None = None, external_timeout: float = 8.0, + searchspace_coordinate: SearchspaceCoordinate | None = None, ) -> dict: if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") query_tokens, applied, scored = rank(query, corpus) + if searchspace_coordinate is not None: + index = searchspace_coordinate.index + if corpus._searchspace_index is None or not index.same_source(corpus._searchspace_index): + raise ValueError( + "Load the Find corpus with a SearchSpace index from the same verified source" + ) + index.require_current() + scored = [ + row for row in scored + if _matches_coordinate(corpus.documents[row[2]], searchspace_coordinate) + ] items = [] readers: dict = {} for value, _, index, detail in scored[:limit]: @@ -859,6 +922,10 @@ def find( # Report what a query term was taken to mean, so a wrong expansion is # visible in the result rather than only in the ranking. result["expanded"] = {term: list(values) for term, values in applied.items()} + if searchspace_coordinate is not None: + if items: + searchspace_coordinate.index.require_current() + result["searchspace_filter"] = searchspace_coordinate.view() return _with_channels( result, query, registry=registry, backend=backend, platform=platform, external_limit=external_limit, external_timeout=external_timeout, diff --git a/src/inferrsi/knowledge/searchspace_index.py b/src/inferrsi/knowledge/searchspace_index.py index f86592d76..6cd32c047 100644 --- a/src/inferrsi/knowledge/searchspace_index.py +++ b/src/inferrsi/knowledge/searchspace_index.py @@ -7,12 +7,12 @@ import re from collections import defaultdict from collections.abc import Iterable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from types import MappingProxyType from ._knowledge_errors import MissingSkillsExtra -from .skill_catalog import _effective, _entry, skill_directories +from .skill_catalog import _effective, _entry, skill_registrations LIBRARY = Path("src/inferrsi/knowledge/data/skill_library") CATALOG = LIBRARY / "skill-index.json" @@ -65,12 +65,16 @@ def _sha256(path: Path) -> str: def input_digest(root: Path, paths: Iterable[Path]) -> str: """Hash inputs in repository-relative POSIX path order on every host.""" + return _input_digest(root, {path: _sha256(path) for path in paths}) + + +def _input_digest(root: Path, hashes: Mapping[Path, str]) -> str: digest = hashlib.sha256() - relative = {path: path.relative_to(root).as_posix() for path in paths} + relative = {path: path.relative_to(root).as_posix() for path in hashes} for path in sorted(relative, key=relative.__getitem__): digest.update(relative[path].encode("utf-8")) digest.update(b"\0") - digest.update(bytes.fromhex(_sha256(path))) + digest.update(bytes.fromhex(hashes[path])) return digest.hexdigest() @@ -84,23 +88,71 @@ def _source_paths() -> dict[str, str]: def coordinate_inputs(root: Path) -> tuple[dict[str, str], dict[str, str]]: """Fingerprint the matrix, registry and all files supplying Skill metadata.""" + sources, paths, _ = _coordinate_inputs(root) + return sources, paths + + +def _file_version(path: Path) -> tuple[int, int, int, int, int] | None: + try: + stat = path.stat() + except FileNotFoundError: + return None + return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns + + +@dataclass(frozen=True) +class _SkillInputs: + directory: Path + backend: str | None + body: bytes = field(repr=False) + sidecar: bytes | None = field(repr=False) + sidecar_present: bool + + +def _coordinate_inputs( + root: Path, *, captured: dict[Path, tuple[int, int, int, int, int] | None] | None = None, +) -> tuple[dict[str, str], dict[str, str], dict[str, _SkillInputs]]: root = root.resolve() matrix = root / MATRIX catalog = root / CATALOG sources = {**_source_paths(), "matrix_sha256": _sha256(matrix)} registry_bytes = catalog.read_bytes() sources["catalog_sha256"] = hashlib.sha256(registry_bytes).hexdigest() - directories = skill_directories(root / LIBRARY) - registry = json.loads(registry_bytes)["skills"] - paths = {name: f"{registry[name]['path']}/SKILL.md" for name in directories} - metadata = [] - for name, directory in directories.items(): + registrations = skill_registrations(root / LIBRARY) + registry_record = json.loads(registry_bytes) + registry = registry_record.get("skills") if isinstance(registry_record, dict) else None + if not isinstance(registry, dict) or registrations.keys() != registry.keys(): + raise StaleSearchspaceIndex("SearchSpace registry changed during reading") + paths = {} + hashes = {} + skills = {} + for name, (directory, backend) in registrations.items(): + entry = registry[name] + if ( + not isinstance(entry, dict) + or not isinstance(entry.get("path"), str) + or (root / LIBRARY / entry["path"]).resolve() != directory + or entry.get("backend") != backend + ): + raise StaleSearchspaceIndex("SearchSpace registry changed during reading") + paths[name] = f"{entry['path']}/SKILL.md" entrypoint = root / LIBRARY / paths[name] - metadata.append(entrypoint) + sidecar = entrypoint.with_name("metadata.json") + if captured is not None: + captured[entrypoint] = _file_version(entrypoint) + captured[sidecar] = _file_version(sidecar) + body = entrypoint.read_bytes() + hashes[entrypoint] = hashlib.sha256(body).hexdigest() + metadata = None if _entry(directory, "metadata.json").is_file(): - metadata.append(entrypoint.with_name("metadata.json")) - sources["metadata_sha256"] = input_digest(root, metadata) - return sources, paths + metadata = sidecar.read_bytes() + hashes[sidecar] = hashlib.sha256(metadata).hexdigest() + if captured is not None: + skills[name] = _SkillInputs( + directory, backend, body, metadata, captured[sidecar] is not None, + ) + sources["metadata_sha256"] = _input_digest(root, hashes) + return sources, paths, skills def references(root, path, registered, *, canonical_paths=None): @@ -322,8 +374,53 @@ def matches(self, resource: str, stage: str) -> bool: @dataclass(frozen=True) class SearchspaceIndex: + _checkout: Path _skill_root: Path _entries: Mapping[str, SearchspaceEntry] + _source: Mapping[str, str] + _inputs: Mapping[str, _SkillInputs] = field(repr=False) + _versions: Mapping[Path, tuple[int, int, int, int, int] | None] = field(repr=False) + + @property + def skill_root(self) -> Path: + return self._skill_root + + @property + def matrix_sha256(self) -> str: + return self._source["matrix_sha256"] + + @property + def source(self) -> dict[str, str]: + return { + key: self._source[key] + for key in ("matrix_path", "matrix_sha256", "catalog_sha256", "metadata_sha256") + } + + def same_source(self, other: SearchspaceIndex) -> bool: + return self._skill_root == other._skill_root and self._source == other._source + + def require_current(self) -> None: + """Check the checkout after reading a corpus from the verified inputs.""" + regenerate = ( + "Run `python tools/build_skill_coverage.py --searchspace-index` " + "in that checkout and retry." + ) + try: + current = ( + self.matrix_sha256 == _sha256(self._checkout / MATRIX) + and self._source["catalog_sha256"] == _sha256(self._checkout / CATALOG) + and all(_file_version(path) == version for path, version in self._versions.items()) + ) + except OSError as exc: + raise StaleSearchspaceIndex( + f"SearchSpace sources became unavailable during Find. {regenerate}" + ) from exc + if not current: + raise StaleSearchspaceIndex(f"SearchSpace sources changed during Find. {regenerate}") + + def ranking_skills(self) -> Iterable[tuple[str, _SkillInputs]]: + """Supply the registered paths and exact input bytes from verification.""" + return self._inputs.items() def entry(self, *, skill_root: Path, skill_id: str, path: str) -> SearchspaceEntry: """Look up an identity qualified by its Skill root and relative SKILL.md path.""" @@ -375,15 +472,87 @@ def load_searchspace_index(checkout: Path) -> SearchspaceIndex: if not isinstance(entries, dict) or entries.keys() != paths.keys(): raise StaleSearchspaceIndex("SearchSpace skills disagree with the Skill registry") loaded = {name: _load_entry(entries[name], path) for name, path in paths.items()} + versions: dict[Path, tuple[int, int, int, int, int] | None] = {} try: expected = project_coordinate_entries(root, paths) - still_current = (current, paths) == coordinate_inputs(root) + last_source, last_paths, ranking_skills = _coordinate_inputs(root, captured=versions) except MissingSkillsExtra: raise except (FileNotFoundError, ValueError) as exc: raise StaleSearchspaceIndex("SearchSpace sources are missing or invalid") from exc - if not still_current: + if (current, paths) != (last_source, last_paths): raise StaleSearchspaceIndex("SearchSpace sources changed during verification") if entries != expected: raise StaleSearchspaceIndex("SearchSpace entries disagree with canonical sources") - return SearchspaceIndex((root / LIBRARY).resolve(), MappingProxyType(loaded)) + return SearchspaceIndex( + root, (root / LIBRARY).resolve(), MappingProxyType(loaded), MappingProxyType(current), + MappingProxyType(ranking_skills), MappingProxyType(versions), + ) + + +@dataclass(frozen=True) +class SearchspaceCoordinate: + """One query coordinate bound to a verified checkout index.""" + + index: SearchspaceIndex + resource: str + stage: str + + @property + def skill_root(self) -> Path: + return self.index.skill_root + + def matches(self, *, skill_root: Path, skill_id: str, path: str) -> bool: + try: + entry = self.index.entry(skill_root=skill_root, skill_id=skill_id, path=path) + except SearchspaceSourceMismatch: + return False + return entry.matches(self.resource, self.stage) + + def view(self) -> dict: + return { + "resource": self.resource, + "stage": self.stage, + "source": self.index.source, + } + + +def load_searchspace_index_for_skill_root( + skill_root: Path | None, *, option: str, +) -> SearchspaceIndex: + """Resolve and verify the index belonging to an explicit Find Skill root.""" + root = skill_root.resolve() if skill_root is not None else None + if root is None or root.parts[-len(LIBRARY.parts):] != LIBRARY.parts: + raise ValueError( + f"{option} requires an explicit --skill-root pointing to " + f"{LIBRARY.as_posix()} in a matching InferRSI checkout" + ) + checkout = root.parents[len(LIBRARY.parts) - 1] + regenerate = "Run `python tools/build_skill_coverage.py --searchspace-index` in that checkout." + try: + return load_searchspace_index(checkout) + except MissingSkillsExtra: + raise + except FileNotFoundError as exc: + raise ValueError( + f"SearchSpace index unavailable at {checkout / INDEX}. {regenerate}" + ) from exc + except SearchspaceSourceMismatch as exc: + raise ValueError(f"Foreign SearchSpace index: {exc}. {regenerate}") from exc + except StaleSearchspaceIndex as exc: + raise ValueError(f"Stale SearchSpace index: {exc}. {regenerate}") from exc + except ValueError as exc: + raise ValueError(f"Invalid SearchSpace index: {exc}. {regenerate}") from exc + + +def load_searchspace_coordinate( + skill_root: Path | None, resource: str, stage: str, +) -> SearchspaceCoordinate: + """Resolve an explicit Find filter from the checkout that owns its Skills.""" + if resource not in RESOURCES.values() or stage not in STAGES: + raise ValueError( + f"--searchspace-coordinate requires RESOURCE ({', '.join(RESOURCES.values())}) " + f"and STAGE ({', '.join(STAGES)})" + ) + index = load_searchspace_index_for_skill_root(skill_root, option="--searchspace-coordinate") + return SearchspaceCoordinate(index, resource, stage) diff --git a/tests/test_find_searchspace.py b/tests/test_find_searchspace.py new file mode 100644 index 000000000..322b57bfb --- /dev/null +++ b/tests/test_find_searchspace.py @@ -0,0 +1,225 @@ +"""Find applies a verified SearchSpace pair after lexical ranking.""" + +import json +import shutil +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.knowledge import knowledge_find +from inferrsi.knowledge.knowledge_find import Corpus, find, load_corpus +from inferrsi.knowledge.searchspace_index import ( + CATALOG, + INDEX, + LIBRARY, + MATRIX, + StaleSearchspaceIndex, + load_searchspace_coordinate, +) +from tools.build_skill_coverage import render_coordinate_index + +PROJECT = Path(__file__).resolve().parents[1] +ROOT = PROJECT / LIBRARY +GRAPH = "ascend-graph-mode" +QUERY = "graph mode" + + +@pytest.fixture(scope="module") +def corpus(): + coordinate = load_searchspace_coordinate(ROOT, "SSD", "Diagnose") + return load_corpus(ROOT, searchspace_index=coordinate.index) + + +def test_find_filters_real_pairs_before_limit_without_changing_rank(corpus): + baseline = find(QUERY, corpus, limit=20, explain=True) + assert baseline["items"][0]["id"] == GRAPH + assert "searchspace_filter" not in baseline + + diagnose = load_searchspace_coordinate(ROOT, "SSD", "Diagnose") + graph = find(QUERY, corpus, searchspace_coordinate=diagnose, limit=1, explain=True) + assert graph["items"] == [baseline["items"][0]] + + configure = load_searchspace_coordinate(ROOT, "SSD", "Configure") + filtered = find(QUERY, corpus, searchspace_coordinate=configure, limit=1, explain=True) + all_matches = find(QUERY, corpus, searchspace_coordinate=configure, limit=20, explain=True) + expected_ids = [item["id"] for item in all_matches["items"]] + assert expected_ids[0] == "ascend-model-adaptation" + assert GRAPH not in expected_ids + expected = [item for item in baseline["items"] if item["id"] in expected_ids] + assert filtered["items"] == expected[:1] + assert all_matches["items"][:len(expected)] == expected + assert filtered["corpus_size"] == baseline["corpus_size"] + assert filtered["matched"] == len(expected_ids) > len(filtered["items"]) + assert filtered["no_match"] is False + source = json.loads((PROJECT / INDEX).read_bytes())["source"] + assert filtered["searchspace_filter"] == { + "resource": "SSD", "stage": "Configure", + "source": { + key: source[key] + for key in ("matrix_path", "matrix_sha256", "catalog_sha256", "metadata_sha256") + }, + } + + +def test_find_filters_out_other_document_kinds_even_when_they_rank_first(corpus): + query = "prefill decode graph" + baseline = find(query, corpus, limit=20) + assert baseline["items"][0]["kind"] == "record" + coordinate = load_searchspace_coordinate(ROOT, "Accelerator", "Configure") + filtered = find(query, corpus, searchspace_coordinate=coordinate, limit=1) + assert filtered["items"] == [next(item for item in baseline["items"] if item["id"] == GRAPH)] + + +def test_find_rejects_same_named_skill_with_different_root_or_path(corpus, tmp_path): + coordinate = load_searchspace_coordinate(ROOT, "Accelerator", "Configure") + graph = next(doc for doc in corpus.documents if doc.identity == GRAPH) + cases = ( + replace(graph, root=tmp_path, qualified=""), + replace(graph, path=f"other/{graph.path}", qualified=""), + ) + for document in cases: + foreign = Corpus([document], _searchspace_index=coordinate.index) + result = find(QUERY, foreign, searchspace_coordinate=coordinate) + assert result["matched"] == 0 and result["no_match"] is True + assert result["items"] == [] + + +@pytest.fixture +def checkout(tmp_path): + matrix = tmp_path / MATRIX + matrix.parent.mkdir() + shutil.copyfile(PROJECT / MATRIX, matrix) + registry = json.loads((PROJECT / CATALOG).read_bytes()) + graph = registry["skills"][GRAPH] + registry["skills"] = {GRAPH: graph} + relative = LIBRARY / graph["path"] / "SKILL.md" + entrypoint = tmp_path / relative + entrypoint.parent.mkdir(parents=True) + shutil.copyfile(PROJECT / relative, entrypoint) + (tmp_path / CATALOG).write_text(json.dumps(registry), encoding="utf-8") + (tmp_path / INDEX).write_text(render_coordinate_index(tmp_path), encoding="utf-8", newline="\n") + return tmp_path, entrypoint + + +def test_cli_rejects_an_exclusion_written_after_index_load(checkout, monkeypatch, capsys): + root, entrypoint = checkout + original_load = load_corpus + + def load_after_exclusion(*args, **kwargs): + before = entrypoint.read_bytes() + exclusion = b' "searchspace_not_applicable": "New exclusion during Find",\n' + entrypoint.write_bytes(before.replace(b" {\n", b" {\n" + exclusion, 1)) + return original_load(*args, **kwargs) + + monkeypatch.setattr(knowledge_find, "load_corpus", load_after_exclusion) + with pytest.raises(SystemExit) as exc: + main(["find", QUERY, "--skill-root", str(root / LIBRARY), "--no-external", + "--kinds", "skill", "--searchspace-coordinate", "SSD", "Diagnose", "--json"]) + assert exc.value.code == 2 + captured = capsys.readouterr() + assert captured.out == "" + assert "SearchSpace sources changed during Find" in captured.err + assert "python tools/build_skill_coverage.py --searchspace-index" in captured.err + + +@pytest.mark.parametrize("path", (MATRIX, CATALOG)) +def test_find_rechecks_matrix_and_registry_after_ranking(checkout, monkeypatch, path): + root, _ = checkout + coordinate = load_searchspace_coordinate(root / LIBRARY, "SSD", "Diagnose") + corpus = load_corpus(kinds=("skill",), searchspace_index=coordinate.index) + original_rank = knowledge_find.rank + + def rank_then_edit(*args): + result = original_rank(*args) + source = root / path + source.write_bytes(source.read_bytes() + b"\n") + return result + + monkeypatch.setattr(knowledge_find, "rank", rank_then_edit) + with pytest.raises(StaleSearchspaceIndex, match="changed during Find"): + find(QUERY, corpus, searchspace_coordinate=coordinate) + + +def test_find_uses_bound_corpus_and_ignores_unrelated_file_change(checkout): + root, entrypoint = checkout + coordinate = load_searchspace_coordinate(root / LIBRARY, "SSD", "Diagnose") + bound = load_corpus(kinds=("skill",), searchspace_index=coordinate.index) + unrelated = root / "docs" / "reference-matrix.md" + unrelated.write_text("Unrelated matrix content", encoding="utf-8") + assert find(QUERY, bound, searchspace_coordinate=coordinate)["items"][0]["id"] == GRAPH + plain = load_corpus(root / LIBRARY, kinds=("skill",)) + assert find(QUERY, bound) == find(QUERY, plain) + + entrypoint.write_bytes(entrypoint.read_bytes() + b"\nA new ranking body.\n") + (root / INDEX).write_text(render_coordinate_index(root), encoding="utf-8", newline="\n") + current_coordinate = load_searchspace_coordinate(root / LIBRARY, "SSD", "Diagnose") + current = load_corpus(kinds=("skill",), searchspace_index=current_coordinate.index) + for left, right in ((bound, current_coordinate), (current, coordinate)): + with pytest.raises(ValueError, match="same verified source"): + find(QUERY, left, searchspace_coordinate=right) + + +def test_cli_shows_coordinate_and_source_with_or_without_matches(capsys): + command = ["find", QUERY, "--skill-root", str(ROOT), "--no-external", "--limit", "1"] + assert main(command) == 0 + assert "SearchSpace" not in capsys.readouterr().out + command += ["--searchspace-coordinate", "SSD", "Diagnose"] + assert main(command) == 0 + text = capsys.readouterr().out + assert "SSD × Diagnose" in text and MATRIX.as_posix() in text + assert GRAPH in text + + assert main(command + ["--kinds", "record", "--json"]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["no_match"] is True and result["matched"] == 0 and result["items"] == [] + assert result["searchspace_filter"]["source"]["matrix_path"] == MATRIX.as_posix() + + +@pytest.mark.parametrize("case, diagnostic", [ + ("missing", "SearchSpace index unavailable"), + ("invalid", "Invalid SearchSpace index"), + ("foreign", "Foreign SearchSpace index"), + ("stale", "Stale SearchSpace index"), +]) +def test_cli_reports_actionable_index_failures(tmp_path, capsys, case, diagnostic): + index_path = tmp_path / INDEX + index_path.parent.mkdir() + if case != "missing": + artifact = json.loads((PROJECT / INDEX).read_bytes()) + if case == "foreign": + artifact["source"]["matrix_path"] = "other/searchspace-matrix.md" + index_path.write_text("{" if case == "invalid" else json.dumps(artifact), encoding="utf-8") + with pytest.raises(SystemExit) as exc: + main(["find", QUERY, "--skill-root", str(tmp_path / LIBRARY), + "--searchspace-coordinate", "SSD", "Configure", "--no-external"]) + assert exc.value.code == 2 + text = capsys.readouterr().err + assert diagnostic in text + assert "python tools/build_skill_coverage.py --searchspace-index" in text + + +@pytest.mark.parametrize("args, stage, diagnostic", [ + ([], "Configure", "explicit --skill-root"), + (["--skill-root", "custom-library"], "Configure", "matching InferRSI checkout"), + (["--skill-root", str(ROOT)], "Review", "STAGE"), +]) +def test_cli_reports_an_invalid_request(capsys, args, stage, diagnostic): + with pytest.raises(SystemExit) as exc: + main(["find", QUERY, "--no-external", "--searchspace-coordinate", "SSD", stage, *args]) + assert exc.value.code == 2 + assert diagnostic in capsys.readouterr().err + + +def test_cli_reports_missing_pyyaml_without_requesting_regeneration(monkeypatch, capsys): + monkeypatch.setitem(sys.modules, "yaml", None) + monkeypatch.delenv("INFERRSI_LAUNCHER", raising=False) + with pytest.raises(SystemExit) as exc: + main(["find", QUERY, "--skill-root", str(ROOT), "--no-external", + "--searchspace-coordinate", "SSD", "Configure"]) + assert exc.value.code == 2 + text = capsys.readouterr().err + assert "pip install '[skills]'" in text + assert "build_skill_coverage.py" not in text diff --git a/tests/test_knowledge_channels.py b/tests/test_knowledge_channels.py index 1575f3784..a4eda1728 100644 --- a/tests/test_knowledge_channels.py +++ b/tests/test_knowledge_channels.py @@ -1,6 +1,7 @@ """External channels: gating, per-channel states, and no mixing into `items`.""" import json +from pathlib import Path import pytest @@ -18,7 +19,8 @@ explain_gate, search_channels, ) -from inferrsi.knowledge.knowledge_find import Corpus, Document, find +from inferrsi.knowledge.knowledge_find import Corpus, Document, find, load_corpus +from inferrsi.knowledge.searchspace_index import LIBRARY, load_searchspace_coordinate class FakeChannel: @@ -33,6 +35,7 @@ def __init__(self, *, name="fake", backend="ascend", status=None, items=(), erro self._error = error self._delay_state = delay_state self.searched = 0 + self.query_seen = None self.platform_seen = None self.limit_seen = None @@ -43,6 +46,7 @@ def describe(self, *, request): def search(self, query, *, platform, limit, request): self.searched += 1 + self.query_seen = query self.platform_seen = platform self.limit_seen = limit if self._delay_state: @@ -115,6 +119,29 @@ def test_external_hits_never_enter_items(corpus): assert result["external"][0]["items"][0]["locator"] == "ops/only/external" +def test_find_coordinate_filter_leaves_external_query_and_results_unchanged(): + checkout = Path(__file__).resolve().parents[1] + coordinate = load_searchspace_coordinate(checkout / LIBRARY, "SSD", "Configure") + corpus = load_corpus(kinds=("record",), searchspace_index=coordinate.index) + channel = FakeChannel(items=[_hit()]) + options = {"backend": "ascend", "platform": "a3", "external_limit": 7} + registry = ChannelRegistry([channel]) + query = "tiling across streams" + plain = find(query, corpus, registry=registry, **options) + filtered = find( + query, corpus, registry=registry, searchspace_coordinate=coordinate, **options, + ) + assert plain["items"] and filtered["items"] == [] + assert filtered["no_match"] is True and filtered["matched"] == 0 + assert len(plain["external"]) == len(filtered["external"]) == 1 + baseline_channel, = plain["external"] + filtered_channel, = filtered["external"] + assert filtered_channel == {**baseline_channel, "elapsed_ms": filtered_channel["elapsed_ms"]} + assert plain["external_notes"] == filtered["external_notes"] + assert channel.searched == 2 + assert (channel.query_seen, channel.platform_seen, channel.limit_seen) == (query, "a3", 7) + + def test_hit_carries_score_scale_and_sha(corpus): channel = FakeChannel(items=[_hit()]) result = find("tiling", corpus, backend="ascend", registry=ChannelRegistry([channel])) diff --git a/tests/test_knowledge_fresh_install.py b/tests/test_knowledge_fresh_install.py index d56eaf024..731930f90 100644 --- a/tests/test_knowledge_fresh_install.py +++ b/tests/test_knowledge_fresh_install.py @@ -267,5 +267,25 @@ def test_installed_wheel_outside_the_checkout_holds_every_resource_byte_for_byte assert not package.is_relative_to(REPO) assert package.is_relative_to(venv) assert payload["inventory"] == expected + + find_command = [str(python), "-I", "-X", "utf8", "-m", "inferrsi", "find", "graph mode", + "--no-external", "--limit", "1", "--json"] + run_options = {"capture_output": True, "text": True, "encoding": "utf-8", "cwd": workspace} + plain = subprocess.run(find_command, **run_options) + assert plain.returncode == 0, plain.stderr + default = json.loads(plain.stdout) + assert default["items"][0]["id"] == "ascend-graph-mode" + assert "searchspace_filter" not in default + + find_command += ["--searchspace-coordinate", "SSD", "Diagnose"] + bare = subprocess.run(find_command, **run_options) + assert bare.returncode == 2 and "explicit --skill-root" in bare.stderr + + selected = subprocess.run(find_command + ["--skill-root", str(SKILLS)], **run_options) + assert selected.returncode == 0, selected.stderr + filtered = json.loads(selected.stdout) + assert filtered["items"][0]["id"] == "ascend-graph-mode" + assert "--skill-root" in filtered["items"][0]["ref"] + assert filtered["searchspace_filter"]["stage"] == "Diagnose" finally: shutil.rmtree(workspace, ignore_errors=True)