Skip to content
Draft
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
13 changes: 13 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
# Preserve recorded evidence and historical validator bytes across checkouts.
/evidence/** -text
/tests/fixtures/legacy/** -text
/tests/fixtures/atomic-reader/** -text whitespace=-blank-at-eof
# Migrated task paragraphs and YAML headers retain their original LF separators.
/src/inferrsi/knowledge/atoms/task-*.md text eol=lf whitespace=-blank-at-eof
/src/inferrsi/knowledge/compositions/*-header.yaml text eol=lf 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 All @@ -12,9 +16,18 @@
/evidence/README.md text eol=lf
/evidence/_template/** text eol=lf

/src/inferrsi/knowledge/atoms/casebooks/* -text
/src/inferrsi/knowledge/atoms/workflows/** -text
# Two released Markdown guides use trailing spaces for hard line breaks.
/src/inferrsi/knowledge/atoms/workflows/cite-check-downstream-pr.md whitespace=-blank-at-eol
/src/inferrsi/knowledge/atoms/workflows/competitor-scan.md whitespace=-blank-at-eol

# 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
5 changes: 4 additions & 1 deletion docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,10 @@
"src/inferrsi/apps/cli/__init__.py",
"tests/apps/test_apps_context_provider.py",
"tests/apps/test_apps_knowledge.py",
"tests/harness/test_harness_generation_seal.py"
"tests/apps/test_optimization_session.py",
"tests/harness/test_harness_generation_seal.py",
"tests/knowledge/test_atomic_casebooks.py",
"tests/knowledge/test_atomic_records.py"
],
"status": "retired",
"first_removal_version": "0.3.4"
Expand Down
105 changes: 105 additions & 0 deletions docs/guides/knowledge/knowledge-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,111 @@ 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 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=...,
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.

For a Case backed by released files, `case_resources` maps each public resource
name to a pinned L3 node. The builder derives the entrypoint and required
resource order from the original `case.json`, checks relative paths against the
same source snapshot, and retains both names when the release exposed its JSON
under two names. The public L1 route takes one finding and delivers its source
span with the Case's original applicability, state, limits, credit and sources.
L0 opens the Case's navigation, L2 its guide, and L3 both complete originals.
The [Case migration tests](../../../tests/knowledge/test_atomic_casebooks.py)
replay the released Reader's decision cards through the installed public refs.

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
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.
To preserve native host fields during migration, `skill.frontmatter` can
name a content resource in the pinned composition. The builder verifies its
name and description, requires exactly one header with no procedure text,
and emits its original bytes, including invocation settings and attribution.
The [executable authoring example](../../../tests/knowledge/test_atomic_generation.py)
builds all seven entries and a supporting skill.
- For the task-domain migration, read the [v0.3.4 owner and byte
map](../../../tests/fixtures/atomic-reader/task-domain-v0.3.4.json). Run
`inferrsi skills --root <generation>/skills enter task-debug` against a
built candidate to open the complete primary procedure. Use the same root
with `resource inference-task-router references/routes/debug.json` for its
original routing card. The card's candidate skill IDs identify owners to
consult in the other domains.
- 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
Loading
Loading