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
26 changes: 26 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,32 @@ for provenance and accounting. To capture an installed Case exactly, follow the
`find` result to `read`, then pass its ref and revision to
`campaign capture-context --installed-library --id-ref REF --revision REF=REV`.

#### Collect a pinned body and its L1 decision card

Keep the qualified ref, revision and source options from Find or a known read.
Repeat `--decision-card` for each selected body that needs a full L1 card. For
a Case, append one original finding selector, such as `id:trace-loss` or
`case.json#/findings/1`, to the ref with `=`.

```sh
inferrsi collect --installed-library --id "$REF" --revision "$REF=$REV" \
--context-bytes 65536 --decision-card "$REF" --json
```

Apps can call `inferrsi.apps.workflows.knowledge.knowledge_reader` with the same
source and use `reader.collect(ids=[ref], revisions={ref: rev}, context_bytes=65536,
decision_cards={ref: finding})`. Set `finding=None` for a Skill or Record.
Collect delivers the usual context resources first. It then projects requested
cards from those same bundles in ID order. The shared budget counts UTF-8
resource content and each delivered card's compactly serialized, sorted-key JSON.
`decision_cards` reports each request, including `over_budget` with the whole
card size, `no_body` when Collect omitted the body, and `unavailable` for an
invalid decision source or finding. See `omissions` and `context_omissions` for
the body outcome. Store entries retain their existing `unsupported_context` result.
To reopen a projected card's source or body, use `read REF --revision REV
--resource PATH` with the same source options and the returned `source_resource`
or `body_resource`.

#### Migrate old text queries

- `knowledge search QUERY` and `context QUERY` keep their package scope and
Expand Down
15 changes: 15 additions & 0 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ def _revisions(pairs: list[str]) -> dict[str, str]:
return revisions


def _decision_cards(requests: list[str]) -> dict[str, str | None]:
cards: dict[str, str | None] = {}
for request in requests:
ref, separator, finding = request.partition("=")
if ref in cards:
raise ValueError(f"Duplicate decision card request: {ref}")
cards[ref] = finding if separator else None
return cards


def _tsv(value: str) -> str:
# One line per record: free-text fields may contain tabs or line breaks.
return (
Expand Down Expand Up @@ -676,6 +686,7 @@ def main(argv: list[str] | None = None) -> int:
relevance=args.relevance,
relevance_method=args.relevance_method,
context_bytes=args.context_bytes,
decision_cards=_decision_cards(args.decision_card or []),
)
if args.relevance_method is None and result.get("selection", {}).get("ranking_applied"):
print("collect text queries use Find ranking. "
Expand Down Expand Up @@ -718,6 +729,10 @@ def main(argv: list[str] | None = None) -> int:
print(f"{omission['path']}\tcontext_omitted\t{omission['reason']}")
for omission in result.get("context_omissions", []):
print(f"{omission['ref']}\tcontext_omitted\t{omission['reason']}")
for entry in result.get("decision_cards", []):
print(f"{entry['ref']}\tL1\t{entry['status']}")
if "card" in entry:
_print(entry["card"])
for omission in result["omissions"]:
detail = f"\t{_tsv(omission['detail'])}" if "detail" in omission else ""
print(f"{_tsv(omission['id'])}\tomitted\t{omission['reason']}{detail}")
Expand Down
6 changes: 5 additions & 1 deletion src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,11 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser:
help="Find is the default and only ranking method")
collect.add_argument(
"--context-bytes", type=int,
help="Opt-in context view; total UTF-8 resource-body byte budget",
help="UTF-8 budget for context bodies and any explicitly requested L1 cards",
)
collect.add_argument(
"--decision-card", action="append", metavar="REF[=FINDING]",
help="Add L1 for a qualified --id at its --revision; supply one original Case finding",
)
_read_sources(collect)
collect.add_argument("--json", action="store_true")
Expand Down
49 changes: 49 additions & 0 deletions src/inferrsi/knowledge/knowledge_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,7 @@ def collect(
relevance: str | None = None,
relevance_method: str | None = None,
context_bytes: int | None = None,
decision_cards: dict[str, str | None] | None = None,
) -> dict:
if type(limit) is not int or limit < 1:
raise ValueError("limit must be a positive integer")
Expand Down Expand Up @@ -829,6 +830,18 @@ def collect(
raise ValueError("revisions must map identity strings to revision strings")
if ids is not None and len(set(ids)) != len(ids):
raise ValueError("Duplicate requested identity")
if decision_cards is not None and not isinstance(decision_cards, dict):
raise ValueError("decision_cards must map qualified refs to a finding or None")
if decision_cards:
if not ids or context_bytes is None:
raise ValueError("Decision cards require explicit ids and context_bytes")
for ref, finding in decision_cards.items():
if not isinstance(ref, str) or ref not in ids or ":" not in ref:
raise ValueError("Decision cards require an explicitly selected qualified ref")
if not revisions.get(ref, "").strip():
raise ValueError(f"Decision card requires an exact revision for {ref}")
if finding is not None and (not isinstance(finding, str) or not finding.strip()):
raise ValueError("A finding must be a nonempty selector")
checkout = self
owners = self.owners()
if find_ranking and self.skill_root is None and self.store is None:
Expand Down Expand Up @@ -928,6 +941,7 @@ def matches(metadata: dict, authority: str) -> bool:
selected, seen = [], set()
used = 0
contexts, context_omissions = [], []
delivered_bundles: dict[str, tuple[str, Bundle]] = {}
context_used = 0
matched_count = 0

Expand Down Expand Up @@ -990,6 +1004,8 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
else:
contexts.append(context)
context_used += context["content_bytes"]
if decision_cards and view["ref"] in decision_cards:
delivered_bundles[view["ref"]] = (view["ref"], bundle)

for reference in requested:
if find_ranking and len(selected) >= limit:
Expand Down Expand Up @@ -1082,6 +1098,38 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
"excludes": "provenance, omission and control metadata",
},
})
if decision_cards:
from .decision_cards import project_decision_card

cards = []
for ref in ids:
if ref not in decision_cards:
continue
finding = decision_cards[ref]
entry = {"ref": ref, "revision": pinned[ref]}
if finding is not None:
entry["finding"] = finding
if ref not in delivered_bundles:
cards.append({**entry, "status": "no_body"})
continue
try:
projection = project_decision_card(
delivered_bundles[ref], reference=ref, revision=pinned[ref],
finding=finding, max_bytes=context_bytes - context_used,
)
except (ValueError, KeyError, TypeError):
cards.append({**entry, "status": "unavailable",
"reason": "invalid_decision_source_or_finding"})
continue
cards.append({**entry, **projection})
if "card" in projection:
context_used += projection["card_bytes"]
result["decision_cards"] = cards
result["context_bytes"] = context_used
result["context_budget"].update(
accounting="utf8-resource-content-and-canonical-l1",
excludes="provenance and control metadata outside resource and card payloads",
)
from .retrieval import observation

selection = result.get("selection", {})
Expand All @@ -1091,6 +1139,7 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
"ids": ids, "revisions": revisions, "kind": kind, "repo": repo, "tier": tier,
"backend": backend, "scenario": scenario, "limit": limit,
"max_bytes": max_bytes, "context_bytes": context_bytes,
**({"decision_cards": dict(decision_cards)} if decision_cards else {}),
"sources": ["package"] + (["checkout"] if checkout.skill_root else [])
+ (["store"] if self.store is not None else []),
}, selection={
Expand Down
166 changes: 163 additions & 3 deletions tests/knowledge/test_collect_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,12 @@ def test_source_drift_and_cross_owner_mapping_never_fall_back():
] == "unavailable_revision"


def test_store_delegates_but_copied_package_metadata_cannot_gain_context(tmp_path):
def test_store_delegates_but_copied_package_metadata_cannot_gain_context(tmp_path, monkeypatch):
source = KnowledgeReader().read(CGROUP)
store = KnowledgeStore(tmp_path, skill_root=None)
store.create(Bundle({**source.metadata, "id": "local-cgroup", "state": "candidate"},
dict(source.content), dict(source.dependencies)))
candidate = Bundle({**source.metadata, "id": "local-cgroup", "state": "candidate"},
dict(source.content), dict(source.dependencies))
old = store.create(candidate)
result = store.collect(ids=["store:local-cgroup", CGROUP], context_bytes=65536)
assert [item["authority"] for item in result["items"]] == ["store", "package"]
assert [c["ref"] for c in result["contexts"]] == [f"package:{CGROUP}"]
Expand All @@ -215,6 +216,29 @@ def test_store_delegates_but_copied_package_metadata_cannot_gain_context(tmp_pat
]
filtered = store.collect(ids=["store:local-cgroup"], repo="inferrsi", context_bytes=65536)
assert filtered["omissions"] == [{"id": "store:local-cgroup", "reason": "filters"}]
current = store.update(
Bundle({**candidate.metadata, "limitations": ["updated"]},
candidate.content, candidate.dependencies),
expected=old, reason="Revise the candidate", evidence=[],
)
assert current != old
history = KnowledgeStore(tmp_path, skill_root=None, read_only=True)
read = history.read
calls = []

def count_reads(identity, *, revision):
calls.append((identity, revision))
return read(identity, revision=revision)

monkeypatch.setattr(history, "read", count_reads)
ref = "store:local-cgroup"
result = history.collect(ids=[ref], revisions={ref: old}, decision_cards={ref: None},
context_bytes=65536)
assert calls == [("local-cgroup", old)]
assert result["items"][0]["revision"] == old
assert result["context_omissions"] == [{"ref": ref, "reason": "unsupported_context"}]
assert result["contexts"] == [] and result["context_bytes"] == 0
assert result["decision_cards"] == [{"ref": ref, "revision": old, "status": "no_body"}]


def test_h3_readsets_are_mandatory_even_without_lexical_overlap():
Expand Down Expand Up @@ -331,3 +355,139 @@ def test_cli_exposes_context_in_json_and_text(capsys):
assert "--- begin context package:" in capsys.readouterr().out
assert main(["collect", "--id", CGROUP, "--context-bytes", "1"]) == 0
assert "context_omitted\tcontext_limit" in capsys.readouterr().out


@pytest.fixture
def pinned_skills(tmp_path):
reader = KnowledgeReader(skill_root=tmp_path)
pins = {}
for name in ("alpha", "beta"):
owner = tmp_path / name
owner.mkdir()
declaration = json.dumps({"recommendations": [f"{name} 的建议"]}, ensure_ascii=False)
(owner / "SKILL.md").write_bytes((
f"---\nname: {name}\ndescription: Measure latency.\n---\n{name} 正文\n"
).encode())
(owner / "metadata.json").write_bytes(declaration.encode())
ref = f"checkout:{name}"
pins[ref] = reader.read(ref).revision
return reader, pins


def test_collect_delivers_all_bodies_before_whole_utf8_cards(pinned_skills):
reader, pins = pinned_skills
first, second = pins
options = {"ids": list(pins), "revisions": pins}
default = reader.collect(**options, context_bytes=10000)
empty = reader.collect(**options, context_bytes=10000, decision_cards={})
assert _json(empty) == _json(default)
assert "decision_cards" not in default
assert "decision_cards" not in default["retrieval"]["request"]
requested = {second: None, first: None}
single = reader.read_decision_card(first, revision=pins[first])
payload = json.dumps(single["card"], ensure_ascii=False, sort_keys=True, separators=(",", ":"))
assert "建议" in payload and len(payload.encode()) > len(payload)
body_bytes = sum(len(r["content"].encode()) for c in default["contexts"]
for r in c["resources"])
exact_budget = body_bytes + len(payload.encode())
exact = reader.collect(**options, decision_cards=requested, context_bytes=exact_budget)
fit, omitted = exact["decision_cards"]
assert exact["contexts"] == default["contexts"] and len(exact["contexts"]) == 2
assert fit == single
assert omitted["ref"] == second and omitted["status"] == "over_budget"
assert omitted["max_bytes"] == 0 and "card" not in omitted
assert exact["context_bytes"] == exact_budget
short = reader.collect(**options, decision_cards={first: None}, context_bytes=exact_budget - 1)
failure, = short["decision_cards"]
assert short["contexts"] == default["contexts"] and short["context_bytes"] == body_bytes
assert failure["status"] == "over_budget" and "card" not in failure
assert failure["card_bytes"] == len(payload.encode()) == failure["max_bytes"] + 1
later_bytes = reader.read_decision_card(second, revision=pins[second])["card_bytes"]
later = reader.collect(**options, decision_cards=requested,
context_bytes=body_bytes + later_bytes)
skipped, delivered = later["decision_cards"]
assert skipped["status"] == "over_budget" and delivered["card"]["ref"] == second
assert later["context_bytes"] == body_bytes + later_bytes


def test_collect_projects_from_the_delivered_bundle(pinned_skills, tmp_path, monkeypatch):
reader, pins = pinned_skills
first, second = pins
fresh = reader._read
calls = []

def replace_after_read(ref, revision):
assert ref not in calls, "L1 reopened a selected bundle"
calls.append(ref)
bundle = fresh(ref, revision)
if ref == first:
(tmp_path / "alpha" / "metadata.json").write_bytes(b'{"recommendations":["new"]}')
return bundle

with monkeypatch.context() as patch:
patch.setattr(reader, "_read", replace_after_read)
result = reader.collect(ids=list(pins), revisions=pins, context_bytes=10000,
decision_cards={first: None})
assert calls == [first, second]
entry, = result["decision_cards"]
assert entry["revision"] == result["contexts"][0]["revision"] == pins[first]
assert entry["card"]["decision"]["recommendation"] == ["alpha 的建议"]
assert entry["source_resource"] == "alpha/metadata.json"
assert result["contexts"][0]["resources"][0]["path"] == entry["body_resource"]
result = reader.collect(ids=list(pins), revisions=pins, context_bytes=10000,
decision_cards={first: None, second: None})
missing, valid = result["decision_cards"]
assert missing == {"ref": first, "revision": pins[first], "status": "no_body"}
assert result["omissions"][0]["reason"] == "unavailable_revision"
assert valid["card"]["ref"] == second and [c["ref"] for c in result["contexts"]] == [second]


def test_collect_decision_card_requires_explicit_membership_and_pin(pinned_skills):
reader, pins = pinned_skills
first, second = pins
pairs = [
({"ids": [first], "decision_cards": {"alpha": None}}, "qualified ref"),
({"ids": [first], "decision_cards": {second: None}}, "qualified ref"),
({"ids": [first], "decision_cards": {"package:alpha": None}}, "qualified ref"),
({"ids": [first], "decision_cards": {first: None}}, "exact revision"),
({"decision_cards": {first: None}}, "explicit ids"),
({"ids": [first], "revisions": pins, "decision_cards": {first: ""}}, "selector"),
]
for options, message in pairs:
with pytest.raises(ValueError, match=message):
reader.collect(context_bytes=10000, **options)
with pytest.raises(ValueError, match="context_bytes"):
reader.collect(ids=list(pins), revisions=pins, decision_cards={first: None})
result = reader.collect(ids=list(pins), revisions=pins, decision_cards={first: None},
context_bytes=1)
missing, = result["decision_cards"]
assert missing == {"ref": first, "revision": pins[first], "status": "no_body"}
assert result["context_omissions"][0]["reason"] == "context_limit"


def test_collect_cli_pins_one_original_case_finding(capsys):
from inferrsi.apps.cli import main

reader = KnowledgeReader(skill_root=ROOT)
ref = "checkout:case.qwen-ascend-rejected-directions"
revision = reader.read(ref).revision
args = ["collect", "--installed-library", "--id", ref, "--revision", f"{ref}={revision}",
"--context-bytes", "1000000"]
selector = "case.json#/findings/1"
assert main([*args, "--decision-card", f"{ref}={selector}", "--json"]) == 0
result = json.loads(capsys.readouterr().out)
card, = result["decision_cards"]
expected = reader.read_decision_card(ref, revision=revision, finding=selector)
assert card == {**expected, "finding": selector}
original = json.loads(reader.resource(ref, card["source_resource"], revision=revision))
assert card["card"]["declared"]["finding"] == original["findings"][1]
for wrong in (ref, f"{ref}=id:no-such-finding"):
assert main([*args, "--decision-card", wrong, "--json"]) == 0
rejected = json.loads(capsys.readouterr().out)
assert rejected["contexts"] == result["contexts"]
failure, = rejected["decision_cards"]
assert failure["status"] == "unavailable" and "card" not in failure
with pytest.raises(SystemExit) as duplicate:
main([*args, "--decision-card", ref, "--decision-card", ref])
assert duplicate.value.code == 2
assert "Duplicate decision card request" in capsys.readouterr().err
Loading