Metadata-Version: 2.4
Name: quaspar-shield-core
Version: 0.12.0b1
Summary: Local per-agent request filtering, file screening, isolated workers, and one host-owned text connector
License-Expression: Apache-2.0
Project-URL: Homepage, https://quaspar.com
Project-URL: Security, https://quaspar.com/security
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=46
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == "mcp"
Provides-Extra: langgraph
Requires-Dist: langgraph<2,>=0.2; extra == "langgraph"
Requires-Dist: langchain-core<2,>=0.3; extra == "langgraph"
Requires-Dist: pydantic<3,>=2; extra == "langgraph"
Provides-Extra: openai
Requires-Dist: openai-agents<1,>=0.6; extra == "openai"
Dynamic: license-file

# Charavyuha by Quaspar

Charavyuha is an Apache-2.0 Python library for controlling which signed requests reach your agent. A trusted host enrolls senders, defines the exact work each may do, and runs your handler only after the checks pass. Routine authorized work needs zero review prompts. The optional native worker runs a compatible Python file in an isolated Linux process.

## Install and try the signed inbox

Requires Python 3.11 or newer (tested on 3.11, 3.12 and 3.13). This is a local, single-host beta, not a production or distributed security service. No account, model API key or scanner is needed for this synthetic example.

**Linux or macOS**

```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install quaspar-shield-core==0.12.0b1
quaspar-shield inbox
```

**Windows PowerShell**

```powershell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install quaspar-shield-core==0.12.0b1
.\.venv\Scripts\quaspar-shield.exe inbox
```

These PyPI commands apply after 0.12.0b1 is published. Until then install the released 0.11.0b1 or a reviewed candidate wheel. Two authorized synthetic jobs are delivered; an unknown sender, duplicate request and over-budget request are refused. These are expected security decisions.

Protected credential commands and downstream MCP servers require non-root Linux, bubblewrap and permitted unprivileged user namespaces. Windows and macOS provide the portable inbox, not equivalent process isolation.

Versioned documentation for this candidate is in [docs/0.12.0b1/](docs/0.12.0b1/index.html). The onboarding candidate remains [docs/0.11.0b2/](docs/0.11.0b2/index.html). The published 0.11.0b1 release stays at [docs/0.11.0b1/](docs/0.11.0b1/index.html). `quaspar-shield doctor` names a missing MCP SDK and the separate LangGraph and OpenAI extras. `quaspar-shield audit` reports journal decisions, completion holds, and live receipts. Those counts do not change the configured limit.

## Five-minute protected Linux quickstart

On a supported non-root Linux host, install the prerequisites (Debian/Ubuntu: python3, python3-venv, bubblewrap, util-linux, libseccomp2) and activate a virtual environment. If the host prohibits user namespaces, use an approved compatible environment, not an insecure opt-out.

```sh
python -m pip install "quaspar-shield-core[mcp]==0.12.0b1"
quaspar-shield scaffold ./sample-agent
quaspar-shield doctor --config ./sample-agent/shield.yaml
quaspar-shield audit --config ./sample-agent/shield.yaml
python ./sample-agent/sample_agent.py ./sample-agent/shield.yaml
```

Scaffold creates the configuration, runner, checkpoint and ledger keys. Use a new empty directory for each disposable sample run. The example generates a fresh agent key; a real integration must retain enrolled identities and keys securely. Keep state, witness and keys outside worker mounts.

Optional extras: `mcp`, `langgraph`, `openai`. The base install lacks MCP; CrewAI is not a public extra. A missing human approval returns control to the application. `DurableApprovals` is an optional directory for that pending intent. It does not block a worker and it does not keep an execution reserved while the reviewer is away. An expired signed request still needs a new signature and a new approval. One authorization cannot be reused for a different intent. After a restart, reconciliation reads authenticated execution receipts from the journal bound to that directory, including archived history. A claim is released only when no receipt exists in that journal and no live worker still holds it. Another journal, including one recreated at the same path, is refused. An uncertain effect is not retried. `quaspar-shield recover-approvals` is the operator repair for an interrupted approval transaction; it does not execute a tool. A side-effecting timeout is an uncertain effect. A result withheld after the handler ran stays withheld. This candidate is a local single-host protected Linux deployment. One directory binds one journal. A few thousand authorizations is the practical size of that directory. It is not production-ready and it is not universal exactly-once execution. `ToolDenied.failure` is the machine-readable refusal. It does not include arguments or credentials. `ExternalEffects` commits a host idempotency key before an external call and does not repeat that key, including after a database rollback. A duplicate or unavailable provider answer does not complete the Shield journal. The provider must honor the key; this library does not claim universal exactly-once execution. The application keeps its own workflow checkpoint; this library does not store a Python stack frame. A later mission version is an operator-signed amendment. It keeps spent budget and an unresolved execution, and an agent cannot use it to widen the contract.

### Durable approvals: upgrade and recovery warnings

**Upgrade from 0.11.0b1.** An existing 0.11.0b1 Shield tool journal continues to work for direct Shield calls in 0.12.0b1, but it cannot back `DurableApprovals`: it lacks the authenticated journal instance id required for approval binding. Submitting an intent can succeed before approval is refused. To use durable approvals, create a **new journal with 0.12** using a separate configuration and fresh state and witness locations, then bind a new approval directory to it. Retain the original journal, keys and evidence; do not delete or reinitialize the original journal in place. This is not a migration of existing approval or execution history.

**Backup restore safety.** Joint restoration of the approval database, published head and freshness witness is undetectable. A jointly restored approval directory, or an ambiguous R3 rollback accepted with `recover-approvals`, can make a previously completed intent appear approved again. After the original authorization expires, refreshing it with a new signed request and reviewer approval can cause the external action to **run a second time**, even while the original bound Shield journal retains the completed receipt. **Do not run `recover-approvals` after restoring an approval directory from a backup.** Use recovery only for a known interruption of the current, non-restored directory with its original bound journal. If state was restored or its provenance is uncertain, stop dispatch and refresh, retain the existing evidence, and reconcile outstanding effects with the provider and operator before considering further actions. Never treat a missing approval record or a fresh authorization as proof that the original action did not occur.

## Run your first isolated worker on Linux

The native profile supports 64-bit x86 Linux with Debian-style system Python. On Debian or Ubuntu the relevant packages are `python3`, `python3-venv`, `bubblewrap`, `util-linux` and `libseccomp2`. Your host policy must allow bubblewrap to create user and network namespaces. A Linux VM with those prerequisites is an option for developers who use another operating system.

```sh
quaspar-shield
```

This verifies the native sandbox and runs the bundled worker on a synthetic note. A successful job reports an automatic decision, zero review prompts and one local fixture exchange. Your agent can make its first protected run without sending a prompt to an external provider. Use `quaspar-shield doctor` to diagnose host prerequisites.

To start from an editable worker, run the following commands anywhere you can write. Open `my_agent.py` to change how it handles the supplied note and response, and run the second command again. The host supplies the attachment and holds the connector credential.

```sh
quaspar-shield init my_agent.py
quaspar-shield quickstart --agent my_agent.py
```

The native model host snapshots the worker once per job. Both stages execute those bytes, even if a deployment replaces the file while the job is running. For an approved deployment, record the reviewed worker's SHA-256 with its release in trusted host configuration. The following command reads that independently provisioned value from the environment. A mismatch refuses the job before its model worker or connector runs.

```sh
quaspar-shield quickstart --agent my_agent.py --worker-sha256 "${APPROVED_WORKER_SHA256:?Set the reviewed release digest}" --json
```

Pinning is optional for local editing. The Python host accepts the same value in `NoteModelHost(..., expected_worker_sha256=...)` with its native worker. A pin authenticates the selected code against a reviewed release. The host continues to treat the text it produces as untrusted.

## Connect your existing agent

Keep a receiver in the trusted process that owns the action. Route incoming signed requests to its `dispatch` method. The handler below reads an assigned note. In your host, replace that handler with the corresponding agent operation. Enroll the sender’s public key in advance and deliver the receiver’s audience to that sender over your trusted setup channel.

```python
import json

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from quaspar_shield import Action, sign_action
from quaspar_shield.firewall_ingress import ReceiverGate

# This runnable example creates the sender's key locally. In deployment,
# the sender keeps its private key and the host enrolls only the public key.
sender = Ed25519PrivateKey.generate()
notes = {"daily-note": "The blue folder is on the second shelf."}
job = Action("my-org", "scheduler", "daily", "note.read", "daily-note", "my-agent")
gate = ReceiverGate(
    receiver="my-agent",
    tenant="my-org",
    sender_keys={"scheduler": sender.public_key()},
    allowed_actions=[job],
    handler=lambda approved: notes[approved.resource],
)
signed_request = sign_action(job, sender, audience=gate.audience)
print(gate.dispatch(json.dumps(signed_request)))
```

Every path to this protected operation needs to pass through the gate. The basic inbox uses process-local state. The optional durable configuration below shares replay and admission records between processes on one host. Native worker isolation and attachment scanning each require their own host integration. The managed Quaspar service and its private controls are separate from this SDK.

## Protect a configured tool

`Shield.from_config` loads an operator-owned file. Routine tools run after a signed authorization and need no review prompt. Sensitive tools need a second signature from the configured reviewer. Prohibited tools do not run. A tool result, model reply, or MCP description cannot enroll a key, change the pinned schema, or authorize another tool.

```python
import time

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

from quaspar_shield import Shield
from quaspar_shield.sample_tools import read_document

shield = Shield.from_config("shield.yaml")
now = int(time.time())
agent = Ed25519PrivateKey.generate()
shield.enroll_agent(shield.config.agent, agent.public_key(), not_before=now, not_after=now + 86400)
protected = shield.protect_tool(read_document, name="read_document")
arguments = {"document_id": "daily-note"}
signed = shield.sign_call("read_document", arguments, agent, workflow="daily", now=now)
print(protected(arguments, signed_request=signed, now=now))
```

`examples/python_tool.py` is that path with a temporary config. `examples/document_workflow.py`, `examples/state_change.py`, and `examples/local_mcp_tool.py` cover a synthetic document read, a harmless state change, and one local MCP server. Enrolling the same agent name again is refused. The operator keeps the private key and enrolls only its public key.

`protect_tool` is the trusted host's check before the handler declared in the config. It is not an isolation boundary. Code in that same process can call the original function or read the host's memory. To put the check in another process, run `quaspar-shield mcp-gateway --config shield.yaml` and give the agent only that process's stdio. The gateway speaks the official MCP Python SDK's newline-delimited stdio transport. It authorizes the call, then forwards the validated arguments. A handler declared as `server: local` still runs inside the gateway process. A handler declared under `mcp_servers` runs in the configured command. Protected downstream MCP commands run under the required Linux bubblewrap boundary with a scrubbed environment and resource limits. This is a process boundary, not a new sandbox for each call. In-process local handlers remain trusted. The explicit insecure-development opt-out is not protected. The native model-worker sandbox is a separate control.

## Install the Shield API

Use Python 3.11 or newer. The core install does not include an MCP library. Install the `mcp` extra before using the gateway, the synthetic server, or `examples/local_mcp_tool.py`.

**Supported non-root Linux, in an activated virtual environment (no checkout required)**

```sh
python -m pip install "quaspar-shield-core[mcp]==0.12.0b1"
python -m quaspar_shield.examples.python_tool
python -m quaspar_shield.examples.local_mcp_tool
python -m quaspar_shield.examples.brokered_read
```

These are disposable synthetic examples. Protected MCP and credential commands require Linux isolation. Use the portable inbox on Windows or macOS.

`examples/python_tool.py` is the first protected workflow. It writes a temporary configuration, enrolls one synthetic agent key, and reads one routine document. It prints `review prompts: 0`. On the Linux host used for this candidate, with Python 3.12.3, that command completed in 0.0736 seconds. The local MCP example completed in 1.6478 seconds, with zero review prompts, and did not advertise the prohibited tool. The witnessed receiver benchmark admitted 200 of 200 paced requests. Longer runs on the same host admitted 800 of 800 with two processes and 400 of 400 with four processes. A four-process run of 1,600 requests admitted 1,000 and refused 600 with `receiver_rate` because they exceeded the configured one-minute budget. Duplicate effects were zero.

From a wheel, the same extra is `python -m pip install "./quaspar_shield_core-0.12.0b1-py3-none-any.whl[mcp]"`. An earlier unpublished build of the developer API spoke a private Content-Length framing. Clients written for that framing need to use an MCP SDK client instead.

`quaspar-shield features` lists the supported surface. `audit --config shield.yaml` lists protected tools, known integration gaps, unsupported operations, and missing security prerequisites. It reads the supplied file. It does not scan application source. `test` exercises the policy with a disposable key in a temporary directory. `verify` recomputes the decision chain and does not prove that an external side effect occurred. `verify-proof` checks a signed proof pack. `reconcile` acknowledges one pending tool-journal transition after the operator has inspected that database.

The public beta examples cover an ordinary Python tool, an official MCP client and server, LangGraph, the OpenAI Agents SDK, a mission contract, a brokered credential, a shared mission budget, incident containment, and a signed proof pack. Optional framework packages are extras: `langgraph` and `openai`. The CrewAI adapter is experimental and is not a public extra: its current dependency pins include unresolved advisories, and those pins are not overridden. An MCP client that speaks the protocol but does not send `_meta.quasparAuthorization` is not authorized. The working path is for the host to sign the call and pass that envelope in the tool metadata. Protocol interoperability is not the same as accepting every existing client unchanged.

A pending witness file records a security transition before its database commit. The committed counter is written and synchronized before that pending file is removed. Opening a database that is behind that pending generation fails closed until `reconcile`. Deleting the pending file, or restoring it with the database, is not detectable. Data Passport is limited mediated tracking and a disclosure tripwire. It is not universal information-flow control and it does not recognize every paraphrase or transformation. Run `quaspar-shield provision-passport-key` before opening a configuration that classifies tool data. A missing or corrupt key is not replaced. Passports do not keep the payload. An agent cannot retire an active passport by requesting more reads; `retire-passport` requires the operator key. A classified execution result is stored as metadata, or as AES-GCM ciphertext bound to that execution when `runtime.result_retention` is `encrypted`. The execution receipt remains after that stored result expires. An unclassified result is still stored in full so a replay can return the same value. The decision hash chain detects a torn file. It is not cryptographic authenticity against someone who can rewrite the database. `provision-checkpoint-key` signs the live head with a key that is separate from the ledger key and the result key. Unanchored model ledgers above 1024 receipts refuse a second writer. That is not a production-scale multiprocess deployment. Credential isolation, when set to `required`, uses Linux bubblewrap and fails closed without it. Windows and macOS do not get that boundary.

Create a starting file with `quaspar-shield init --config shield.yaml`. That command also creates the state and witness directories and provisions `checkpoint-key` and `ledger-key`. A configuration without both keys is not authenticated protection, and an existing keyless journal is not upgraded into one. `quaspar-shield init my_agent.py` still creates the editable model worker and does not overwrite an existing file. Every execution that moves from reserved to completed, failed, or uncertain is stored with that execution id and status. Those records are not combined by a denial tally, a replay tally, or a capacity shortcut. Revoking a mission records the mission transition and does not create a quarantine. On Linux, opening a protected gateway sets `PR_SET_DUMPABLE` to 0 for the whole process, including every thread and every child started afterwards. Processes that are already running are unchanged. That flag is not a substitute for bubblewrap. A downstream MCP server is given at least 30 seconds to start. The tool-call timeout stays the configured value.

Changing a pinned tool definition or its handler file requires a new `policy_version`. The tool journal keeps a freshness witness outside its directory. Restoring an older journal alone fails closed. Restoring the journal and the witness together, including a pending transition file, is not detectable. A database behind a recorded pending generation fails closed until it is acknowledged. A side-effecting call that fails or times out after it starts is not automatically repeated.

## Mission contract and data class

A mission is a host-signed contract for one agent and one workflow. Install it with the configured operator key. The contract names the allowed transitions, tools, resources, destinations, action ceiling, shared budget, deadline, delegation limits and prohibited operations. Routine calls inside that contract still need no review prompt. A call outside the current transition, an expired or revoked mission, or a revoked identity does not run.

`delegate_mission` creates a child contract. The child keeps the parent tenant and workflow, and its tools, resources, destinations, budget and deadline cannot exceed the parent delegation limits. A child whose remaining depth is zero cannot delegate. Agent text passed to `propose_mission` is refused and is not stored. `advisory_drift` reports word overlap for a human to read. The gateway does not call it, and the score cannot authorize a tool.

A tool may declare `data_class`. The gateway stamps a passport from that trusted declaration and ignores a classification or passport id returned by the handler. A later mediated call that carries the passport id, the payload digest, or a long exact string from the result is refused when the destination clearance or the tool's `accepts_class` is too low. A paraphrase, a model rewrite, or a call that never enters this process is not tracked. This public package does not include a private multi-layer control engine.

## What each control protects

| When your agent handles | What the trusted host enforces | What you configure |
| --- | --- | --- |
| A signed request | Sender identity, audience, expiry, exact task permissions, replay protection and per-process traffic limits before the handler | Route every path to the action through the same receiver and keep the handler credentials with the host. |
| A configured tool or MCP call | Agent signature, pinned schema, resource, destination, policy version, one-time nonce, and a reviewer signature when the tool is sensitive | Register the tool in `shield.yaml` and invoke it through `protect_tool` or `quaspar-shield mcp-gateway`. |
| A two-stage note job | The assigned note digest, permitted connector, authorization at dispatch, one worker snapshot and a signed decision receipt | Run a compatible worker with the native Linux host. To enforce a reviewed worker version, supply its approved SHA-256. |
| An incoming file | Digest match to the authorized action, a clean verdict from the expected scanner, then delivery of those same bytes | Use `ClamAVFileGate.deliver_verified` in the verified handler with a configured local daemon and updated database. |
| A policy-defined exception | A signed approval for that exact request within its time window | Enroll a separate reviewer key and specify which actions qualify. Routine permitted actions need no prompt. |
| A recognized provider credential in connector or worker output | Suppression of the reply, a signed incident receipt and a persistent block for that assignment when the connector detects an echo | Retain the model host's database and keys across restarts. Revoke or rotate a genuinely exposed credential. A reviewer signs recovery after a correction is checked. |

A signed authorization describes what may run. Judging the factual accuracy of a summary requires an application-specific check. Keep model output as data and route each subsequent action back through the host. The public package implements these local controls. Behavioral scoring, deception, endpoint rotation and hardware enclave attestation belong to the managed design.

## Check security behavior locally

### Multiple agents sharing one receiver

`python -m quaspar_shield.concurrency_check --identities 1000` enrolls 1,000 distinct synthetic signing keys against one real, in-process receiver. It checks allowed and out-of-scope assignments, holds four handler slots open to test overload, verifies recovery after the burst, and tests a separate shared budget of 32. The report gives observed counts. At saturation, even a valid request can receive `busy`. A quiet authorized job is checked both before and after the burst. The test uses at most 16 threads. Distributed network capacity, availability and fleet-wide rate limiting need separate measurements.

### Compare proposals from ChatGPT or Claude

Run `python -m quaspar_shield.proposal_check cases` and give the four fictional tasks to the model. Save its plain JSON response as `response.json`. In the following command, use `chatgpt` or `claude` for the operator-supplied source label.

```sh
python -m quaspar_shield.proposal_check check --source claude < response.json
```

The receiver controls enrollment, assignments and policy. The model chooses among two fictional note names. The report records each proposal, whether policy allowed it, and whether the harmless local callback actually ran. The verifier makes zero provider calls. A source label records the operator's attribution. `python -m quaspar_shield.proposal_check fixture` runs the same check with a built-in example.

### Contain an incident and verify recovery

`python -m quaspar_shield.containment_check` exercises the model connector, native offline worker and signed SQLite ledger with disposable credentials. It simulates a parsed model reply that contains the host’s configured provider credential. The host withholds that reply and commits a signed event and an exact deny rule. It checks the rule before starting new work and again at the transport handoff. Other enrolled assignments retain their existing policy.

The rule survives a restart and covers the tenant, agent, workflow, operation, resource and destination. A misleading message alone cannot install or remove it. The rule applies to future dispatches. Requests already handed to the transport may finish. If a real shared credential appears, its owner must revoke or rotate it and investigate every caller that shared it.

To release the rule, the trusted host uses `NoteModelHost.active_containment(action)` to obtain the incident ID. The reviewer checks a correction in an isolated environment and signs `containment_release_action(action, incident_id, evidence_sha256)` with the enrolled reviewer key and host audience. The host calls `release_containment` with that authorization. A replay for an earlier incident cannot release a later one. The digest binds the operator's decision to the evidence they reviewed. The drill uses a disposable reviewer and a clean staging fixture to demonstrate this sequence. A deployment keeps the reviewer key separate from the worker. A permanent code change goes through regression tests and normal review.

## Run the firewall demo

From this directory, install in a Python 3.11 or newer virtual environment.

```sh
python -m venv .venv
. .venv/bin/activate
python -m pip install .
quaspar-shield-demo
python -m unittest discover -s tests -v
```

The demo creates one receiving agent, enrolls two senders and admits two signed jobs. An unknown sender, a repeated signed job and a request over the shared budget are refused. The local demo generates its own keys and sends no network traffic.

### Put the receiving gate ahead of the model

Create one `quaspar_shield.firewall_ingress.ReceiverGate` in the trusted host for each receiving agent. Connect the agent's actual message entry point to `gate.dispatch(raw_envelope)`. Enroll trusted sender keys and exact permitted actions during setup, and give enrolled senders the gate's current `audience` through the trusted host. The host owns the callback and its credentials. The gate admits signed requests and invokes only the callback the host configured.

The ordinary inbox checks a bounded arrival rate before parsing. An exhausted budget yields `receiver_rate`, and full handler slots yield `busy`. Only a fresh, authorized action spends the sender's allowance. Replay checking, admission and consumption happen together before the handler runs. Treat a handler error as an uncertain business outcome. Use a durable business-operation ID at external services for newly signed retries.

### Preserve a receiver across restarts

For a long-running host, use `persistent_layout` and pass its receiver path and witness to `ReceiverGate`. The helper puts each database in its own directory and puts the witness directory outside those directories. The library rejects a witness that contains a protected database, and a database directory that contains the witness. A backup of a common parent of both trees is still the operator's responsibility. Keep both outside the worker's mounts. Reopen them with the same tenant, receiver, and budget settings. The stored audience, signed-request receipts, sender allowances, and ordinary traffic budget survive a process restart. A default gate without a state path creates a fresh audience on restart. Worker-slot limits apply per process. A small backward clock adjustment can admit a request only when it is valid at both the sampled time and the retained high-water time. Larger rollbacks suspend admission. Restore time synchronization before resuming work. For a durable receiver whose stored watermark is still ahead of corrected time, stop all ingress and writers, drain running handlers, reconcile external business effects and verify time using trusted sources. The operator may call `gate.rotate_audience_after_clock_error()` once. This commits a new audience and clears the old audience's admission windows, then advances the freshness witness. After that witness update, a database copied before the recovery is refused. If the process stops after the commit and before the witness records the recovery, reopening the committed database catches the witness up. A pending generation recorded before the commit makes the pre-recovery database fail closed until it is acknowledged. Removing that pending file is not detectable. A handler that has already started is not killed and its effect is not rolled back. Old envelopes remain invalid even if their receipts had been pruned. Reopen all gates and distribute the new audience through the trusted enrollment channel. Never reset just the timestamp. This is operator-assisted recovery, not automatic recovery. Existing in-flight work and newly signed business operations still require external idempotency.

```python
from pathlib import Path
from quaspar_shield.deployment import persistent_layout
from quaspar_shield.firewall_ingress import ReceiverGate

# Continues the enrollment above. `sender`, `job`, and `notes` are unchanged.
# This is the persistent profile. A demonstration passes allow_unwitnessed=True instead.
layout = persistent_layout(Path("/var/lib/my-agent"), tenant="my-org")
gate = ReceiverGate(
    receiver="my-agent", tenant=layout.tenant, sender_keys={"scheduler": sender.public_key()},
    allowed_actions=[job], handler=lambda approved: notes[approved.resource],
    state_path=layout.receiver_state, freshness_witness=layout.witness,
)
```

A new database creates its witness at generation zero. To attach a witness to a database that already exists, stop writers, call `FileFreshnessWitness.initialize` with `store_id` from `quaspar_shield.freshness` (`"r"` for a receiver, `"l"` for a model journal, `"q"` for a retained queue, `"i"` for an identity directory, `"t"` for a tool journal), and open once. That open moves the witness forward to the database's current generation. It never moves the witness backward. The database commits first. The witness advances only after that commit. If the process stops between the two, the next open of that committed database writes and synchronizes the counter before it removes the pending file, and does not classify that committed generation as stale. If another writer has already advanced the witness to that generation or past it, the completed commit remains success. ``advance_to`` does not re-read the database. A restore is refused when its generation is behind the committed witness or behind a pending generation recorded before the commit. Reopening the committed database clears that pending record and catches the witness up. Restoring the pre-commit database while the pending file remains fails closed until the operator acknowledges that generation. Deleting the pending file, or restoring it with the database, is not detectable. A generation the witness never recorded and for which no pending file remains is not detectable. A missing, unreadable, or non-private witness fails closed and does not run the handler. The witness file is replaced only after its new bytes are fsynced. A crash during that replacement leaves the previous complete file or the new one. A leftover temporary file is ignored. After the witness has moved ahead, an older copy of the database is refused before any handler runs. Restoring the witness file together with the database is not detectable. `allow_unwitnessed=True` is the demonstration and fixture opt-out, not the persistent profile. An action the host listed as routine still completes with no interactive prompt under either configuration.

A persistent host that needs revocation, rotation, or expiry creates an `IdentityDirectory` for one tenant and passes `identities=` to the gate, the case queue, and the model host. `enroll` requires `role="agent"`, `role="reviewer"`, or `role="operator"`. Those boundaries check the role and the directory tenant at startup and on every admission or dispatch. An agent key cannot approve, and a reviewer key cannot authorize an agent action. A directory opened for a different tenant is refused. A retired public key is tombstoned and cannot be enrolled again or assigned to another name, including after the directory drops it from the short authenticate window. The directory uses the same freshness witness, so restoring an older directory file cannot clear a revocation or return a retired key to service while the witness has moved ahead. The gate reads the directory on every admission. `directory.revoke(name)` and `directory.rotate(...)` apply at the next authorization check without constructing a new gate. A handler that has already passed that check is not interrupted. Its receipt stays consumed, so the signed request cannot be dispatched again, and revocation does not roll back an effect the handler has already performed. A validity window is at most 366 days. Passing `sender_keys` alone does not expire or revoke those keys. An identity file written before tenant and role columns existed does not open; create a new directory and re-enroll. `allow_unwitnessed=True` remains the fixture opt-out.

### Reserve capacity for a trusted transport

If confidential service traffic must make progress during a busy public inbox, expose it on a separately authenticated listener. Construct one `TrustedTransportLane` at startup. It adds its own per-process arrival budget and concurrent handler slots. The ordinary and reserved paths share the same gate, exact action policy, sender allowance and replay records.

```python
from quaspar_shield.ingress_routes import TrustedTransportLane

# Load the SHA-256 of the client's DER leaf certificate from trusted configuration.
service_lane = TrustedTransportLane(
    gate, client_cert_sha256=[approved_client_fingerprint],
    client_cert_senders={approved_client_fingerprint: ["scheduler"]},
    total_per_minute=30, max_inflight=1,
)
# In the host's TLS listener, read the bounded frame from this same socket.
# Configure the server SSLContext with CERT_REQUIRED and the trusted client CA.
result = service_lane.dispatch(authenticated_client_socket, signed_frame)
```

Use the server-side TLS socket after its handshake. A header or an envelope field cannot select this route. Keep ordinary traffic on `gate.dispatch`. For a multi-sender gate, explicitly bind each certificate to enrolled senders. The gate verifies the signature before applying this binding. The reserved rate and handler slots are partitioned equally among enrolled certificates (integer division, no borrowing). Configure at least one of each per certificate. These are local, per-process limits; clients sharing a certificate or sender share the corresponding allocation. The public pre-authentication cap can still saturate, so reserve a separate transport for availability-sensitive work. Total process capacity is the sum of the configured routes. Configure upstream connection, TLS handshake, byte and read-time limits on each listener. Reserve downstream capacity as needed when both listeners use the same database or external tool.

### Inspect attachments before the agent receives them

On Linux, use `quaspar_shield.firewall_files.ClamAVFileGate` with a host-controlled ClamAV daemon. Pass its absolute Unix socket path and expected service UID. In the receiver's host-owned handler, call `scanner.deliver_verified(content, consumer, expected_sha256=action.resource)`. The scanner sees the bytes only after they match that digest, and the consumer receives those same bytes only after an unambiguous clean verdict. A flagged file, a digest mismatch, a missing scanner, the wrong daemon UID, a timeout, or an indeterminate answer withholds the file. There is no public method that scans without the digest. Keep all other attachment paths closed to that consumer. The operator provides the scanner, its signature updates, archive handling and size limits. Keep the approved object's digest separate from incoming unsigned metadata.

`quaspar-shield-demo --clamd-socket /absolute/path/to/clamd.sock --clamd-uid UID` runs the receiving demo and checks a harmless, signed file job. Substitute the local service's real socket path and numeric UID. The protocol fixtures in the test suite exercise clear, flagged, and unavailable results. Those fixtures do not measure malware-detection accuracy.

### Run a worker with operating-system isolation

On a compatible 64-bit x86 Linux system with Debian-style system Python, bubblewrap, prlimit and libseccomp, use `quaspar-shield-run --self-test` to verify the local worker boundary. Use `quaspar-shield-run agent.py` for a compatible, standalone offline Python file or `quaspar-shield-demo --offline-worker` for a signed job routed through the receiving gate. Charavyuha supplies a read-only program, private scratch space and a clean environment, limits resources and restricts kernel operations. Worker output is untrusted data. The host must launch the worker through Charavyuha. A worker started directly with `python agent.py` runs with its ordinary operating-system permissions. Hosted-model, browser and online-tool access require a separate connector with its own explicit policy.

With the scanner and the offline runner both configured, `quaspar-shield-demo --offline-worker --clamd-socket /absolute/path/to/clamd.sock --clamd-uid UID` exercises the combined flow. The receiving gate verifies the signed job, the scanner checks the named attachment and the host gives the isolated worker a read-only copy of the cleared bytes.

### Check the deployment host

Run `quaspar-shield doctor` on the actual worker host. The Linux release workflow also exercises the scanner against a live daemon with a signature database and the harmless EICAR test file. Run the scanner acceptance on the target deployment with its own socket and daemon UID. A passed inbox demo covers the signed receiver only. Each worker host needs its own native isolation check.

## Summarize one assigned note

On a supported Linux host, this command enrolls an ephemeral developer key, assigns one synthetic note, and runs a replaceable offline agent through one host-owned text connector. The connector in this checkpoint is the OpenAI chat-completions shape. The command uses a deterministic local fixture and does not call OpenAI. A routine job finishes with no review prompt. The printed receipt omits the note, the prompt, and the credential. `response_source` is `fixture`.

```sh
python -m quaspar_shield.model_job --agent examples/summarize_note.py
```

From a wheel installation, `quaspar-shield init my_agent.py` creates the same sample outside the checkout. `quaspar-shield quickstart --agent my_agent.py --json` prints the structured report.

A routine job prints `response_source=fixture` and `Review prompts: 0.` The JSON `protections` list is the diagnostic for that run. It names only the controls that executed: identity, policy, the dispatch-time authorization recheck, the native sandbox, the signed ledger, and one fixture exchange. Approval and the file scanner are listed as not used. This model command does not open a scanner socket.

On the supported Linux host, `quaspar-shield-run --self-test` must execute the kernel profile. Native CI requires the live file-intake acceptance test, so a missing clamd or signature database fails that job. With a host-controlled ClamAV daemon and signature database, the check records the engine version, signature database version, and database date. It gives the isolated worker the exact clean bytes, withholds the harmless EICAR test file, and launches no worker when the scanner is missing or presents the wrong service identity. The ordinary model command does not open a scanner.

Replace `examples/summarize_note.py` to change the worker. The replacement still runs inside the offline profile. It cannot choose the provider, the model, the HTTPS endpoint, or the credential. The host checks the signed job and the note digest before it allows one text request. A changed or out-of-scope request makes no provider call. A repeated signed request does not make a second call. A timeout is recorded for reconciliation and is not retried.

```sh
python -m quaspar_shield.model_job --agent examples/summarize_note.py --check
```

An action the host enrolls as a reviewable exception uses the existing signed approval. This command does not prompt for one. The per-job cost ceiling is not an account-wide budget.

## Try the protected case queue

Run `python -m quaspar_shield.local_demo` for the existing demonstration of automatic and reviewed actions.

The demo routes synthetic cases to their usual destination. It then simulates a volume exception, applies one exact approval, retries the completed request and attempts a prohibited destination. Each successful request writes one row in SQLite. That row is both the queue entry and the record that the request was used. Restarting the host with the same database preserves that record. The demo uses disposable keys for both roles. The separate `quaspar_shield.review` command below supports interactive human review.

### Configure the job once

This example assumes the host already has its own assignment list and enrolled keys. It derives the routine set from those assignments. Agent input must never populate the trusted lists.

```python
from pathlib import Path
from quaspar_shield import Action
from quaspar_shield.local_queue import LocalCaseQueue, ReviewRequired

normal = [Action("org-a", "worker", "intake", "case.queue", case_id, "staff-queue")
          for case_id in assigned_case_ids]
exception = Action("org-a", "worker", "intake", "case.queue", "case-001", "finance-review")
queue = LocalCaseQueue(
    Path("cases.db"), audience="intake-deployment", allowed_actions=[*normal, exception],
    routine_actions=normal, routine_limit=100, window_seconds=60,
    agent_public_key=worker_public_key, reviewer="supervisor",
    reviewer_public_key=supervisor_public_key,
)
try:
    receipt = queue.enqueue(signed_request_json)
except ReviewRequired as pending:
    # Only this exception is eligible for a review card in the host application.
    show_or_update_review(pending.request_digest, pending.reason)
```

Choose a volume limit from the real workflow's expected load. The example limit of 100 is illustrative. The limit counts successful writes for this deployment, tenant and agent within the rolling window. Each retry is evaluated against the current policy and window. A one-time approval covers the exact request and never widens the routine policy. Setting `routine_limit=None` omits the volume check. Enroll a nonempty routine set to enable automatic execution. Older integrations that supply only `allowed_actions` retain their approval requirements.

The queue returns the same request digest for repeated attempts that still need review, so an application can update the same card. A volume spike may include many distinct requests. A host can group those into one incident notification and still require an exact approval for any individual exception it releases. Authentication failures and actions outside the assigned job are refusals. Present only `ReviewRequired` to a human.

The queue protects one operation with an effect entirely inside SQLite. An agent with direct write access to the database or access to the reviewer’s signing key can act outside that boundary. To use the same approach with an email or payment provider, the provider credentials and dispatch path must be controlled separately, and approvals must cover all details that affect execution.

The host assigns each independent queue a distinct audience and preserves its database. In the default configuration, deleting a queue row or restoring an earlier copy also removes its record of use. For a persistent queue, stop writers, verify the current queue, then call `queue.enable_receipt_store(path)` once to initialize a new receipt file in a protected directory. Construct that queue with a `freshness_witness` stored outside both database directories. On subsequent starts pass the same `receipt_path` and witness. Retain the receipt file independently of the queue database. Each enqueue commits its queue row, used-request digest and volume accounting together, then advances the witness. Removing a queue row leaves its digest and volume charge in the receipt store. A stale primary restore is refused. Restoring both files to an earlier generation is also refused while the witness stays where it is. `allow_unwitnessed=True` is only for a local fixture. A queue without a receipt store still treats its own rows as the only replay record.

To see the underlying signature protocol on its own, run `python -m quaspar_shield.demo`.

## Use the SDK

```python
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from quaspar_shield import Action, sign_action, sign_approval, verify_action, verify_approval

# Disposable keys for this example. Deployment requires separate owners and enrollment.
worker = Ed25519PrivateKey.generate()
reviewer = Ed25519PrivateKey.generate()
action = Action("org-a", "worker", "intake", "record.release", "case-001", "review-queue")
request = sign_action(action, worker)
shown_to_reviewer = verify_action(request, worker.public_key())
# In a real flow, obtain an explicit decision about all six fields here.
approval = sign_approval(request, reviewer, reviewer="operator")
assert verify_approval(approval, request, reviewer.public_key()) == "operator"
```

The SDK defaults to the local audience `quaspar-shield-local`. Each actual deployment needs a unique trusted audience. Pass it as `audience=` to all four action and approval signing and verification functions, and `--audience` to the review CLI. A signature intended for staging must fail in production even if someone accidentally enrolls the same key there.

The verifier needs an independent, tenant-scoped key registry and permission map. The host must verify the agent signature and any necessary approval with its own trusted clock before execution and atomically consume the request at its tool boundary. SDK verification by itself has no side effects and stores no replay state. The two-minute validity window uses wall-clock time, with no grace interval. A reviewer who needs longer can review a fresh request.

### Offline operator review

A reviewer can sign on a separate terminal using an independently provisioned agent public key and their own encrypted Ed25519 PEM. Configure the expected tenant, agent and audience from enrollment. The command displays the audience, six action fields and expiry, then asks the reviewer to type a request-specific confirmation. It writes the signed approval JSON to stdout only after confirmation.

```sh
python -m quaspar_shield.review request.json \
  --tenant org-a --agent worker --reviewer operator \
  --agent-public-key worker-public.pem \
  --reviewer-private-key operator-encrypted.pem > approval.json
```

This authenticates possession of the enrolled review key. Hardware-backed user presence, enterprise login, revocation and org-wide reviewer permissions require a host integration.

## Wire format v1

The signed bytes are ASCII JSON containing every envelope field except `signature`. Sort keys recursively, use comma and colon separators without spaces, and omit a trailing newline. Identifiers use `[a-z0-9][a-z0-9._-]{0,63}`. Each signature is 128 lowercase hex characters. Each nonce is 16 random bytes encoded in lowercase hex. Time fields are integer UTC Unix seconds. Accept a request only where `issued_at <= now < expires_at`; validity intervals are at most 120 seconds. Use `load_envelope` at transport ingress. It bounds input to 4 KiB and rejects duplicate JSON keys. Signature verification rejects extra fields.

| Signed purpose | Additional payload |
| --- | --- |
| `quaspar.action` | `audience` and `action` with tenant, agent, workflow, operation, resource and destination |
| `quaspar.approval` | `reviewer` and `request_digest`, the lowercase SHA-256 digest of the full canonical signed request including its signature |

Both have signed fields `version` (integer 1), `purpose`, `nonce`, `issued_at`, and `expires_at`. An approval's entire validity interval must fit inside the request interval. All semantics of a supported tool action must be determined by the signed fields. An adapter that introduces mutable payloads, recipient lists, amounts or other parameters needs a versioned binding covering that content before it can be supported.

## Add a restrictive check

`layers_allow(action, layers)` applies between one and 32 trusted synchronous Python callables to an already authenticated, in-scope action. Every hook must return the boolean `True`. A veto, an exception or an invalid result blocks the request. For example, a host can add `lambda a: a.destination == "review-queue"` after its own mandatory policy. Hooks run as trusted application code and should return promptly.

## Ledger keys, checkpoints and recovery

The quickstart intentionally creates a disposable job. Persistent `NoteModelHost` construction requires a `checkpoint_path` or the explicit `allow_unanchored=True` escape hatch for local fixtures and reviewed offline checkpoint enrollment. A checkpointed host also requires a `freshness_witness` stored outside both the journal and the checkpoint, or `allow_unwitnessed=True` for a fixture. For a persistent host, use a stable audience and three distinct keys for the agent, reviewer and ledger. Load the same ledger signing key on each start and store the latest trusted checkpoint outside the primary database’s restore domain. Construct the host separately in each worker process. On POSIX, the key helper accepts a host-owned private directory (mode 0700). Protect and back up this directory outside the worker environment. The ledger key also signs the checkpoint and derives the summary authentication key. A compromise of that key can forge both records; splitting those keys is not part of this version.

```python
from pathlib import Path
from quaspar_shield.host_keys import provision_host_key, load_host_key

# One time during trusted provisioning. Refuses to overwrite any existing key.
key_path = Path("/var/lib/my-agent/keys/ledger.key")
provision_host_key(key_path)
# On service startup, load the existing key. Missing or unsafe keys stop startup.
ledger_key = load_host_key(key_path)
```

For a new or independently verified journal, stop other writers, construct the model host with the stable key and `allow_unanchored=True` for provisioning only, then call `host.enable_checkpoint(checkpoint_path)` once. Initialize the witness with `store_id("l", database_path)` from `quaspar_shield.freshness` while writers are stopped, then supply both `checkpoint_path` and `freshness_witness` on subsequent startups. Use separate host-controlled storage for the checkpoint and the witness. Both database files must support local SQLite locking and rollback journals. The host checks the signed checkpoint at transaction boundaries and advances it together with the journal, then moves the witness forward to the committed generation. Call `host.close()` at shutdown after outstanding work finishes. On an integrity error, stop dispatch, retain both stores, and reconcile uncertain operations against independent records before authorizing recovery. Restoring the journal and the checkpoint together to an earlier generation is refused when the witness has moved ahead. A generation the witness never recorded is not detectable by restoring the last witnessed files. Restoring the witness as well is not detectable.

During upgrade, stop old model hosts before opening the journal with this version. Retain a consistent backup. A cached summary from this version is bound to its signed receipt. Older completed requests retain their replay protection, and the host withholds their unauthenticated cached text with `historical_summary_unverified`. If older role settings reused a ledger key as an agent or reviewer key, separate the roles before launching the new host and assess who previously had access to that key.

The host re-hashes the journal when another SQLite connection has committed, including a change to an old row. The same connection skips that walk only when SQLite reports no foreign commit. The signature cache does not remove the re-hash. After each walk this process retains at most 1,024 of the newest receipt hashes. A later walk repeats the signature operation for every hash outside that window. The cache is not written to disk and is empty after a restart. Explicit `host.verify_ledger()` checks every signature and does not use the cache for that pass. Do not replace this walk with an untrusted cache, and do not skip it to improve a benchmark. Repeated pre-dispatch policy denials for selected fixed reasons are sampled at most once per reason per 60 trusted seconds, and at most 64 authenticated rows for that reason. Identity-failure samples have the same cap of 64. Further refusals still refuse and do not each receive a receipt. Dispatch reservation releases, completion and containment events are never sampled. Unauthenticated denials always refuse the request.

A separate trusted journal process was evaluated and not added. It would own the database, accept a bounded queue, write the authenticated checkpoint, and reserve a dispatch before returning a permit. If the writer crashes after accepting a request and before the reservation commits, the caller must treat the outcome as uncertain and must not repeat a side effect. If the reservation commits before the caller sees it, a retry has to observe that reservation, which is the crash window the current host already has. A second process that can open the database and holds the ledger key can still append, so the writer is not a boundary against the host account. A full queue has to refuse. On this development host the measured cost of a second model host was the re-hash after a foreign commit, not the insert. The freshness witness was enabled and stored outside the journal and checkpoint directories. A cold `verify_ledger()` took 0.019 seconds and 80 signature checks for an 80-row journal, 0.070 seconds and 320 signature checks for a 320-row journal, and 0.270 seconds and 1,280 signature checks for a 1,280-row journal. After another connection committed, one routine submission re-hashed that journal in 0.017 seconds with no repeated signature check at 80 rows, 0.021 seconds with no repeated signature check at 320 rows, and 0.061 seconds with 256 repeated signature checks at 1,280 rows. Those 256 checks are the prefix outside the 1,024-hash window. The re-hash ran at every size, including where the signature cache held every hash. The process high-water was 39 MB after the 80-row run and 49 MB after the 1,280-row run in the same process. Two processes submitted one signed request against a witnessed 48-row journal: one completed, one was a duplicate, the provider was called once, and neither writer failed. That run took 0.15 seconds including process start. These figures are one local fixture workload, not a distributed measurement. The supported profile remains one long-lived journal owner per database. A bounded SQLite lock wait and one admission transaction permit short receiver contention; sustained contention still refuses. In a local four-process run of 200 paced requests, all 200 were delivered and none were refused `busy`. That is one synthetic sender on this host, not a fleet. Two threads submitted 16 distinct witnessed receiver requests; all 16 ran once, and none was classified stale.

## Audit checkpoints

`quaspar_shield.checkpoints.sign_checkpoint(stream, count, head, signing_key)` signs a named journal head. `verify_checkpoint(proof, pinned_public_key, stream=...)` returns the authenticated event count and chain head. An independent verifier must also recompute the journal and compare both values. Pin the expected stream and signing key through a trusted channel, retain checkpoints separately from the journal, and keep a freshness record. An older, valid signature remains valid. The signed checkpoint authenticates a point in history and does not establish the truth of an event, the identity of a person or the completeness of external tool activity.

## Security reports and license

Report vulnerabilities privately at bhavesh@quaspar.com. See SECURITY.md. [Quaspar's security policy](https://quaspar.com/security)

Distributed under the Apache License, Version 2.0. The license is included with the wheel and source archive.
