Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down
85 changes: 76 additions & 9 deletions src/inferrsi/knowledge/knowledge_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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 = [
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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]:
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading