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
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# Preserve recorded evidence and historical validator bytes across checkouts.
/evidence/** -text
/tests/fixtures/legacy/** -text
/tests/fixtures/atomic-reader/** -text whitespace=-blank-at-eof
# A session started by an older runtime keeps its exact bytes; its plan pins file hashes.
/tests/fixtures/optimization-session/pre-infra-removal-session/** -text
/tests/fixtures/optimization-session/pre-trials-rename-session/** -text
Expand Down
1 change: 1 addition & 0 deletions docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,7 @@
"src/inferrsi/apps/cli/__init__.py",
"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"
],
"status": "retired",
Expand Down
71 changes: 71 additions & 0 deletions docs/guides/knowledge/knowledge-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,77 @@ The diagrams and counts record the layout migration in [#516](https://github.com

To reproduce the #516 search comparison, use the baseline and candidate checkouts from that migration on the same machine. The [search comparison](../../../tools/compare_find_layouts.py) checks ordered results across both trees and times the end-to-end CLI. The [task queries and acceptance criteria](../../../tests/fixtures/find/layout-queries.json) define the workload.

## Atomic candidate for domain authors and Apps

The shared candidate accepts one JSON descriptor per atom or composition. 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=...,
source_roots=...)`. Supply physical source snapshots keyed by the exact Git commit
or, for a content-addressed source, the complete file SHA-256. Use the original
source paths within each snapshot. A release wheel can be staged under the
corresponding repository paths after verifying its release digest.
The existing wheel and plugin continue to load the published library during
candidate review.

Each descriptor carries normalized Bundle `metadata`, optional in-bundle
`dependencies`, and a `content` mapping. A resource is either `{"text": "..."}`
or `{"path": "inputs/file"}` relative to its descriptor directory. The default
authority is `package`. An explicit `authority` preserves a different source's
identity and requires its own grants. A navigation composition can omit its
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.

- `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
file against `sources[index].sha256` and compares the declared slice with the
atom's actual bytes. A content-addressed atom containing its complete file at
offset zero carries its own snapshot. The reader records `verified_at_build`
for each atom whose range the build compared with a separately supplied file
and whose installed generation matches the caller's trusted release ID.
Without either check the receipt records `declared`. Its Bundle revision
covers metadata and resources.
- `metadata.composition` declares named `nodes` (qualified ref, exact revision,
required prerequisite nodes), `routes` (layer, required and optional roots,
conditions, finding, conflicts and superseded routes), and its grants and
license. An exportable composition adds `skill` with `name`, `description`,
an L0 node called out by `body`, and a mapping from public relative resource
paths to pinned nodes. For a host that loads a complete procedure, list its
additional pinned text nodes in `skill.sections` in reading order. The
builder appends their original bytes, including whitespace, to the L0 body.
A Reader request for L0 still returns the composition's L0 route. Each of
the seven public task names has one owner.
The [executable authoring example](../../../tests/knowledge/test_atomic_generation.py)
builds all seven entries and a supporting skill.
- The installer writes `knowledge/{atoms,compositions}/`, the generated catalog
and file digests in `knowledge/generation.json`, and `skills/<name>/SKILL.md`
with the declared references, assets and scripts. Two builds of the same
input yield the same generation ID. `InstalledGeneration(root)` verifies the
complete tree against its own seal before exposing `tasks`, `skills`,
`catalog` or `read_resolved`. To attest the build, obtain the expected ID
independently of the installation (for example from the trusted release
record) and open `InstalledGeneration(root, expected=release_id)`. An ID
mismatch refuses the open. A prior generation can reopen its own receipts.
- Ordinary callers use `apps.workflows.knowledge.read_selection(source, ref,
permits=..., revision=..., layer=..., finding=..., context=..., max_bytes=...)`.
Managed optimization uses `apps.workflows.campaign.capture_selection(root,
source, ref, ...)` with the same selection and the additional retain grant.
The response binds original bytes, digests, source ranges and dependency
paths to the chosen revision. A required-group refusal delivers zero
bodies. Optional omissions carry a reason.

Project-service reuse has a separate receipt format that excludes content
fingerprints. The pinned-finding capture above covers ordinary managed
optimization. For `evaluation_mode=service_reuse`, use the service's own
receipt path. In the [#709 CLI](https://github.com/InferMatrixLab/InferRSI/pull/709),
`find --session` retains the source at search time and its returned `read_args`
open and page that retained version, including relative resources. The new
pinned capture rejects this mode before reading or writing session state.
Atomic finding selection for this mode needs a service-compatible receipt
and belongs to the subsequent Reader adaptation.

## 1. Task layers and evidence

```mermaid
Expand Down
17 changes: 16 additions & 1 deletion src/inferrsi/apps/workflows/campaign.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
from pathlib import Path

from inferrsi import __version__
from inferrsi.harness.records import campaign_records, knowledge_capture
from inferrsi.harness import optimization
from inferrsi.harness.records import atomic_capture, campaign_records, knowledge_capture
from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method
from inferrsi.knowledge.atomic_reader import AtomicReader, PinnedSource
from inferrsi.knowledge.catalog import BACKENDS
from inferrsi.knowledge.context_projection import (
PROVENANCE_FIELDS,
Expand All @@ -31,6 +33,14 @@ def create_campaign(root: Path, campaign_id: str, *, target: float | None = None
)


def capture_selection(root: Path, source: PinnedSource, reference: str, *,
permits, **request) -> dict:
"""Supply the same Reader as an ordinary read to the managed campaign."""
return optimization.capture_selection(root, AtomicReader(source, permits=permits),
reference=reference, assemble_text=assemble_context_text,
**request)


def capture_context(root: Path, *, context_id: str, reader, query: str = "",
relevance: str | None = None,
relevance_method: str | None = None,
Expand Down Expand Up @@ -177,6 +187,11 @@ def verify_capture(raw: bytes) -> tuple[dict | None, str]:
document, state = knowledge_capture.verify_capture(raw)
if document is None:
return None, state
if document["request"].get("mode") == "pinned_selection":
try:
atomic_capture.verify_stored(document)
except (KeyError, TypeError, ValueError, AttributeError):
return None, "atomic_receipt_mismatch"
if assemble_context_text(document["contexts"]) != document["assembled_text"]:
return None, "assembly_mismatch"
return document, "verified"
6 changes: 6 additions & 0 deletions src/inferrsi/apps/workflows/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from pathlib import Path

from inferrsi.knowledge.atomic_reader import AtomicReader, GroupDelivery, PinnedSource
from inferrsi.knowledge.knowledge_operations import KnowledgeReader, safe_path
from inferrsi.knowledge.knowledge_store import KnowledgeStore

Expand Down Expand Up @@ -40,3 +41,8 @@ def read(
raise ValueError(f"Unknown resource: {path}")
view.update(content=bundle.content[path].decode("utf-8"), content_resource=path)
return qualified, view["revision"], view


def read_selection(source: PinnedSource, reference: str, *, permits, **request) -> GroupDelivery:
"""Ordinary Apps read of a fixed composition using this project's grants."""
return AtomicReader(source, permits=permits).read_selection(reference, **request)
45 changes: 35 additions & 10 deletions src/inferrsi/harness/optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from . import attempt_recovery, candidates
from .artifact_primitives import digest, file_lock, sha256
from .atomic_json import atomic_write_json, durable_write_json
from .records import atomic_capture
from .records.evidence import bounded_record_bytes, sanitized_text
from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES
from .task_protocol import TaskProtocolError
Expand Down Expand Up @@ -442,6 +443,37 @@ def _store_knowledge(root, kind, number, record):
"kind": kind, "round": number}


def _register_context(root, state, number, binding, path, fingerprint, *, selected=False):
reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint,
"kind": "delivered_context"}
document = _read_context(root, reference)
if selected and document["selection"]["status"] != "delivered":
reference["kind"] = "knowledge_refusal"
retained = {**reference, "round": number} if number is not None else dict(reference)
if binding:
retained["diagnosis_id"] = binding["diagnosis_id"]
state["contexts"].append(retained)
return {"reference": reference, "context": document}


def capture_selection(root: Path, reader, *, assemble_text, **request) -> dict:
"""Retain an explicit pin in a managed optimization campaign with its current diagnosis."""
with _locked(root):
plan, state = _load(root)
if plan.get("evaluation_mode") == "service_reuse":
raise ValueError("Service-reuse sessions require their fingerprint-free capture format")
number = _knowledge_round(plan, state)
binding = _context_diagnosis(plan, state)
path, fingerprint = atomic_capture.retain_selection(
root, reader=reader, context_id="context-" + uuid.uuid4().hex,
diagnosis_binding=binding, ranking_policy=plan.get("ranking_policy"),
assemble_text=assemble_text, **request,
)
response = _register_context(root, state, number, binding, path, fingerprint, selected=True)
atomic_write_json(root / "state.json", state)
return response


def capture_context(root: Path, reader, *, retain_context, external_provider=None,
external_provider_for=None, **request) -> dict:
with _locked(root):
Expand All @@ -457,14 +489,7 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non
binding = _context_diagnosis(plan, state)
path, fingerprint = retain_context(root, context_id="context-" + uuid.uuid4().hex,
reader=reader, diagnosis_binding=binding, **request)
reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint,
"kind": "delivered_context"}
# Keep the local tool response compatible with stored Codex trace verification.
retained = {**reference, "round": number} if number is not None else reference
if binding:
retained = {**retained, "diagnosis_id": binding["diagnosis_id"]}
state["contexts"].append(retained)
response = {"reference": reference, "context": _read_context(root, reference)}
response = _register_context(root, state, number, binding, path, fingerprint)
if settings:
remaining = _knowledge_time(plan, state)
if remaining > 0:
Expand All @@ -474,7 +499,7 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non
limit=request["limit"], timeout=remaining)
else:
result = {"state": "timeout", "items": [], "count": 0}
search = {**result, **settings, "context_ref": reference["path"]}
search = {**result, **settings, "context_ref": response["reference"]["path"]}
search_ref = _store_knowledge(root, "external_search", number, search)
state["contexts"].append(search_ref)
response["external"] = {**search, "reference": search_ref}
Expand Down Expand Up @@ -524,7 +549,7 @@ def _validate_knowledge_refs(root, contexts, refs):
if len(set(refs)) != len(refs):
raise ValueError("Cite unique delivered knowledge references")
delivered = {entry["path"]: entry for entry in contexts
if entry["kind"] != "external_search"}
if entry["kind"] not in ("external_search", "knowledge_refusal")}
for ref in refs:
path, separator, item = ref.partition("#")
reference = delivered.get(path)
Expand Down
107 changes: 107 additions & 0 deletions src/inferrsi/harness/records/atomic_capture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Verify bytes returned by an injected Reader and retain the selected delivery or refusal."""

from __future__ import annotations

import base64
import hashlib
from pathlib import Path

from inferrsi import __version__

from . import knowledge_capture

_REFUSALS = {"over_budget", "unavailable_revision", "permission_denied",
"not_applicable", "conflict"}


def _verify_receipt(receipt, bodies, request):
selection = receipt["selection"]
if any(selection[key] != request[key] for key in ("ref", "revision", "layer", "finding")):
raise ValueError("Reader receipt belongs to a different selection")
records = receipt["delivered"]
if not isinstance(records, list) or len(records) != len(bodies):
raise ValueError("Reader receipt must enumerate exactly the delivered bodies")
status = receipt["status"]
if status == "delivered":
if not records:
raise ValueError("Successful delivery requires at least one atom")
elif status not in _REFUSALS or records:
raise ValueError("Invalid Reader refusal or nonempty refused delivery")
seen = set()
for body, record in zip(bodies, records):
pin = (record["ref"], record["revision"])
if pin in seen:
raise ValueError("An atom may occur only once in a delivery")
seen.add(pin)
if not isinstance(body, bytes):
raise ValueError("The Reader must supply the original bytes")
digest = hashlib.sha256(body).hexdigest()
if (record["sha256"] != digest or record["source_sha256"] != digest
or type(record["bytes"]) is not int or record["bytes"] != len(body)):
raise ValueError("Delivered bytes differ from the Reader receipt")
span = record["source_byte_range"]
if (not isinstance(span, list) or len(span) != 2
or not all(type(offset) is int for offset in span)
or span[0] < 0 or span[1] - span[0] != len(body)):
raise ValueError("Source range differs from the delivered bytes")
total = sum(map(len, bodies))
if (type(receipt["body_bytes"]) is not int or receipt["body_bytes"] != total
or total > request["max_bytes"]):
raise ValueError("Invalid delivered byte count or budget")


def _resource(body, record):
resource = {"path": record["source_path"], "sha256": record["sha256"]}
try:
resource["content"] = body.decode("utf-8")
except UnicodeDecodeError:
resource.update(content=base64.b64encode(body).decode("ascii"), content_encoding="base64")
return resource


def verify_stored(document):
"""Check a retained atomic receipt against the resources a caller can actually recover."""
request, receipt = document["request"], document["selection"]
records, contexts = receipt["delivered"], document["contexts"]
if len(records) != len(contexts) or len(records) != len(document["items"]):
raise ValueError("Atomic capture does not match the delivered atom count")
bodies = []
for record, context, item in zip(records, contexts, document["items"]):
identity = {"ref": record["ref"], "revision": record["revision"]}
if item != identity or any(context[key] != value for key, value in identity.items()):
raise ValueError("Retained atom does not match its receipt")
resource, = context["resources"]
if resource["path"] != record["source_path"] or resource["sha256"] != record["sha256"]:
raise ValueError("Retained resource differs from its receipt")
bodies.append(knowledge_capture.resource_bytes(resource))
_verify_receipt(receipt, bodies, request)
if (document["context_bytes_used"] != receipt["body_bytes"]
or document["context_budget"] != request["max_bytes"]):
raise ValueError("Atomic capture accounting differs from its request")


def retain_selection(root: Path, *, reader, context_id, reference, revision, layer, max_bytes,
context, assemble_text, finding=None, diagnosis_binding=None,
ranking_policy=None):
campaign = knowledge_capture.capture_campaign(root, context_id)
request = {"mode": "pinned_selection", "ref": reference, "revision": revision, "layer": layer,
"finding": finding, "max_bytes": max_bytes, "context": dict(context),
"operations": ["read", "retain"]}
if ranking_policy is not None:
request["ranking_policy"] = ranking_policy
delivery = reader.read_selection(reference, revision=revision, layer=layer, finding=finding,
max_bytes=max_bytes, context=context, operations=("retain",))
receipt, bodies = delivery.receipt, delivery.bodies
_verify_receipt(receipt, bodies, request)
items = [{"ref": record["ref"], "revision": record["revision"]}
for record in receipt["delivered"]]
contexts = [{**item, "resources": [_resource(body, record)], "omissions": []}
for item, body, record in zip(items, bodies, receipt["delivered"])]
return knowledge_capture.store_capture(
root, campaign_id=campaign["campaign_id"], context_id=context_id, request=request,
selection=receipt, items=items, omissions=receipt.get("omissions", []),
context_omissions=[],
context_budget=max_bytes, context_bytes_used=receipt["body_bytes"], contexts=contexts,
assembled_text=assemble_text(contexts), diagnosis_binding=diagnosis_binding,
captured_by=f"inferrsi pinned knowledge read {__version__}",
)
Loading
Loading