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
45 changes: 27 additions & 18 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,13 @@ def _fixed_attempt_command(args) -> int:
return 0


def _knowledge_reader(args) -> KnowledgeReader:
def _knowledge_reader(args, *, include_package: bool = True) -> KnowledgeReader:
root = args.skill_root
if getattr(args, "installed_library", False):
from ...knowledge.knowledge_find import installed_skill_root

root = installed_skill_root()
return knowledge_reader(skill_root=root, store_root=args.store)
return knowledge_reader(skill_root=root, store_root=args.store, include_package=include_package)


def _revisions(pairs: list[str]) -> dict[str, str]:
Expand Down Expand Up @@ -719,12 +719,18 @@ def main(argv: list[str] | None = None, *, bundled_seal: str | None = None) -> i
_print_find(result)
return 0
if args.command == "collect":
from .atomic_knowledge import GENERATION_SELECTOR, AtomicKnowledgeCLI

revisions = _revisions(args.revisions or [])
if bundled_seal is not None and args.skill_root is None and args.store is None:
if args.skill_root is not None or args.store is not None:
atomic = None
elif bundled_seal is not None:
atomic = AtomicKnowledgeCLI.bundled(bundled_seal)
else:
atomic = AtomicKnowledgeCLI.installed()
if atomic is not None:
from .atomic_collect import collect_inventory
from .atomic_knowledge import AtomicKnowledgeCLI

atomic = AtomicKnowledgeCLI.bundled(bundled_seal)
result = collect_inventory(atomic, args, revisions)
else:
result = _knowledge_reader(args).collect(
Expand All @@ -743,8 +749,8 @@ def main(argv: list[str] | None = None, *, bundled_seal: str | None = None) -> i
relevance_method=args.relevance_method,
context_bytes=args.context_bytes,
decision_cards=_decision_cards(args.decision_card or []),
# Sealed plugin runtimes omit the legacy package catalog.
include_package=bundled_seal is None,
# Sealed installs can omit the legacy package catalog.
include_package=bundled_seal is None and GENERATION_SELECTOR not in os.environ,
)
if args.relevance_method is None and result.get("selection", {}).get("ranking_applied"):
print("collect text queries use Find ranking. "
Expand Down Expand Up @@ -801,25 +807,27 @@ def main(argv: list[str] | None = None, *, bundled_seal: str | None = None) -> i
)
return 0
if args.command == "read":
from .atomic_knowledge import AtomicKnowledgeCLI
from .atomic_knowledge import GENERATION_SELECTOR, AtomicKnowledgeCLI

exact_default_read = (
args.revision is not None and args.skill_root is None and args.store is None
)
atomic = (
AtomicKnowledgeCLI.bundled(bundled_seal)
if bundled_seal is not None and (args.layer == "L0" or exact_default_read)
else AtomicKnowledgeCLI.installed()
)
explicit_source = args.skill_root is not None or args.store is not None
if explicit_source:
atomic = None
elif bundled_seal is not None and (args.layer == "L0" or args.revision is not None):
atomic = AtomicKnowledgeCLI.bundled(bundled_seal)
else:
atomic = AtomicKnowledgeCLI.installed()
if atomic:
_print(atomic.read(args), compact=True)
return 0
if args.layer not in (None, "L1"):
raise ValueError("L0, L2 and L3 require a pinned installed generation")
include_package = not explicit_source or (
bundled_seal is None and GENERATION_SELECTOR not in os.environ
)
if args.layer == "L1":
if args.material or args.resource is not None or args.omit_resources:
raise ValueError("L1 accepts --finding, --compact and --max-bytes")
reader = _knowledge_reader(args)
reader = _knowledge_reader(args, include_package=include_package)
result = reader.read_decision_card(
args.id, revision=args.revision, finding=args.finding, max_bytes=args.max_bytes,
compact=args.compact,
Expand Down Expand Up @@ -850,7 +858,8 @@ def main(argv: list[str] | None = None, *, bundled_seal: str | None = None) -> i
if args.finding is not None or args.max_bytes is not None or args.compact:
raise ValueError("--finding, --max-bytes and --compact require --layer L1")
ref, _, view = read_knowledge(
_knowledge_reader(args), args.id, revision=args.revision, material=args.material,
_knowledge_reader(args, include_package=include_package), args.id,
revision=args.revision, material=args.material,
resource=args.resource,
)
if args.omit_resources:
Expand Down
4 changes: 2 additions & 2 deletions src/inferrsi/apps/cli/atomic_collect.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""The host's bounded public inventory of its installed Knowledge generation."""
"""Bounded public inventory of an installed Knowledge generation."""

import sys
from argparse import Namespace
Expand All @@ -15,7 +15,7 @@ def collect_inventory(atomic: AtomicKnowledgeCLI, args: Namespace, revisions: di
args.skill_root is not None, args.store is not None,
)):
raise ValueError(
"Bundled generation Collect supports inventory with --id, --revision, --kind, "
"Installed generation Collect supports inventory with --id, --revision, --kind, "
"--limit and --max-bytes. Use the returned pinned read for L0 content."
)
if args.limit < 1 or (args.max_bytes is not None and args.max_bytes < 1):
Expand Down
5 changes: 3 additions & 2 deletions src/inferrsi/apps/cli/atomic_knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from .atomic_records import InstalledRecords

_SKILL_LIBRARY_SOURCE = "src/inferrsi/knowledge/data/skill_library/"
GENERATION_SELECTOR = "INFERRSI_KNOWLEDGE_GENERATION"


class AtomicKnowledgeCLI:
Expand All @@ -38,11 +39,11 @@ def __init__(self, installed: InstalledGeneration) -> None:

@classmethod
def installed(cls) -> AtomicKnowledgeCLI | None:
expected = os.environ.get("INFERRSI_KNOWLEDGE_GENERATION")
expected = os.environ.get(GENERATION_SELECTOR)
if expected is None:
return None
if not re.fullmatch(r"sha256:[0-9a-f]{64}", expected):
raise ValueError("INFERRSI_KNOWLEDGE_GENERATION requires a full SHA-256 generation")
raise ValueError(f"{GENERATION_SELECTOR} requires a full SHA-256 generation")
root = Path(__file__).resolve().parents[2] / "_atomic"
return cls(InstalledGeneration(root, expected=expected))

Expand Down
3 changes: 2 additions & 1 deletion src/inferrsi/apps/workflows/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ def open_knowledge_store(

def knowledge_reader(
*, skill_root: Path | None = None, store_root: Path | None = None,
include_package: bool = True,
) -> KnowledgeReader:
"""Select a Knowledge reader without enabling store writes."""
store = (
open_knowledge_store(store_root=store_root, skill_root=skill_root)
if store_root is not None
else None
)
return KnowledgeReader(skill_root=skill_root, store=store)
return KnowledgeReader(skill_root=skill_root, store=store, include_package=include_package)


def read(
Expand Down
4 changes: 2 additions & 2 deletions src/inferrsi/knowledge/knowledge_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,12 +432,12 @@ def collect_service_context(
}
)

def __init__(self, *, skill_root: Path | None = None, store=None):
def __init__(self, *, skill_root: Path | None = None, store=None, include_package: bool = True):
self.skill_root = skill_root.resolve() if skill_root is not None else None
if store is not None and store.skill_root != self.skill_root:
raise ValueError("Store must reserve identities from the same checkout")
self.store = store
self._records: dict[str, dict] | None = None
self._records: dict[str, dict] | None = None if include_package else {}
self._opened_records: dict[str, dict | None] = {}
self._library: tuple[dict[str, bytes], str] | None = None

Expand Down
55 changes: 48 additions & 7 deletions tests/apps/test_host_default_collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,24 @@ def bundled(tmp_path, monkeypatch):
atomic_knowledge, "__file__", str(tmp_path / "apps/cli/atomic_knowledge.py"),
)

def legacy_reader(_args):
pytest.fail("A bundled generation must never fall back to the legacy Collect source")
def legacy_reader(*_args, **_kwargs):
pytest.fail("Installed defaults must never fall back to the legacy Knowledge reader")

monkeypatch.setattr(cli, "_knowledge_reader", legacy_reader)
return target, generation, digest((target / SEAL).read_bytes())


def test_default_collect_and_next_read_share_one_host_generation(bundled, capsys):
@pytest.fixture(params=["host", "standalone"])
def installed_selection(request, bundled, monkeypatch):
target, generation, seal = bundled
if request.param == "standalone":
monkeypatch.setenv("INFERRSI_KNOWLEDGE_GENERATION", generation)
seal = None
return target, generation, seal


def test_collect_and_next_read_share_one_installed_generation(installed_selection, capsys):
target, generation, seal = installed_selection
before = file_bytes(target)

assert cli.main(DEFAULT_COLLECT, bundled_seal=seal) == 0
Expand Down Expand Up @@ -138,8 +147,8 @@ def load_selected(skill_root, *, kinds, searchspace_index):
assert "knowledge_generation" not in result and not result["items"]


def test_inventory_limits_and_exact_revisions_use_the_bundled_source(bundled, capsys):
_, generation, seal = bundled
def test_inventory_limits_and_exact_revisions_use_the_installed_source(installed_selection, capsys):
_, generation, seal = installed_selection
assert cli.main(DEFAULT_COLLECT, bundled_seal=seal) == 0
result = json.loads(capsys.readouterr().out)
[item] = result["items"]
Expand All @@ -165,8 +174,8 @@ def test_inventory_limits_and_exact_revisions_use_the_bundled_source(bundled, ca
assert empty["omissions"] == [{"id": ref, "reason": reason}]


def test_host_collect_obeys_reader_authorization(bundled, monkeypatch, capsys):
_, _, seal = bundled
def test_installed_collect_obeys_reader_authorization(installed_selection, monkeypatch, capsys):
_, _, seal = installed_selection
ref = "package:entry-analysis-example"
original = AtomicReader.__init__

Expand Down Expand Up @@ -204,6 +213,38 @@ def test_unavailable_host_generation_fails_closed(bundled, problem, capsys):
assert not output.out and "Cannot open bundled Knowledge generation" in output.err


@pytest.mark.parametrize(("problem", "diagnostic"), [
("empty-selector", "requires a full SHA-256 generation"),
("stale-selector", "Requested generation is unavailable"),
("missing-seal", Path(SEAL).name),
("changed-payload", "differ from the sealed generation"),
])
def test_unavailable_standalone_generation_fails_closed(
bundled, problem, diagnostic, monkeypatch, capsys,
):
target, generation, _ = bundled
monkeypatch.setenv("INFERRSI_KNOWLEDGE_GENERATION", generation)
assert cli.main(DEFAULT_COLLECT) == 0
[item] = json.loads(capsys.readouterr().out)["items"]
if problem == "empty-selector":
generation = ""
elif problem == "stale-selector":
generation = f"sha256:{'0' * 64}"
elif problem == "missing-seal":
(target / SEAL).unlink()
else:
payload = target / "skills/task-day-0/SKILL.md"
payload.write_bytes(payload.read_bytes() + b"\n")
monkeypatch.setenv("INFERRSI_KNOWLEDGE_GENERATION", generation)

for arguments in (DEFAULT_COLLECT, item["read_args"]):
with pytest.raises(SystemExit) as rejected:
cli.main(arguments)
assert rejected.value.code == 2
output = capsys.readouterr()
assert not output.out and diagnostic in output.err


def test_host_manifest_preserves_the_legacy_default_until_cutover():
project = Path(__file__).resolve().parents[2]
launcher = project / "plugins/inferrsi/skills/inferrsi/scripts/inferrsi.py"
Expand Down
50 changes: 43 additions & 7 deletions tests/knowledge/test_knowledge_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@

import pytest

from inferrsi.apps.cli import main
from inferrsi.apps.cli import atomic_knowledge, main
from inferrsi.knowledge import knowledge_find, knowledge_operations
from inferrsi.knowledge.atomic_generation import SEAL, digest
from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader
from inferrsi.knowledge.knowledge_store import KnowledgeStore
from tests.knowledge.test_atomic_generation import build_release, make_author_root
from tests.knowledge.test_atomic_reader import allow

REPO = Path(__file__).resolve().parents[2]
SKILLS = REPO / "src/inferrsi/knowledge/data/skill_library"
Expand Down Expand Up @@ -126,8 +129,9 @@ def test_collect_selects_explicit_checkout_identity():

@pytest.mark.parametrize("authority", ["checkout", "store"])
@pytest.mark.parametrize("ranked", [False, True], ids=["exact", "ranked"])
def test_collect_explicit_source_uses_its_own_authority(
authority, ranked, capsys, monkeypatch, tmp_path,
@pytest.mark.parametrize("selection", ["host", "standalone", "stale-pin"])
def test_collect_and_read_explicit_source_use_their_own_authority(
authority, ranked, selection, capsys, monkeypatch, tmp_path,
):
identity = f"checkout:{SOURCE}"
source_args = ["--skill-root", str(SKILLS)]
Expand All @@ -138,19 +142,30 @@ def test_collect_explicit_source_uses_its_own_authority(
identity = f"store:{LOCAL}"
source_args = ["--store", str(tmp_path)]

def missing_records():
raise FileNotFoundError("The sealed plugin omits the legacy Record catalog")
target = tmp_path / "_atomic"
generation = build_release(make_author_root(tmp_path), target, permits=allow)
bundled_seal = digest((target / SEAL).read_bytes()) if selection == "host" else None
monkeypatch.setattr(
atomic_knowledge, "__file__", str(tmp_path / "apps/cli/atomic_knowledge.py"),
)
monkeypatch.setenv(
"INFERRSI_KNOWLEDGE_GENERATION",
generation if selection == "standalone" else f"sha256:{'0' * 64}",
)

def missing_records(*_args):
pytest.fail("Explicit Collect and Read must not consult the legacy package catalog")

monkeypatch.setattr(knowledge_operations, "knowledge_records", missing_records)
monkeypatch.setattr(knowledge_operations, "lookup_record", missing_records)
monkeypatch.setattr(knowledge_find, "installed_skill_root", lambda: tmp_path / "absent-library")
monkeypatch.setenv("INFERRSI_KNOWLEDGE_GENERATION", f"sha256:{'0' * 64}")
selectors = (
["calibrate serving simulation", "--relevance-method", "find-lexical-v1"]
if ranked else ["--id", identity, "--revision", f"{identity}={source.revision}"]
)
assert main(
["collect", *selectors, *source_args, "--json"],
bundled_seal=f"sha256:{'1' * 64}",
bundled_seal=bundled_seal,
) == 0
streams = capsys.readouterr()
assert not streams.err
Expand All @@ -160,6 +175,27 @@ def missing_records():
item = next(item for item in result["items"] if item["ref"] == identity)
assert item["revision"] == source.revision

read_args = ["--revision", item["revision"], *source_args]
assert main(["read", item["ref"], *read_args, "--material"], bundled_seal=bundled_seal) == 0
streams = capsys.readouterr()
assert not streams.err
assert json.loads(streams.out) == {**source.view(material=True), "ref": identity}

path = source.metadata["entrypoint"]
assert main(
["read", source.metadata["id"], *read_args, "--resource", path, "--omit-resources"],
bundled_seal=bundled_seal,
) == 0
resource = json.loads(capsys.readouterr().out)
assert (resource["ref"], resource["revision"]) == (identity, source.revision)
assert resource["content"].encode() == source.content[path] and "resources" not in resource

with pytest.raises(SystemExit) as missing:
main(["read", f"package:{SOURCE}", *read_args], bundled_seal=bundled_seal)
assert missing.value.code == 2
streams = capsys.readouterr()
assert not streams.out and f"Unknown identity: package:{SOURCE}" in streams.err


def test_read_returns_bundle_view_and_rejects_wrong_revision():
code, stdout, _ = run_cli("read", SOURCE, "--skill-root", str(SKILLS), "--material")
Expand Down
Loading