From da904044a5c39c026ead13f380372a96a799ba97 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:57:31 +0800 Subject: [PATCH 1/3] Read pinned internal knowledge decision cards Project Skill, Record and Case finding decisions from one verified revision and expose opt-in Find links and bounded L1 reads. Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/knowledge-contribution-workflow.md | 21 ++ docs/knowledge-operations.md | 50 +++++ docs/operations.md | 4 + src/inferrsi/apps/cli/__init__.py | 43 +++- src/inferrsi/apps/cli/arguments.py | 7 +- src/inferrsi/knowledge/decision_cards.py | 139 +++++++++++++ src/inferrsi/knowledge/knowledge_find.py | 95 +++++++-- .../knowledge/knowledge_operations.py | 36 +++- src/inferrsi/knowledge/knowledge_store.py | 3 +- tests/test_decision_cards.py | 196 ++++++++++++++++++ 10 files changed, 568 insertions(+), 26 deletions(-) create mode 100644 src/inferrsi/knowledge/decision_cards.py create mode 100644 tests/test_decision_cards.py diff --git a/docs/knowledge-contribution-workflow.md b/docs/knowledge-contribution-workflow.md index 8cd2c667b..04b802cab 100644 --- a/docs/knowledge-contribution-workflow.md +++ b/docs/knowledge-contribution-workflow.md @@ -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 diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index 7f2686d44..fa4d29beb 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -38,6 +38,56 @@ 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:`. +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. +`card.decision` exposes applicability, prerequisites, refusal or limits, +recommendation and validation. Values come from the frozen declaration. +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 `:`. Public IDs are unchanged and may be used unqualified while they resolve to exactly one authority. An ID owned by more than diff --git a/docs/operations.md b/docs/operations.md index a35047b4c..67729ef3b 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -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`, diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 59ca05bec..59e7ea59b 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -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"]: @@ -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", []): @@ -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") @@ -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, @@ -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, diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index edf0446db..5934251fa 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -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", @@ -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( diff --git a/src/inferrsi/knowledge/decision_cards.py b/src/inferrsi/knowledge/decision_cards.py new file mode 100644 index 000000000..faa5cce50 --- /dev/null +++ b/src/inferrsi/knowledge/decision_cards.py @@ -0,0 +1,139 @@ +"""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 {} + decision = { + "applicability": applies, + "prerequisites": conditions.get("prerequisites") or conditions.get("conditions"), + "refusal_or_limits": conditions.get("refusal_point") or conditions.get("failure_modes") + or record.get("limitations"), + "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} diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index dce4793bc..f71588a87 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -38,6 +38,7 @@ if TYPE_CHECKING: from .channels import ChannelRegistry + from .knowledge_operations import Bundle from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends @@ -217,7 +218,7 @@ def cohort(self) -> str: return " · ".join(str(part) for part in parts if part) return str(declared) if declared else "" - def relevant_findings(self, query_tokens: list[str]) -> tuple[list[Finding], int]: + def relevant_finding_indices(self, query_tokens: list[str]) -> list[int]: """Rank this entry's findings by query overlap, then by recorded order. Scoring the whole entry says it is relevant; it does not say which of a @@ -237,7 +238,7 @@ def relevant_findings(self, query_tokens: list[str]) -> tuple[list[Finding], int follows the sequence the directions were tried in. """ if not self.findings: - return [], 0 + return [] terms = [_term_counts(finding.search_text()) for finding in self.findings] appearances = Counter(token for counts in terms for token in counts) total = len(terms) @@ -256,9 +257,12 @@ def relevant_findings(self, query_tokens: list[str]) -> tuple[list[Finding], int continue # Rarer within the entry means more distinguishing. overlap += math.log(total / carrying + 1.0) * math.sqrt(hits) - ranked.append((-overlap, position, self.findings[position])) - ranked.sort(key=lambda row: (row[0], row[1])) - shown = [finding for _, _, finding in ranked[:_MAX_SHOWN_FINDINGS]] + ranked.append((-overlap, position)) + ranked.sort() + return [position for _, position in ranked[:_MAX_SHOWN_FINDINGS]] + + def relevant_findings(self, query_tokens: list[str]) -> tuple[list[Finding], int]: + shown = [self.findings[i] for i in self.relevant_finding_indices(query_tokens)] return shown, max(0, len(self.findings) - len(shown)) def view( @@ -749,17 +753,27 @@ def expand(query: str) -> tuple[list[str], dict[str, tuple[str, ...]]]: return [token for token in dict.fromkeys(found) if token not in _QUERY_STOP_WORDS], applied -def _read_preview(document: Document, readers: dict) -> tuple[tuple[str, ...], int | None]: - """Validate a hit, returning its command and UTF-8 content size without extra reads.""" +@dataclass +class _ReadPreview: + args: tuple[str, ...] + size: int + bundle: Bundle + view: dict + source_args: tuple[str, ...] + + +def _read_preview(document: Document, readers: dict) -> _ReadPreview | None: + """Validate a hit once and keep the exact material used for its preview.""" from .knowledge_operations import KnowledgeReader if not document.qualified: - return (), None + return None reader = readers.get(document.root) if reader is None: reader = readers[document.root] = KnowledgeReader(skill_root=document.root) try: - material = reader.read(document.qualified).view(material=True) + bundle = reader.read(document.qualified) + material = bundle.view(material=True) except MissingSkillsExtra: if document.source_location != "installed": raise @@ -777,15 +791,47 @@ def _read_preview(document: Document, readers: dict) -> tuple[tuple[str, ...], i args = ( "read", ref, "--omit-resources", "--resource", core, "--revision", view["revision"], ) - return args, len(bundle.content[core]) + return _ReadPreview(args, len(bundle.content[core]), bundle, view, ()) - parts = ("read", document.qualified, "--material", "--omit-resources") + source_args = () if document.root is not None: if document.source_location == "installed": - parts += ("--installed-library",) + source_args = ("--installed-library",) else: - parts += ("--skill-root", str(document.root)) - return parts, len(material["content"].encode("utf-8")) + source_args = ("--skill-root", str(document.root)) + args = ("read", document.qualified, "--material", "--omit-resources", *source_args) + size = len(material["content"].encode("utf-8")) + return _ReadPreview(args, size, bundle, material, source_args) + + +def _decision_links( + hit: dict, document: Document, preview: _ReadPreview, tokens: list[str], +) -> None: + from .decision_cards import DecisionSource + + source = DecisionSource.from_bundle(preview.args[1], preview.bundle, preview.view) + + def link(selector: str | None = None) -> dict: + projection = source.project(finding=selector) + args = ["read", source.ref, "--revision", source.revision, "--layer", "L1", + *preview.source_args] + if selector is not None: + args += ["--finding", selector] + return {"ref": source.ref, "revision": source.revision, "status": projection["status"], + "card_bytes": projection["card_bytes"], "read_args": args, + "open_argv": [*launcher(), *args]} + + if source.kind != "case": + hit["decision_card"] = link() + return + # The ranker saw an earlier filesystem read. Never attach a pinned + # position to a different finding if the checkout changed meanwhile. + if _findings(source.record, document.identity) != document.findings: + raise ValueError("Case findings changed after ranking; repeat Find") + for row, index in zip(hit.get("findings", []), document.relevant_finding_indices(tokens)): + row["decision_card"] = link(source.finding_locator(index)) + if not document.findings: + hit["decision_card"] = {"status": "unavailable", "reason": "no_findings"} def rank(query: str, corpus: Corpus) -> tuple[ @@ -814,6 +860,7 @@ def find( *, limit: int = 5, explain: bool = False, + decision_cards: bool = False, registry: "ChannelRegistry | None" = None, backend: str | None = None, platform: str | None = None, @@ -828,15 +875,25 @@ def find( for value, _, index, detail in scored[:limit]: document = corpus.documents[index] try: - read_args, size = _read_preview(document, readers) + preview = _read_preview(document, readers) unreadable = None except (ValueError, KeyError, OSError, TypeError) as exc: - read_args, size, unreadable = (), None, str(exc) or type(exc).__name__ + preview, unreadable = None, str(exc) or type(exc).__name__ view = document.view( - score=value, query_tokens=query_tokens, read_args=read_args, unreadable=unreadable, + score=value, query_tokens=query_tokens, read_args=preview.args if preview else (), + unreadable=unreadable, ) - if size is not None: - view["next_read_content_bytes"] = size + if preview: + view["next_read_content_bytes"] = preview.size + if decision_cards: + if preview: + try: + _decision_links(view, document, preview, query_tokens) + except (ValueError, KeyError, TypeError) as exc: + view["decision_card"] = {"status": "unavailable", "reason": str(exc)} + else: + view["decision_card"] = {"status": "unavailable", + "reason": unreadable or "missing qualified reference"} if explain: view["matched"] = detail items.append(view) diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index 36c559a89..426f76840 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -32,6 +32,10 @@ class RevisionConflict(ValueError): pass +class UnavailableRevision(RevisionConflict): + """The authority does not retain the requested revision.""" + + class IdentityError(ValueError): def __init__(self, code: str, message: str): super().__init__(message) @@ -522,13 +526,32 @@ def read_resolved(self, reference: str, *, revision: str | None = None) -> tuple qualified = self.resolve(reference) return qualified, self._read(qualified, revision) + def read_decision_card( + self, reference: str, *, revision: str, finding: str | None = None, + max_bytes: int | None = None, + ) -> dict: + """Read the L1 projection of one atom at the requested content revision.""" + from .decision_cards import DecisionSource + + if not revision: + raise ValueError("L1 requires an exact --revision") + try: + ref, bundle = self.read_resolved(reference, revision=revision) + 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) + def _read(self, qualified: str, revision: str | None) -> Bundle: authority, _, identity = qualified.partition(":") if authority == "store": return self.store.read(identity, revision=revision) bundle = self._checkout(identity) if authority == "checkout" else self._knowledge(identity) if revision is not None and bundle.revision != revision: - raise RevisionConflict( + raise UnavailableRevision( f"Revision unavailable in this snapshot: {qualified} at {revision}" ) return bundle @@ -537,7 +560,10 @@ def _checkout(self, identity: str) -> Bundle: cases = self._cases() if identity in cases: path = cases[identity] - record = json.loads(path.read_text(encoding="utf-8")) + original = path.read_bytes() + record = json.loads(original.decode("utf-8")) + if record.get("id") != identity or record.get("kind") != "case": + raise ValueError(f"Case identity changed during read: {identity}") for field in ("references", "dependencies"): if field in record: raise ValueError(f"Case {field} are not supported; declare required_resources") @@ -548,12 +574,14 @@ def _checkout(self, identity: str) -> Bundle: raise ValueError("Case required_resources must not repeat a path") relative = record["content"] required = [relative, "case.json", *(p for p in declared if p != relative)] - content = {"case.json": path.read_bytes()} + content = {"case.json": original} for resource in [relative, *required[2:]]: resource_path = case_resource_path(self.skill_root, path, resource) if not resource_path.is_file(): raise ValueError(f"Missing case resource: {resource}") - content[resource] = resource_path.read_bytes() + content[resource] = ( + original if resource_path == path else resource_path.read_bytes() + ) return Bundle( { **record, diff --git a/src/inferrsi/knowledge/knowledge_store.py b/src/inferrsi/knowledge/knowledge_store.py index 4cb585703..ef71995c9 100644 --- a/src/inferrsi/knowledge/knowledge_store.py +++ b/src/inferrsi/knowledge/knowledge_store.py @@ -14,6 +14,7 @@ IdentityError, KnowledgeReader, RevisionConflict, + UnavailableRevision, _json, safe_path, ) @@ -263,7 +264,7 @@ def read(self, identity: str, *, revision: str | None = None) -> Bundle: (identity, revision), ).fetchone() if row is None: - raise RevisionConflict(f"Unknown revision: store:{identity} at {revision}") + raise UnavailableRevision(f"Unknown revision: store:{identity} at {revision}") resources = connection.execute( "SELECT path, data FROM resources WHERE id=? AND revision=?", (identity, revision) ).fetchall() diff --git a/tests/test_decision_cards.py b/tests/test_decision_cards.py new file mode 100644 index 000000000..698523c67 --- /dev/null +++ b/tests/test_decision_cards.py @@ -0,0 +1,196 @@ +"""Pinned L0 → L1 → source reads across the three searchable atom kinds.""" + +import json +import sys +from importlib.resources import files +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.knowledge.knowledge_find import find, load_corpus +from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader +from inferrsi.knowledge.knowledge_store import KnowledgeStore + +ROOT = Path(files("inferrsi.knowledge").joinpath("data", "skill_library")) + + +def cli(capsys, args): + assert main(args) == 0 + return json.loads(capsys.readouterr().out) + + +def encoded(card): + return json.dumps(card, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + + +@pytest.mark.parametrize("legacy", [False, True]) +def test_checkout_skill_pinned_cli_and_byte_budget(tmp_path, capsys, legacy): + owner = tmp_path / "pilot" + owner.mkdir() + declaration = { + "status": "candidate", "empirical_validation": "not_run", + "applicability": {"prerequisites": ["fixed seed"], "refusal_point": "quality unknown"}, + "recommendations": ["比较质量" * 90], "validation_plan": ["check error"], + } + header = "---\nname: pilot\ndescription: Inspect pilot quality.\n" + metadata = json.dumps(declaration, ensure_ascii=False) + if legacy: + (owner / "metadata.json").write_text(metadata, encoding="utf-8") + else: + header += f"metadata:\n inferrsi: |\n {metadata}\n" + (owner / "SKILL.md").write_text(header + "---\nProcedure.\n", encoding="utf-8") + (owner / "sample.txt").write_bytes(b"frozen attachment") + args = ["find", "pilot", "--skill-root", str(tmp_path), "--kinds", "skill", + "--no-external", "--json"] + original = cli(capsys, args) + result = cli(capsys, [*args, "--decision-cards"]) + hit, = result["items"] + link = hit.pop("decision_card") + assert result == original + assert link["ref"] == "checkout:pilot" + assert link["open_argv"][-len(link["read_args"]):] == link["read_args"] + assert cli(capsys, hit["read_args"])["content"].splitlines()[-1] == "Procedure." + + read = cli(capsys, link["read_args"]) + card = read["card"] + assert card["layer"] == "L1" and card["atom"]["kind"] == "skill" + assert card["revision"] == link["revision"] == read["revision"] + assert card["declared"] == declaration + assert card["decision"]["recommendation"] == declaration["recommendations"] + assert card["decision"]["refusal_or_limits"] == "quality unknown" + assert read["status"] == "complete" and not card["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 + small = cli(capsys, [*link["read_args"], "--max-bytes", str(size - 1)]) + assert small["status"] == "over_budget" and small["card_bytes"] == size + assert "card" not in small + assert str(tmp_path) in read["next_read_args"] + assert cli(capsys, read["next_read_args"])["revision"] == link["revision"] + if legacy: + assert json.loads(cli(capsys, read["source_read_args"])["content"]) == declaration + target = tmp_path / "copy.txt" + cli(capsys, ["resource", link["ref"], "pilot/sample.txt", "--revision", link["revision"], + "--skill-root", str(tmp_path), "--output", str(target)]) + assert target.read_bytes() == b"frozen attachment" + + +def test_real_case_finding_links_follow_visible_order_and_reopen_original(capsys): + args = ["find", "Sarathi chunked prefill", "--kinds", "case", "--limit", "1", + "--no-external", "--json"] + default = cli(capsys, args) + result = cli(capsys, [*args, "--decision-cards"]) + hit, = result["items"] + assert hit["id"] == "case.sarathi-chunk-budget" + for row, position in zip(hit["findings"], (0, 1, 3), strict=True): + link = row.pop("decision_card") + assert "--installed-library" in link["read_args"] + read = cli(capsys, link["read_args"]) + card = read["card"] + pointer = f"case.json#/findings/{position}" + assert card["atom"]["selector"] == card["atom"]["pointer"] == pointer + assert card["decision"]["recommendation"]["direction"] == row["direction"] + assert link["card_bytes"] == len(encoded(card)) + assert card["declared"]["state"] == "candidate" + assert card["declared"]["empirical_validation"] == "not_run" + source = cli(capsys, read["source_read_args"]) + 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] + assert result == default + + +def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys): + owner = tmp_path / "pilot" + cases = owner / "cases" + cases.mkdir(parents=True) + (owner / "SKILL.md").write_text("---\nname: pilot\ndescription: Pilot.\n---\nBody.") + (cases / "notes.md").write_text("Pilot history.") + record = { + "id": "case.pilot", "kind": "case", "content": "notes.md", "origin": ["unknown"], + "state": "candidate", "sources": [{"type": "unknown"}], "attribution": [], + "applicability": [], "limitations": [], + "findings": [ + {"direction": "Initial", "reason": "size", "outcome": "caveat"}, + {"id": "trace-loss", "direction": "Trace loss", + "reason": "absent", "outcome": "rejected"}, + ], + } + path = cases / "pilot.json" + path.write_text(json.dumps(record)) + corpus = load_corpus(tmp_path, kinds=("case",)) + hit, = find("trace loss", corpus, decision_cards=True)["items"] + link = hit["findings"][0]["decision_card"] + assert link["read_args"][-1] == "id:trace-loss" + old = cli(capsys, link["read_args"]) + assert old["card"]["atom"]["pointer"] == "case.json#/findings/1" + assert old["status"] == "partial" + assert {"validation", "prerequisites", "refusal_or_limits"} <= set( + old["card"]["missing_fields"]) + oversized = cli(capsys, [*link["read_args"], "--max-bytes", "0"]) + assert oversized["status"] == "over_budget" and "card" not in oversized + assert oversized["missing_fields"] == old["card"]["missing_fields"] + record["findings"].reverse() + path.write_text(json.dumps(record)) + stale = find("trace loss", corpus, decision_cards=True)["items"][0] + assert stale["decision_card"]["status"] == "unavailable" + 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 + 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" + assert new["card"]["atom"]["pointer"] == "case.json#/findings/0" + assert new["revision"] != old["revision"] + + +def test_package_record_original_evidence_and_legacy_read(capsys): + identity = "xdit.cuda.diffusion.parallelism_freshness_and_topology" + raw = json.loads((ROOT / "records" / f"{identity}.json").read_text(encoding="utf-8")) + hit, = cli(capsys, ["find", identity, "--kinds", "record", "--limit", "1", + "--no-external", "--decision-cards", "--json"])["items"] + link = hit["decision_card"] + assert link["ref"] == f"package:{identity}" + read = cli(capsys, link["read_args"]) + card = read["card"] + assert card["atom"] == {"kind": "record", "resource": "record.json"} + for key in ("verification", "sources", "status", "claims", "limitations", "validation_plan"): + assert card["declared"][key] == raw[key] + assert card["declared"]["verification"]["locally_verified"] is False + 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"] + + +def test_installed_skill_package_fallback_without_yaml(monkeypatch, capsys): + monkeypatch.setitem(sys.modules, "yaml", None) + hit, = cli(capsys, ["find", "ascend-device-health", "--kinds", "skill", "--limit", "1", + "--no-external", "--decision-cards", "--json"])["items"] + link = hit["decision_card"] + assert link["ref"].startswith("package:") and "--installed-library" not in link["read_args"] + read = cli(capsys, link["read_args"]) + card = read["card"] + 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"] + + +@pytest.mark.parametrize("entrypoint", ["note.md", "record.json"]) +def test_store_record_reopens_retained_metadata_and_body(tmp_path, capsys, entrypoint): + store = KnowledgeStore(tmp_path, skill_root=None) + metadata = { + "id": "pilot", "kind": "knowledge", "entrypoint": entrypoint, "state": "candidate", + "sources": [{"type": "unknown"}], "attribution": [], "applicability": {}, "limitations": [], + } + old = store.create(Bundle(metadata, {entrypoint: b"first note"}, {})) + store.update(Bundle(metadata, {entrypoint: b"revision two"}, {}), + expected=old, reason="extend", evidence=[]) + args = ["read", "store:pilot", "--store", str(tmp_path), "--layer", "L1", "--revision"] + read = cli(capsys, [*args, old]) + 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" + 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="") From 5a99667d1fd7bc276d7d2525eb85c310b93001c6 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:23:56 +0800 Subject: [PATCH 2/3] Keep decision cards tied to ranked Case declarations Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/knowledge-operations.md | 2 ++ src/inferrsi/knowledge/decision_cards.py | 7 +++++-- src/inferrsi/knowledge/knowledge_find.py | 14 +++++++++----- tests/test_decision_cards.py | 16 ++++++++++++++-- 4 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index fa4d29beb..76565b598 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -59,6 +59,8 @@ the opt-in link. The returned `card` identifies the qualified reference, revision and atom. `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 diff --git a/src/inferrsi/knowledge/decision_cards.py b/src/inferrsi/knowledge/decision_cards.py index faa5cce50..e9c486fc2 100644 --- a/src/inferrsi/knowledge/decision_cards.py +++ b/src/inferrsi/knowledge/decision_cards.py @@ -101,11 +101,14 @@ def project(self, *, finding: str | None = None, max_bytes: int | None = None) - ) 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": conditions.get("refusal_point") or conditions.get("failure_modes") - or record.get("limitations"), + "refusal_or_limits": refusal_or_limits, "recommendation": record.get("recommendations"), "validation": record.get("validation_plan"), } diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index f71588a87..ec58e4d08 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -20,6 +20,7 @@ from __future__ import annotations +import hashlib import json import math import os @@ -200,6 +201,7 @@ class Document: source_location: str = "" locally_verified: bool | None = None backend: str | None = None + case_declaration_digest: bytes | None = None def unverified(self) -> bool: return self.locally_verified is False or any( @@ -417,7 +419,8 @@ def _case_documents(root: Path, *, source_location: str) -> list[Document]: documents = [] for identity, path in sorted(KnowledgeReader(skill_root=root).cases().items()): - record = json.loads(path.read_text(encoding="utf-8")) + declaration = path.read_bytes() + record = json.loads(declaration.decode("utf-8")) try: body_path = case_resource_path(root, path, record.get("content")) except (ValueError, OSError): @@ -447,6 +450,7 @@ def _case_documents(root: Path, *, source_location: str) -> list[Document]: applicability=record.get("applicability"), limitations=tuple(record.get("limitations", [])), findings=findings, + case_declaration_digest=hashlib.sha256(declaration).digest(), backend=backend if backend in (*BACKENDS, "common") else None, )) return documents @@ -824,10 +828,10 @@ def link(selector: str | None = None) -> dict: if source.kind != "case": hit["decision_card"] = link() return - # The ranker saw an earlier filesystem read. Never attach a pinned - # position to a different finding if the checkout changed meanwhile. - if _findings(source.record, document.identity) != document.findings: - raise ValueError("Case findings changed after ranking; repeat Find") + # Author IDs and other declaration fields may be absent from the ranked rows. + pinned_digest = hashlib.sha256(preview.bundle.content["case.json"]).digest() + if pinned_digest != document.case_declaration_digest: + raise ValueError("Case declaration changed after ranking; repeat Find") for row, index in zip(hit.get("findings", []), document.relevant_finding_indices(tokens)): row["decision_card"] = link(source.finding_locator(index)) if not document.findings: diff --git a/tests/test_decision_cards.py b/tests/test_decision_cards.py index 698523c67..921433c40 100644 --- a/tests/test_decision_cards.py +++ b/tests/test_decision_cards.py @@ -30,7 +30,9 @@ def test_checkout_skill_pinned_cli_and_byte_budget(tmp_path, capsys, legacy): owner.mkdir() declaration = { "status": "candidate", "empirical_validation": "not_run", - "applicability": {"prerequisites": ["fixed seed"], "refusal_point": "quality unknown"}, + "applicability": {"prerequisites": ["fixed seed"], "refusal_point": "quality unknown", + "failure_modes": ["trace loss", "missing samples"]}, + "limitations": [{"hardware": "pilot only"}], "recommendations": ["比较质量" * 90], "validation_plan": ["check error"], } header = "---\nname: pilot\ndescription: Inspect pilot quality.\n" @@ -58,7 +60,10 @@ def test_checkout_skill_pinned_cli_and_byte_budget(tmp_path, capsys, legacy): assert card["revision"] == link["revision"] == read["revision"] assert card["declared"] == declaration assert card["decision"]["recommendation"] == declaration["recommendations"] - assert card["decision"]["refusal_or_limits"] == "quality unknown" + assert card["decision"]["refusal_or_limits"] == { + "refusal_point": "quality unknown", "failure_modes": ["trace loss", "missing samples"], + "limitations": [{"hardware": "pilot only"}], + } assert read["status"] == "complete" and not card["missing_fields"] size = len(encoded(card)) assert read["card_bytes"] == link["card_bytes"] == size @@ -131,6 +136,13 @@ def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys): oversized = cli(capsys, [*link["read_args"], "--max-bytes", "0"]) assert oversized["status"] == "over_budget" and "card" not in oversized assert oversized["missing_fields"] == old["card"]["missing_fields"] + original = find("trace loss", corpus) + record["findings"][1]["id"] = "different-id" + path.write_text(json.dumps(record)) + stale = find("trace loss", corpus, decision_cards=True) + assert stale["items"][0].pop("decision_card")["status"] == "unavailable" + assert stale == original == find("trace loss", corpus) + record["findings"][1]["id"] = "trace-loss" record["findings"].reverse() path.write_text(json.dumps(record)) stale = find("trace loss", corpus, decision_cards=True)["items"][0] From f34730e82d69401c59b2c0e662c2489fb1367563 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:29:40 +0800 Subject: [PATCH 3/3] Bind all decision cards to the ranked source bytes Agent-assisted-by: Codex / gpt-6.2-astra [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/knowledge-operations.md | 2 + src/inferrsi/knowledge/knowledge_find.py | 52 ++++++++++++++------- src/inferrsi/knowledge/skill_catalog.py | 13 ++++-- tests/test_decision_cards.py | 57 ++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 19 deletions(-) diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index 76565b598..0ce642ee5 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -57,6 +57,8 @@ 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`, diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index ec58e4d08..d49c64ad2 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -29,11 +29,11 @@ import sys from collections import Counter from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from functools import lru_cache from importlib.resources import files from io import BytesIO -from pathlib import Path +from pathlib import Path, PurePosixPath from statistics import median from typing import TYPE_CHECKING, Any @@ -201,7 +201,7 @@ class Document: source_location: str = "" locally_verified: bool | None = None backend: str | None = None - case_declaration_digest: bytes | None = None + ranked_sources: dict[str, bytes | None] = field(default_factory=dict) def unverified(self) -> bool: return self.locally_verified is False or any( @@ -425,6 +425,10 @@ def _case_documents(root: Path, *, source_location: str) -> list[Document]: body_path = case_resource_path(root, path, record.get("content")) except (ValueError, OSError): body_path = None + body, raw_body = _body_source(body_path) if body_path is not None else ("", None) + ranked_sources = {"case.json": _source_digest(declaration)} + if body_path is not None: + ranked_sources[record["content"]] = _source_digest(raw_body) findings = _findings(record, identity) backend = record.get("backend") documents.append(Document( @@ -445,23 +449,28 @@ def _case_documents(root: Path, *, source_location: str) -> list[Document]: "tags": " ".join(record.get("tags", [])), "findings": " ".join(finding.search_text() for finding in findings), "applicability": _flatten(record.get("applicability")), - "body": _body_text(body_path) if body_path is not None else "", + "body": body, }, applicability=record.get("applicability"), limitations=tuple(record.get("limitations", [])), findings=findings, - case_declaration_digest=hashlib.sha256(declaration).digest(), + ranked_sources=ranked_sources, backend=backend if backend in (*BACKENDS, "common") else None, )) return documents -def _body_text(path: Path) -> str: +def _source_digest(raw: bytes | None) -> bytes | None: + return hashlib.sha256(raw).digest() if raw is not None else None + + +def _body_source(path: Path) -> tuple[str, bytes | None]: try: - return path.read_text(encoding="utf-8") + raw = path.read_bytes() + return raw.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n"), raw except (OSError, UnicodeError): # Metadata can still match; read reports why the material is unavailable. - return "" + return "", None def _skill_description(body: str) -> str: @@ -486,12 +495,12 @@ def _skill_documents(root: Path, *, source_location: str) -> list[Document]: and carries no index, so the default search raised on a library whose cases `find` could already rank and `read` could already open. """ - from .skill_catalog import _sidecar, _skill_search_source, skill_registrations + from .skill_catalog import _sidecar_source, _skill_search_source, skill_registrations documents = [] for name, (directory, backend) in sorted(skill_registrations(root).items()): core = directory / "SKILL.md" - body = _body_text(core) + body, raw_body = _body_source(core) try: body, metadata = _skill_search_source(body) except ValueError: @@ -499,9 +508,11 @@ def _skill_documents(root: Path, *, source_location: str) -> list[Document]: continue if metadata is not None and (directory / "metadata.json").exists(): continue + raw_sidecar = None try: if metadata is None: - metadata = _sidecar(directory) or {} + metadata, raw_sidecar = _sidecar_source(directory) + metadata = metadata or {} except (ValueError, OSError): metadata = {} # Task entrypoints remain addressable through the registry. Counting @@ -534,6 +545,8 @@ def _skill_documents(root: Path, *, source_location: str) -> list[Document]: }, applicability=applicability, limitations=tuple(metadata.get("limitations", [])), + ranked_sources={"SKILL.md": _source_digest(raw_body), + "metadata.json": _source_digest(raw_sidecar)}, )) return documents @@ -542,6 +555,8 @@ def _record_documents(records: Iterable[dict]) -> list[Document]: """Imported engine records. Skill projections are skipped: the checkout documents above already cover them, and counting both double-ranks one owner under two identities.""" + from .knowledge_operations import _json + documents = [] for record in records: if record.get("index_type") == "packaged-skill": @@ -577,6 +592,7 @@ def _record_documents(records: Iterable[dict]) -> list[Document]: }, applicability=record.get("applicability"), limitations=tuple(record.get("limitations", [])), + ranked_sources={"record.json": _source_digest(_json(record))}, )) return documents @@ -814,6 +830,16 @@ def _decision_links( from .decision_cards import DecisionSource source = DecisionSource.from_bundle(preview.args[1], preview.bundle, preview.view) + directory = PurePosixPath(source.body).parent if source.kind == "skill" else PurePosixPath() + if source.kind == "skill": + prefix = "data/skill_library/" if source.ref.startswith("package:") else "" + if source.body != f"{prefix}{document.path}": + raise ValueError("Skill location 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() + ): + raise ValueError("Source changed after ranking; repeat Find") def link(selector: str | None = None) -> dict: projection = source.project(finding=selector) @@ -828,10 +854,6 @@ def link(selector: str | None = None) -> dict: if source.kind != "case": hit["decision_card"] = link() return - # Author IDs and other declaration fields may be absent from the ranked rows. - pinned_digest = hashlib.sha256(preview.bundle.content["case.json"]).digest() - if pinned_digest != document.case_declaration_digest: - raise ValueError("Case declaration changed after ranking; repeat Find") for row, index in zip(hit.get("findings", []), document.relevant_finding_indices(tokens)): row["decision_card"] = link(source.finding_locator(index)) if not document.findings: diff --git a/src/inferrsi/knowledge/skill_catalog.py b/src/inferrsi/knowledge/skill_catalog.py index 72f2dece2..0b9969c47 100644 --- a/src/inferrsi/knowledge/skill_catalog.py +++ b/src/inferrsi/knowledge/skill_catalog.py @@ -194,15 +194,20 @@ def _entry(directory: Path, filename: str) -> Path: return path -def _sidecar(directory: Path) -> dict | None: +def _sidecar_source(directory: Path) -> tuple[dict | None, bytes | None]: # metadata.json shares the directory-boundary loading path with SKILL.md. path = _entry(directory, "metadata.json") if not path.is_file(): - return None - metadata = json.loads(path.read_text(encoding="utf-8")) + return None, None + raw = path.read_bytes() + metadata = json.loads(raw.decode("utf-8")) if not isinstance(metadata, dict): raise ValueError(f"Skill metadata must be a mapping: {directory.name}") - return metadata + return metadata, raw + + +def _sidecar(directory: Path) -> dict | None: + return _sidecar_source(directory)[0] def _references(metadata: dict, name: str) -> list[str]: diff --git a/tests/test_decision_cards.py b/tests/test_decision_cards.py index 921433c40..651486c18 100644 --- a/tests/test_decision_cards.py +++ b/tests/test_decision_cards.py @@ -24,6 +24,58 @@ def encoded(card): return json.dumps(card, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() +@pytest.mark.parametrize("sidecar", [False, True]) +def test_stale_checkout_skill_cannot_link_new_declaration(tmp_path, sidecar): + owner = tmp_path / "pilot" + owner.mkdir() + core = owner / "SKILL.md" + header = "---\nname: pilot\ndescription: " + + def write(term): + metadata = json.dumps({"applicability": {"scope": term}}) + if sidecar: + core.write_text(header + "Pilot.\n---\nProcedure.\n", encoding="utf-8") + (owner / "metadata.json").write_text(metadata, encoding="utf-8") + else: + core.write_text(header + f"{term}.\nmetadata:\n inferrsi: |\n {metadata}\n" + "---\nProcedure.\n", encoding="utf-8") + + write("oldquartz") + corpus = load_corpus(tmp_path, kinds=("skill",)) + assert find("oldquartz", corpus, decision_cards=True)["items"][0]["decision_card"]["revision"] + write("newamber") + stale = find("oldquartz", corpus, decision_cards=True) + assert stale["items"][0].pop("decision_card") == { + "status": "unavailable", "reason": "Source changed after ranking; repeat Find", + } + assert stale == find("oldquartz", corpus) + fresh = load_corpus(tmp_path, kinds=("skill",)) + assert not find("oldquartz", fresh, decision_cards=True)["items"] + assert find("newamber", fresh, decision_cards=True)["items"][0]["decision_card"]["revision"] + + +def test_stale_package_record_cannot_link_updated_owner(tmp_path, monkeypatch): + from inferrsi.knowledge import catalog + + identity = "xdit.cuda.diffusion.parallelism_freshness_and_topology" + name = identity + ".json" + path = tmp_path / "knowledge" / "data" / "skill_library" / "records" / name + path.parent.mkdir(parents=True) + record = json.loads((ROOT / "records" / name).read_text(encoding="utf-8")) + record["summary"] = "oldquartz" + path.write_text(json.dumps(record), encoding="utf-8") + monkeypatch.setattr(catalog, "files", lambda _: tmp_path) + corpus = load_corpus(kinds=("record",)) + assert find("oldquartz", corpus, decision_cards=True)["items"][0]["decision_card"]["revision"] + record["summary"] = "newamber" + path.write_text(json.dumps(record), encoding="utf-8") + stale = find("oldquartz", corpus, decision_cards=True) + assert stale["items"][0].pop("decision_card") == { + "status": "unavailable", "reason": "Source changed after ranking; repeat Find", + } + assert stale == find("oldquartz", corpus) + + @pytest.mark.parametrize("legacy", [False, True]) def test_checkout_skill_pinned_cli_and_byte_budget(tmp_path, capsys, legacy): owner = tmp_path / "pilot" @@ -136,6 +188,11 @@ def test_author_id_reordering_and_missing_checkout_revision(tmp_path, capsys): oversized = cli(capsys, [*link["read_args"], "--max-bytes", "0"]) assert oversized["status"] == "over_budget" and "card" not in oversized assert oversized["missing_fields"] == old["card"]["missing_fields"] + (cases / "notes.md").write_text("Different search terms.") + stale_body = find("trace loss", corpus, decision_cards=True)["items"][0] + assert stale_body["decision_card"]["status"] == "unavailable" + assert all("decision_card" not in row for row in stale_body["findings"]) + (cases / "notes.md").write_text("Pilot history.") original = find("trace loss", corpus) record["findings"][1]["id"] = "different-id" path.write_text(json.dumps(record))