# RSI Kernel · 草稿、评估与条件发布

The kernel maintains the accepted ontology revision while agents edit isolated drafts. A host provides the ontology codec, evidence selector and evaluator, command plugins, approval policy and conditional target adapter. The frozen Python protocols live in `ancrel_rsi_kernel.ports`.

## Local state

Construct `storage.KernelDatabase(path)` once at startup and share it among services. Give `artifacts.LocalArtifactStore` and `drafts.DraftStore` separate private directories on a local volume. SQLite serializes competing writers. Each draft directory contains the adapter's serialized document in `material`. To update, send both the accepted `base_revision` and the `expected_draft_revision` observed by the editor. An external edit preserves the file and holds the draft for review. Open a fresh draft to incorporate reviewed changes.

## Evaluation and approval

Freeze the selected suites with `EvalGate.freeze_inputs`, evaluate each distinct case, then call `EvalGate.summarize`. The result counts shared cases once and reports coverage separately for each tier. A versioned policy defines minimum coverage, the failure budget and whether a reviewer may acknowledge unverified evidence. The default requires full coverage and verified passing evidence.

## Publish and recover

Create a `WritebackJournal(db, artifacts, adapter)` and pass it to `ReleasePreviewManager`. The manager pins the evaluation, material, diff, accepted revision and target pre-image for 900 seconds. Submit the preview with the reviewed material, reason and authenticated command context. The human capability and `release.publish` belong to the trusted host's authorization layer. The external adapter must conditionally apply the exact bytes to its target under the expected digest.

On startup call `WritebackReconciler(journal).reconcile()`. An observed post-image completes the internal revision and receipt. An unapplied intent with the original pre-image closes without a receipt. A third digest holds the scope and target for inspection, preserving any third-party changes. Replaying a committed preview returns its release receipt. Internal rollback appends a revision restoring the release's parent. External revert needs a separate capability, the original target bytes and the expected current target digest.

## Host boundaries

HTTP and CLI requests share `CommandHandler.dispatch` with the scoped tool gateway. Supply a JSON Schema validator and authenticated context at the host boundary. Register revision-sensitive verbs with their current revision lookup and enforce CAS in the domain handler's mutation. Mutating clients should use a stable idempotency key. An unfinished command reservation signals unknown delivery and requires inspection of durable operation state. Tokens expire, are single-use and are invalidated on restart.

Use one `RedactedDeltaStream` per fenced output stream. Flush it before a non-delta or terminal event. Use `RedactionPolicy` for structured errors, diagnostics and other event payloads. The subprocess runner enforces a shared byte budget and wall timeout within a POSIX process group. Its temporary directory and minimal environment suit trusted commands. It refuses workloads requiring OS isolation, network denial, memory or CPU quotas. The concurrency limit applies to one runner instance.

## Run the example

```sh
uv run --project packages/backend/python python examples/be.rsi-kernel/demo.py
```

```py
"""Run from the repository root with the Python workspace selected."""

from pathlib import Path
from tempfile import TemporaryDirectory

from ancrel_rsi_kernel.artifacts import LocalArtifactStore
from ancrel_rsi_kernel.evaluation import TIERS, EvalGate
from ancrel_rsi_kernel.models import EvaluationSuite, PerCaseOutcome


def main() -> None:
    with TemporaryDirectory() as folder:
        store = LocalArtifactStore(Path(folder))
        baseline = store.put(b"Write a summary.\n")
        candidate = store.put(b"Write a concise summary.\n", baseline.artifact_id)
        suites = [
            EvaluationSuite(suite_id=tier, tier=tier, case_ids=["sample"]) for tier in TIERS
        ]
        frozen = EvalGate.freeze_inputs(suites, candidate.sha256)
        before = EvalGate.summarize(frozen, [])
        case = PerCaseOutcome(case_id="sample", verdict="passed", trust_level="verified",
                              violations=[])
        after = EvalGate.summarize(frozen, [case])
        print(f"Without evidence: {before.verdict}")
        print(f"With evidence: {after.verdict} ({after.unique_case_count} case across 3 tiers)")
        print(f"Baseline: {store.read(baseline).decode().strip()}")


if __name__ == "__main__":
    main()
```

Expected:

Run `uv run --project packages/backend/python python examples/be.rsi-kernel/demo.py` from the repository root. The three tiers share one case. Supplying its verified outcome gives each tier full coverage.

```text
Without evidence: not_evaluated
With evidence: passed (1 case across 3 tiers)
Baseline: Write a summary.
```

## Wire contract

[Schema](https://ancrel.prts.dev/v/0.3.0/schemas/rsi-release.v1.json) · [Example](https://ancrel.prts.dev/v/0.3.0/examples/be.rsi-kernel/demo.py)

```sh
uv run --project packages/backend/python python examples/be.rsi-kernel/demo.py
```
