# Policy gate example

The full pattern is [PATTERN.md](PATTERN.md). The effect is first: the protected text is committed before the model runs, the model may read it and return a proposal, and the proposal may not replace those bytes. The agent and any later service accept only when those bytes still match and the action is inside the committed policy. The three objects are the committed input, the untrusted proposal, and the receipt. The two sites are the agent on the reply and the destination before create, read, modify, or delete. The destination does not trust the agent allow flag.

`eni6ma-policy-gate-example` signs a policy object and a prompt with the vendored ID4 circuit. The agent checks that proof, then accepts or rejects a scripted model action. The local HTML console shows the payload, the model reply, the agent action, and the ledger row.

## Circuit

The crate depends on `vendor/eni6ma-id4-auto`. `validate_policy_gate(request_hash)` opens `vendor/sealed/policy-gate.blob`, runs the auto-prover, and runs the verifier in `vendor/eni6ma-response-verifier`. The seal is ID4-class, colour class six, one 12-character secret. The challenge has 12 rounds. The proof `bearings` array has length 12. `circuit_hash` is SHA-256 of `policy-gate.blob`. The wallet-compare seal is five groups of 12 characters. This folder does not include that `circuit.blob` and does not mint a seed. `bind.rs` and `tx.rs` in the vendored crate hash Bitcoin `vin` and `vout` for the wallet-compare demo. This example does not pass those fields and does not expose that demo as a second product.

On 2026-11-23, `cargo run --bin gate` printed:

```text
circuit_hash=c41a3e7f0dc7caae542624e95157f7bf4edfd6a2384c0ce2b98ecae332334616
```

## Signed payload

Canonical JSON matches `eni6ma-id4-auto` `src/canon.rs`: object keys are sorted, and the separators are a comma and a colon with no extra space.

The hashed body has six fields:

- `method`: `llm_apply`
- `endpoint_id`: `document-store` from the policy
- `policy`: default deny, executable `apply_patch`, upstream and downstream endpoint `document-store`, mutable region `exhibit_summary`, immutable regions `signature_page` and `clause_4`, `max_patch_bytes` 256
- `prompt`: the exact string in `fixtures/prompt.txt`
- `tau`: application tau for the case
- `nonce_uuid`: application nonce for the case

`request_hash` is SHA-256 of that canonical body. The ledger row stores `base64` of the canonical policy, `policy_hash` as SHA-256 of those bytes, and the proof fields `circuit_hash`, `tau`, `nonce_uuid`, `status`, `request_hash`, `proof_hash`, `bearings`, `prime_shard`, and `Y`.

`validate` derives the proof `tau` and `nonce_uuid` from `request_hash`. The payload `tau` and `nonce_uuid` are the application values. The agent burns the application nonce. The proof covers the request hash. The proof does not cover the model reply.

## Gate

The agent accepts the stored row when all three checks hold:

1. The decoded policy bytes rehash to `policy_hash`.
2. `policy_hash` equals SHA-256 of the canonical `body.policy`.
3. `validate_policy_gate(request_hash)` returns `Y = 1` and 12 bearings for that same `request_hash`.

The agent then matches the action to the policy. Default is deny. The executable must be listed. The endpoint must be listed as both an upstream endpoint and a downstream endpoint. The region must be mutable. Immutable region text in the signed prompt must still match the document. The replacement length must be within `max_patch_bytes`.

A passing action writes `exhibit_summary`, marks the nonce `SPENT`, and stamps `accept`. A rule failure marks the nonce `SPENT`, leaves the document unchanged, and stamps `reject`. A policy or prompt mismatch stamps `reject` and leaves the nonce `RESERVED`. A second submit of a `SPENT` nonce stamps `reject` and does not apply the patch again.

There is no HMAC. Each scripted reply is a fixed proposal in the case list. `cargo run --bin serve` sends the submitted policy and prompt to the xAI Chat Completions API, then runs the same checks on the returned proposal. `request_hash` covers the policy and the prompt. The model reply stays outside that hash.

## Cases

| Case | Action | Stamp | Nonce after the decision |
| --- | --- | --- | --- |
| `allowed_patch` | `apply_patch` on `exhibit_summary` at `document-store` | accept | SPENT |
| `hallucinated_call` | executable `run_shell` and endpoint `billing-export` | reject | SPENT |
| `immutable_region` | patch region `clause_4` | reject | SPENT |
| `direct_forbidden` | empty model reply, endpoint `wire-export` | reject | SPENT |
| `tampered_policy` | ledger `policy_b64` changed to `default: allow` | reject | RESERVED |
| `nonce_replay` | same nonce as `allowed_patch` | reject | SPENT |

`cargo test` also checks a prompt that differs from the signed prompt (`request_hash_mismatch`, nonce `RESERVED`) and an `apply_patch` call to `billing-export` (`endpoint_denied`, nonce `SPENT`).

## Run

From this directory:

```text
cargo test
cargo run --bin console
```

`cargo run --bin console` writes `console/index.html` and `ledger.json`. The page lists every case, including the reject cases, and shows one case at a time in four panels: Payload, Model reply, Agent action, Ledger. That page does not call a model. The page does not contain phi or the sealed secret units.

`cargo run --bin gate` prints `circuit_hash` and one decision line per case.

## Interactive server

From this directory:

```text
cargo run --bin serve
```

On this branch `cargo run --bin serve` is the Wasmer HTTP handler. It reads one CGI request from the environment and stdin, then writes one CGI response to stdout. It does not bind `127.0.0.1:8787`. The native tests still open a loopback socket through `RunningGate`. `GET /` from that test socket returns the policy strip, the model line, the policy and prompt fields, and a ledger table. The Edge `GET /` returns the static export in `web/out` when that file is present.

The policy field is a textarea, `id="policy"`, prefilled with `fixtures/policy.json`. The prompt field is a second textarea. The policy strip shows the policy parsed from that field while the field is edited, and the last submitted policy after Submit or Inject. On a fresh process the strip matches the fixture: default deny, executable `apply_patch`, upstream and downstream `document-store`, mutable `exhibit_summary`, immutable `signature_page` and `clause_4`, `max_patch_bytes` 256, plus `policy_hash` and `circuit_hash`.

The model line shows `GROK_MODEL` or `grok-4`.

The action band has Submit, Inject 5 passes, and Inject 9 rejects.

The ledger table lists history oldest first. Columns: pass or fail mark (`PASS` or `FAIL`), case id, prompt hash (first 12 hex characters), request hash (first 12), model id, decision, reason, nonce status. Each row has an expander. The expander shows the payload, the model reply, the agent action, the ledger metadata, and the check list. The checks, in order, are policy hash, prompt hash, request hash, circuit Y, executable, endpoint, region, size, and nonce. The first failed check is the stamp reason. The row stores the full prompt hash and the full request hash.

`POST /submit` reads a canonical `http6-w1-00` body: profile, operation id, record id, action, resource, purpose, content digest, root receipt `r-income`, grant `g-income`, policy, prompt, and file. The request also carries `Content-Digest` and one HTTP message signature over method, target, content digest, profile, operation id, record id, action, resource, and purpose. Unknown members and noncanonical bytes are rejected. The server still signs the policy plus the prompt with `signed_body` and runs the same nine checks. The history row stores them on `ledger.checks` as `{ "name", "pass" }`. `pass` is true for PASS and false for FAIL. The first FAIL is `agent_action.reason` and `ledger.reason`. A proposal that satisfies every check and the grant stores nine PASS results and reason `allow`, and the response `w1` object is an outcome. A proposal outside grant `g-income` (`infer` on `document-store`) stores reason `grant_denied` and a closure. The model reply stays outside `request_hash`. The circuit proof stays bound to `request_hash`. TLS 1.3 is a front door in front of this listener. This listener does not implement a TLS stack.

The server calls `POST https://api.x.ai/v1/chat/completions`. Submit uses Grok. `POST /submit` does not open a socket to `api.openai.com`. The key is read once at process start from the environment. `XAI_API_KEY` is the name. `GROK_API` is the fallback name in that same environment. The process does not read the key from a file. The key is not compiled into the binary, not written into the HTML, and not written into JSON responses or `console/history.json`. When the key is missing, Submit appends a reject row with reason `grok_unavailable` and does not open a socket to the API.

The system instruction tells the model to return one JSON object with `executable`, `endpoint_id`, `region`, `replacement`, and `policy_hash`. `policy_hash` is the hash of the policy in the user message. The model may copy that policy object into `policy`. The gate does not treat the model policy object or the echoed hash as authority. Immutable regions and any secured reference block in the prompt, for example a financial statement, are reference material and must not be the modification target.

After the API returns, the server parses the proposal. `confine_reply` keeps `executable`, `endpoint_id`, `region`, and `replacement`, then scans the raw completion for each protected span name. When the text after that name differs from the committed span, the row stamps `protected_span_mismatch`, stores `raw_completion`, and does not write. The server then runs the existing checks against the submitted policy: executable, endpoint, immutable region, mutable region, `max_patch_bytes`, and immutable text in the prompt still matching the document. A block marked `[[secured NAME]]` ... `[[end secured]]`, or a line `secured NAME: ...`, is a secured reference. A proposal whose `region` is that name, an immutable region, or `secured` stamps `immutable_region`. Accept calls `destination_apply`, which writes only a mutable region named by the policy. In the fixture that region is `exhibit_summary`. The secured reference text stays in the prompt and is left out of the document. `destination_apply` calls `verify_receipt` again and does not read `agent_action.decision`. An executable absent from the committed policy does not change the document.

The history row stores the committed policy object, `policy_b64`, the committed `policy_hash`, `model_policy`, `model_policy_hash`, `policy_hash_comparison` (`match`, `mismatch`, or `absent`), `prompt_hash`, `protected_span_hashes`, `expected_action`, `broken_clause`, `request_hash`, `application_tau`, `application_nonce`, the model id, and the per-check list. `expected_action` is the allowed executable, the allowed endpoint, and the mutable region. `broken_clause` is `executables`, `endpoints`, `immutable_regions`, `max_patch_bytes`, or the span name. A pass leaves `broken_clause` empty. `protected_span_hashes` maps each immutable region and each secured span to SHA-256 of its committed text. The agent stores that map before the model call. After the proposal returns, a difference between those hashes and the document fails the region check and does not write. The expander shows the committed policy, the committed policy hash, the model policy, the comparison, the prompt hash, the request hash, and the check list. An echoed policy hash that differs from the committed hash fails the policy hash check. A reply that is not the JSON object appends `proposal_parse` and does not call `validate`. A transport failure appends `grok_unavailable` and does not call `validate`. An HTTP error appends `grok_http_<status>:<code>` (the error type when the code is empty) and stores `http_status`, `error_type`, and `error_code` on `model_reply`. The error message is not stored.

`POST /inject` reads `{ "set": "pass" }`, `{ "set": "reject" }`, or `{ "set": "examples" }`. When the body includes `policy` as an object or JSON string, `pass` and `reject` sign that policy. `examples` signs the catalog policy for each case, and uses the posted policy for `synthetic-violate-prompt`. When `policy` is omitted or blank, the server uses `fixtures/policy.json`. Inject does not call xAI. The model id on those rows stays `synthetic`. Each row gets its own nonce.

Pass ids are `synthetic-pass-1` through `synthetic-pass-5`: `apply_patch` on `exhibit_summary` at `document-store`, with five different exhibit sentences under 256 bytes. Reject ids are one row per gate: `synthetic-reject-policy-hash` (`policy_hash_mismatch`), `synthetic-reject-prompt-hash` (`prompt_hash_mismatch`), `synthetic-reject-request-hash` (`request_hash_mismatch`), `synthetic-reject-circuit-y` (`proof_rejected`), `synthetic-reject-executable` (`executable_denied`), `synthetic-reject-endpoint` (`endpoint_denied`), `synthetic-reject-region` (`immutable_region`), `synthetic-reject-size` (`patch_too_large`), `synthetic-reject-nonce` (`nonce_spent`). Each reject row has that gate as FAIL and the earlier gates as PASS. The document changes only on the five passes, and only in the mutable region.

`examples` ids are `synthetic-document-pass`, `synthetic-code-read-pass`, `synthetic-code-read-file-reject`, `synthetic-code-write-pass`, `synthetic-code-write-host-reject`, `synthetic-policy-hash-mismatch`, `synthetic-violate-prompt`, `synthetic-statement-pass`, and `synthetic-statement-reject`. `synthetic-statement-pass` writes only `inference_note` under the income-statement policy. `synthetic-statement-reject` targets the secured `income_statement` span and leaves that span hash unchanged. `synthetic-code-read-pass` is `http_get` of a GitHub page into `fetch_body`. `synthetic-code-read-file-reject` targets `src/main.rs` under code-read and stamps `immutable_region`. `synthetic-code-write-pass` patches `src/main.rs` at `workspace`. `synthetic-code-write-host-reject` uses endpoint `github.com` under code-write and stamps `endpoint_denied`. `synthetic-policy-hash-mismatch` echoes the code-read policy hash against the committed document-edit hash. That comparison is `mismatch` and the policy hash check is FAIL. The gate still checks the committed policy. `synthetic-violate-prompt` tells the model to break the posted policy. When the posted policy is document-edit, the proposal targets `clause_4` and the echoed hash matches the committed hash, so the stamp reason is `immutable_region`.

The server keeps one ledger in memory for the process. At startup it reads `console/history.json`. Each result, including a reject, is appended to that file. A later process reads the file and sets `prior_process` on those rows. The new process starts a new nonce table and a new document from `fixtures/prompt.txt`. `POST /reset` clears that in-memory history, the nonce table, and `apply_count`, restores the document from the prompt and policy loaded at process start, and writes `[]` to `console/history.json`. The Ledger tab button Clear ledger sends that POST after `window.confirm`. Fixtures and policy definitions stay on disk.

| Variable | Role |
| --- | --- |
| `XAI_API_KEY` | Bearer credential for xAI Chat Completions. Read at process start from the environment. On Wasmer this name is an app secret. It is not a file in the package. A missing key appends `grok_unavailable` and skips the network. |
| `GROK_API` | Fallback bearer credential when `XAI_API_KEY` is empty. Read from the environment. |
| `GROK_MODEL` | Model id sent to xAI and stored on live submit rows. The default is `grok-4`. |
| `PORT` | TCP port for `serve`. Unset on wasm: 80. Unset on native: 8787. |

`submit_prompt` allocates a new `nonce_uuid` and `tau`, signs the submitted policy plus the submitted prompt, and calls `validate_policy_gate(request_hash)`. Allow calls `destination_apply`, which writes the replacement into the named mutable region, and stamps accept. The agent calls `verify_receipt` before that call. `destination_apply` calls `verify_receipt` again. A rule failure stamps reject and marks the nonce `SPENT`. The prompt hash is SHA-256 of the prompt bytes.

`POST /verify` reads `{ "receipt", "policy", "prompt", "proposal" }`. `policy` is the presented policy bytes as a JSON object or a JSON string. The handler calls `verify_receipt` and returns `{ "pass", "reason", "checks" }`. The check list covers `policy_hash`, `prompt_hash`, `protected_span_hashes`, `request_hash`, `circuit_y`, `executable`, `endpoint`, `region`, and `size`. The handler does not read `agent_action.decision`.

The six scripted cases stay on `cargo run --bin console` and `cargo run --bin gate`. Those commands do not call xAI and do not write `console/history.json`. `console/index.html` remains the static four-panel report.

## Themed UI

`web/` is a Next.js app on one page. Tabs are Analysis, Policy and prompt, and Ledger. Analysis is the landing view. `/?tab=instructions` and `/?tab=analysis` open Analysis. Analysis opens with Pattern, then How to operate, What each result means, and Flow. Pattern follows [PATTERN.md](PATTERN.md): effect, three objects, two sites, then the catalog of hashes, policies, resource verbs, and stamps. The Policy and prompt tab lists `document-edit`, `code-read`, `code-write`, and `income-statement`, and an Example selector. Choosing `income-statement` fills the policy, the prompt, and the file. The file bytes are the secured `income_statement` span inside that prompt. Submit sends that policy and that prompt. The Agent action tab shows three lines: expected action, actual proposal, and broken clause. The page uses Material Dashboard cards, buttons, and table cells. The page omits the theme drawer. `/policy` and `/prompt` redirect to `/?tab=request`. `/ledger` redirects to `/?tab=ledger`. A ledger row expander shows one tab at a time: Payload, Model reply, Agent action, Hashes, and Checks. Hashes shows the full `policy_hash`, `prompt_hash`, `request_hash`, and `protected_span_hashes`, the committed policy, and the policy object echoed by the model when that field is present.

Start the API from this directory. The native process listens on `127.0.0.1:8787` when `PORT` is unset.

```text
cargo run --bin serve
```

The Edge page is the static export. `GET /` returns `web/out/index.html`. `POST /submit` sends the `http6-w1-00` body to the same origin, with `Content-Digest`, `Signature-Input`, and `Signature`. `POST /inject` sends `{ "set": "examples" }` with the selected policy object. The page and the JSON responses do not contain `XAI_API_KEY` or `GROK_API`.

`npm run dev` is not the Edge process. Build the static export from `web/` with `npm install` and `npm run build`. The export is `web/out`.

## Wasmer

The app kind is `wasmer.io/App.v0`. The published package name is `soltrinox/policy-gate-example`. `app.yaml` carries the kind, sets `owner` to `soltrinox`, and sets `package` to `.`. Deploy reads the local `wasmer.toml` for that package name. A `package` value that repeats the `wasmer.toml` name is rejected as deprecated deploy behaviour. `wasmer.toml` carries the package, the `wasm32-wasmer-wasi` module, the WASI runner, and the `/public` mount of `web/out`. The serve process binds `127.0.0.1` and reads `PORT`. On wasm the unset default is 80. Wasmer Edge proxies HTTP to that socket. The handler reads the request from the TCP stream. It does not read `REQUEST_METHOD`. The package owner is the active registry user from `wasmer whoami`. This branch does not use the `eni6ma` namespace.

Build the static UI, then the Wasm package, from this directory:

```text
cd web
npm install
npm run build
cd ..
RUSTC="$(rustup which --toolchain wasix rustc)" cargo build --release --bin serve --target wasm32-wasmer-wasi
```

That command writes `target/wasm32-wasmer-wasi/release/serve.wasm`. `cargo wasix build` rewrites `.cargo/config.toml` so crates.io resolves through the WASIX registry, then fails: the active `wasix` toolchain has `rustc` and no `cargo`, and the fallback host `cargo` cannot select locked `libc` 0.2.191 from that registry. Point `RUSTC` at the `wasix` toolchain and keep crates.io.

`POST /submit` uses one HTTPS client on the native target and on `wasm32-wasmer-wasi`. The client is rustls 0.23.22 with the `rustls-rustcrypto` provider. That provider is pure Rust and does not link `ring` 0.17. The module does not depend on `ureq`. When `XAI_API_KEY` is set, the client sends `POST https://api.x.ai/v1/chat/completions` with that bearer credential. When the key is absent, Submit appends `grok_unavailable` and does not open a socket. A transport failure also appends `grok_unavailable`. An HTTP status outside 200-299 appends `grok_http_<status>:<code>`. The client error text does not include the key.

The Grok key is the Wasmer app secret `XAI_API_KEY`. It is not a file in the package. After the app exists, set it with:

```text
wasmer app secret create --app soltrinox/policy-gate-example --non-interactive XAI_API_KEY
```

Pass the secret value as the next argument, or omit the value and use the prompt. Do not commit the value.

Deploy publishes the package and creates the Edge app:

```text
wasmer deploy --non-interactive --publish-package
```

`wasmer whoami` prints the active registry user. `app.yaml` `owner` and the `wasmer.toml` package owner must be that user. On this branch the user is `soltrinox`. A deploy whose owner is a namespace the active user cannot access stops before publish and does not return a URL.

A local `GET /` runs the Wasm module as an HTTP server. Map `web/out` to `/public` and set `PORT`:

```text
wasmer run --volume "$PWD/web/out:/public" --env PORT=8787 ./target/wasm32-wasmer-wasi/release/serve.wasm
```

`GET http://127.0.0.1:8787/` returns HTTP 200. The body contains `Policy gate`.
