From 6afde12769f669019f6848da9664379599a0ee07 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:47:45 +0800 Subject: [PATCH 1/3] Filter Find by a verified SearchSpace coordinate Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/contributing.md | 12 ++ src/inferrsi/apps/cli/__init__.py | 16 ++- src/inferrsi/apps/cli/arguments.py | 4 + src/inferrsi/knowledge/knowledge_find.py | 18 +++ src/inferrsi/knowledge/searchspace_index.py | 66 +++++++++- tests/test_find_searchspace.py | 136 ++++++++++++++++++++ tests/test_knowledge_channels.py | 24 ++++ tests/test_knowledge_fresh_install.py | 20 +++ 8 files changed, 294 insertions(+), 2 deletions(-) create mode 100644 tests/test_find_searchspace.py diff --git a/docs/contributing.md b/docs/contributing.md index 08948aac8..b0d56577f 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -60,6 +60,18 @@ 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 applies to registered checkout Skills. External channels receive the +original query. The CLI and JSON show the pair and matrix source. 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..2068bd17d 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,23 @@ 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 if coordinate is None else coordinate.skill_root, kinds=kinds, + ), 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..9240dc42d 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 from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends @@ -808,6 +809,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 +829,16 @@ 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: + 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 +875,8 @@ 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: + 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..a89746f4f 100644 --- a/src/inferrsi/knowledge/searchspace_index.py +++ b/src/inferrsi/knowledge/searchspace_index.py @@ -324,6 +324,7 @@ def matches(self, resource: str, stage: str) -> bool: class SearchspaceIndex: _skill_root: Path _entries: Mapping[str, SearchspaceEntry] + matrix_sha256: str 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.""" @@ -386,4 +387,67 @@ def load_searchspace_index(checkout: Path) -> SearchspaceIndex: 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 / LIBRARY).resolve(), MappingProxyType(loaded), current["matrix_sha256"], + ) + + +@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": {"matrix_path": MATRIX.as_posix(), "matrix_sha256": self.index.matrix_sha256}, + } + + +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)})" + ) + 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( + "--searchspace-coordinate 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: + index = 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 + 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..a9732bc23 --- /dev/null +++ b/tests/test_find_searchspace.py @@ -0,0 +1,136 @@ +"""Find applies a verified SearchSpace pair after lexical ranking.""" + +import hashlib +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.knowledge.knowledge_find import Corpus, find, load_corpus +from inferrsi.knowledge.searchspace_index import INDEX, LIBRARY, MATRIX, load_searchspace_coordinate + +PROJECT = Path(__file__).resolve().parents[1] +ROOT = PROJECT / LIBRARY +GRAPH = "ascend-graph-mode" +QUERY = "graph mode" + + +@pytest.fixture(scope="module") +def corpus(): + return load_corpus(ROOT) + + +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 + assert filtered["searchspace_filter"] == { + "resource": "SSD", "stage": "Configure", + "source": {"matrix_path": MATRIX.as_posix(), + "matrix_sha256": hashlib.sha256((PROJECT / MATRIX).read_bytes()).hexdigest()}, + } + + +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: + result = find(QUERY, Corpus([document]), searchspace_coordinate=coordinate) + assert result["matched"] == 0 and result["no_match"] is True + assert result["items"] == [] + + +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..a119f7715 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 @@ -19,6 +20,7 @@ search_channels, ) from inferrsi.knowledge.knowledge_find import Corpus, Document, find +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,26 @@ 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(corpus): + checkout = Path(__file__).resolve().parents[1] + coordinate = load_searchspace_coordinate(checkout / LIBRARY, "SSD", "Configure") + 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) From 76611f3194cc8c572f255cc91ae513e5300a849e Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:50:27 +0800 Subject: [PATCH 2/3] Bind Find coordinates to the ranked source snapshot Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/contributing.md | 11 +- src/inferrsi/apps/cli/__init__.py | 3 +- src/inferrsi/knowledge/knowledge_find.py | 69 ++++++-- src/inferrsi/knowledge/searchspace_index.py | 165 ++++++++++++++++---- tests/test_find_searchspace.py | 101 +++++++++++- tests/test_knowledge_channels.py | 9 +- 6 files changed, 304 insertions(+), 54 deletions(-) diff --git a/docs/contributing.md b/docs/contributing.md index b0d56577f..1f079eb79 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -67,10 +67,13 @@ inferrsi find "graph mode" --skill-root src/inferrsi/knowledge/data/skill_librar ``` Find ranks the chosen corpus and applies the coordinate before the result limit. -The filter applies to registered checkout Skills. External channels receive the -original query. The CLI and JSON show the pair and matrix source. 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. +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 diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 2068bd17d..fdd9e95a1 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -598,7 +598,8 @@ def main(argv: list[str] | None = None) -> int: ) result = find( args.query, load_corpus( - args.skill_root if coordinate is None else coordinate.skill_root, kinds=kinds, + 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(), diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index 9240dc42d..97f810f12 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -38,7 +38,7 @@ if TYPE_CHECKING: from .channels import ChannelRegistry - from .searchspace_index import SearchspaceCoordinate + from .searchspace_index import SearchspaceCoordinate, SearchspaceIndex from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends @@ -471,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. @@ -482,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 @@ -577,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 = [ @@ -658,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: @@ -669,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 @@ -684,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) @@ -835,6 +876,12 @@ def find( 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) @@ -876,6 +923,8 @@ def find( # 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, diff --git a/src/inferrsi/knowledge/searchspace_index.py b/src/inferrsi/knowledge/searchspace_index.py index a89746f4f..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,9 +374,53 @@ def matches(self, resource: str, stage: str) -> bool: @dataclass(frozen=True) class SearchspaceIndex: + _checkout: Path _skill_root: Path _entries: Mapping[str, SearchspaceEntry] - matrix_sha256: str + _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.""" @@ -376,19 +472,21 @@ 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), current["matrix_sha256"], + root, (root / LIBRARY).resolve(), MappingProxyType(loaded), MappingProxyType(current), + MappingProxyType(ranking_skills), MappingProxyType(versions), ) @@ -402,7 +500,7 @@ class SearchspaceCoordinate: @property def skill_root(self) -> Path: - return self.index._skill_root + return self.index.skill_root def matches(self, *, skill_root: Path, skill_id: str, path: str) -> bool: try: @@ -415,29 +513,24 @@ def view(self) -> dict: return { "resource": self.resource, "stage": self.stage, - "source": {"matrix_path": MATRIX.as_posix(), "matrix_sha256": self.index.matrix_sha256}, + "source": self.index.source, } -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)})" - ) +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( - "--searchspace-coordinate requires an explicit --skill-root pointing to " + 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: - index = load_searchspace_index(checkout) + return load_searchspace_index(checkout) except MissingSkillsExtra: raise except FileNotFoundError as exc: @@ -450,4 +543,16 @@ def load_searchspace_coordinate( 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 index a9732bc23..322b57bfb 100644 --- a/tests/test_find_searchspace.py +++ b/tests/test_find_searchspace.py @@ -1,7 +1,7 @@ """Find applies a verified SearchSpace pair after lexical ranking.""" -import hashlib import json +import shutil import sys from dataclasses import replace from pathlib import Path @@ -9,8 +9,17 @@ 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 INDEX, LIBRARY, MATRIX, load_searchspace_coordinate +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 @@ -20,7 +29,8 @@ @pytest.fixture(scope="module") def corpus(): - return load_corpus(ROOT) + 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): @@ -44,10 +54,13 @@ def test_find_filters_real_pairs_before_limit_without_changing_rank(corpus): 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": {"matrix_path": MATRIX.as_posix(), - "matrix_sha256": hashlib.sha256((PROJECT / MATRIX).read_bytes()).hexdigest()}, + "source": { + key: source[key] + for key in ("matrix_path", "matrix_sha256", "catalog_sha256", "metadata_sha256") + }, } @@ -68,11 +81,87 @@ def test_find_rejects_same_named_skill_with_different_root_or_path(corpus, tmp_p replace(graph, path=f"other/{graph.path}", qualified=""), ) for document in cases: - result = find(QUERY, Corpus([document]), searchspace_coordinate=coordinate) + 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 diff --git a/tests/test_knowledge_channels.py b/tests/test_knowledge_channels.py index a119f7715..a4eda1728 100644 --- a/tests/test_knowledge_channels.py +++ b/tests/test_knowledge_channels.py @@ -19,7 +19,7 @@ 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 @@ -119,15 +119,18 @@ 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(corpus): +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) + 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 From c1a9bf05ed05ec0c350f69633f57880cce9caaa0 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:54:16 +0800 Subject: [PATCH 3/3] Show verified SearchSpace coordinates on Find hits Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/operations.md | 20 ++++ src/inferrsi/apps/cli/__init__.py | 22 ++++- src/inferrsi/apps/cli/arguments.py | 4 + src/inferrsi/knowledge/knowledge_find.py | 54 +++++++--- tests/test_find_searchspace.py | 14 ++- tests/test_find_searchspace_display.py | 120 +++++++++++++++++++++++ tests/test_knowledge_channels.py | 25 +++-- 7 files changed, 231 insertions(+), 28 deletions(-) create mode 100644 tests/test_find_searchspace_display.py diff --git a/docs/operations.md b/docs/operations.md index 5e1444def..f62b58880 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -278,6 +278,26 @@ question calls for prior evidence. - **Side effects:** none. Retain the revision returned by `read` for evidence and resource followups. - **Example:** `inferrsi find "NPU OOM after caching per-step masks" --limit 3` returns the casebook entry recording that attempt first. A vaguer phrasing ranks the procedural skills above it, which is the first limit below rather than a defect. +#### Show SearchSpace coordinates on Find hits + +Run this command from an InferRSI checkout with its verified SearchSpace index. + +```text +inferrsi find "graph mode" --skill-root src/inferrsi/knowledge/data/skill_library --show-searchspace-coordinates +``` + +Find annotates the ranked local Skill hits from the verified registry with their +coverage state and all declared resource × stage pairs. A registered Skill with +`unknown` coverage has an empty pair list. In JSON, `searchspace_coordinates` +is attached to the hit, and `searchspace_source` reports the matrix path and +SHA-256 along with the Skill registry and metadata digests. + +Add `--searchspace-coordinate SSD Configure` to restrict the result to Skills +with that exact pair. Each remaining hit still shows all its pairs. Find reports +an error if the index is missing, stale or from a different checkout source. +Run `python tools/build_skill_coverage.py --searchspace-index` in that checkout +to regenerate the index, then retry. + #### External channels are not installed with this package `find` can also query separately enabled read-only channels. A fresh install diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index fdd9e95a1..cb99b8a60 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -203,6 +203,8 @@ def _print_find(result: dict) -> None: source = coordinate["source"] print(f"SearchSpace\t{coordinate['resource']} × {coordinate['stage']}\t" f"{source['matrix_path']} (sha256 {source['matrix_sha256']})") + elif source := result.get("searchspace_source"): + print(f"SearchSpace\t{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") @@ -215,6 +217,14 @@ def _print_find(result: dict) -> None: if item.get("locally_verified") is False: labels.append("not locally verified") print(f"\n{item['id']}\t[{' · '.join(labels)}]\tscore {item['score']}") + if coverage := item.get("searchspace_coordinates"): + pairs = ", ".join( + f"{resource} × {stage}" for resource, stage in coverage["coordinates"] + ) + suffix = f" {pairs}" if pairs else "" + print(f" SearchSpace [{coverage['state']}]{suffix}") + if reason := coverage.get("exclusion_reason"): + print(f" SearchSpace exclusion: {_tsv(reason)}") if item.get("ref"): label = "open (PowerShell)" if sys.platform == "win32" else "open" print(f" {label}: {item['ref']}") @@ -590,16 +600,23 @@ def main(argv: list[str] | None = None) -> int: if unknown or not kinds: raise ValueError("--kinds takes a subset of case,skill,record") coordinate = None + searchspace_index = 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, ) + searchspace_index = coordinate.index + elif args.show_searchspace_coordinates: + from ...knowledge.searchspace_index import load_searchspace_index_for_skill_root + + searchspace_index = load_searchspace_index_for_skill_root( + args.skill_root, option="--show-searchspace-coordinates", + ) result = find( args.query, load_corpus( - args.skill_root, kinds=kinds, - searchspace_index=coordinate.index if coordinate is not None else None, + args.skill_root, kinds=kinds, searchspace_index=searchspace_index, ), limit=args.limit, explain=args.explain, registry=None if args.no_external else _channels(), @@ -607,6 +624,7 @@ def main(argv: list[str] | None = None) -> int: external_limit=args.external_limit, external_timeout=args.external_timeout, searchspace_coordinate=coordinate, + show_searchspace_coordinates=args.show_searchspace_coordinates, ) if args.json: _print(result) diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 76ce65928..4cfd64756 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -681,6 +681,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: "--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( + "--show-searchspace-coordinates", action="store_true", + help="Show matrix pairs and coverage on local Skill hits from an explicit checkout", + ) 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 97f810f12..aea326962 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -38,7 +38,7 @@ if TYPE_CHECKING: from .channels import ChannelRegistry - from .searchspace_index import SearchspaceCoordinate, SearchspaceIndex + from .searchspace_index import SearchspaceCoordinate, SearchspaceEntry, SearchspaceIndex from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends @@ -850,13 +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 _searchspace_entry(document: Document, index: SearchspaceIndex) -> SearchspaceEntry | None: + from .searchspace_index import SearchspaceSourceMismatch + + if document.kind != "skill" or document.root is None or document.path is None: + return None + try: + return index.entry(skill_root=document.root, skill_id=document.identity, path=document.path) + except SearchspaceSourceMismatch: + return None def find( @@ -871,25 +873,38 @@ def find( external_limit: int | None = None, external_timeout: float = 8.0, searchspace_coordinate: SearchspaceCoordinate | None = None, + show_searchspace_coordinates: bool = False, ) -> dict: + """Find local matches, optionally annotating them from the verified ranking source.""" if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") query_tokens, applied, scored = rank(query, corpus) + index = None 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" ) + elif show_searchspace_coordinates: + index = corpus._searchspace_index + if index is None: + raise ValueError( + "Load the Find corpus with a verified SearchSpace index to show coordinates" + ) + if index is not None: index.require_current() + if searchspace_coordinate is not None: + resource, stage = searchspace_coordinate.resource, searchspace_coordinate.stage scored = [ row for row in scored - if _matches_coordinate(corpus.documents[row[2]], searchspace_coordinate) + if (entry := _searchspace_entry(corpus.documents[row[2]], searchspace_coordinate.index)) + is not None and entry.matches(resource, stage) ] items = [] readers: dict = {} - for value, _, index, detail in scored[:limit]: - document = corpus.documents[index] + for value, _, position, detail in scored[:limit]: + document = corpus.documents[position] try: read_args, size = _read_preview(document, readers) unreadable = None @@ -902,6 +917,16 @@ def find( view["next_read_content_bytes"] = size if explain: view["matched"] = detail + if show_searchspace_coordinates and index is not None: + entry = _searchspace_entry(document, index) + if entry is not None: + coverage = { + "state": entry.state, + "coordinates": [list(pair) for pair in sorted(entry.coordinates)], + } + if entry.exclusion_reason is not None: + coverage["exclusion_reason"] = entry.exclusion_reason + view["searchspace_coordinates"] = coverage items.append(view) result = { "query": query, @@ -922,9 +947,12 @@ 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 index is not None: if items: - searchspace_coordinate.index.require_current() + index.require_current() + if show_searchspace_coordinates: + result["searchspace_source"] = index.source + if searchspace_coordinate is not None: result["searchspace_filter"] = searchspace_coordinate.view() return _with_channels( result, query, registry=registry, backend=backend, platform=platform, diff --git a/tests/test_find_searchspace.py b/tests/test_find_searchspace.py index 322b57bfb..119097bf0 100644 --- a/tests/test_find_searchspace.py +++ b/tests/test_find_searchspace.py @@ -126,7 +126,8 @@ def load_after_exclusion(*args, **kwargs): @pytest.mark.parametrize("path", (MATRIX, CATALOG)) -def test_find_rechecks_matrix_and_registry_after_ranking(checkout, monkeypatch, path): +@pytest.mark.parametrize("display", (False, True)) +def test_find_rechecks_matrix_and_registry_after_ranking(checkout, monkeypatch, path, display): root, _ = checkout coordinate = load_searchspace_coordinate(root / LIBRARY, "SSD", "Diagnose") corpus = load_corpus(kinds=("skill",), searchspace_index=coordinate.index) @@ -140,7 +141,8 @@ def rank_then_edit(*args): monkeypatch.setattr(knowledge_find, "rank", rank_then_edit) with pytest.raises(StaleSearchspaceIndex, match="changed during Find"): - find(QUERY, corpus, searchspace_coordinate=coordinate) + find(QUERY, corpus, searchspace_coordinate=None if display else coordinate, + show_searchspace_coordinates=display) def test_find_uses_bound_corpus_and_ignores_unrelated_file_change(checkout): @@ -184,7 +186,11 @@ def test_cli_shows_coordinate_and_source_with_or_without_matches(capsys): ("foreign", "Foreign SearchSpace index"), ("stale", "Stale SearchSpace index"), ]) -def test_cli_reports_actionable_index_failures(tmp_path, capsys, case, diagnostic): +@pytest.mark.parametrize("options", [ + ["--searchspace-coordinate", "SSD", "Configure"], + ["--show-searchspace-coordinates"], +]) +def test_cli_reports_actionable_index_failures(tmp_path, capsys, case, diagnostic, options): index_path = tmp_path / INDEX index_path.parent.mkdir() if case != "missing": @@ -194,7 +200,7 @@ def test_cli_reports_actionable_index_failures(tmp_path, capsys, case, diagnosti 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"]) + "--no-external", *options]) assert exc.value.code == 2 text = capsys.readouterr().err assert diagnostic in text diff --git a/tests/test_find_searchspace_display.py b/tests/test_find_searchspace_display.py new file mode 100644 index 000000000..646b1483c --- /dev/null +++ b/tests/test_find_searchspace_display.py @@ -0,0 +1,120 @@ +"""Find can annotate ranked hits with the checked-in SearchSpace pairs.""" + +import hashlib +import json +from dataclasses import replace +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.knowledge.knowledge_find import Corpus, find, load_corpus +from inferrsi.knowledge.searchspace_index import ( + LIBRARY, + MATRIX, + load_searchspace_coordinate, + load_searchspace_index, +) + +PROJECT = Path(__file__).resolve().parents[1] +ROOT = PROJECT / LIBRARY +DISPLAY = "--show-searchspace-coordinates" +QUERY = "graph mode" +GRAPH = "ascend-graph-mode" +GRAPH_COORDINATES = { + "state": "covered", + "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], + ["Accelerator", "Verify"], ["SSD", "Diagnose"]], +} + + +@pytest.fixture(scope="module") +def index(): + return load_searchspace_index(PROJECT) + + +@pytest.fixture(scope="module") +def verified_corpus(index): + return load_corpus(searchspace_index=index) + + +def test_display_keeps_plain_find_order_and_scores(verified_corpus, index): + baseline = find(QUERY, load_corpus(ROOT), limit=12, explain=True) + displayed = find(QUERY, verified_corpus, limit=12, explain=True, + show_searchspace_coordinates=True) + + assert displayed["items"][0]["id"] == GRAPH + assert displayed["items"][0]["searchspace_coordinates"] == GRAPH_COORDINATES + assert displayed.pop("searchspace_source") == index.source + assert index.source["matrix_path"] == MATRIX.as_posix() + matrix_sha256 = hashlib.sha256((PROJECT / MATRIX).read_bytes()).hexdigest() + assert index.source["matrix_sha256"] == matrix_sha256 + for hit in displayed["items"]: + hit.pop("searchspace_coordinates", None) + assert displayed == baseline + + +def test_display_keeps_all_pairs_after_coordinate_filter(verified_corpus): + filter_coordinate = load_searchspace_coordinate(ROOT, "SSD", "Configure") + displayed = find(QUERY, verified_corpus, limit=1, searchspace_coordinate=filter_coordinate, + show_searchspace_coordinates=True) + + assert displayed["searchspace_filter"]["source"] == displayed["searchspace_source"] + assert displayed["items"][0]["id"] == "ascend-model-adaptation" + assert displayed["items"][0]["searchspace_coordinates"] == { + "state": "covered", + "coordinates": [["Accelerator", "Configure"], ["SSD", "Configure"], ["SSD", "Diagnose"]], + } + + +def test_display_requires_a_verified_ranking_source(): + with pytest.raises(ValueError, match="verified SearchSpace index"): + find(QUERY, Corpus([]), show_searchspace_coordinates=True) + + +def test_display_distinguishes_unknown_coverage_and_other_sources(verified_corpus, index, tmp_path): + display = {"show_searchspace_coordinates": True} + unknown = find("husky", verified_corpus, limit=1, **display)["items"][0] + assert unknown["id"] == "husky" + assert unknown["searchspace_coordinates"] == {"state": "unknown", "coordinates": []} + + graph = next(doc for doc in verified_corpus.documents if doc.identity == GRAPH) + for document in ( + replace(graph, identity="unregistered", qualified=""), + replace(graph, root=tmp_path, qualified=""), + replace(graph, path=f"other/{graph.path}", qualified=""), + ): + corpus = Corpus([document], _searchspace_index=index) + assert "searchspace_coordinates" not in find(QUERY, corpus, **display)["items"][0] + + for kind, query in ( + ("record", "prefill decode graph"), ("case", "NPU OOM after caching per-step masks"), + ): + result = find(query, verified_corpus, limit=15, **display) + hits = [hit for hit in result["items"] if hit["kind"] == kind] + assert hits + assert all("searchspace_coordinates" not in hit for hit in hits) + + +def test_cli_displays_full_pairs_and_provenance(capsys): + command = ["find", QUERY, "--skill-root", str(ROOT), "--no-external", "--limit", "1"] + assert main(command) == 0 + assert "SearchSpace" not in capsys.readouterr().out + + assert main(command + [DISPLAY]) == 0 + text = capsys.readouterr().out + assert MATRIX.as_posix() in text and "sha256" in text + assert "[covered]" in text and "Accelerator × Verify" in text and "SSD × Diagnose" in text + assert "SSD × Configure" not in text + + assert main(command + [DISPLAY, "--searchspace-coordinate", "SSD", "Configure", "--json"]) == 0 + result = json.loads(capsys.readouterr().out) + assert ["SSD", "Diagnose"] in result["items"][0]["searchspace_coordinates"]["coordinates"] + assert result["searchspace_source"] == result["searchspace_filter"]["source"] + + +def test_cli_display_requires_explicit_checkout_root(capsys): + with pytest.raises(SystemExit) as error: + main(["find", QUERY, "--no-external", DISPLAY]) + assert error.value.code == 2 + assert "explicit --skill-root" in capsys.readouterr().err diff --git a/tests/test_knowledge_channels.py b/tests/test_knowledge_channels.py index a4eda1728..624d57d88 100644 --- a/tests/test_knowledge_channels.py +++ b/tests/test_knowledge_channels.py @@ -119,7 +119,10 @@ 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(): +@pytest.mark.parametrize("filter_matches, show_coordinates", [ + (True, False), (False, True), (True, True), +]) +def test_find_searchspace_options_leave_external_search_unchanged(filter_matches, show_coordinates): checkout = Path(__file__).resolve().parents[1] coordinate = load_searchspace_coordinate(checkout / LIBRARY, "SSD", "Configure") corpus = load_corpus(kinds=("record",), searchspace_index=coordinate.index) @@ -128,16 +131,20 @@ def test_find_coordinate_filter_leaves_external_query_and_results_unchanged(): registry = ChannelRegistry([channel]) query = "tiling across streams" plain = find(query, corpus, registry=registry, **options) - filtered = find( - query, corpus, registry=registry, searchspace_coordinate=coordinate, **options, + result = find( + query, corpus, registry=registry, + searchspace_coordinate=coordinate if filter_matches else None, + show_searchspace_coordinates=show_coordinates, **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 + assert plain["items"] and result["items"] == ([] if filter_matches else plain["items"]) + assert result["no_match"] is filter_matches + if show_coordinates: + assert result["searchspace_source"] == coordinate.index.source + assert len(plain["external"]) == len(result["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"] + channel_result, = result["external"] + assert channel_result == {**baseline_channel, "elapsed_ms": channel_result["elapsed_ms"]} + assert plain["external_notes"] == result["external_notes"] assert channel.searched == 2 assert (channel.query_seen, channel.platform_seen, channel.limit_seen) == (query, "a3", 7)