From 1734d2cf3e0855b41c76df65cc49c56f2d7945cc Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:00:07 +0800 Subject: [PATCH 1/4] Project requested catalog decisions from the delivered sources Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/catalog-selection.md | 50 ++- src/inferrsi/knowledge/catalog_selection.py | 69 ++++- .../knowledge/knowledge_operations.py | 4 + tests/test_catalog_selection.py | 292 ++++++++++++++++++ 4 files changed, 404 insertions(+), 11 deletions(-) diff --git a/docs/catalog-selection.md b/docs/catalog-selection.md index f2d297196..c5d404b57 100644 --- a/docs/catalog-selection.md +++ b/docs/catalog-selection.md @@ -55,6 +55,40 @@ are independent copies. Reader-local resource digest reuse is keyed by path and immutable bytes; metadata and dependency validation still run for every manifest. Snapshots are content identities, not an authorization credential. +### Request a decision card with a selected source + +Add `"layer": "L1"` to a selection to request the decision view of its original +Skill or Record. For a Case, also supply a `finding` selector for its original +`case.json`, such as `"case.json#/findings/0"` or `"id:"`. +You can supply `revision` from the selected catalog entry to check the pin +explicitly. Both the CLI and the Apps `select_catalog_evidence` callback accept +`layer` per entry. Other entries in the same response keep the default delivery. + +```json +{"ref": "checkout:case.admission-drain-occupancy", "reason": "Check the decode occupancy interval", + "questions": [], "layer": "L1", "finding": "case.json#/findings/0"} +``` + +Each requested view appears in `decision_cards` in selection order, with the +catalog ref and revision. The catalog projects each card from the same resolved +bundle that supplied that entry's delivered body. A delivered view includes the +complete canonical card, its UTF-8 `card_bytes`, and the original `source_resource` and +`body_resource` locators. Store Record declarations live in the pinned bundle +manifest, so their `source_resource` is null. Reopen a selected source through +this catalog with the original snapshot, selection and revision. Catalog +checkout closures can have different revisions from ordinary Find and Read. + +All selected bodies take priority. Each complete or partial card is charged once, +in full, against the remaining `context_bytes`. When a card does not fit, its +selected body stays delivered even if `expansion_bytes` has space to spare. +An `over_budget` result retains the required size and the original pin. Its +`scope: decision_card` omission gives the bytes available for retry. +`base_unavailable` records that the selected body could not be delivered. +The retrieval assembly includes charged cards in `content_bytes` and reports +their subtotal in `decision_card_bytes`. Expansion has its own budget. +For a claim assessment, quote the delivered original at its ref, revision and +resource path. Card text alone cannot confirm a quote. + Python uses the same implementation: ```python @@ -136,13 +170,15 @@ Within one ref/revision, shared required resources are delivered and charged onc Each expansion checks its complete closure before budgeting the remaining unique resources, so deduplication does not permit partial required deliveries. -`context_bytes` and `expansion_bytes` count the UTF-8 bytes in delivered -resource `content`. For a typed `SKILL.md`, the reader delivers the procedure -with its embedded `metadata.inferrsi` block removed, records the original file -hash and byte ranges, and charges the resulting procedure bytes. A separately -delivered `metadata.json` or `record.json` counts in full. JSON keys, hashes, -the output envelope and trace are outside these two resource budgets. The -selection prompt has its own serialized-input token budget. +`context_bytes` counts selected resource `content` plus explicitly requested, +delivered canonical cards. `expansion_bytes` counts only expanded resource +`content`. Both are measured in UTF-8 bytes. For a typed `SKILL.md`, the reader +delivers the procedure with its embedded `metadata.inferrsi` block removed, +records the original file hash and byte ranges, and charges the resulting +procedure bytes. A separately delivered `metadata.json` or `record.json` +counts in full. The output envelope, resource hash fields and retrieval trace +are outside both budgets. The selection prompt has its own serialized-input +token budget. Top-level omissions use `scope: entry` when a whole entry could not be delivered. A failed optional resource expansion uses `scope: resource` and diff --git a/src/inferrsi/knowledge/catalog_selection.py b/src/inferrsi/knowledge/catalog_selection.py index 5c1b93591..d05e1cae1 100644 --- a/src/inferrsi/knowledge/catalog_selection.py +++ b/src/inferrsi/knowledge/catalog_selection.py @@ -54,6 +54,34 @@ def __init__(self, code, detail): self.code = code +def _selected_decisions(requests, cards, delivered_bundles, available): + """Use the bundles that supplied the selected bodies, after accounting for every body.""" + from .decision_cards import project_decision_card + + results, omissions = [], [] + charged = 0 + for ref, selection in requests.items(): + revision = cards[ref]["revision"] + selector = {"finding": selection["finding"]} if "finding" in selection else {} + identity = {"ref": ref, "revision": revision, **selector} + if ref not in delivered_bundles: + results.append({**identity, "status": "base_unavailable"}) + omissions.append({**identity, "scope": "decision_card", "reason": "base_unavailable"}) + continue + remaining = available - charged + result = project_decision_card( + delivered_bundles[ref], reference=ref, revision=revision, + max_bytes=remaining, **selector, + ) + results.append({**result, **selector}) + if result["status"] == "over_budget": + omissions.append({**identity, "scope": "decision_card", "reason": "over_budget", + "available_bytes": remaining, "required_bytes": result["card_bytes"]}) + else: + charged += result["card_bytes"] + return results, omissions, charged + + def _preview(value, size=400): text = value if isinstance(value, str) else encoded(value).decode() raw = text.encode() @@ -435,11 +463,13 @@ def snapshot(self, **scope): return deepcopy(self._load(**scope)[0]) @staticmethod - def _context(reader, ref, revision, available): - bundle = reader.read(ref, revision=revision) + def _context(reader, ref, revision, available, retained=None): + resolved = reader.read_resolved(ref, revision=revision) + _, bundle = resolved if bundle.metadata["kind"] != "skill" and not ref.startswith("store:"): return reader.collect( - ids=[ref], revisions={ref: revision}, context_bytes=available, limit=1 + ids=[ref], revisions={ref: revision}, context_bytes=available, limit=1, + _context_sources=retained, ) # Direct skills and store bundles need their complete declared closure. # Collect's generic record context intentionally only opens an entrypoint. @@ -479,6 +509,8 @@ def _context(reader, ref, revision, available): ], "contexts": [], } + if retained is not None: + retained[ref] = resolved return { "omissions": [], "contexts": [ @@ -581,6 +613,7 @@ def _complete( if not isinstance(selections, list): raise ValueError("selections must be a list") selected = {} + decision_requests = {} for selection in selections: if not isinstance(selection, dict): raise ValueError("Each selection must be an object") @@ -598,9 +631,21 @@ def _complete( ): raise ValueError("Each selection needs a questions list (possibly empty)") compare_conditions({}, conditions, purpose=selection.get("purpose", "conclusion")) + if "layer" in selection or "finding" in selection: + if selection.get("layer") != "L1": + raise ValueError("Select layer L1 to request a decision card") + if cards[ref]["kind"] == "case": + if not isinstance(selection.get("finding"), str) or not selection["finding"]: + raise ValueError("A Case L1 selection needs an original finding selector") + elif "finding" in selection: + raise ValueError("Only Case L1 selections take a finding selector") + if "revision" in selection and selection["revision"] != cards[ref]["revision"]: + raise SelectionError("revision_mismatch", f"Revision outside catalog: {ref}") + decision_requests[ref] = selection selected[ref] = selection queue = deque((ref, 0, None) for ref in selected) seen = set() + decision_bundles = {} contexts, judgments, omissions, paths = [], [], [], [] used = optional_used = optional_count = 0 while queue: @@ -623,7 +668,8 @@ def _complete( omissions.append({"ref": ref, "scope": "entry", "reason": "context_limit", "via": via}) continue - result = self._context(readers[ref], ref, card["revision"], available) + retained = decision_bundles if ref in decision_requests else None + result = self._context(readers[ref], ref, card["revision"], available, retained) delivered = result.get("contexts", []) omissions.extend({**item, "scope": "entry"} for item in result["omissions"] + result.get("context_omissions", [])) @@ -631,6 +677,10 @@ def _complete( paths.append({"ref": ref, "via": via, "stop": "context_unavailable"}) continue context = delivered[0] + if ref in decision_requests and ( + (context["ref"], context["revision"]) != identity or ref not in decision_bundles + ): + raise SelectionError("revision_mismatch", f"Delivery does not match {ref}") amount = context["content_bytes"] if depth: optional_used += amount @@ -717,6 +767,15 @@ def _complete( paths.append({"via": trail, "status": "delivered", "bytes": amount}) else: paths.append({"via": trail, "stop": edge["kind"]}) + decision_output, decision_assembly = {}, {} + if decision_requests: + results, missed, charged = _selected_decisions( + decision_requests, cards, decision_bundles, context_bytes - used, + ) + decision_output["decision_cards"] = results + omissions.extend(missed) + decision_assembly["decision_card_bytes"] = charged + used += charged # Detect mutations during assembly as well as before it; return no stale payload. if self.snapshot(**scope)["snapshot_id"] != snapshot_id: raise SelectionError( @@ -746,12 +805,14 @@ def _complete( "omissions": omissions, "content_bytes": used, "expansion_bytes": optional_used, + **decision_assembly, "elapsed_seconds": perf_counter() - started, }, ) return { "snapshot_id": snapshot_id, "contexts": contexts, + **decision_output, "judgments": judgments, "omissions": omissions, "retrieval": trace, diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index 0ae6302d3..14cacc3a7 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -808,6 +808,7 @@ def collect( relevance: str | None = None, relevance_method: str | None = None, context_bytes: int | None = None, + _context_sources: dict[str, tuple[str, Bundle]] | None = None, ) -> dict: if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") @@ -1008,6 +1009,9 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: context_omissions.append(omission) else: contexts.append(context) + if _context_sources is not None: + # Pin the exact read that supplied this whole body for the catalog's L1. + _context_sources[view["ref"]] = (view["ref"], bundle) context_used += context["content_bytes"] for reference in requested: diff --git a/tests/test_catalog_selection.py b/tests/test_catalog_selection.py index 1bc46378d..af4081dfd 100644 --- a/tests/test_catalog_selection.py +++ b/tests/test_catalog_selection.py @@ -1,6 +1,8 @@ import json import os import shutil +from importlib.resources import files +from pathlib import Path import pytest @@ -28,6 +30,257 @@ def selection(ref, **extra): return {"ref": ref, "reason": "Relevant mechanism", "questions": [], **extra} +def test_catalog_l1_uses_remaining_selected_bytes(tmp_path): + from inferrsi.apps.knowledge import confirm_catalog_evidence + from inferrsi.knowledge.catalog_selection import encoded + + note = "仅限固定输入" + metadata = json.dumps({"limitations": [note]}, ensure_ascii=False) + owner = skill(tmp_path, "alpha") + (owner / "SKILL.md").write_text( + "---\nname: alpha\ndescription: Alpha\nmetadata:\n inferrsi: |\n" + f" {metadata}\n---\nRead the original procedure. [Extra](../extra/SKILL.md)\n", + encoding="utf-8", + ) + skill(tmp_path, "extra", "Separately budgeted expansion.") + skill(tmp_path, "beta", "Second selected procedure.") + ref = "checkout:alpha" + catalog = CatalogSelection(skill_root=tmp_path) + scope = {"kinds": ("skill",)} + snapshot = catalog.snapshot(**scope) + pin = next(c["revision"] for c in snapshot["cards"] if c["ref"] == ref) + selected = [selection(ref), selection("checkout:beta")] + + def complete(selections, **options): + return catalog.complete(snapshot["snapshot_id"], selections, **scope, **options) + + default = complete(selected) + assert "decision_cards" not in default and "decision_card_bytes" not in ( + default["retrieval"]["assembly"]) + base = default["retrieval"]["assembly"]["content_bytes"] + expanded = default["retrieval"]["assembly"]["expansion_bytes"] + assert expanded == default["contexts"][2]["content_bytes"] > 0 + assert [c["ref"] for c in default["contexts"]] == [ref, "checkout:beta", "checkout:extra"] + request = [selection(ref, layer="L1", revision=pin), selected[1]] + first = complete(request) + projected, = first["decision_cards"] + assert projected["ref"] == ref and projected["revision"] == pin + assert projected["source_resource"] == projected["body_resource"] == "alpha/SKILL.md" + assert projected["card"]["declared"]["limitations"] == [note] + size = len(encoded(projected["card"])) + assert size == projected["card_bytes"] and size > len(encoded(projected["card"]).decode()) + exact = complete(request, context_bytes=base + size, expansion_bytes=expanded) + small = complete(request, context_bytes=base + size - 1, expansion_bytes=expanded + size) + assert exact["contexts"] == small["contexts"] == default["contexts"] + assert exact["judgments"] == small["judgments"] == default["judgments"] + assert exact["decision_cards"] == first["decision_cards"] + assert exact["retrieval"]["assembly"]["content_bytes"] == base + size + assert exact["retrieval"]["assembly"]["decision_card_bytes"] == size + assert small["retrieval"]["assembly"]["content_bytes"] == base + assert small["retrieval"]["assembly"]["decision_card_bytes"] == 0 + omitted, = small["decision_cards"] + assert omitted["status"] == "over_budget" and "card" not in omitted + assert omitted["ref"] == ref and omitted["revision"] == pin + assert small["omissions"] == [{"ref": ref, "revision": pin, "scope": "decision_card", + "reason": "over_budget", "required_bytes": size, + "available_bytes": size - 1}] + assert exact["retrieval"]["assembly"]["expansion_bytes"] == expanded + assert small["retrieval"]["assembly"]["expansion_bytes"] == expanded + no_expansion = complete(request, context_bytes=base + size + 1, expansion_bytes=0) + assert no_expansion["decision_cards"] == exact["decision_cards"] + assert no_expansion["contexts"] == default["contexts"][:2] + assert no_expansion["retrieval"]["assembly"]["expansion_bytes"] == 0 + assert no_expansion["retrieval"]["assembly"]["content_bytes"] == base + size + assert all(i["agent_read"] == i["adopted"] == "unknown" for i in exact["retrieval"]["items"]) + assessment = dict(ref=ref, revision=pin, path="alpha/SKILL.md", quote=note, + claim="Pilot evidence", reason="Source procedure", verdict="unknown", + missing=[], validation_step="Replay original procedure") + with pytest.raises(ValueError, match="quote"): + confirm_catalog_evidence(exact, [assessment]) + confirmed = confirm_catalog_evidence(exact, [{**assessment, "quote": "original procedure"}]) + assert confirmed["assessments"][0]["source_verification_upgraded"] is False + unavailable = complete(request, context_bytes=1) + assert unavailable["decision_cards"] == [{"ref": ref, "revision": pin, + "status": "base_unavailable"}] + + +def test_catalog_l1_ancestor_license_separates_reader_pins(tmp_path): + from inferrsi.knowledge.knowledge_operations import KnowledgeReader + + library = Path(files("inferrsi.knowledge").joinpath("data", "skill_library")) + shutil.copytree(library / "workflows/governance/claim-contract", tmp_path / "claim-contract") + license_file = tmp_path / "LICENSE" + license_file.write_text("Ancestor license") + ref = "checkout:claim-contract" + ordinary = KnowledgeReader(skill_root=tmp_path) + legacy_pin = ordinary.read(ref).revision + catalog = CatalogSelection(skill_root=tmp_path) + scope = {"kinds": ("skill",)} + snapshot = catalog.snapshot(**scope) + card, = snapshot["cards"] + pin = card["revision"] + assert pin != legacy_pin + + def complete(revision): + requested = selection(ref, layer="L1", revision=revision) + return catalog.complete(snapshot["snapshot_id"], [requested], **scope) + + assert ordinary.read_decision_card(ref, revision=legacy_pin)["card"]["revision"] == legacy_pin + assert complete(pin)["decision_cards"][0]["card"]["revision"] == pin + refused = ordinary.read_decision_card(ref, revision=pin) + assert refused["status"] == "unavailable_revision" and "card" not in refused + with pytest.raises(SelectionError) as error: + complete(legacy_pin) + assert error.value.code == "revision_mismatch" + license_file.write_text("Amended ancestor license") + assert ordinary.read(ref).revision == legacy_pin + with pytest.raises(SelectionError) as error: + complete(pin) + assert error.value.code == "stale_snapshot" + + +def test_catalog_l1_case_original_finding_and_reorder_cli(tmp_path, capsys): + from inferrsi.apps.cli import main + + root = tmp_path / "library" + root.mkdir() + cases = skill(root, "pilot") / "cases" + cases.mkdir() + source = Path(files("inferrsi.knowledge").joinpath("data", "skill_library", "casebooks", + "inference", "inference-optimization-casebook", "cases")) + filename = "admission-drain-occupancy.json" + path = cases / filename + shutil.copyfile(source / filename, path) + original = json.loads(path.read_text(encoding="utf-8")) + shutil.copyfile(source / original["content"], cases / original["content"]) + args = ["catalog-select", "decode occupancy", "--skill-root", str(root), "--kinds", "case", + "--expansion-depth", "0", "--context-bytes", "100000"] + ref = "checkout:case.admission-drain-occupancy" + pointer = "case.json#/findings/0" + + def query(*options): + assert main([*args, *options]) == 0 + return json.loads(capsys.readouterr().out) + + def read(snapshot, finding): + snapshot_id = snapshot["snapshot_id"] + chosen, = snapshot["prompt"]["catalog"]["cards"] + request = selection(ref, layer="L1", revision=chosen["revision"], finding=finding) + answer = tmp_path / "selection.json" + answer.write_text(json.dumps({"snapshot_id": snapshot_id, "selections": [request]})) + return query("--selection", str(answer))["decision_cards"][0] + + initial = query() + first = read(initial, pointer) + assert first["source_resource"] == "case.json" + assert first["body_resource"] == original["content"] + assert first["card"]["declared"]["finding"] == original["findings"][0] + original["findings"][0]["id"] = "original-observation" + original["findings"].reverse() + path.write_text(json.dumps(original), encoding="utf-8") + fresh = query() + assert fresh["snapshot_id"] != initial["snapshot_id"] + stale = selection(ref, layer="L1", revision=first["revision"], finding=pointer) + for snapshot, code in ((initial, "stale_snapshot"), (fresh, "revision_mismatch")): + with pytest.raises(SelectionError) as error: + CatalogSelection(skill_root=root).complete( + snapshot["snapshot_id"], [stale], kinds=("case",), + ) + assert error.value.code == code + last = read(fresh, "id:original-observation") + assert last["revision"] != first["revision"] + assert last["card"]["atom"]["pointer"] == "case.json#/findings/2" + assert last["card"]["declared"]["finding"] == original["findings"][2] + + +def test_catalog_l1_installed_package_skill_and_record(): + from inferrsi.knowledge.knowledge_operations import KnowledgeReader + + catalog = CatalogSelection() + scope = {"kinds": ("skill", "record")} + snapshot = catalog.snapshot(**scope) + wanted = {"ascend-device-health", "xdit.cuda.diffusion.parallelism_freshness_and_topology"} + chosen = [card for card in snapshot["cards"] if card["id"] in wanted] + assert {card["id"] for card in chosen} == wanted + requests = [selection(card["ref"], layer="L1", revision=card["revision"]) for card in chosen] + result = catalog.complete(snapshot["snapshot_id"], requests, context_bytes=2000000, + expansion_depth=0, **scope) + for card, item in zip(chosen, result["decision_cards"], strict=True): + assert item["ref"] == card["ref"] and item["ref"].startswith("package:") + assert item["revision"] == card["revision"] and item["card"]["atom"]["kind"] == card["kind"] + original = KnowledgeReader().read_decision_card(card["ref"], revision=card["revision"]) + assert item == original + if card["kind"] == "record": + assert item["card"]["declared"]["verification"]["locally_verified"] is False + + +def test_catalog_l1_rejects_delivery_from_different_owner(catalog, monkeypatch): + scope = {"kinds": ("skill",)} + snapshot = catalog.snapshot(**scope) + original_context = catalog._context + + def wrong_owner(reader, ref, revision, available, retained): + result = original_context(reader, ref, revision, available, retained) + result["contexts"][0]["ref"] = "store:alpha" + return result + + monkeypatch.setattr(catalog, "_context", wrong_owner) + with pytest.raises(SelectionError) as error: + catalog.complete(snapshot["snapshot_id"], [selection("checkout:alpha", layer="L1")], + **scope) + assert error.value.code == "revision_mismatch" + + +def test_catalog_l1_projects_the_actual_body_bundle(tmp_path, tmp_path_factory, monkeypatch): + from inferrsi.knowledge import decision_cards + from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader + from inferrsi.knowledge.knowledge_store import KnowledgeStore + + library = tmp_path / "library" + library.mkdir() + skill(library, "beta", "Inspect the source.") + catalog = CatalogSelection(skill_root=library) + store = KnowledgeStore(tmp_path_factory.mktemp("store"), skill_root=library) + source = catalog._reader().read("checkout:beta") + candidate = {**source.metadata, "id": "beta-copy", "state": "candidate"} + store.create(Bundle(candidate, source.content, source.dependencies)) + catalog.store = store + refs = ["checkout:beta", "store:beta-copy", + "package:xdit.cuda.diffusion.parallelism_freshness_and_topology"] + snapshot = catalog.snapshot(kinds=("skill", "record")) + latest, body_bundles, projected = {}, {}, [] + original_read = KnowledgeReader._read + original_context = catalog._context + original_project = decision_cards.project_decision_card + + def track_read(reader, ref, revision): + bundle = original_read(reader, ref, revision) + if revision is not None: + latest[ref] = bundle + return bundle + + def track_body(reader, ref, revision, available, retained): + result = original_context(reader, ref, revision, available, retained) + if result["contexts"]: + body_bundles[ref] = latest[ref] + return result + + def project(resolved, **options): + ref, bundle = resolved + assert ref == options["reference"] + assert bundle is body_bundles[ref] + projected.append(ref) + return original_project(resolved, **options) + + monkeypatch.setattr(KnowledgeReader, "_read", track_read) + monkeypatch.setattr(catalog, "_context", track_body) + monkeypatch.setattr(decision_cards, "project_decision_card", project) + result = catalog.complete(snapshot["snapshot_id"], [selection(ref, layer="L1") for ref in refs], + kinds=("skill", "record"), expansion_depth=0, context_bytes=2000000) + assert [item["ref"] for item in result["decision_cards"] if "card" in item] == refs + assert projected == refs + + @pytest.fixture def catalog(tmp_path): skill(tmp_path, "alpha", "Alpha [beta](../beta/SKILL.md) [web](https://example.org)") @@ -413,6 +666,45 @@ def selector(prompt): assert "prompt" not in result +@pytest.mark.parametrize("entrypoint", ["apps", "cli"]) +def test_per_entry_l1_preserves_default_delivery(catalog, entrypoint, tmp_path_factory, + capsys, monkeypatch): + from inferrsi.apps.cli import main + from inferrsi.knowledge.catalog_selection import encoded + + monkeypatch.setattr("time.perf_counter", lambda: 0.0) + monkeypatch.setattr("inferrsi.knowledge.catalog_selection.perf_counter", lambda: 0.0) + + answer = tmp_path_factory.mktemp("selector") / "answer.json" + + def run(**options): + requests = [selection("checkout:alpha", **options), selection("checkout:beta")] + if entrypoint == "cli": + snapshot = catalog.snapshot(kinds=("skill",)) + answer.write_text(json.dumps({"snapshot_id": snapshot["snapshot_id"], + "selections": requests}), encoding="utf-8") + assert main(["catalog-select", "beta", "--kinds", "skill", "--skill-root", + str(catalog.skill_root), "--selection", str(answer)]) == 0 + return json.loads(capsys.readouterr().out) + + def selector(prompt): + return {"snapshot_id": prompt["catalog"]["snapshot_id"], "selections": requests} + + return select_catalog_evidence(catalog, "beta", selector, model="fixture-selector", + token_budget=1000000, kinds=("skill",)) + + plain = run() + enriched = run(layer="L1") + projected, = enriched.pop("decision_cards") + assert projected["ref"] == "checkout:alpha" + assembly = enriched["retrieval"]["assembly"] + charged = assembly.pop("decision_card_bytes") + assert charged == len(encoded(projected["card"])) + assembly["content_bytes"] -= charged + assert enriched["retrieval"]["selection"]["selections"][0].pop("layer") == "L1" + assert encoded(enriched) == encoded(plain) + + def test_filters_record_all_exclusions(catalog): snapshot = catalog.snapshot(kinds=("skill",)) assert snapshot["scope"]["considered"] == ( From 5a5bb6a18aab4caf24deb1939e315db389824344 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:31:31 +0800 Subject: [PATCH 2/4] Verify the effective checkout backend against the ranked Skill bytes Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/knowledge/knowledge_find.py | 24 +++++++---- tests/knowledge/test_decision_cards.py | 52 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index 5533e4e53..0b73ddb17 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -900,21 +900,27 @@ def _decision_links( prefix = "data/skill_library/" if source.ref.startswith("package:") else "" if source.body != f"{prefix}{document.path}": return "Skill location changed after ranking; repeat Find" - # Checkout bundles cover the Skill directory. Its registration lives in the root. - if query_backend and source.ref.startswith("checkout:"): - registration = skill_registrations(document.root).get(document.identity) - if registration is None or ( - registration[0] / "SKILL.md" != document.root / document.path - or _backend_weight(registration[1], query_backend) - != _backend_weight(document.backend, query_backend) - ): - return "Skill registration changed after ranking; repeat Find" if not document.ranked_sources or any( _source_digest(preview.bundle.content.get(str(directory / name))) != expected for name, expected in document.ranked_sources.items() ): return "Source changed after ranking; repeat Find" + if query_backend and source.kind == "skill" and source.ref.startswith("checkout:"): + registration = skill_registrations(document.root).get(document.identity) + if registration is None or registration[0] / "SKILL.md" != document.root / document.path: + return "Skill registration changed after ranking; repeat Find" + backend = registration[1] + if backend is None: + # Flat checkouts declare the backend in the verified Skill resources. + if "backend" in source.record: + backend = source.record["backend"] + else: + _, backend = _skill_header(preview.bundle.content[source.body].decode("utf-8")) + ranked_weight = _backend_weight(document.backend, query_backend) + if _backend_weight(backend, query_backend) != ranked_weight: + return "Skill registration changed after ranking; repeat Find" + def link(selector: str | None = None) -> dict: projection = source.project(finding=selector) args = ["read", source.ref, "--revision", source.revision, "--layer", "L1", diff --git a/tests/knowledge/test_decision_cards.py b/tests/knowledge/test_decision_cards.py index 5d8551193..fc40fa79c 100644 --- a/tests/knowledge/test_decision_cards.py +++ b/tests/knowledge/test_decision_cards.py @@ -129,6 +129,58 @@ def register(pilot, peer): assert fresh[0]["decision_card"] == pin +@pytest.mark.parametrize("declaration", ["header", "embedded", "sidecar"]) +def test_find_pin_follows_effective_checkout_backend(tmp_path, declaration): + skill = tmp_path / "queue-drain" + skill.mkdir() + body = skill / "SKILL.md" + declared_in = body + header = "---\nname: queue-drain\ndescription: marigold scheduling\n" + if declaration == "header": + header += "backend: rocm\n" + elif declaration == "embedded": + header += 'metadata:\n inferrsi: |\n {"backend":"rocm"}\n' + else: + declared_in = skill / "metadata.json" + declared_in.write_text('{"backend":"rocm"}', encoding="utf-8") + body.write_text(header + "---\nDrain the queue.\n", encoding="utf-8") + + def snapshot(): + return load_corpus(tmp_path, kinds=("skill",)) + + def decision(corpus): + hit, = find("cuda marigold", corpus, decision_cards=True)["items"] + return hit["decision_card"] + + index = tmp_path / "skill-index.json" + + def register(backend): + entry = {"path": skill.name, "backend": backend} + index.write_text(json.dumps({"schema_version": 1, "skills": {skill.name: entry}}), + encoding="utf-8") + + flat = snapshot() + pin = decision(flat) + assert pin["revision"] + register("ascend") # Both rocm and ascend carry the same weight for a CUDA query. + indexed = snapshot() + assert decision(flat) == decision(indexed) == pin + index.unlink() + assert decision(indexed) == pin + + register("cuda") + assert decision(flat)["status"] == "unavailable" + matching = snapshot() + assert decision(matching) == pin + index.unlink() + assert decision(matching)["status"] == "unavailable" + + # Even an equal-weight declaration cannot replace the bytes that were ranked. + declared_in.write_bytes(declared_in.read_bytes().replace(b"rocm", b"ascend")) + assert decision(flat)["reason"] == "Source changed after ranking; repeat Find" + assert decision(snapshot())["revision"] != pin["revision"] + + @pytest.mark.parametrize("failure", ["registration", "preview"]) def test_find_reports_safe_decision_source_failure(tmp_path, monkeypatch, failure): from inferrsi.knowledge import knowledge_find, skill_catalog From 46e9a691585c843708b1246657a6befef0709d89 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:15:05 +0800 Subject: [PATCH 3/4] Keep catalog delivery when a selected case finding is unavailable Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation, documentation and regression tests) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/catalog-selection.md | 8 ++- src/inferrsi/knowledge/catalog_selection.py | 16 +++-- src/inferrsi/knowledge/decision_cards.py | 12 +++- tests/knowledge/test_catalog_selection.py | 70 ++++++++++++++++++++- 4 files changed, 94 insertions(+), 12 deletions(-) diff --git a/docs/catalog-selection.md b/docs/catalog-selection.md index b52d58326..4e079029d 100644 --- a/docs/catalog-selection.md +++ b/docs/catalog-selection.md @@ -83,7 +83,13 @@ in full, against the remaining `context_bytes`. When a card does not fit, its selected body stays delivered even if `expansion_bytes` has space to spare. An `over_budget` result retains the required size and the original pin. Its `scope: decision_card` omission gives the bytes available for retry. -`base_unavailable` records that the selected body could not be delivered. +`base_unavailable` records that the selected body could not be delivered. The +`scope: entry` omission with the same `ref` gives the cause, such as the bytes +required and available for that body. +If the requested finding is missing or its author ID is ambiguous, its card +returns `unavailable` with reason `unknown_or_ambiguous_finding`. The omission +identifies the selected ref, revision and finding. That card costs zero bytes. +The response still contains the selected bodies and other available cards. The retrieval assembly includes charged cards in `content_bytes` and reports their subtotal in `decision_card_bytes`. Expansion has its own budget. For a claim assessment, quote the delivered original at its ref, revision and diff --git a/src/inferrsi/knowledge/catalog_selection.py b/src/inferrsi/knowledge/catalog_selection.py index 30ea7283e..640cc93b1 100644 --- a/src/inferrsi/knowledge/catalog_selection.py +++ b/src/inferrsi/knowledge/catalog_selection.py @@ -58,7 +58,7 @@ def __init__(self, code, detail): def _selected_decisions(requests, cards, delivered_bundles, available): """Use the bundles that supplied the selected bodies, after accounting for every body.""" - from .decision_cards import project_decision_card + from .decision_cards import FindingSelectionError, project_decision_card results, omissions = [], [] charged = 0 @@ -71,10 +71,16 @@ def _selected_decisions(requests, cards, delivered_bundles, available): omissions.append({**identity, "scope": "decision_card", "reason": "base_unavailable"}) continue remaining = available - charged - result = project_decision_card( - delivered_bundles[ref], reference=ref, revision=revision, - max_bytes=remaining, **selector, - ) + try: + result = project_decision_card( + delivered_bundles[ref], reference=ref, revision=revision, + max_bytes=remaining, **selector, + ) + except FindingSelectionError: + omitted = {**identity, "reason": "unknown_or_ambiguous_finding"} + results.append({**omitted, "status": "unavailable"}) + omissions.append({**omitted, "scope": "decision_card"}) + continue results.append({**result, **selector}) if result["status"] == "over_budget": omissions.append({**identity, "scope": "decision_card", "reason": "over_budget", diff --git a/src/inferrsi/knowledge/decision_cards.py b/src/inferrsi/knowledge/decision_cards.py index 69c513ea7..00e9f15f6 100644 --- a/src/inferrsi/knowledge/decision_cards.py +++ b/src/inferrsi/knowledge/decision_cards.py @@ -12,6 +12,10 @@ from .knowledge_operations import AUTHORITIES, Bundle, IdentityError, UnavailableRevision, _json +class FindingSelectionError(ValueError): + """The selector does not identify one finding in the pinned Case.""" + + def project_decision_card( resolved: tuple[str, Bundle], *, reference: str, revision: str, finding: str | None = None, max_bytes: int | None = None, compact: bool = False, @@ -108,9 +112,11 @@ def finding(self, selector: str) -> tuple[int, dict]: index = indices[0] return index, findings[index] match = re.fullmatch(r"case\.json#/findings/(0|[1-9][0-9]*)", selector) - if match and (index := int(match[1])) < len(findings): - return index, findings[index] - raise ValueError(f"Unknown or ambiguous finding at {self.revision}: {selector}") + if match and len(match[1]) <= len(str(len(findings))): + index = int(match[1]) + if index < len(findings): + return index, findings[index] + raise FindingSelectionError(f"Unknown or ambiguous finding at {self.revision}: {selector}") def project( self, *, finding: str | None = None, max_bytes: int | None = None, compact: bool = False, diff --git a/tests/knowledge/test_catalog_selection.py b/tests/knowledge/test_catalog_selection.py index 27198d61f..8985221ed 100644 --- a/tests/knowledge/test_catalog_selection.py +++ b/tests/knowledge/test_catalog_selection.py @@ -102,6 +102,11 @@ def complete(selections, **options): unavailable = complete(request, context_bytes=1) assert unavailable["decision_cards"] == [{"ref": ref, "revision": pin, "status": "base_unavailable"}] + entry, card = [item for item in unavailable["omissions"] if item["ref"] == ref] + assert entry["scope"] == "entry" and entry["required_bytes"] > entry["available_bytes"] == 1 + assert card == {"ref": ref, "revision": pin, "scope": "decision_card", + "reason": "base_unavailable"} + assert unavailable["retrieval"]["assembly"]["decision_card_bytes"] == 0 def test_catalog_l1_ancestor_license_separates_reader_pins(tmp_path): @@ -139,9 +144,8 @@ def complete(revision): assert error.value.code == "stale_snapshot" -def test_catalog_l1_case_original_finding_and_reorder_cli(tmp_path, capsys): - from inferrsi.apps.cli import main - +@pytest.fixture +def catalog_case(tmp_path): root = tmp_path / "library" root.mkdir() cases = skill(root, "pilot") / "cases" @@ -153,6 +157,13 @@ def test_catalog_l1_case_original_finding_and_reorder_cli(tmp_path, capsys): shutil.copyfile(source / filename, path) original = json.loads(path.read_text(encoding="utf-8")) shutil.copyfile(source / original["content"], cases / original["content"]) + return root, path, original + + +def test_catalog_l1_case_original_finding_and_reorder_cli(tmp_path, capsys, catalog_case): + from inferrsi.apps.cli import main + + root, path, original = catalog_case args = ["catalog-select", "decode occupancy", "--skill-root", str(root), "--kinds", "case", "--expansion-depth", "0", "--context-bytes", "100000"] ref = "checkout:case.admission-drain-occupancy" @@ -193,6 +204,59 @@ def read(snapshot, finding): assert last["card"]["declared"]["finding"] == original["findings"][2] +@pytest.mark.parametrize("entrypoint", ["apps", "cli"]) +@pytest.mark.parametrize("selector", [ + "case.json#/findings/999", "id:duplicate", + pytest.param("case.json#/findings/" + "9" * 5000, id="oversized-pointer"), +]) +def test_catalog_l1_invalid_finding_preserves_other_deliveries(catalog_case, selector, entrypoint, + tmp_path, capsys): + root, path, original = catalog_case + for finding in original["findings"][:2]: + finding["id"] = "duplicate" + path.write_text(json.dumps(original), encoding="utf-8") + case_ref = "checkout:case.admission-drain-occupancy" + skill_ref = "checkout:pilot" + + def choose(prompt): + snapshot = prompt["catalog"] + pins = {card["ref"]: card["revision"] for card in snapshot["cards"]} + return {"snapshot_id": snapshot["snapshot_id"], "selections": [ + selection(case_ref, layer="L1", revision=pins[case_ref], finding=selector), + selection(skill_ref, layer="L1", revision=pins[skill_ref]), + ]} + + if entrypoint == "apps": + result = select_catalog_evidence( + CatalogSelection(skill_root=root), "decode occupancy", choose, model="test", + kinds=("case", "skill"), token_budget=2000000, read_options={"expansion_depth": 0}, + ) + else: + from inferrsi.apps.cli import main + + args = ["catalog-select", "decode occupancy", "--skill-root", str(root), "--kinds", + "case,skill", "--token-budget", "2000000", "--expansion-depth", "0"] + assert main(args) == 0 + answer = choose(json.loads(capsys.readouterr().out)["prompt"]) + answer_file = tmp_path / "selection.json" + answer_file.write_text(json.dumps(answer), encoding="utf-8") + assert main([*args, "--selection", str(answer_file)]) == 0 + result = json.loads(capsys.readouterr().out) + case_body, skill_body = result["contexts"] + assert [case_body["ref"], skill_body["ref"]] == [case_ref, skill_ref] + omitted, delivered = result["decision_cards"] + identity = {"ref": case_ref, "revision": case_body["revision"], "finding": selector} + reason = "unknown_or_ambiguous_finding" + assert omitted == {**identity, "status": "unavailable", "reason": reason} + assert result["omissions"] == [{**identity, "scope": "decision_card", "reason": reason}] + assert delivered["card"]["ref"] == skill_ref + assembly = result["retrieval"]["assembly"] + assert assembly["decision_card_bytes"] == delivered["card_bytes"] + assert assembly["content_bytes"] == ( + case_body["content_bytes"] + skill_body["content_bytes"] + delivered["card_bytes"] + ) + + def test_catalog_l1_installed_package_skill_and_record(): from inferrsi.knowledge.knowledge_operations import KnowledgeReader From 3e27a8188d33ff9ff02c00112ec54c30c5bc364a Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:07:53 +0800 Subject: [PATCH 4/4] Clarify byte accounting for omitted decision cards Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (documentation and verification) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/catalog-selection.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/catalog-selection.md b/docs/catalog-selection.md index 4e079029d..7fd45471f 100644 --- a/docs/catalog-selection.md +++ b/docs/catalog-selection.md @@ -81,17 +81,20 @@ checkout closures can have different revisions from ordinary Find and Read. All selected bodies take priority. Each complete or partial card is charged once, in full, against the remaining `context_bytes`. When a card does not fit, its selected body stays delivered even if `expansion_bytes` has space to spare. -An `over_budget` result retains the required size and the original pin. Its -`scope: decision_card` omission gives the bytes available for retry. +An `over_budget` result keeps the original pin and reports the required UTF-8 +size in `card_bytes`. It charges zero bytes. Its `scope: decision_card` +omission gives the bytes available for retry. `base_unavailable` records that the selected body could not be delivered. The `scope: entry` omission with the same `ref` gives the cause, such as the bytes required and available for that body. If the requested finding is missing or its author ID is ambiguous, its card returns `unavailable` with reason `unknown_or_ambiguous_finding`. The omission -identifies the selected ref, revision and finding. That card costs zero bytes. +identifies the selected ref, revision and finding. The response still contains the selected bodies and other available cards. -The retrieval assembly includes charged cards in `content_bytes` and reports -their subtotal in `decision_card_bytes`. Expansion has its own budget. +Both `unavailable` and `base_unavailable` omit `card_bytes` and charge zero +bytes. To find the total actually charged for cards, read +`retrieval.assembly.decision_card_bytes`. It is included in `content_bytes`. +Expansion has its own budget. For a claim assessment, quote the delivered original at its ref, revision and resource path. Card text alone cannot confirm a quote.