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`.

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
still describes the full card.

The compact card has `view: "compact"` and retains the full `decision`,
`status`, `missing_fields`, qualified reference, revision and atom. Its
`declared` object keeps the author's origin, status, state and downstream
impact when present. `validation_evidence` keeps any original
`empirical_validation` and `verification` declarations, including an explicit
`false` for local verification. A null value means neither field was
declared. A validation plan describes what to check. Evidence of execution
comes from the source declaration. For Case findings, `finding_context`
preserves extra qualifiers such as scope. The decision already carries the
direction, outcome, reason, bounds and revisit condition when declared.

`omitted_declared_fields` names raw full-L1 fields whose original form is
available at the pin, including sources, claims or the original finding.
Use the response's `full_read_args` to open full L1 with the same source
options and selector. In Python, pass `compact=True` to
`reader.read_decision_card(...)`, then call
`reader.read_decision_card(**result["full_read"])` on that reader. Both
routes are available even when `over_budget` omits the compact card.

Every item has an owning `authority` (`package`, `checkout` or `store`) and a qualified
`ref` of the form `<authority>:<id>`. Public IDs are unchanged and may be used
unqualified while they resolve to exactly one authority. An ID owned by more than
Expand Down
29 changes: 17 additions & 12 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,22 +725,27 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "read":
if args.layer == "L1":
if args.material or args.resource is not None or args.omit_resources:
raise ValueError("L1 takes --finding and --max-bytes as its view options")
result = _knowledge_reader(args).read_decision_card(
raise ValueError("L1 accepts --finding, --compact and --max-bytes")
reader = _knowledge_reader(args)
result = reader.read_decision_card(
args.id, revision=args.revision, finding=args.finding, max_bytes=args.max_bytes,
compact=args.compact,
)
if "body_resource" in result:
sources = []
if args.installed_library:
sources.append("--installed-library")
elif args.skill_root is not None:
sources += ["--skill-root", str(args.skill_root.resolve())]
if args.store is not None:
sources += ["--store", str(args.store.resolve())]
pinned = [
"read", result["ref"], "--revision", result["revision"], *sources,
"--omit-resources",
]
elif reader.skill_root is not None:
sources += ["--skill-root", str(reader.skill_root)]
if reader.store is not None:
sources += ["--store", str(reader.store.workspace)]
pinned = ["read", result["ref"], "--revision", result["revision"], *sources]
if args.compact:
full_args = [*pinned, "--layer", "L1"]
if "finding" in result["full_read"]:
full_args += ["--finding", result["full_read"]["finding"]]
result["full_read_args"] = full_args
pinned.append("--omit-resources")
result["next_read_args"] = [*pinned, "--resource", result["body_resource"]]
if result["source_resource"] != result["body_resource"]:
result["source_read_args"] = (
Expand All @@ -749,8 +754,8 @@ def main(argv: list[str] | None = None) -> int:
)
_print(result)
return 0
if args.finding is not None or args.max_bytes is not None:
raise ValueError("--finding and --max-bytes require --layer L1")
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,
resource=args.resource,
Expand Down
1 change: 1 addition & 0 deletions src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser:
)
read.add_argument("id")
read.add_argument("--layer", choices=("L1",), help="Read a decision card at --revision")
read.add_argument("--compact", action="store_true", help="Read the compact L1 decision card")
read.add_argument("--finding", help="L1 Case selector returned by find --decision-cards")
read.add_argument("--max-bytes", type=int, help="Maximum canonical UTF-8 L1 card bytes")
read.add_argument("--revision", help="Exact revision returned by collect or read")
Expand Down
24 changes: 23 additions & 1 deletion src/inferrsi/knowledge/decision_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ def finding(self, selector: str) -> tuple[int, dict]:
return index, findings[index]
raise ValueError(f"Unknown or ambiguous finding at {self.revision}: {selector}")

def project(self, *, finding: str | None = None, max_bytes: int | None = None) -> dict:
def project(
self, *, finding: str | None = None, max_bytes: int | None = None, compact: bool = False,
) -> dict:
if max_bytes is not None and (type(max_bytes) is not int or max_bytes < 0):
raise ValueError("L1 max_bytes must be a nonnegative integer")
if (self.kind == "case") != (finding is not None):
Expand Down Expand Up @@ -133,9 +135,29 @@ def project(self, *, finding: str | None = None, max_bytes: int | None = None) -
"atom": atom, "decision": decision, "declared": declared,
"status": "partial" if missing else "complete", "missing_fields": missing,
}
full_read = None
if compact:
# Preserve the entire decision and its source's actual evidence vocabulary.
# Lists of sources, claims and duplicate raw fields stay on the full pin.
context = ("origin", "status", "state", "downstream_impact")
retained = {key: declared[key] for key in context if key in declared}
evidence = {key: declared[key] for key in ("verification", "empirical_validation")
if key in declared}
omitted = sorted(declared.keys() - retained.keys() - evidence.keys())
card.update(view="compact", declared=retained, validation_evidence=evidence or None,
omitted_declared_fields=omitted)
full_read = {"reference": self.ref, "revision": self.revision}
if finding is not None:
full_read["finding"] = atom["selector"]
# Keep finding-specific scope and any additional authored qualifiers.
card["finding_context"] = {key: value for key, value in item.items() if key not in (
"direction", "outcome", "reason", "revisit_when", "bounds", "id", "keywords",
)}
size = len(_json(card))
result = {"ref": self.ref, "revision": self.revision, "card_bytes": size,
"body_resource": self.body, "source_resource": self.resource}
if full_read is not None:
result["full_read"] = full_read
if max_bytes is not None and size > max_bytes:
return {**result, "status": "over_budget", "max_bytes": max_bytes,
"missing_fields": missing}
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 @@ -528,7 +528,7 @@ def read_resolved(self, reference: str, *, revision: str | None = None) -> tuple

def read_decision_card(
self, reference: str, *, revision: str, finding: str | None = None,
max_bytes: int | None = None,
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
Expand All @@ -543,7 +543,7 @@ def read_decision_card(
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)
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
98 changes: 98 additions & 0 deletions tests/test_decision_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest

from inferrsi.apps.cli import main
from inferrsi.knowledge.decision_cards import DecisionSource
from inferrsi.knowledge.knowledge_find import find, load_corpus
from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader
from inferrsi.knowledge.knowledge_store import KnowledgeStore
Expand All @@ -24,6 +25,21 @@ def encoded(card):
return json.dumps(card, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()


def compact_read(capsys, link, full):
"""Reopen both projections and the pinned source through their actual CLI routes."""
result = cli(capsys, [*link["read_args"], "--compact"])
card = result["card"]
assert card["view"] == "compact" and result["card_bytes"] == len(encoded(card))
for key in ("ref", "revision", "atom", "decision", "status", "missing_fields"):
assert card[key] == full["card"][key]
assert cli(capsys, result["full_read_args"]) == full
source_args = result.get("source_read_args", result["next_read_args"])
for args in (result["full_read_args"], result["next_read_args"], source_args):
assert ("--installed-library" in args) == ("--installed-library" in link["read_args"])
assert cli(capsys, source_args)["revision"] == card["revision"]
return result


@pytest.mark.parametrize("sidecar", [False, True])
def test_stale_checkout_skill_cannot_link_new_declaration(tmp_path, sidecar):
owner = tmp_path / "pilot"
Expand Down Expand Up @@ -213,6 +229,16 @@ def test_checkout_skill_pinned_cli_and_byte_budget(tmp_path, capsys, legacy):
"limitations": [{"hardware": "pilot only"}],
}
assert read["status"] == "complete" and not card["missing_fields"]
compact = compact_read(capsys, link, read)
assert compact["card"]["validation_evidence"] == {"empirical_validation": "not_run"}
assert compact["card"]["declared"] == {"status": "candidate"}
assert "recommendations" in compact["card"]["omitted_declared_fields"]
limit = compact["card_bytes"]
args = [*link["read_args"], "--compact", "--max-bytes"]
assert cli(capsys, [*args, str(limit)]) == compact
under = cli(capsys, [*args, str(limit - 1)])
assert under["status"] == "over_budget" and under["card_bytes"] == limit and "card" not in under
assert under["full_read_args"] == compact["full_read_args"] and under["missing_fields"] == []
size = len(encoded(card))
assert read["card_bytes"] == link["card_bytes"] == size
assert cli(capsys, [*link["read_args"], "--max-bytes", str(size)])["card"] == card
Expand Down Expand Up @@ -251,6 +277,9 @@ def test_real_case_finding_links_follow_visible_order_and_reopen_original(capsys
assert source["revision"] == link["revision"]
assert cli(capsys, read["next_read_args"])["revision"] == link["revision"]
assert card["declared"]["finding"] == json.loads(source["content"])["findings"][position]
compact = compact_read(capsys, link, read)["card"]
assert compact["finding_context"]["scope"] == card["declared"]["finding"]["scope"]
assert compact["declared"]["origin"] == card["declared"]["origin"]
assert result == default


Expand All @@ -277,6 +306,12 @@ 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"])
compact = compact_read(capsys, link, old)
assert compact["card"]["validation_evidence"] is None
assert compact["full_read"]["finding"] == "id:trace-loss"
by_position = [*link["read_args"][:-1], "case.json#/findings/1", "--compact"]
assert cli(capsys, by_position) == compact
assert compact["card"]["decision"]["recommendation"]["outcome"] == "rejected"
assert old["card"]["atom"]["pointer"] == "case.json#/findings/1"
assert old["status"] == "partial"
assert {"validation", "prerequisites", "refusal_or_limits"} <= set(
Expand All @@ -303,6 +338,7 @@ def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys):
assert all("decision_card" not in row for row in stale["findings"])
failed = cli(capsys, link["read_args"])
assert failed["status"] == "unavailable_revision" and "card" not in failed
assert cli(capsys, [*link["read_args"], "--compact"]) == failed
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 All @@ -323,6 +359,11 @@ def test_package_record_original_evidence_and_legacy_read(capsys):
for key in ("verification", "sources", "status", "claims", "limitations", "validation_plan"):
assert card["declared"][key] == raw[key]
assert card["declared"]["verification"]["locally_verified"] is False
compact = compact_read(capsys, link, read)
assert compact["card"]["validation_evidence"] == {"verification": raw["verification"]}
assert set(("sources", "claims")) <= set(compact["card"]["omitted_declared_fields"])
assert compact["card"]["declared"]["downstream_impact"] == raw["downstream_impact"]
assert KnowledgeReader().read_decision_card(**compact["full_read"])["card"] == card
assert card["decision"]["prerequisites"] == raw["applicability"]["conditions"]
assert json.loads(cli(capsys, read["next_read_args"])["content"]) == raw
assert cli(capsys, ["read", identity])["ref"] == link["ref"]
Expand All @@ -339,6 +380,7 @@ def test_installed_skill_package_fallback_without_yaml(monkeypatch, capsys):
assert card["atom"]["kind"] == "skill" and card["atom"]["resource"].endswith("/SKILL.md")
assert len(encoded(card)) == link["card_bytes"]
assert cli(capsys, read["next_read_args"])["revision"] == card["revision"]
assert compact_read(capsys, link, read)["card"]["missing_fields"] == card["missing_fields"]


@pytest.mark.parametrize("entrypoint", ["note.md", "record.json"])
Expand All @@ -356,6 +398,62 @@ def test_store_record_reopens_retained_metadata_and_body(tmp_path, capsys, entry
assert read["status"] == "partial" and read["source_resource"] is None
assert cli(capsys, read["source_read_args"])["revision"] == old
assert cli(capsys, read["next_read_args"])["content"] == "first note"
compact = cli(capsys, [*args, old, "--compact"])
assert cli(capsys, compact["full_read_args"]) == read
assert cli(capsys, [*args, "sha256:" + "0" * 64])["status"] == "unavailable_revision"
with pytest.raises(ValueError, match="exact --revision"):
KnowledgeReader(store=store).read_decision_card("store:pilot", revision="")


def test_l1_followups_keep_the_open_checkout_and_store(tmp_path, monkeypatch, capsys):
library = tmp_path / "sources" / "library"
library.mkdir(parents=True)
workspace = tmp_path / "store"
workspace.mkdir()
store = KnowledgeStore(workspace, skill_root=library)
metadata = {"id": "pilot", "kind": "knowledge", "entrypoint": "note.md",
"state": "candidate", "sources": [{"type": "unknown"}],
"applicability": {}, "limitations": [], "attribution": []}
revision = store.create(Bundle(metadata, {"note.md": b"original note"}, {}))
read = KnowledgeReader.read_decision_card

def read_then_chdir(reader, *args, **kwargs):
result = read(reader, *args, **kwargs)
monkeypatch.chdir(library)
return result

monkeypatch.chdir(tmp_path)
with monkeypatch.context() as patch:
patch.setattr(KnowledgeReader, "read_decision_card", read_then_chdir)
compact = cli(capsys, ["read", "store:pilot", "--revision", revision, "--layer", "L1",
"--compact", "--skill-root", "sources/library", "--store", "store"])
for key in ("full_read_args", "next_read_args", "source_read_args"):
args = compact[key]
assert args[args.index("--skill-root") + 1] == str(library)
assert args[args.index("--store") + 1] == str(workspace)
assert cli(capsys, args)["revision"] == revision


def test_compact_projection_uses_only_supplied_bundle(monkeypatch):
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()

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

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"]}


def test_compact_requires_explicit_l1(capsys):
with pytest.raises(SystemExit) as failure:
main(["read", "pilot", "--compact"])
assert failure.value.code == 2 and "require --layer L1" in capsys.readouterr().err
Loading