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
76 changes: 54 additions & 22 deletions src/inferrsi/knowledge/atomic_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
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 .atomic_skill_directory import directory_content, export_directory_skill, skill_spans
from .decision_cards import DecisionSource
from .knowledge_operations import IDENTITY, Bundle, _json, case_required_resources, safe_path

Expand Down Expand Up @@ -98,25 +99,29 @@ def required_spans(roots):
raise ValueError("Case must provide a decision route for every original finding")


def _case_content(metadata: dict, bindings: dict, material: dict) -> dict[str, bytes]:
"""Resolve the original Case and its declared relative resources from pinned L3 nodes."""
if not isinstance(bindings, dict) or "case.json" not in bindings:
raise ValueError("Case resources must bind the original case.json")
def _pinned_resources(metadata: dict, bindings: dict, material: dict) -> tuple[dict, dict]:
content, origins = {}, {}
nodes = metadata["composition"]["nodes"]
for name, key in bindings.items():
safe_path(name)
if not isinstance(key, str) or key not in nodes:
raise ValueError(f"Undeclared Case resource node for {name}")
raise ValueError(f"Undeclared resource node for {name}")
node = nodes[key]
pin = AtomPin(node["ref"], node["revision"])
if pin not in material:
raise ValueError(f"Missing pinned Case resource for {name}")
raise ValueError(f"Missing pinned resource for {name}")
body, origin = material[pin]
if not _complete_original(body, origin):
raise ValueError(f"Case resource requires a complete L3 original: {name}")
raise ValueError(f"Resource requires a complete L3 original: {name}")
content[name], origins[name] = body, origin["source"]
return content, origins


def _case_content(metadata: dict, bindings: dict, material: dict) -> dict[str, bytes]:
"""Resolve the original Case and its declared relative resources from pinned L3 nodes."""
if not isinstance(bindings, dict) or "case.json" not in bindings:
raise ValueError("Case resources must bind the original case.json")
content, origins = _pinned_resources(metadata, bindings, material)
source = origins["case.json"]
record = json.loads(content["case.json"])
if (not isinstance(record, dict) or record.get("kind") != "case"
Expand All @@ -139,15 +144,28 @@ def _case_content(metadata: dict, bindings: dict, material: dict) -> dict[str, b
return content


def _authored(directory, path, field, descriptor, material) -> tuple[AtomPin, Bundle]:
def _authored(directory, path, field, descriptor, material, roots) -> 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}")
content = {}
directory_export = metadata[field].get("skill") == {"directory_entry": True}
if directory_export and "directory_resources" not in descriptor:
raise ValueError("Directory Skill export requires checked original directory resources")
if "case_resources" in descriptor:
if field != "composition" or metadata["kind"] != "case" or "content" in descriptor:
raise ValueError("Only a Case composition may bind its content through case_resources")
content = _case_content(metadata, descriptor["case_resources"], material)
if "directory_resources" in descriptor:
if (field != "composition" or metadata["kind"] != "skill"
or descriptor.get("authority") != "checkout" or "content" in descriptor
or descriptor.get("dependencies")):
raise ValueError("Directory resources require a self-contained checkout Skill")
bindings = descriptor["directory_resources"]
if not isinstance(bindings, dict):
raise ValueError("Skill directory resources must bind original relative names")
content, origins = _pinned_resources(metadata, bindings, material)
content = directory_content(metadata, bindings, content, origins, material, roots)
for name, value in descriptor.get("content", {}).items():
safe_path(name)
if isinstance(value, dict) and value.keys() == {"path"}:
Expand Down Expand Up @@ -230,12 +248,12 @@ def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> bool
return True


def _authored_inputs(directory: Path, field: str, material: dict):
def _authored_inputs(directory: Path, field: str, material: dict, roots=None):
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)
pin, bundle = _authored(directory, path, field, descriptor, material, roots)
yield path.stem, pin, bundle
if "parts" not in descriptor:
continue
Expand All @@ -247,30 +265,40 @@ def _authored_inputs(directory: Path, field: str, material: dict):
parts = descriptor["parts"]
if not isinstance(parts, dict) or not parts:
raise ValueError("Atom parts must declare named source spans")
members = member_spans(body)
is_skill = PurePosixPath(origin["source_path"]).name == "SKILL.md"
members = skill_spans(body) if is_skill else 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}")
if is_skill:
section = part.get("skill_section")
if (not isinstance(section, str)
or members.get(section) != (part["layer"], start, end)):
raise ValueError(f"Mismatched Skill section source range or layer: {name}")
locator = {"source_section": section}
fields = section
else:
pointers = part.get("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}")
locator = {"source_pointers": pointers}
fields = ", ".join(ptr.removeprefix("/") for ptr in pointers)
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},
"source_span": span, **locator},
}, {"excerpt": body[start:end]}, {})
child_pin = AtomPin(pin.ref + "." + name, child.revision)
yield path.stem + "." + name, child_pin, child
Expand All @@ -283,7 +311,7 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi
directory = owned_path(source, family)
if not directory.is_dir():
raise ValueError(f"Missing authored {family} directory")
for stem, pin, bundle in _authored_inputs(directory, field, material):
for stem, pin, bundle in _authored_inputs(directory, field, material, roots):
if pin.ref in entries:
raise ValueError(f"Duplicate qualified reference: {pin.ref}")
view = bundle.view()
Expand All @@ -296,7 +324,8 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi
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()})
if declaration.get("skill") != {"directory_entry": True}:
files.update({prefix + "/" + name: data for name, data in bundle.content.items()})
entry = {"revision": pin.revision, "manifest": prefix + ".json", "kind": view["kind"]}
for key in ("title", "summary"):
if isinstance(view.get(key), str):
Expand Down Expand Up @@ -324,7 +353,10 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi
if route["layer"] not in layers:
raise ValueError(f"No required root supplies {route['layer']} for {pin.ref}")
if "skill" in declaration:
name, output = _host_skill(declaration["skill"], nodes, material)
if declaration["skill"] == {"directory_entry": True}:
name, output = export_directory_skill(bundle)
else:
name, output = _host_skill(declaration["skill"], nodes, material)
if name in skills:
raise ValueError(f"Multiple compositions export host skill {name}")
skills[name] = pin.ref
Expand Down
21 changes: 16 additions & 5 deletions src/inferrsi/knowledge/atomic_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import hashlib
import json
from pathlib import Path
from pathlib import Path, PurePosixPath

from .atomic_composition import AtomPin
from .knowledge_operations import Bundle, UnavailableRevision, _json, safe_path
Expand All @@ -21,6 +21,12 @@ def digest(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()


def directory_skill_path(metadata: dict, name: str) -> str:
entry = PurePosixPath(safe_path(metadata["entrypoint"]))
relative = PurePosixPath(safe_path(name)).relative_to(entry.parent)
return f"skills/{safe_path(metadata['id'])}/{relative.as_posix()}"


def owned_path(root: Path, name: str) -> Path:
"""Resolve a portable resource within its owner, rejecting links and Windows junctions."""
path = root
Expand Down Expand Up @@ -68,16 +74,21 @@ def __init__(self, root: Path, *, expected: str | None = None):
pin = AtomPin(ref, entry["revision"])
path = safe_path(entry["manifest"])
manifest = json.loads(files[path])
content = {name: files[path.removesuffix(".json") + "/" + safe_path(name)]
for name in manifest["resources"]}
metadata = manifest["metadata"]
skill = metadata.get("composition", {}).get("skill")
if skill == {"directory_entry": True}:
content = {name: files[directory_skill_path(metadata, name)]
for name in manifest["resources"]}
else:
content = {name: files[path.removesuffix(".json") + "/" + safe_path(name)]
for name in manifest["resources"]}
bundle = Bundle(manifest["metadata"], content, manifest["dependencies"])
if (ref.partition(":")[2] != bundle.metadata["id"] or bundle.manifest() != manifest
or bundle.revision != pin.revision):
raise ValueError(f"Installed Bundle differs from its catalog entry: {ref}")
self._bundles[pin] = bundle
skill = bundle.metadata.get("composition", {}).get("skill")
if skill is not None:
name = skill["name"]
name = metadata["id"] if skill == {"directory_entry": True} else skill["name"]
if name in exports or f"skills/{name}/SKILL.md" not in files:
raise ValueError(f"Invalid host skill export: {name}")
exports[name] = ref
Expand Down
97 changes: 97 additions & 0 deletions src/inferrsi/knowledge/atomic_skill_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Build the pinned sections, relative resources and host export of a self-contained Skill."""

from __future__ import annotations

import re
from io import BytesIO
from pathlib import PurePosixPath

from ._skill_selection import skill_procedure
from .atomic_composition import AtomPin, select_routes
from .atomic_generation import directory_skill_path, owned_path
from .knowledge_operations import Bundle, _tree, safe_path
from .skill_catalog import _effective, _frontmatter_parts


def skill_spans(body: bytes) -> dict:
_, procedure = skill_procedure("SKILL.md", body)
header = re.match(rb"\A---[ \t]*\r?\n.*?^---[ \t]*(?:\r?\n|\Z)", body, re.M | re.S)
if not procedure or not header:
raise ValueError("Skill sections require a complete guide with embedded decision metadata")
navigation_end = procedure["source_byte_ranges"][0][1]
public, _ = _frontmatter_parts(BytesIO(body[:navigation_end] + b"---\n"))
if not all(isinstance(public.get(key), str) and public[key].strip()
for key in ("name", "description")):
raise ValueError("Skill navigation must include its original name and description")
return {"navigation": ("L0", 0, navigation_end), "decision": ("L1", 0, header.end()),
"procedure": ("L2", header.end(), len(body))}


def _verify_directory_routes(declaration, bindings, guide, source, material):
sections = skill_spans(guide)
if any(any(route.get(key) for key in ("when", "optional", "supersedes", "conflicts"))
for route in declaration["routes"].values()):
raise ValueError("Directory routes must preserve their unconditional delivery")
nodes = declaration["nodes"]
originals = {AtomPin(nodes[name]["ref"], nodes[name]["revision"]) for name in bindings.values()}
for layer, names in (("L0", ["navigation"]), ("L1", ["decision"]),
("L2", ["decision", "procedure"]), ("L3", [])):
selected = select_routes(declaration, layer=layer, context={}, case=None, finding=None)
pins = {use.pin for use in selected.required}
if layer == "L3":
if pins != originals:
raise ValueError("Skill L3 must deliver the complete original directory")
continue
actual = set()
for pin in pins:
if pin not in material:
raise ValueError(f"Missing pinned Skill section: {pin.ref}")
origin = material[pin][1]
if origin["source"] != source:
raise ValueError(f"Skill {layer} must deliver its own pinned guide sections")
actual.add((origin["layer"], *origin["source_byte_range"]))
if actual != {sections[name] for name in names}:
raise ValueError(f"Skill {layer} must deliver its own pinned guide sections")


def directory_content(metadata, bindings, content, origins, material, roots) -> dict[str, bytes]:
"""Keep all the original names and bytes of a self-contained checkout Skill directory."""
entry = PurePosixPath(safe_path(metadata["entrypoint"]))
if (not isinstance(bindings, dict) or entry.as_posix() not in bindings
or entry.name != "SKILL.md" or entry.parent.name != metadata["id"]):
raise ValueError("Skill directory must bind its original SKILL.md and identity")
source = origins[entry.as_posix()]
original = PurePosixPath(source["path"])
if (source != metadata["sources"][0] or original.parts[-len(entry.parts):] != entry.parts
or not roots or source.get("commit") not in roots):
raise ValueError("Skill directory requires its pinned source root")
for name, origin in origins.items():
if (not PurePosixPath(name).is_relative_to(entry.parent)
or source.get("repo") != origin.get("repo")
or source["commit"] != origin.get("commit")
or original.parent / PurePosixPath(name).relative_to(entry.parent)
!= PurePosixPath(origin["path"])):
raise ValueError(f"Skill resource differs from its original relative source: {name}")
root = roots[source["commit"]]
directory = owned_path(root, original.parent.as_posix())
if _effective(directory).get("references"):
raise ValueError("Self-contained directory cannot omit declared Skill references")
released = _tree(directory, entry.parent.as_posix(), root=root)
if content != released or metadata["required_resources"] != sorted(released):
raise ValueError("Skill directory bindings must cover the complete original directory")
_verify_directory_routes(metadata["composition"], bindings, content[entry.as_posix()],
source, material)
return content


def export_directory_skill(bundle: Bundle) -> tuple[str, dict[str, bytes]]:
name = bundle.metadata["id"]
entry = PurePosixPath(bundle.metadata["entrypoint"])
header, _ = _frontmatter_parts(BytesIO(bundle.content[entry.as_posix()]))
description = header.get("description")
if (len(name) > 64 or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name)
or header.get("name") != name or not isinstance(description, str)
or not 1 <= len(description.strip()) <= 1024):
raise ValueError("Directory Skill must have a valid matching host name and description")
return name, {directory_skill_path(bundle.metadata, path): raw
for path, raw in bundle.content.items()}
Loading
Loading