Skip to content
Open
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
59 changes: 52 additions & 7 deletions docs/catalog-selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,49 @@ 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:<unique-author-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 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.
The response still contains the selected bodies and other available cards.
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.

Python uses the same implementation:

```python
Expand Down Expand Up @@ -136,13 +179,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
Expand Down
69 changes: 66 additions & 3 deletions src/inferrsi/knowledge/catalog_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,40 @@ 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 FindingSelectionError, 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
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",
"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()
Expand Down Expand Up @@ -439,8 +473,7 @@ 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, bundle):
if bundle.metadata["kind"] != "skill" and not ref.startswith("store:"):
# Use Collect's projectors on the pinned bundle, including when no bytes remain.
authority, _, identity = ref.partition(":")
Expand Down Expand Up @@ -575,6 +608,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")
Expand All @@ -592,9 +626,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:
Expand All @@ -613,11 +659,17 @@ def _complete(
"detail": card["unreadable"]})
continue
available = context_bytes - used if not depth else expansion_bytes - optional_used
context, omission = self._context(readers[ref], ref, card["revision"], available)
reader = readers[ref]
resolved = reader.read_resolved(ref, revision=card["revision"])
context, omission = self._context(reader, ref, card["revision"], available, resolved[1])
if omission is not None:
omissions.append({**omission, "scope": "entry", "via": via})
paths.append({"ref": ref, "via": via, "stop": "context_unavailable"})
continue
if ref in decision_requests:
if (context["ref"], context["revision"]) != identity or resolved[0] != ref:
raise SelectionError("revision_mismatch", f"Delivery does not match {ref}")
decision_bundles[ref] = resolved
amount = context["content_bytes"]
if depth:
optional_used += amount
Expand Down Expand Up @@ -705,6 +757,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(
Expand Down Expand Up @@ -734,12 +795,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,
Expand Down
12 changes: 9 additions & 3 deletions src/inferrsi/knowledge/decision_cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
24 changes: 15 additions & 9 deletions src/inferrsi/knowledge/knowledge_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading