From c398ee23a41273d9f41f11fcb38e29a3dc99e8b3 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 07:59:43 -0500 Subject: [PATCH] Docs: Writing an adapter, with a runnable to-do host example The guide covers the authority's three methods, ctx, decisions, result labels, exposure and register_input, pipeline wiring and approvals, checked against the SDK. examples/adapter/todo_adapter.py is self-checking; CI runs it against the installed wheel. Closes gap 7 of the independent reproduction. Issue #57 records that a refused or held call lowers exposure for the rest of the trace. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +- CHANGELOG.md | 1 + README.md | 4 + STATUS.md | 2 +- docs/WRITING-AN-ADAPTER.md | 110 +++++++++++++++++++ examples/adapter/todo_adapter.py | 174 +++++++++++++++++++++++++++++++ 6 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 docs/WRITING-AN-ADAPTER.md create mode 100644 examples/adapter/todo_adapter.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 073ff53..1356efd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,12 +81,13 @@ jobs: with: {toolchain: "1.99.0", components: "rustfmt, clippy"} - name: build the python wheel run: pip wheel --no-deps -w dist ./python - - name: install the wheel into a clean venv and run the offline example from outside the checkout + - name: install the wheel into a clean venv and run both examples from outside the checkout run: | python -m venv "$RUNNER_TEMP/v" "$RUNNER_TEMP/v/bin/pip" install dist/interplane-*.whl cd "$RUNNER_TEMP" INTERPLANE_REQUIRE_INSTALLED=1 "$RUNNER_TEMP/v/bin/python" "$GITHUB_WORKSPACE/examples/offline/run_offline.py" + INTERPLANE_REQUIRE_INSTALLED=1 "$RUNNER_TEMP/v/bin/python" "$GITHUB_WORKSPACE/examples/adapter/todo_adapter.py" - name: conformance from the installed wheel equals conformance from the checkout run: | (cd "$RUNNER_TEMP" && "$RUNNER_TEMP/v/bin/interplane-conformance" "$GITHUB_WORKSPACE/conformance/fixtures" --out "$RUNNER_TEMP/wheel-verdicts.json") diff --git a/CHANGELOG.md b/CHANGELOG.md index ec2f8ef..a98ac37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased (0.3, Trust lane) +- Docs: `docs/WRITING-AN-ADAPTER.md` (the authority's three methods, `ctx`, decisions, result labels, exposure and `register_input`, pipeline wiring, approvals) with the runnable, self-checking `examples/adapter/todo_adapter.py`; CI runs it against the installed wheel. Closes gap 7 of the independent reproduction. Filed issue #57: a refused or held call lowers exposure to `external_untrusted` for the rest of the trace (spec as written; question for the next protocol). - Spec: CORE.md "Adding an adapter" (Adapter subsets) answers the newcomer questions from the independent reproduction: table entry and digest revision, effect classes for hosts without files or mail, native reads without a workspace, argument transforms, which approval rule applies, the compared record fields (`result_digest` excluded), approval id and grant expiry, the exact injection counts, A15, and the delivered-read limit. `adapter_subset.py` accepts any adapter named in the table. No fixture, table or digest change; T3 43 and T4 32 unchanged. - Independent adapter reproduction (plan 19.7 item 8, `docs/REPORT-adapter-repro.md`, evidence `bench/runs/adapter-repro-20261005T1215Z/`): Codex (`gpt-6-sol`) built a to-do host adapter from the v0.3.0 spec, corpus and wheel alone, with no SDK source or existing adapter. 38/38 subset fixtures executed, violations 0, content-derived 0, 27 injected intents; with its exposure check removed, 18 cases fail. Reproduced byte for byte from a fresh clone. 15 spec gaps recorded; fixes follow separately. - Bench receipts: `attempt` is now the number of runs of that condition. Before, a pair whose re-run also failed was labelled one too high (`attempt: 3` after two runs, REPORT-0.2x Limits), and in campaign mode a condition that never failed carried the pair's count. Offline test added (the old code fails it). Re-running `analyze.py` on `heldout-0.2x-20261005T0102Z` reproduces both committed summaries byte for byte. diff --git a/README.md b/README.md index 021321a..7f9a20e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,10 @@ is in view) and executes none of them. The script checks this and exits 1 on any uses only the Python standard library. CI runs it against the built wheel installed in a clean environment (job `package`). +To connect your own program, see `docs/WRITING-AN-ADAPTER.md` and its runnable example +`examples/adapter/todo_adapter.py`: a to-do list host with its own policy, an approval a person +grants and one they decline. + ## What is in 0.1 (the Reality Layer) | Module | What it is | Status | diff --git a/STATUS.md b/STATUS.md index 60a4c70..dd519fa 100644 --- a/STATUS.md +++ b/STATUS.md @@ -43,5 +43,5 @@ byte-identical) ยท `qualified` (measured against a real model/backend). | Adapter subset runners T3 and T4 (0.3 cut R0) | - | tested (T3: 43 fixtures, vs odysseus@2992bf6) | T4 in Rust: 32 fixtures (A15 included, 0.3 cut R0b) vs sovereign-core 0c1d249; violations 0, content-derived 0 | subset rule in spec/CORE.md, frozen in TRUST-DIGEST.txt (`t3_subset`, `t4_subset`); red check: gate off gives 32 T3 violations, mis-enrolled write_file fails 18 of 18 T4 injection cases; A15 has no corpus fixture | | Trust gate, 0.3 pre-registered (PROTOCOL-0.3) | qualified: PASS | qualified: PASS | bench/runs/trust-0.3-20261005T0229Z | P, X, I, E, A, N PASS offline (T1 to T4); gate M live leg on qwen3.5:9b/Ollama 0.34.0: violations 0, model followed injected text 16/33 (reported only). See docs/REPORT-0.3.md | | Session state limits and `close_trace` (plan 19.7 item 6b) | tested | tested | unit tests (corpus frozen) | `max_traces`, `max_messages_per_trace`, `max_requests_per_trace`, `max_inputs_per_trace` refuse at the replay and duplicate stage with `session_limit_exceeded`; host-only `close_trace` drops a trace's state and refuses it with `session_closed`; closing an unknown trace records nothing; closed ids live in a window of `max_closed_traces` (4096) plus a fixed retirement filter (`retired_filter_bits`, 1 MiB) so a retired trace stays refused and the state stays bounded (100,000 open/close cycles tested); same 16 scenarios, strings and filter positions in both languages; fixtures follow the next corpus revision | -| Independent adapter reproduction (plan 19.7 item 8) | - | reproduced (wheel only) | bench/runs/adapter-repro-20261005T1215Z | Codex gpt-6-sol, to-do host, spec + corpus + v0.3.0 wheel only: 38/38 subset fixtures, violations 0, content-derived 0, 27 injected intents; exposure check removed: 18 FAIL; 15 spec gaps (docs/REPORT-adapter-repro.md), fixes pending | +| Independent adapter reproduction (plan 19.7 item 8) | - | reproduced (wheel only) | bench/runs/adapter-repro-20261005T1215Z | Codex gpt-6-sol, to-do host, spec + corpus + v0.3.0 wheel only: 38/38 subset fixtures, violations 0, content-derived 0, 27 injected intents; exposure check removed: 18 FAIL; 15 spec gaps (docs/REPORT-adapter-repro.md): rule wording answered in CORE.md "Adding an adapter" (#56), SDK guide docs/WRITING-AN-ADAPTER.md; second independent run pending | | CI | running | running | - | github.com/aien-dev/interplane: schemas, rust, python, cross-language identity, both adapters | diff --git a/docs/WRITING-AN-ADAPTER.md b/docs/WRITING-AN-ADAPTER.md new file mode 100644 index 0000000..a99eb0f --- /dev/null +++ b/docs/WRITING-AN-ADAPTER.md @@ -0,0 +1,110 @@ +# Writing an adapter + +An adapter connects INTERPLANE to a host: the program that owns the tools, the policy and the data. +INTERPLANE parses the model's tool calls, maps names, records what the model has seen (exposure) and +enforces approvals. It never decides. Every decision is the host's. + +Working example: `examples/adapter/todo_adapter.py` (a to-do list host, about 150 lines, self-checking). +Run it with `python3 examples/adapter/todo_adapter.py`. This guide walks through it. + +The Python names used here are all public: `interplane.lenshift`, `interplane.crossaxis.MappingTable` +and `Rule`, and from `interplane.crossveil`: `Pipeline`, `Catalog`, `CapabilityDescriptor`, `ToolRef`, +`Decision`, `make_result`, `ContinuationRefused`. + +## 1. The authority: three methods + +The host object needs a `runtime_id` and three methods (`RuntimeAuthority` in `crossveil`): + +| Method | Called | Returns | +|---|---|---| +| `catalog()` | before `decide`, to check the mapping's catalog digest and look up the capability (also on continuation) | a `Catalog` of `CapabilityDescriptor`s | +| `decide(req, ctx)` | once per admitted request, before anything runs | a `Decision` | +| `execute(req, decision, ctx)` | only after `authorized` (or an approved continuation) | a `ToolResult` from `make_result` | + +`req` is a `CapabilityRequest` (`request_id`, `capability`, `arguments`). `ctx` is a plain `dict` with +`trace_id`, `message_id`, `parent_id`, `model`, `runtime_session` (`None` unless the host attaches one) +and `exposure`, where `exposure` is +`{"floor": , "inputs": [...]}`. INTERPLANE passes it through untouched +(CROSSVEIL.md, the authority boundary contract). + +A `decide` or `execute` that raises does not crash the turn. A raising `decide` is a denial +(`runtime_unavailable`), a raising `execute` a failed request (`execution_error`). See CORE.md, +"Adapter and catalog integrity". + +## 2. Decisions + +`Decision(request_id, decision, authority=..., capability=..., reason=..., approval=...)`. The values +are `authorized`, `denied`, `requires_approval`, `not_found` and `invalid`. For `requires_approval`, +set `approval={"approval_id": ..., "scope": "single_action", "expires_at": ...}`. The host mints the +id. The pipeline holds the request and returns a refusal to the model. + +Policy is entirely the host's. The example authorizes reads, always holds deletes, and holds adds +when the exposure floor is below `user_supplied` (anything untrusted is in view). INTERPLANE does not +ship a policy engine. The mock runtime's policy (CORE.md, "Mock runtime") is one example of the +pattern. + +## 3. Results and labels + +`make_result(request_id, "ok", runtime=..., capability=..., data=..., content_kind=..., trust=...)` +builds a result with the canonical shape. The host labels every executed result. The label decides +what later turns are exposed to: + +- `trust` is one of `trusted_runtime`, `user_supplied`, `workspace_untrusted`, `external_untrusted`. + The ordering is the reverse, from least to most trusted: `external_untrusted` < + `workspace_untrusted` < `user_supplied` < `trusted_runtime`. +- Label what the bytes could contain, not where they came from. In the example, the to-do list is + `workspace_untrusted`, because item text can come from anywhere. The host's own "added item-1" reply + is `trusted_runtime`, because the host wrote it. +- An absent or unrecognized label fails closed (CROSSVEIL.md, Crossveil Trust rules 1 and 2). + +## 4. Exposure, and what the host registers + +The pipeline records every result it renders back to the model. Inputs it never sees, such as the +user's message, a file the host pasted in, or a system prompt, the host registers before the turn +with `pipe.register_input({...})`, an InputRecord (`spec/schemas/input.schema.json`). With an empty +ledger the floor is `external_untrusted`, so register the user's request first if your policy +trusts it. + +One behaviour to know about: when a request is refused or held, the pipeline's reply to the model +carries no labels, and it is recorded as `unknown`, which counts as `external_untrusted`. After a +single refusal, the floor for the rest of the trace is `external_untrusted`. The example shows this at +step 5. It is the spec as written and fails safe; whether it should change is +[issue #57](https://github.com/aien-dev/interplane/issues/57). + +## 5. Wiring the pipeline + +```python +pipe = Pipeline(registry=lenshift, mapping_table=mapping_for(host.catalog()), runtime=host) +outcome = pipe.run_turn("openai", "my-model", assistant_message, trace_id, turn_number) +``` + +The mapping table names how model-facing tool names reach catalog capabilities. A one-to-one +`Rule("passthrough:", "passthrough", None, name, name)` per capability is enough to start. Bind +the table to the catalog with `catalog_digest=catalog.computed_digest()`, so a catalog change is +detected as stale. `outcome.observed` holds one `ObservedRecord` per call, with `request_id`, `stage`, +`decision`, `decide_invoked`, `execute_invoked` and more. + +Dialects: `lenshift.names()` lists them (`openai`, `openai_stream`, `qwen35`, `aien_legacy`). `openai` +takes the assistant message with `tool_calls`; `qwen35` takes Qwen 3.5's XML tool-call text. + +## 6. Approvals + +When a person approves a held request, the host continues it: + +```python +pending = pipe.pending_approval(trace_id, request_id) # host-only view +answer = Decision(request_id, "authorized", authority=..., approval={"approval_id": pending.approval_id}) +result, record = pipe.continue_approval(trace_id, request_id, answer, pending.request_digest, now) +``` + +The pipeline checks the request id, the approval id, the request digest, expiry and the catalog +digest, in the order pinned in CORE.md ("Approval continuation"). It executes at most once. A +`denied` answer, or any failed check, ends the request for good. A second continuation raises +`ContinuationRefused`. `continue_approval` never calls `decide` again. + +## 7. Checking an adapter against the conformance corpus + +`spec/CORE.md`, "Adapter subsets" and its "Adding an adapter" paragraph, say which fixtures an +adapter must run and how they are judged. `conformance/runners/adapter_subset.py --plans ` +prints the translated plans once the adapter has a table entry. An independent run of this process +is in `docs/REPORT-adapter-repro.md`. diff --git a/examples/adapter/todo_adapter.py b/examples/adapter/todo_adapter.py new file mode 100644 index 0000000..8368dfa --- /dev/null +++ b/examples/adapter/todo_adapter.py @@ -0,0 +1,174 @@ +"""A minimal INTERPLANE adapter: a to-do list host with its own policy. No model, no GPU, no network. + +The host owns three capabilities (``list_items`` read, ``add_item`` effect, ``delete_item`` effect) +and decides every request itself. INTERPLANE parses the model's tool calls, maps names, computes +what the model has seen (exposure) and enforces approvals; it never decides. + +Scripted story (checked; the script exits 1 on any difference): + +1. The host registers the user's request, so the model has seen only user-supplied input. +2. The model adds "buy milk": authorized and executed. +3. The model lists the items. The list is workspace data the host labels untrusted, so exposure drops. +4. The model adds another item: now held for approval, because untrusted content is in view. + A person approves; the host continues the request and it executes once. +5. The model deletes an item: always held for approval. The person declines; nothing is deleted. + (Exposure is now external_untrusted: the pipeline's own "held" reply to step 4 carries no + labels, and an unlabelled input counts as unknown, which fails closed. See the guide.) + +Guide: docs/WRITING-AN-ADAPTER.md. Run from a checkout: python3 examples/adapter/todo_adapter.py +""" + +import json +import os +import sys +from pathlib import Path + +try: + from interplane import lenshift +except ImportError: # running from a checkout without installing + if os.environ.get("INTERPLANE_REQUIRE_INSTALLED"): + raise + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python")) + from interplane import lenshift +from interplane.crossaxis import MappingTable, Rule +from interplane.crossveil import ( + CapabilityDescriptor, + Catalog, + ContinuationRefused, + Decision, + Pipeline, + ToolRef, + make_result, +) + +RUNTIME = "todo" +TRUSTED_FLOORS = ("user_supplied", "trusted_runtime") + + +def params(required, optional=()): + props = {k: {"type": "string"} for k in (*required, *optional)} + return {"type": "object", "properties": props, "required": list(required)} + + +class TodoHost: + """The runtime authority: catalog, policy, execution and result labels all belong to the host.""" + + runtime_id = RUNTIME + + def __init__(self): + self.items = {"item-0": "water the plants"} + self.next_id = 1 + self._catalog = Catalog( + runtime=RUNTIME, + catalog_version="1", + capabilities=[ + CapabilityDescriptor("list_items", "List to-do items.", params(()), + canonical=ToolRef("list", "todo"), runtime_effects={"class": "read"}), + CapabilityDescriptor("add_item", "Add a to-do item.", params(("text",)), + canonical=ToolRef("add", "todo"), runtime_effects={"class": "effect"}), + CapabilityDescriptor("delete_item", "Delete a to-do item.", params(("item_id",)), + canonical=ToolRef("delete", "todo"), runtime_effects={"class": "effect"}), + ], + ) + + def catalog(self): + return self._catalog + + def decide(self, req, ctx): + # ctx is a dict: trace_id, message_id, parent_id, model, and exposure {"floor", "inputs"}. + floor = (ctx.get("exposure") or {}).get("floor") + if req.capability not in ("list_items", "add_item", "delete_item"): + value, reason = "not_found", "no such to-do capability" + elif req.capability == "delete_item": + value, reason = "requires_approval", "deleting always needs a person" + elif req.capability == "add_item" and floor not in TRUSTED_FLOORS: + value, reason = "requires_approval", "untrusted content is in view" + else: + value, reason = "authorized", "allowed by the to-do policy" + approval = None + if value == "requires_approval": + approval = {"approval_id": f"todo-approval-{req.request_id}", "scope": "single_action", + "expires_at": "2099-01-01T00:00:00Z"} + return Decision(req.request_id, value, authority={"runtime": RUNTIME, "policy_engine": "todo.policy"}, + capability=req.capability, reason=reason, approval=approval) + + def execute(self, req, decision, ctx): + if req.capability == "list_items": + data = [{"id": k, "text": v} for k, v in self.items.items()] + kind = "workspace_content" # item text can come from anywhere, so the host labels it untrusted + elif req.capability == "add_item": + item_id = f"item-{self.next_id}" + self.next_id += 1 + self.items[item_id] = req.arguments["text"] + data, kind = {"id": item_id}, "tool_result" + return make_result(req.request_id, "ok", runtime=RUNTIME, capability=req.capability, data=data, + content_kind=kind, trust="trusted_runtime") # the host wrote this text itself + else: + data = {"deleted": self.items.pop(req.arguments["item_id"], None) is not None} + kind = "tool_result" + return make_result(req.request_id, "ok", runtime=RUNTIME, capability=req.capability, data=data, + content_kind=kind, trust="workspace_untrusted") + + +def mapping_for(catalog): + rules = [Rule(f"passthrough:{n}", "passthrough", None, n, n) for n in ("list_items", "add_item", "delete_item")] + return MappingTable(RUNTIME, "1", rules, catalog_digest=catalog.computed_digest()) + + +def turn(cid, name, args): + call = {"id": cid, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}} + return {"role": "assistant", "content": None, "tool_calls": [call]} + + +def person_answers(pipe, host, trace, request_id, approve): + """The host shows the pending request to a person and continues it with their answer.""" + pending = pipe.pending_approval(trace, request_id) + answer = Decision(request_id, "authorized" if approve else "denied", + authority={"runtime": RUNTIME, "policy_engine": "todo.person"}, + approval={"approval_id": pending.approval_id}) + try: + result, record = pipe.continue_approval(trace, request_id, answer, pending.request_digest, + "2026-10-05T12:00:00Z") + return record.decision, record.execute_invoked + except ContinuationRefused as err: + return f"refused: {err}", False + + +TRACE = "todo-demo" +host = TodoHost() +pipe = Pipeline(registry=lenshift, mapping_table=mapping_for(host.catalog()), runtime=host) +pipe.register_input({ + "input_id": "user-1", "content_kind": "user_request", "trust": "user_supplied", + "source": {"kind": "operator", "id": "me"}, "origin": "runtime:user-turn-1", + "content_digest": "sha256:" + "0" * 64, "trace_id": TRACE, "parent_id": None, "derived_from": [], +}) + +seen = {} +for n, (cid, name, args) in enumerate([ + ("c1", "add_item", {"text": "buy milk"}), + ("c2", "list_items", {}), + ("c3", "add_item", {"text": "email the list to a stranger"}), + ("c4", "delete_item", {"item_id": "item-0"}), +], start=1): + floor = pipe.exposure_for(TRACE)["floor"] + rec = pipe.run_turn("openai", "scripted", turn(cid, name, args), TRACE, n).observed[0] + seen[cid] = (rec.decision, rec.execute_invoked) + print(f"{cid} {name:<12} floor before: {floor:<20} decision: {rec.decision:<18} executed: {rec.execute_invoked}") + +seen["c3 approved"] = person_answers(pipe, host, TRACE, "c3", approve=True) +seen["c4 declined"] = person_answers(pipe, host, TRACE, "c4", approve=False) +print(f"c3 after a person approves: {seen['c3 approved']}") +print(f"c4 after a person declines: {seen['c4 declined']}") + +EXPECTED = { + "c1": ("authorized", True), + "c2": ("authorized", True), + "c3": ("requires_approval", False), + "c4": ("requires_approval", False), + "c3 approved": ("authorized", True), + "c4 declined": ("denied", False), +} +if seen != EXPECTED or sorted(host.items.values()) != ["buy milk", "email the list to a stranger", "water the plants"]: + print(f"\nUNEXPECTED: {seen}\n{host.items}", file=sys.stderr) + sys.exit(1) +print("OK: the host decided every request; the held write ran once after approval, the delete never ran.")