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
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
# Retain this upstream license's original CRLF Git blob bytes.
/src/inferrsi/knowledge/data/skill_library/systems/frameworks/torch-npu/torch-npu/references/licenses/op-plugin-LICENSE.txt -text

# Source-backed Record atoms pin byte ranges in the original release files.
/src/inferrsi/knowledge/atoms/records/*.json -text

# Generated third-party bundles, with source references and notices beside them.
/plugins/inferrsi-dsh/vendor/ssh2.cjs linguist-generated=true linguist-vendored=true
/plugins/inferrsi-dsh/vendor/yaml.cjs linguist-generated=true linguist-vendored=true
3 changes: 2 additions & 1 deletion docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,8 @@
"tests/apps/test_apps_context_provider.py",
"tests/apps/test_apps_knowledge.py",
"tests/apps/test_optimization_session.py",
"tests/harness/test_harness_generation_seal.py"
"tests/harness/test_harness_generation_seal.py",
"tests/knowledge/test_atomic_records.py"
],
"status": "retired",
"first_removal_version": "0.3.4"
Expand Down
15 changes: 14 additions & 1 deletion docs/guides/knowledge/knowledge-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ To reproduce the #516 search comparison, use the baseline and candidate checkout

## Atomic candidate for domain authors and Apps

The shared candidate accepts one JSON descriptor per atom or composition. An
The shared candidate accepts JSON descriptors for atoms and compositions. An
author works under `src/inferrsi/knowledge/atoms/` or `compositions/`. For a
clean build, pass that Knowledge root and a separate, new installation directory
to `inferrsi.knowledge.atomic_build.build_generation(source, target, permits=...,
Expand All @@ -26,6 +26,19 @@ entrypoint and content. The builder derives its navigation record. A Case
provides the original `case.json` so a finding can be reopened by stable ID or
by its JSON pointer at the requested revision.

A self-contained Record keeps its released JSON bytes under `atoms/records/`.
Its L3 descriptor can declare named `parts`, each with a layer, source JSON
pointers, a half-open byte range and a digest. The builder seals each part as
an individually addressable atom using the original source and grants. The
public Record composition pins the full original and its parts. A
`record.json` entrypoint with `{"record_node": "original"}` derives the canonical
resource from that complete L3 node. L1 routes include the Record's original
scope, limitations, verification, status, recommendations and validation plan
alongside its claims and sources. L3 reopens the original file byte for byte.
Records declaring linked skill documents need their full relative resource set.
The [Record migration checks](../../../tests/knowledge/test_atomic_records.py)
compare the candidate with decision cards captured from the released wheel.

- `metadata.atom` declares its L0–L3 layer, applicability (`when`), license,
separate read/retain/redistribute grants, and a `source_span` with source
index, path, half-open byte range and SHA-256. Publication checks the whole
Expand Down
86 changes: 79 additions & 7 deletions src/inferrsi/knowledge/atomic_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,38 @@

from .atomic_composition import AtomPin, applies, select_routes
from .atomic_generation import FORMAT, PUBLIC_TASKS, SEAL, InstalledGeneration, digest, owned_path
from .atomic_json import matches_span, member_spans
from .atomic_reader import atom_material, permits_operations
from .decision_cards import DecisionSource
from .knowledge_operations import IDENTITY, Bundle, _json, safe_path

_PUBLISH = {"read", "retain", "redistribute"}


def _authored(directory: Path, path: Path, field: str) -> tuple[AtomPin, Bundle]:
descriptor = json.loads(owned_path(directory, path.name).read_bytes())
def _complete_original(body: bytes, origin: dict) -> bool:
return (origin["layer"] == "L3" and origin["source_byte_range"] == [0, len(body)]
and origin["sha256"] == origin["source"].get("sha256"))


def _record_content(metadata: dict, node: str, material: dict) -> bytes:
nodes = metadata["composition"]["nodes"]
if not isinstance(node, str) or node not in nodes:
raise ValueError("Record entrypoint must name a declared source node")
pin = nodes[node]
target = AtomPin(pin["ref"], pin["revision"])
if target not in material:
raise ValueError(f"Missing pinned Record source: {target.ref}")
body, origin = material[target]
if not _complete_original(body, origin):
raise ValueError("Record entrypoint requires the complete L3 original")
record = json.loads(body)
if (not isinstance(record, dict) or record.get("id") != metadata["id"]
or record.get("skill_documents")):
raise ValueError("Record source must match its identity and be self-contained")
return _json(record)


def _authored(directory, path, field, descriptor, material) -> tuple[AtomPin, Bundle]:
metadata = descriptor["metadata"]
if field not in metadata or ("atom" in metadata and "composition" in metadata):
raise ValueError(f"{path.name} must declare one {field}")
Expand All @@ -27,6 +50,10 @@ def _authored(directory: Path, path: Path, field: str) -> tuple[AtomPin, Bundle]
safe_path(name)
if isinstance(value, dict) and value.keys() == {"path"}:
content[name] = owned_path(directory, value["path"]).read_bytes()
elif (field == "composition" and metadata["kind"] == "knowledge"
and name == metadata.get("entrypoint") == "record.json"
and isinstance(value, dict) and value.keys() == {"record_node"}):
content[name] = _record_content(metadata, value["record_node"], material)
elif (isinstance(value, dict) and value.keys() == {"text"}
and isinstance(value["text"], str)):
content[name] = value["text"].encode()
Expand Down Expand Up @@ -101,17 +128,60 @@ def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> bool
return True


def _authored_inputs(directory: Path, field: str, material: dict):
for path in sorted(directory.glob("*.json")):
if not re.fullmatch(IDENTITY, path.stem):
raise ValueError(f"Invalid descriptor filename: {path.name}")
descriptor = json.loads(owned_path(directory, path.name).read_bytes())
pin, bundle = _authored(directory, path, field, descriptor, material)
yield path.stem, pin, bundle
if "parts" not in descriptor:
continue
if field != "atom" or len(bundle.content) != 1 or bundle.dependencies:
raise ValueError("Atom parts require a single, self-contained original")
body, origin = material[pin]
if not _complete_original(body, origin):
raise ValueError("Atom parts require a complete L3 source")
parts = descriptor["parts"]
if not isinstance(parts, dict) or not parts:
raise ValueError("Atom parts must declare named source spans")
members = member_spans(body)
for name, part in parts.items():
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", name):
raise ValueError(f"Invalid atom part name: {name}")
start, end = part["byte_range"]
if type(start) is not int or type(end) is not int or not 0 <= start < end <= len(body):
raise ValueError(f"Invalid source range for atom part {name}")
pointers = part["pointers"]
if (not isinstance(pointers, list) or not pointers
or not all(isinstance(ptr, str) and ptr.startswith("/") for ptr in pointers)):
raise ValueError(f"Expected source JSON pointers for atom part {name}")
if not matches_span(members, pointers, start, end):
raise ValueError(f"JSON pointers do not match the source range for part {name}")
atom = bundle.metadata["atom"]
span = {**atom["source_span"], "byte_range": [start, end], "sha256": part["sha256"]}
title = bundle.metadata.get("title", bundle.metadata["id"])
fields = ", ".join(ptr.removeprefix("/") for ptr in pointers)
child = Bundle({
**bundle.metadata, "id": bundle.metadata["id"] + "." + name,
"title": part.get("title", f"{title} — {fields}"),
"summary": part.get("summary", bundle.metadata.get("summary", "")),
"entrypoint": "excerpt",
"atom": {**atom, "resource": "excerpt", "layer": part["layer"],
"source_span": span, "source_pointers": pointers},
}, {"excerpt": body[start:end]}, {})
child_pin = AtomPin(pin.ref + "." + name, child.revision)
yield path.stem + "." + name, child_pin, child


def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mapping[str, Path]):
files, entries, material, compositions = {}, {}, {}, {}
skills = {}
for family, field in (("atoms", "atom"), ("compositions", "composition")):
directory = owned_path(source, family)
if not directory.is_dir():
raise ValueError(f"Missing authored {family} directory")
for path in sorted(directory.glob("*.json")):
if not re.fullmatch(IDENTITY, path.stem):
raise ValueError(f"Invalid descriptor filename: {path.name}")
pin, bundle = _authored(directory, path, field)
for stem, pin, bundle in _authored_inputs(directory, field, material):
if pin.ref in entries:
raise ValueError(f"Duplicate qualified reference: {pin.ref}")
view = bundle.view()
Expand All @@ -120,7 +190,9 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi
or not permits_operations(declaration, _PUBLISH)):
raise PermissionError(f"Publication denied for {pin.ref}")
applies(declaration["when"], {})
prefix = f"knowledge/{family}/{path.stem}"
prefix = f"knowledge/{family}/{stem}"
if prefix + ".json" in files:
raise ValueError(f"Duplicate generated manifest: {prefix}")
files[prefix + ".json"] = _json(bundle.manifest())
files.update({prefix + "/" + name: data for name, data in bundle.content.items()})
entry = {"revision": pin.revision, "manifest": prefix + ".json", "kind": view["kind"]}
Expand Down
65 changes: 65 additions & 0 deletions src/inferrsi/knowledge/atomic_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Locate JSON members in the exact UTF-8 source used to build an atom."""

import json
import re
from dataclasses import dataclass


@dataclass(frozen=True)
class Member:
parent: str
index: int
start: int
end: int


_TOKEN = re.compile(rb'"(?:[^"\\]|\\.)*"|[{}\[\],:]|[^{}\[\],:" \t\r\n]+')


def member_spans(source: bytes) -> dict[str, Member]:
# The standard decoder validates syntax. Token positions retain the original
# bytes, including escaped keys, UTF-8 text and the spacing between members.
json.loads(source.decode("utf-8"))
tokens = _TOKEN.finditer(source)
members = {}

def visit(pointer, token):
opening = token.group()
if opening not in (b"{", b"["):
return token.end()
closing = b"}" if opening == b"{" else b"]"
token = next(tokens)
index = 0
while token.group() != closing:
start = token.start()
if opening == b"{":
key = json.loads(token.group())
segment = key.replace("~", "~0").replace("/", "~1")
next(tokens) # colon after the key
token = next(tokens)
else:
segment = str(index)
child = pointer + "/" + segment
if child in members:
raise ValueError(f"Duplicate JSON member at {child}")
end = visit(child, token)
members[child] = Member(pointer, index, start, end)
index += 1
token = next(tokens)
if token.group() == b",":
token = next(tokens)
return token.end()

visit("", next(tokens))
return members


def matches_span(members: dict[str, Member], pointers: list[str], start: int, end: int) -> bool:
"""A part covers complete, consecutive siblings, from the first key/item to the last value."""
if not pointers or any(pointer not in members for pointer in pointers):
return False
selected = [members[pointer] for pointer in pointers]
first = selected[0]
return (first.start == start and selected[-1].end == end
and all(item.parent == first.parent and item.index == first.index + offset
for offset, item in enumerate(selected)))
Loading
Loading