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
24 changes: 24 additions & 0 deletions docs/knowledge-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,30 @@ Python callers can use
`reader.read_decision_card(ref, revision=revision, finding=selector, max_bytes=limit)`.
For a Skill or Record omit `finding`.

A selector that already holds the result of `reader.read_resolved` can project
directly from that read. Keep the returned pair together, including its
qualified owner. The Bundle revision covers the manifest and resource bytes.
Only the reader supplies their authority. Two checkouts can use the same
`checkout:` reference, so keep the pair from the checkout that supplied the body.

```python
from inferrsi.knowledge.decision_cards import project_decision_card

held = reader.read_resolved(selected_ref, revision=selected_revision)
result = project_decision_card(
held, reference=selected_ref, revision=selected_revision,
finding=selector, max_bytes=remaining_bytes,
)
```

The projection checks the selected qualified reference, Bundle ID and revision
in memory. A mismatched identity raises `IdentityError`. A changed revision
raises `UnavailableRevision`. Pass `compact=True` for the compact form. A
caller that delivers bodies first can pass the remaining budget and charge
`card_bytes` only when the result includes `card`. Ordering multiple selections,
accounting for their bodies and checking catalog snapshot freshness belong to
the caller.

For a compact read, append `--compact` to the L1 link's `read_args`. For
example, append `--compact --max-bytes 4096` to request the entire decision
within 4 KiB. The caller chooses the budget. The size advertised by Find
Expand Down
28 changes: 27 additions & 1 deletion src/inferrsi/knowledge/decision_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,33 @@

from ._skill_selection import indexed_skill
from .catalog import _skill_search_source
from .knowledge_operations import Bundle, _json
from .knowledge_operations import AUTHORITIES, Bundle, IdentityError, UnavailableRevision, _json


def project_decision_card(
resolved: tuple[str, Bundle], *, reference: str, revision: str, finding: str | None = None,
max_bytes: int | None = None, compact: bool = False,
) -> dict:
"""Project a selected qualified ref and revision from the pair returned by read_resolved."""
resolved_ref, held = resolved
if not revision:
raise ValueError("L1 requires an exact --revision")
# Bundle mappings are mutable. Hash and project the same bytes, and keep
# the returned Store declaration independent of the caller's held metadata.
bundle = Bundle(held.metadata, dict(held.content), dict(held.dependencies))
view = bundle.view()
authority, _, identity = reference.partition(":")
if reference != resolved_ref or authority not in AUTHORITIES or identity != view["id"]:
raise IdentityError(
"identity_mismatch", f"Selected reference does not match bundle: {reference}"
)
if view["revision"] != revision:
raise UnavailableRevision(
f"Revision unavailable in this snapshot: {reference} at {revision}"
)
return DecisionSource.from_bundle(reference, bundle, view).project(
finding=finding, max_bytes=max_bytes, compact=compact,
)


@dataclass(frozen=True)
Expand Down
11 changes: 7 additions & 4 deletions src/inferrsi/knowledge/knowledge_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,19 +531,22 @@ def read_decision_card(
max_bytes: int | None = None, compact: bool = False,
) -> dict:
"""Read the L1 projection of one atom at the requested content revision."""
from .decision_cards import DecisionSource
from .decision_cards import project_decision_card

if not revision:
raise ValueError("L1 requires an exact --revision")
try:
ref, bundle = self.read_resolved(reference, revision=revision)
resolved = self.read_resolved(reference, revision=revision)
return project_decision_card(
resolved, reference=reference if ":" in reference else resolved[0],
revision=revision, finding=finding,
max_bytes=max_bytes, compact=compact,
)
except (IdentityError, UnavailableRevision) as exc:
if isinstance(exc, IdentityError) and exc.code != "unknown_identity":
raise
return {"ref": reference, "revision": revision, "status": "unavailable_revision",
"detail": str(exc)}
source = DecisionSource.from_bundle(ref, bundle, bundle.view())
return source.project(finding=finding, max_bytes=max_bytes, compact=compact)

def _read(self, qualified: str, revision: str | None) -> Bundle:
authority, _, identity = qualified.partition(":")
Expand Down
70 changes: 58 additions & 12 deletions tests/knowledge/test_decision_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@
import pytest

from inferrsi.apps.cli import main
from inferrsi.knowledge.decision_cards import DecisionSource
from inferrsi.knowledge.decision_cards import project_decision_card
from inferrsi.knowledge.knowledge_find import find, load_corpus
from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader
from inferrsi.knowledge.knowledge_operations import (
Bundle,
IdentityError,
KnowledgeReader,
UnavailableRevision,
)
from inferrsi.knowledge.knowledge_store import KnowledgeStore

ROOT = Path(files("inferrsi.knowledge").joinpath("data", "skill_library"))
Expand Down Expand Up @@ -306,6 +311,8 @@ def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys):
link = hit["findings"][0]["decision_card"]
assert link["read_args"][-1] == "id:trace-loss"
old = cli(capsys, link["read_args"])
reader = KnowledgeReader(skill_root=tmp_path)
held = reader.read_resolved(link["ref"], revision=link["revision"])
compact = compact_read(capsys, link, old)
assert compact["card"]["validation_evidence"] is None
assert compact["full_read"]["finding"] == "id:trace-loss"
Expand Down Expand Up @@ -339,6 +346,8 @@ def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys):
failed = cli(capsys, link["read_args"])
assert failed["status"] == "unavailable_revision" and "card" not in failed
assert cli(capsys, [*link["read_args"], "--compact"]) == failed
retained = project_decision_card(held, **compact["full_read"])
assert retained["card"] == old["card"]
fresh = find("trace loss", load_corpus(tmp_path, kinds=("case",)), decision_cards=True)
new = cli(capsys, fresh["items"][0]["findings"][0]["decision_card"]["read_args"])
assert new["card"]["atom"]["selector"] == "id:trace-loss"
Expand Down Expand Up @@ -434,23 +443,60 @@ def read_then_chdir(reader, *args, **kwargs):
assert cli(capsys, args)["revision"] == revision


def test_compact_projection_uses_only_supplied_bundle(monkeypatch):
@pytest.fixture
def stored_pilot(tmp_path):
metadata = {"id": "pilot", "kind": "knowledge", "entrypoint": "note.md",
"state": "candidate", "sources": [{"type": "unknown"}],
"applicability": {}, "limitations": [], "attribution": []}
bundle = Bundle(metadata, {"note.md": b"body"}, {})
view = bundle.view()
"applicability": {}, "limitations": ["仅限固定输入"], "attribution": []}
store = KnowledgeStore(tmp_path, skill_root=None)
revision = store.create(Bundle(metadata, {"note.md": b"body"}, {}))
return KnowledgeReader(store=store), revision


@pytest.mark.parametrize("compact", [False, True])
def test_resolved_decision_card_uses_only_held_bytes(stored_pilot, monkeypatch, compact):
reader, revision = stored_pilot
held = reader.read_resolved("pilot", revision=revision)
request = {"reference": "store:pilot", "revision": revision, "compact": compact}
ordinary = reader.read_decision_card("pilot", revision=revision, compact=compact)

def no_files(*args, **kwargs):
pytest.fail("The in-memory decision projection opened a file")
pytest.fail("Projection reopened the source")

monkeypatch.setattr("io.open", no_files)
monkeypatch.setattr("builtins.open", no_files)
source = DecisionSource.from_bundle("store:pilot", bundle, view)
compact = source.project(compact=True)
assert compact["status"] == "partial" and "validation" in compact["card"]["missing_fields"]
assert compact["card"]["validation_evidence"] is None
assert compact["full_read"] == {"reference": "store:pilot", "revision": view["revision"]}
monkeypatch.setattr(KnowledgeReader, "resolve", no_files)
monkeypatch.setattr(KnowledgeStore, "read", no_files)
size = len(encoded(ordinary["card"]))
assert size > len(encoded(ordinary["card"]).decode())
exact = project_decision_card(held, **request, max_bytes=size)
assert exact == ordinary and exact["card_bytes"] == size
assert exact["status"] == "partial" and "validation" in exact["card"]["missing_fields"]
if compact:
assert exact["card"]["validation_evidence"] is None
assert exact["full_read"] == {"reference": "store:pilot", "revision": revision}
small = project_decision_card(held, **request, max_bytes=size - 1)
assert small["status"] == "over_budget" and "card" not in small
assert (small["ref"], small["revision"], small["card_bytes"]) == (held[0], revision, size)
exact["card"]["decision"]["refusal_or_limits"]["limitations"].clear()
assert held[1].revision == revision


def test_resolved_decision_card_checks_authority_identity_and_held_revision(stored_pilot):
reader, revision = stored_pilot
held = reader.read_resolved("pilot")
ref, bundle = held
for other in ("checkout:pilot", "store:other", "pilot"):
with pytest.raises(IdentityError) as mismatch:
project_decision_card(held, reference=other, revision=revision)
assert mismatch.value.code == "identity_mismatch"
bundle.content["note.md"] = b"amended"
with pytest.raises(UnavailableRevision):
project_decision_card(held, reference=ref, revision=revision)
bundle.metadata["id"] = "another"
with pytest.raises(IdentityError) as mismatch:
project_decision_card(held, reference=ref, revision=bundle.revision)
assert mismatch.value.code == "identity_mismatch"


def test_compact_requires_explicit_l1(capsys):
Expand Down
Loading