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
21 changes: 21 additions & 0 deletions docs/knowledge-contribution-workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ metadata:
Write the procedure after the closing delimiter. Add references or cases only
when the procedure needs those resources.

### Decision fields and Case finding identity

Review decision fields in the canonical source. For a Skill use the
`metadata.inferrsi` object above. For a Record use its authored JSON. Put the
conditions for use in `applicability`, with `prerequisites` or `conditions`
when available. Preserve explicit `refusal_point`, `failure_modes` and
`limitations`. Use `recommendations` for the proposed action and
`validation_plan` for the checks. Keep imported claims, measurements and
verification in the source's own vocabulary. An absent field is visible on a
partial card, so authors can review gaps without inventing a conclusion.

For a new finding in a Case's `findings` array, choose a stable, unique string
`id` within that Case and retain it when editing or reordering the finding.
Keep its attempted `direction`, `outcome` and `reason` together. Record
`scope`, `bounds` and `revisit_when` when the evidence supplies them.
Existing entries without a unique ID use a position in the revision-pinned
original JSON. For example, the historical Sarathi TTFT/TBT comparison is
`case.sarathi-chunk-budget` at `case.json#/findings/3` in the source revision
returned by Find. Reviewers can compare its card and original using the
[decision card read contract](knowledge-operations.md#read-a-decision-card).

## Steps

1. Edit the canonical skill files and the matrices, then commit them. This commit is
Expand Down
54 changes: 54 additions & 0 deletions docs/knowledge-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,60 @@ Direct reads of checkout Skill bodies require PyYAML, a core dependency (the
opens a matching indexed installed Skill through its package projection.
Package-only operations and direct Case reads also work without it.

### Read a decision card

`find --decision-cards` adds a `decision_card` to each readable Skill and Record
hit and to each displayed Case finding. For example, this query shows three
findings from the existing Sarathi Case in query-relevance order.

```bash
inferrsi find 'Sarathi chunked prefill' --kinds case --limit 1 --decision-cards --json
```

Follow the selected link's `open_argv` (executable and arguments) or pass its
`read_args` to the CLI. It specifies `read REF --revision REV --layer L1`, the
same source options, and the finding selector when needed. For the TTFT/TBT
finding the selector is `case.json#/findings/3`. The index counts from zero in
the original Case JSON at that revision. A unique authored ID yields `id:<id>`.
The usual L0 ranking, material command and hit preview are available alongside
the opt-in link.

The returned `card` identifies the qualified reference, revision and atom.
If a ranked source changes before Find can pin the decision link, the link
reports `unavailable`. Repeat Find to rank the current declaration and body.
`card.decision` exposes applicability, prerequisites, refusal or limits,
recommendation and validation. Values come from the frozen declaration.
The `refusal_or_limits` object carries each populated `refusal_point`,
`failure_modes` and `limitations` field under its original name.
A Case recommendation carries the attempted direction **with its outcome and
reason**, and its validation field gives the author's revisit condition.
`card.declared` preserves the corresponding source fields, including the original
verification, evidence state, sources and limitations when supplied.
For example, a Record can declare `verification.locally_verified: false` and
an evidence level of `guidance`. A projected field may be empty or null.

- `complete` means all decision fields have a declaration. `partial` returns
the card and its `missing_fields`. The source's evidence state applies in
either case.
- `card_bytes` counts the UTF-8 bytes of the canonical JSON **card object**.
Object keys are sorted, non-ASCII characters use UTF-8, and separators are
a comma and a colon with no whitespace. The enclosing response and CLI
formatting are outside the count. Add `--max-bytes N` to the pinned read to
enforce a limit. A card of exactly N bytes fits. `over_budget` returns the
required size, missing field names and source read options, and omits the
whole card.
- `unavailable_revision` reports the requested reference and revision when the
selected authority lacks that snapshot. A retained Store revision can remain
readable after its head advances.

`next_read_args` opens the original L2 body at the same revision. When the
declaration lives separately, `source_read_args` opens it (the original
`case.json`, a legacy Skill sidecar, or Store metadata). Use `resource` with
the same reference, revision and source options for L3 attachment bytes.
Python callers can use
`reader.read_decision_card(ref, revision=revision, finding=selector, max_bytes=limit)`.
For a Skill or Record omit `finding`.

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
4 changes: 4 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,10 @@ question calls for prior evidence.
counts omitted entries. Open the owner for the complete list.
Case findings are ordered by query overlap,
with `findings_total` and `findings_withheld` describing the available preview.
Pass `--decision-cards` to add a revision-pinned L1 read and its exact card
size to each readable Skill, Record or displayed Case finding. Follow the
selected `decision_card.read_args` to read that atom. See the
[decision card read contract](knowledge-operations.md#read-a-decision-card).
Each finding carries its outcome, reason, revisit condition and any assessed
scope and bounds. `bounds_source` identifies whether bounds apply to the
finding or the whole entry. The envelope reports `corpus_size`, `matched`,
Expand Down
43 changes: 42 additions & 1 deletion src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ def _print_external(result: dict) -> None:
print(f" note: {_clip(note, 140)}")


def _print_decision_link(entry: dict) -> None:
from ...knowledge.knowledge_find import shell_command

card = entry.get("decision_card")
if card and "open_argv" in card:
print(f" L1 ({card['status']}, {card['card_bytes']} UTF-8 bytes): "
f"{shell_command(card['open_argv'])}")
elif card:
print(f" L1 unavailable: {card['reason']}")


def _print_find(result: dict) -> None:
"""Lead with what was tried and how far the evidence goes, then the path."""
if result["no_match"]:
Expand All @@ -225,6 +236,7 @@ def _print_find(result: dict) -> None:
print(f" read content: {item['next_read_content_bytes']} UTF-8 bytes")
elif item.get("unreadable"):
print(f" cannot open: {_clip(item['unreadable'], 120)}")
_print_decision_link(item)
if item.get("summary"):
print(f" {_clip(item['summary'])}")
for finding in item.get("findings", []):
Expand All @@ -241,6 +253,7 @@ def _print_find(result: dict) -> None:
print(f" bounds ({whose}): {_clip(finding['bounds'], 120)}")
if finding.get("revisit_when"):
print(f" revisit: {_clip(finding['revisit_when'], 120)}")
_print_decision_link(finding)
if item.get("findings_withheld"):
print(f" ... {item['findings_withheld']} more of "
f"{item['findings_total']} recorded directions in the file")
Expand Down Expand Up @@ -590,7 +603,7 @@ def main(argv: list[str] | None = None) -> int:
raise ValueError("--kinds takes a subset of case,skill,record")
result = find(
args.query, load_corpus(args.skill_root, kinds=kinds),
limit=args.limit, explain=args.explain,
limit=args.limit, explain=args.explain, decision_cards=args.decision_cards,
registry=None if args.no_external else _channels(),
backend=args.backend, platform=args.platform,
external_limit=args.external_limit,
Expand Down Expand Up @@ -669,6 +682,34 @@ def main(argv: list[str] | None = None) -> int:
)
return 0
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(
args.id, revision=args.revision, finding=args.finding, max_bytes=args.max_bytes,
)
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",
]
result["next_read_args"] = [*pinned, "--resource", result["body_resource"]]
if result["source_resource"] != result["body_resource"]:
result["source_read_args"] = (
[*pinned, "--resource", result["source_resource"]]
if result["source_resource"] else pinned
)
_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")
ref, _, view = read_knowledge(
_knowledge_reader(args), args.id, revision=args.revision, material=args.material,
resource=args.resource,
Expand Down
7 changes: 6 additions & 1 deletion src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,9 +665,11 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser:
find = commands.add_parser(
"find",
help="Rank packaged skills, imported records and checkout cases for one "
"question; returns corpus paths, not pinned revisions",
"question; returns corpus paths with optional pinned decision card reads",
)
find.add_argument("query", help="Describe the problem in your own words")
find.add_argument("--decision-cards", action="store_true",
help="Add pinned L1 read commands and their UTF-8 card sizes")
find.add_argument("--limit", type=int, default=5)
find.add_argument(
"--kinds", default="case,skill,record",
Expand Down Expand Up @@ -740,6 +742,9 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser:
help="Read one bundle from the package, a skill library, or a store",
)
read.add_argument("id")
read.add_argument("--layer", choices=("L1",), help="Read a decision card at --revision")
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")
read.add_argument("--material", action="store_true")
read.add_argument(
Expand Down
142 changes: 142 additions & 0 deletions src/inferrsi/knowledge/decision_cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""L1 decision views of a single verified bundle. No external reads or inference."""

from __future__ import annotations

import json
import re
from dataclasses import dataclass
from pathlib import PurePosixPath

from ._skill_selection import indexed_skill
from .catalog import _skill_search_source
from .knowledge_operations import Bundle, _json


@dataclass(frozen=True)
class DecisionSource:
ref: str
revision: str
kind: str
resource: str | None
body: str
record: dict

@classmethod
def from_bundle(cls, ref: str, bundle: Bundle, view: dict) -> DecisionSource:
"""Project only the resource bytes covered by the supplied Bundle view."""
body = view["entrypoint"]
kind = view["kind"]
resource = body
if kind == "knowledge":
kind = "record"
resource = body if ref.startswith("package:") else None
# Package records expose their authored schema in record.json.
# Store entries declare metadata on bundles with arbitrary bodies.
record = json.loads(bundle.content[body]) if resource else bundle.metadata
if not isinstance(record, dict):
raise ValueError("Record decision source must be an object")
if resource and record.get("index_type") == "packaged-skill":
body, _, _ = indexed_skill(
record, {**view, "authority": ref.partition(":")[0]}, bundle.content,
)
kind = "skill"
if kind == "skill":
resource = body
_, record = _skill_search_source(bundle.content[body].decode("utf-8"))
sidecar = str(PurePosixPath(body).with_name("metadata.json"))
if sidecar in bundle.content:
if record is not None:
raise ValueError("Skill declares metadata in two resources")
resource = sidecar
record = json.loads(bundle.content[sidecar])
if record is None:
record = {}
elif kind == "case":
resource = "case.json"
if resource not in bundle.content:
raise ValueError("Case decision cards require the original case.json")
record = json.loads(bundle.content[resource])
if not isinstance(record, dict):
raise ValueError("Decision source must be a JSON object")
return cls(ref, view["revision"], kind, resource, body, record)

def _findings(self) -> list[dict]:
findings = self.record.get("findings", [])
if not isinstance(findings, list) or any(not isinstance(f, dict) for f in findings):
raise ValueError("Case findings must be an array of objects")
return findings

def finding_locator(self, index: int) -> str:
findings = self._findings()
identity = findings[index].get("id")
if isinstance(identity, str) and identity.strip():
if sum(f.get("id") == identity for f in findings) == 1:
return f"id:{identity}"
return f"case.json#/findings/{index}"

def finding(self, selector: str) -> tuple[int, dict]:
findings = self._findings()
if selector.startswith("id:") and selector[3:].strip():
indices = [i for i, f in enumerate(findings) if f.get("id") == selector[3:]]
if len(indices) == 1:
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}")

def project(self, *, finding: str | None = None, max_bytes: int | None = None) -> 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):
raise ValueError("Select one --finding for a Case L1 read; omit it for other kinds")

record = self.record
atom = {"kind": self.kind, "resource": self.resource}
declared = {key: record[key] for key in (
"origin", "sources", "provenance_readsets", "source_pins", "attribution",
"status", "state", "verification", "empirical_validation", "limitations",
"applicability", "recommendations", "validation_plan", "claims", "downstream_impact",
) if key in record}
applies = record.get("applicability")
conditions = applies if isinstance(applies, dict) else {}
refusal_or_limits = {key: conditions[key] for key in ("refusal_point", "failure_modes")
if conditions.get(key)}
if record.get("limitations"):
refusal_or_limits["limitations"] = record["limitations"]
decision = {
"applicability": applies,
"prerequisites": conditions.get("prerequisites") or conditions.get("conditions"),
"refusal_or_limits": refusal_or_limits,
"recommendation": record.get("recommendations"),
"validation": record.get("validation_plan"),
}
if finding is not None:
index, item = self.finding(finding)
atom.update(kind="case_finding", selector=self.finding_locator(index),
pointer=f"case.json#/findings/{index}")
declared["finding"] = item
decision.update(
prerequisites=item.get("bounds") or decision["prerequisites"]
or (applies if isinstance(applies, list) else None),
recommendation={
k: item[k] for k in ("direction", "outcome", "reason") if k in item
},
validation=item.get("revisit_when"),
)
missing = [name for name, value in decision.items() if not value]
if finding is not None:
missing.extend(key for key in ("direction", "outcome", "reason") if not item.get(key))
card = {
"schema_version": 1, "layer": "L1", "ref": self.ref, "revision": self.revision,
"atom": atom, "decision": decision, "declared": declared,
"status": "partial" if missing else "complete", "missing_fields": missing,
}
size = len(_json(card))
result = {"ref": self.ref, "revision": self.revision, "card_bytes": size,
"body_resource": self.body, "source_resource": self.resource}
if max_bytes is not None and size > max_bytes:
return {**result, "status": "over_budget", "max_bytes": max_bytes,
"missing_fields": missing}
return {**result, "status": card["status"], "card": card}
Loading
Loading