Metadata-Version: 2.5
Name: sanning-anchor
Version: 0.24.0
Summary: Sanning write SDK for Python — produce verifiable evidence from your agents
Project-URL: Homepage, https://sanning.io
Project-URL: Documentation, https://docs.sanning.io
Project-URL: Source, https://github.com/sanning-io/anchor
Project-URL: Issues, https://github.com/sanning-io/anchor/issues
Author: Sanning
License: MIT
License-File: LICENSE
Keywords: agents,audit,evidence,provenance,verification
Requires-Python: >=3.11
Requires-Dist: sanning-proof<0.21,>=0.20
Provides-Extra: dev
Requires-Dist: black>=24.0; extra == 'dev'
Requires-Dist: langchain-core>=0.3; extra == 'dev'
Requires-Dist: langchain>=1.0; extra == 'dev'
Requires-Dist: langgraph>=1.0; extra == 'dev'
Requires-Dist: pytest-xdist>=3.5; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.3; extra == 'langchain'
Provides-Extra: s3
Requires-Dist: boto3>=1.34; extra == 's3'
Description-Content-Type: text/markdown

# `sanning-anchor`

Produce verifiable evidence from your Python agents: hash locally, anchor a
signed commitment, and hand an auditor a pack they verify offline. Nothing in
this package needs a wallet, a chain identity, or a Sanning account to check.

Node is not required at any point. The `bundle` command that assembles a
evidence pack is a Python console script, and so is everything before it.

- The path from a first conversation with Sanning to a verified event is at
  [docs.sanning.io](https://docs.sanning.io).
- The wire format, the envelope profile and the pack body type are specified
  in documents that ship inside
  [`sanning-proof`](https://pypi.org/project/sanning-proof/), beside the kernel
  that implements them.

## Install

```bash
pip install sanning-anchor
```

Access to the console comes through a conversation with Sanning; there is no
self-service sign-up. Once your organization has a console login, create an
API key at [console.sanning.io](https://console.sanning.io). Give the key `agent:enroll` and
`anchor:write` to anchor, and `anchor:read` as well if the same key will later
build an evidence pack. The console pre-checks the first two. A key holding
only `anchor:write` anchors nothing, because the plane refuses an envelope
whose signing key the organization has not enrolled; a key holding no
`anchor:read` anchors correctly and then fails when you build the evidence pack.

## Anchor an event

```python
import json
import os

from sanning_anchor import Anchorer, FsLogStore, LocalEd25519Signer

anchorer = Anchorer(
    # Writes to a permanent public record. Use "dev" until you mean it.
    environment="production",
    # Your Ed25519 identity key. Keep the seed: a different seed is a different agent.
    signer=LocalEd25519Signer.from_seed_hex(os.environ["SANNING_SIGNING_SEED"]),
    subject={"type": "agent", "agent_id": "claims-triage"},
    api_key=os.environ["SANNING_API_KEY"],
    log_store=FsLogStore("./logstore"),
)

decision = {"claim_id": "c-1", "outcome": "approved"}  # your own data

result = anchorer.anchor(
    # Hashed in this process. These bytes are never sent to Sanning.
    content=json.dumps(decision).encode(),
    metadata={"reviewer": "queue-3"},
)

anchorer.close()

result.event_id  # the id this process minted
result.event_bytes  # retain these: the bytes payload_hash commits to
```

Replace the following:

- `SANNING_SIGNING_SEED` with a 32-byte Ed25519 seed, 64 hex characters, that
  your service keeps across restarts. An agent's identity is this key, not its
  name. `bytes.fromhex` accepts either case; the TypeScript SDK's
  `fromSeedHex` takes lowercase only.
- `SANNING_API_KEY` with the key from the console.
- `claims-triage` with the identity you want the evidence attributed to.

`@sanning/anchor` takes the same arguments under TypeScript naming and writes
the same bytes, so a mixed fleet hands over one pack.

### Start in the sandbox

Start with a Sandbox API key, which begins `sanning_test_`, and set no
`environment`. The SDK signs `"dev"`, stamps are simulated, and nothing reaches
the public record. A pack built from those records reads `verified` with the
sandbox label: `sanning-proof verify` prints the `Sandbox:` line and exits 3. When you are ready for
evidence, switch `SANNING_API_KEY` to a Live API key, which begins
`sanning_prod_`, and use a new signing seed. See
[Sandbox and live](https://docs.sanning.io/concepts/sandbox-and-live) and [Go live](https://docs.sanning.io/guides/go-live).

### The environment and your API key

With an API key, `environment` is optional: the SDK reads it from the key's
prefix. `sanning_test_` signs `"dev"` and `sanning_prod_` signs
`"production"`, at the same host. A `sanning_test_` key with
`environment="production"` raises `ValueError` at construction, and so does a
`sanning_prod_` key with `environment="dev"` (the Live plane refuses a `dev`
record): dev records need a Sandbox key, or drop `environment` to sign
`"production"`. Any other explicit value is used as given. With a key that has neither prefix, or with
your own `client` and no key, `environment` is required and its absence raises
`TypeError`. An `api_key` that is not a `str` raises `TypeError`.

A Live plane refuses a Sandbox API key, and a Sandbox refuses a Live API key.
Only the prefix is read, and the value is sealed into every record. `base_url`
still points the SDK at another origin, such as staging.

**From CI, persist one seed.** Calling `LocalEd25519Signer.generate()` in
every run enrolls a new key under the same `agent_id`, which the plane refuses
as an unauthorized rotation. Generate a seed once (`openssl rand -hex 32`),
store it as a CI secret beside a Sandbox API key, and pass it as the signer:

```python
anchorer = Anchorer(
    signer=LocalEd25519Signer.from_seed_hex(os.environ["SANNING_SIGNING_SEED"]),
    subject={"type": "agent", "agent_id": "claims-triage"},
    api_key=os.environ["SANNING_API_KEY"],
    log_store=FsLogStore("./logstore"),
)
```

### Chains need a durable store

`anchor(chain="orders")` links each record to the one before it under that
chain key, and keeps the head in the anchorer's `store`. The default
`MemoryStore` loses its heads on a restart, so the next record on the same
chain key starts again at `GENESIS`: one chain with two roots, a fork whose
links all verify. `sanning-proof` reports it as the `chain-second-root`
finding, which does not change the verdict.

Use a durable store with one writer for any chain key that outlives one
process. A durable store does not make two writers safe, because the store has
no compare-and-set: two instances on one chain key fork the same way. In
production, `anchor(chain=...)` on the default store warns once per anchorer.
If every chain key lives only as long as the process (the LangChain handler's
per-run key, for example), pass `store=MemoryStore()` to say so and the warning
stays quiet.

## Enrollment is automatic

The example writes no enrollment step, and that is the whole of it: on the first
`anchor()`, the SDK proves possession of your signing key to the control plane,
and your agent appears on Fleet under `agent_id`. One organization key
covers the whole fleet: no per-agent credential, no enroll script. It is not
optional politeness, because the plane refuses an envelope signed by a key your
organization has not enrolled (`SIGNING_KEY_NOT_ENROLLED`, HTTP 403).

Three properties are load-bearing:

- **The challenge is shape-checked before it is signed.** Enrollment is the one
  moment your identity key signs bytes the *server* chose, and that key also
  seals your envelopes, so the SDK refuses anything that is not a nonce rather
  than trusting Sanning not to send an envelope pre-image. Sanning is never in
  the trust path, including here.
- **A different key for an `agent_id` your organization has enrolled is a
  rotation**, and it needs the retiring key's counter-signature
  (`previous_signer=`). It is never inferred from a refusal: that is what
  stops a leaked organization key silently taking over an identity that is
  already producing evidence.
- **Verification never depends on the roster.** Enrollment is the plane's door
  policy, not the trust path. Every signed record verifies offline against
  `sanning-proof`, enrolled or not.

Enrolling out of band at deploy time instead? `auto_enroll=False` turns the
call off, and `enroll()` is exported for you to drive:

```python
from sanning_anchor import enroll

enroll(
    api_key=os.environ["SANNING_API_KEY"],
    agent_id="claims-triage",
    signer=signer,
)
```

Behaviour is identical to the TypeScript SDK, pinned by a shared conformance
oracle that calls neither of them.

## Parallel workers on one key

Enrollment is limited per API key, to 12 calls a minute by default, and each
enrollment takes at least two of them (the challenge and the enroll). Workers
that share one key and one signing key, such as a serverless fleet or several
agent processes, all enroll on their first `anchor()` and draw from that one
limit. When they start together, some of them get `EnrollmentThrottledError`.

The key needs enrolling once, not once per worker:

1. Enroll the key once, at deploy time or in a first job, with `enroll()`.
   Enrolling a key that is already enrolled changes nothing, so a deploy can
   run it every time.
2. Start every worker with `auto_enroll=False`. A worker then makes no
   enrollment call, and its first `anchor()` sends the envelope straight away.

```python
import os

from sanning_anchor import Anchorer, LocalEd25519Signer, enroll

signer = LocalEd25519Signer.from_seed_hex(os.environ["SANNING_SIGNING_SEED"])

# Once, at deploy time or in a first job.
enroll(api_key=os.environ["SANNING_API_KEY"], agent_id="claims-triage", signer=signer)

# In every worker: the same seed, the same agent_id, no enrollment.
anchorer = Anchorer(
    api_key=os.environ["SANNING_API_KEY"],
    subject={"type": "agent", "agent_id": "claims-triage"},
    signer=signer,
    auto_enroll=False,
)
```

If a worker starts before the key is enrolled, Sanning refuses its envelopes
with HTTP 403, and the SDK raises `SigningKeyNotEnrolledError`, an
`IngestError` (in direct mode, on the `cause` of the `AnchorDeliveryError`
that `anchor()` raises). Run `enroll()` for that key, or leave `auto_enroll` on.

When `enroll()` itself meets a 429 on the enroll call, it waits the
`Retry-After` and sends the same signed challenge again, without asking for a
new one, so a throttled enrollment costs no extra call against the limit. It
asks for a new challenge only when Sanning says the one it holds has expired
or been used.

## When Sanning answers 429

Sanning limits how fast an organization can anchor. Over the limit, it answers
HTTP 429 with a `Retry-After` header. The SDK then waits that long, plus up to
20% more, and sends the same bytes again: the envelope is not rebuilt or signed
again, so the record Sanning accepts is the one that used the chain link. A
wait never holds the chain: the next record on the same chain is built and
signed meanwhile.

- **`rate_limit_wait_ms` is a deadline**, 10,000 ms by default
  (`DEFAULT_RATE_LIMIT_WAIT_MS`), measured on the clock from the start of the
  delivery, so slow answers count against it. No resend goes when its wait
  would end past the deadline: the delivery fails at once instead. In direct
  mode, `anchor()` therefore takes at most `rate_limit_wait_ms` longer than the
  first refusal, plus one round trip.
- **Every wait is at least 1 second, and one delivery resends at most 10
  times.** A wait Sanning states as shorter than 1 second waits 1 second. A
  wait longer than 60 seconds counts as 60 seconds.
- **After a 429, no delivery from the anchorer starts before the time Sanning
  named**, whichever thread heard it.
- **Past the budget, the record fails as it would without the wait.** In direct
  mode, `anchor()` raises `AnchorDeliveryError` and the record is on
  `anchorer.gaps`. With a buffer, the record stays in the buffer and the next
  drain attempt goes no sooner than the time Sanning named, even when the
  backoff is shorter. A `drain()` call does not send before that time either.
- **Inside the budget, a drain pass waits within the pass.** Each record
  Sanning refuses can hold the pass for up to `rate_limit_wait_ms` plus one
  round trip (about 10 seconds by default) before it is delivered, and the
  first record that runs out of budget ends the pass. So a pass, and a
  `drain()` or `close()` called during a block, can take up to that long for
  each refused record.
- **`rate_limit_wait_ms=0` turns the wait off**: a 429 fails the delivery at once.
- **No other refusal is waited on.** A 429 without `Retry-After` (a spent quota,
  `QUOTA_EXCEEDED`), every 403 (a full sandbox, `SANDBOX_LIMIT_REACHED`,
  included) and every other status fail at once.

`IngestError.retry_after_ms` is the wait Sanning asked for, at most 60,000, or
`None`. `rate_limit_wait_ms` applies to the client the anchorer builds from
`api_key`. A `client` of your own does its own waiting.

### When Sanning refuses for a limit

Two refusals hold until a person acts: a 403 `SANDBOX_LIMIT_REACHED` (a Sandbox
ceiling, such as `records` or `bytes`) and a 429 `QUOTA_EXCEEDED`
with no `Retry-After` (the Live monthly quota). With a buffer, the drain then:

- **Keeps every record in the buffer.** Nothing is quarantined, dropped or
  recorded as a gap.
- **Retries at `drain_retry_max_ms`** (60 s by default) from the first refusal,
  instead of climbing from `drain_retry_base_ms`.
- **Sets `recording_status().blocked_by`** to a `RecordingBlock(status, code,
  limit)`. `limit` is the ceiling Sanning named (`records`, `bytes`,
  ...) or the quota spent (`requests`). `last_error` carries the code too.
- **Resumes on its own** once Sanning accepts again, with no restart, and the
  first delivery clears `blocked_by`.

To lift the limit, a person acts: in the Sandbox, reset the Sandbox (Settings,
Sandbox, Reset the sandbox in the console), which deletes the organization's
Sandbox records; on Live, raise the plan, or wait for the next month's quota.
The Sandbox rate refusal, `SANDBOX_LIMIT_REACHED` as a 429 with `Retry-After`,
is a wait (above) and does not set `blocked_by`. In direct mode, `anchor()`
raises `AnchorDeliveryError` for either limit, as before.

## What never leaves your process

**Your content does not.** It is hashed locally and only the hash goes into the
signed envelope. The control plane never sees your content, by construction
rather than by policy: it never receives the bytes, so it cannot disclose them.

**`event_bytes` is your retention obligation.** It is what `payload_hash`
commits to. Sanning never holds it, so losing it leaves you holding a
commitment to something you can no longer produce.

**Beside the envelope goes a projection of the signed record, for indexing.**
It holds ids and fixed formats: never a name, a content length, a hash of
content, a locator or a file path. Ids are sent in clear, the case id included.
It is unsigned, never placed and never evidence.

**No Arweave wallet, no chain identity, no data item.** Placement is Sanning's
act, which is why this package holds no blockchain code at all, and why it is a
few hundred lines rather than a chain client.

## Retain what you anchored

Pass `log_store=` and the SDK writes both halves an auditor needs before the
event is anchored: the content you handed it, and the canonical event record
the envelope commits to. If the store write fails, nothing is anchored. There
is deliberately no best-effort mode, because under this write path nothing else
holds those bytes.

Beside each record it also writes the signed envelope over it, at
`envelopes/<payload_hash>`, so a record read back from your own store carries
its signature and its `signed_at`. That time is the one your agent declared
when it signed: it is never trusted for ordering and never used as proof. A
store written before this change holds no envelopes and reads exactly as it did.

`FsLogStore` keeps your records on local disk, and it works on Live as it does in
the Sandbox. The folder holds the only copy of your records. If you lose the disk,
you lose the evidence for the records on it. Sanning keeps only a hash and a time
for each one, and no pack can be built from them. For Live, use an S3-compatible
bucket you own (versioning or Object Lock recommended), or back the folder up.
`sanning_anchor.s3`
(`from sanning_anchor.s3 import S3ObjectStore`, with `pip install "sanning-anchor[s3]"`)
supplies an S3-compatible object store behind the same seam, the same shape as
TypeScript's `@sanning/anchor/s3`, and the on-disk
shape is a versioned contract, `specs/log-store.md` in the `sanning-proof`
package, so an auditor holding nothing but the directory can resolve it without a
connector and without Sanning.

`--logs` takes a local store root or an `s3://` URL. Reading a bucket uses the same settings as recording: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_ENDPOINT_URL_S3`, or the AWS credential chain (roles, single sign-on, profiles), read by the AWS library itself. There is no flag for a credential: argv lands in shell history. The reader credential is enough: `s3:GetObject` and `s3:ListBucket`, plus `s3:PutObject` when `bundle` declares (`SANNING_SIGNING_SEED` set), because it writes the declaration's content to the bucket before it sends it. With that policy the store protection check cannot read the bucket's configuration, and `bundle` prints that it cannot tell whether Object Lock is enabled and writes anyway. See [the log store bucket](../docs/log-store-bucket.md).

A storage backend other than the S3 protocol is added through `ObjectStore` (the write side) and `LogStoreReader` (the read side, and the resolver `bundle` uses for a `--logs` scheme). There is no built-in Azure Blob or native Google Cloud Storage adapter. A log store you bundle from more than once must be durable and must keep what `bundle` writes into it: a declaration's record and content go to the `--logs` store of the run that anchored it, and a later `bundle` of the same case from a store without them refuses (exit 4).

## Record an agent run

`RunRecorder` writes one agent invocation as `agent.*` records of `sanning.agent/1`. Use it to record from your own code, or to build an adapter for a framework: the LangChain handler below is built on it. It gives every record its place in the invocation (`run.seq` and `run.prev_event_id`, so a deleted or reordered record shows), pairs each end with its start, lists on the first record what you cannot capture, keeps an approval request across a resume, and writes the closing record.

It does not read your framework. You decide which event is which call, what content each record commits to, and what to name it.

One `RunRecorder` serves many invocations: it holds the anchorer, the case and your agent version. `case_id` is 1 to 128 characters of `A-Z a-z 0-9 _ . : -`, or the constructor raises `ValueError`. `agent_version` must be a label of 1 to 128 characters with no control characters, or the constructor raises `ValueError`. `open_run` opens one invocation and writes its first record, `agent.run_opened`, at `run.seq` 0. Warnings go to the `sanning_anchor.run` logger and never raise into your code. Every call holds the run's lock while it writes, `anchor()` included, so one run is safe to call from several threads.

### Three ways in

**Start and end.** `start` writes an operation's start and returns a handle. `end` writes its end, named by the handle's `run_id`. The four operation kinds are `agent.step`, `agent.model_call`, `agent.tool_call` and `agent.retrieval`. `record` writes a record that is not an operation: `agent.step.occurred`, `agent.decision`, `agent.file`, `agent.error` or `agent.custom`.

```python
from sanning_anchor import RunRecorder, decision_content

recorder = RunRecorder(anchorer, case_id="claim-4821", agent_version="2026.11.0")
run = recorder.open_run(input={"claim_id": "c-1"})

# The root step has the root run id. How the run ended, as the closing record observes it, is its end.
run.start("agent.step", run_id=run.root_run_id)

call = run.start("agent.tool_call", run={"name": "lookup_policy"}, content={"claim_id": "c-1"})
run.end("agent.tool_call", call.run_id, "completed", content={"policy": "p-9"})

run.record(
    "agent.decision",
    content=decision_content(name="claim_verdict", value="approved"),
    extra={"decision": {"name": "claim_verdict"}},
)

run.end("agent.step", run.root_run_id, "completed", content={"answer": "approved"})

result = run.close(outcome="completed")
```

**`wrap`.** `wrap` runs a function as one operation: its start, then its end, `completed` with what it returned or `failed` with what it raised, which it raises on. An operation started inside the function, with no parent given, is its child. `awrap` is the form for a coroutine function.

```python
run = recorder.open_run(input={"claim_id": "c-1"})


def answer_claim():
    # Runs inside the root step, so its parent is the root step.
    policy = run.wrap("agent.tool_call", lambda: lookup_policy("c-1"), run={"name": "lookup_policy"})
    return decide(policy)


answer = run.wrap("agent.step", answer_claim, run_id=run.root_run_id)

observed = run.close().observed
```

**End only.** When your framework tells you that an operation ended and never that it started, `end_only` writes the end with no start. Declare the start's type in `not_captured` when you open the run, or a verifier reads the end as undeclared and `end_only` refuses it.

```python
run = recorder.open_run(not_captured=["agent.tool_call.started"])

# The framework reported the end only, so the start is declared not captured on the first record.
run.end_only(
    "agent.tool_call",
    "completed",
    run={"name": "lookup_policy"},
    content={"policy": "p-9"},
)

result = run.close()
```

Each call writes its record before it returns. A record that cannot be written never raises into your code: a call after `close()`, an id outside the grammar and a failed build are in `run.unbuilt`, and a delivery failure is in `run.gaps`. A record that is not written keeps its position, so the next record shows a gap where it would be. `run.is_complete` is false while either has an entry, and `run.assert_complete()` raises `IncompleteTrailError` for them.

With a `fail_closed` anchorer, `wrap` does not run its function when the start record is lost.

### Close the run

`close()` writes `agent.run_closed` once every earlier call has settled, then returns `RunCloseResult(steps, gaps, unbuilt, open, observed)`. Call it in a `finally`, so an exception from your agent still writes it: a run that never closes shows `closing.promised` on its first record and no `agent.run_closed`.

The closing record lists the records the run anchored and says how it ended in two places. `closing.outcome.observed` is what the helper saw, read from the end of the root step, the operation whose run id is `run.root_run_id`: `completed`, `failed` (reason `error`) or `interrupted` (reason `interrupted`), or `interrupted` with no reason when an operation is still open (below). A run with no root step, or whose root end is not among the records the closing record lists, is `unknown`. `closing.outcome.stated` is what you said:

```python
run.close(outcome="failed", reason="error")
```

`outcome` is `completed`, `failed`, `interrupted` or `unknown`, and `reason` is a code: `error`, `timeout`, `cancelled`, `interrupted` or `policy`. Anything else is refused before a record is written. Your statement never replaces `observed`.

An operation with no end when `close()` runs gets no end written for it. It is in `open`, and a warning names it. When the root step ended `completed` and its end is among the records the closing record lists, `observed` is `{"status": "interrupted"}` with no reason. An approval request still waiting for its answer is one of them. `interrupt()` is the call for a run that stops on purpose: it ends every open operation `interrupted`, innermost first, and the closing record observes `{"status": "interrupted", "reason": "interrupted"}`, also when the root step had already ended `completed`. A root step that ended `failed` still observes `failed`.

`close()` reports gaps and does not raise for them. `close(strict=True)` raises `IncompleteTrailError` after the closing record is written. A second `close()` writes nothing and returns the first one's result; one that states an outcome logs that the statement is not in the trail. Every call after `close()` is refused. A `close()` made from inside `on_event`, which runs while the helper places a record, raises `RuntimeError` and leaves the run open: call it once the call that wrote the record has returned. A second `close()` waits at most `RUN_CLOSE_WAIT_MS` (120 s) for the first, then raises `ClosingNotDeliveredError`.

### One record outside a run

Some events happen outside any run: a session that starts, or a context compacted between two turns. `recorder.record_one(type, ...)` writes such an event as a one-record invocation (`sanning.agent/1` section 4.4). The record has its own root run id, which is also its run id, no parent, `run.seq` 0 and no previous record. No `agent.run_opened` and no `agent.run_closed` are written.

Use `open_run` when the event is part of a run, so the run's record positions cover it. Use `record_one` only when no run is open, or when the event does not belong to the run that is open.

```python
result = recorder.record_one(
    "agent.custom",
    content={"name": "session.compacted", "value": {"trigger": "manual"}},
    extra={"custom": {"name": "session.compacted"}},
)
# RecordOneResult(step, gaps, unbuilt)
```

`record_one` writes the types `record` writes: `agent.step.occurred`, `agent.decision`, `agent.file`, `agent.error` and `agent.custom`. It takes the same fields as `record`, and writes the content, case, agent version and scope as a run writes them. Any other type raises `ValueError` before a record is written. The record is the first record of its invocation, so a `not_captured` you pass is the `capture.not_captured` list a verifier reads. A `conversation_id` you pass is written as `gen_ai.conversation.id`, which `sanning.agent/1` allows on every type; the SDK never generates one. It groups the record with that conversation's runs and never pairs it with an approval: section 9.1 pairs an approval request with its answer across invocations, and `record_one` writes neither. It uses a fresh chain key by default and hands the key back to the anchorer once the record is written, so it never takes a position in a run's chain. A record that is not written is in `unbuilt`, and a delivery failure is in `gaps`, as in a run. Neither raises.

### Approvals and the store

An approval is two records in two invocations. `request_approval` writes `agent.approval.requested` about an operation of this run, named by its start's `event_id`, with the `actor` that decides: `human`, `policy` or `model`. When you open the run with a `conversation_id`, the helper keeps the request in an `ApprovalStore`, keyed by the conversation and by the request's own event id. The invocation that answers opens with the same `conversation_id` and `resume=True`, which reads the store before the first record, then calls `resolve_approval`. The answer's `approval.policy_hash` is the request's, or the `policy_hash` you pass to `resolve_approval` when the request names none. An answer whose `policy_hash` differs from the request's is refused, and the request still leaves the store.

```python
recorder = RunRecorder(anchorer, approvals=store)

# The first invocation stops for a person.
first = recorder.open_run(conversation_id="thread-7")
step = first.start("agent.step", run_id=first.root_run_id)
first.request_approval(subject_event_id=step.event_id, actor="human")
first.interrupt()
first.close()

# The answer arrives later, in this process or another that shares the store.
second = recorder.open_run(conversation_id="thread-7", resume=True)
second.resolve_approval(verdict="approved", actor="human", reviewer="alice")
result = second.close()
```

`resolve_approval` finds the request by its subject and its decider. With no `subject_event_id`, it answers the one request that is pending. It never guesses: an answer that matches two or more requests, or that matches none, is not written and is in `unbuilt`. Once exactly one request matches, it is taken out of the store whatever becomes of the answer's record. A resume that finds nothing pending writes the first record with `agent.approval.requested` in `capture.not_captured`. A request with the run id of an earlier unanswered request of the same run replaces it. For a resume whose answer you do not write, `recorder.take_resumed(conversation_id, actor)` takes out the one request that answer would have resolved. New input on a conversation, which a framework can treat as dropping what it waited on, is `open_run(conversation_id=..., supersedes_pending=True)`: the waiting requests are removed from the store with a warning naming each, and stay unanswered in the trail.

The calls that reach the store have `a`-prefixed forms (`aopen_run`, `arequest_approval`, `aresolve_approval`, `aset_conversation_id`, `awrap`, `aclose` and `atake_resumed`). They take an `AsyncApprovalStore`, whose methods are coroutines, as well as a synchronous one. A synchronous call that would reach an async store raises `TypeError`.

#### A store that outlives the process

Without `approvals`, the helper keeps requests in a `MemoryApprovalStore`, one per process. Pass your own store when the resume can arrive in another process: after a restart, on another host, or behind a queue. A memory store in another process holds nothing, so the answer is not written, and a run that closes with a request still held in memory logs a warning.

This is the store's contract, from the `ApprovalStore` docstring:

> Where pending approvals wait between two invocations of one conversation, keyed by the conversation id, one entry per request, by its `requested_event_id` (agent-events.md section 5.6). Two requests can be about one subject, as when a policy asks and then a human does. Pass a store that outlives the process when a resume can arrive in another one.
>
> The helper calls each method on a worker thread and waits at most `approval_timeout_ms` for it. A read past the limit holds nothing; a `put`, `take` or `clear` past it is a warning, and the call keeps running and can still land.
>
> Concurrency. Each method must be atomic on its own. The helper holds no lock that another run or process shares, so a `list` and the `take` after it are separate steps. The helper calls `put` once a request is handed to the anchorer. A resume calls `list` once, before its first record, and answers from what it read; it calls `take` once its answer is handed to the anchorer or found unbuildable, and it ignores what `take` returns. `take` returns `None` when the entry is already gone: another resume took it, `clear` removed it, or a later request with the same run id replaced it.
>
> Two processes that resume one conversation at once can both read the request before either takes it. Each then writes an `agent.approval.resolved` naming it, so the trail holds two answers to one request; one `take` gets the entry and the other gets `None`, and the helper warns for the one that got `None`. A store cannot prevent this through this interface: run one resume per conversation at a time.

The methods are `put(conversation_id, pending)`, `list(conversation_id)`, `take(conversation_id, requested_event_id)` and `clear(conversation_id)`. A store that lacks one of them is refused when the `RunRecorder` or the handler is built: the `TypeError` names each missing method.

This store is an example, not part of the package. It follows the contract on Redis, with redis-py: one hash per conversation, one field per request, and `take` and `clear` as one script each, so two resumes cannot both receive an entry.

```python
import json
from dataclasses import asdict

from sanning_anchor import PendingApproval

TAKE = """local v = redis.call('HGET', KEYS[1], ARGV[1])
if v then redis.call('HDEL', KEYS[1], ARGV[1]) end
return v"""
CLEAR = """local all = redis.call('HVALS', KEYS[1])
redis.call('DEL', KEYS[1])
return all"""


class RedisApprovalStore:
    def __init__(self, redis):  # redis.Redis(decode_responses=True)
        self._redis = redis
        self._take = redis.register_script(TAKE)
        self._clear = redis.register_script(CLEAR)

    @staticmethod
    def _key(conversation_id):
        return f"sanning:approvals:{conversation_id}"

    def put(self, conversation_id, pending):
        self._redis.hset(
            self._key(conversation_id), pending.requested_event_id, json.dumps(asdict(pending))
        )

    def list(self, conversation_id):
        return [PendingApproval(**json.loads(s)) for s in self._redis.hvals(self._key(conversation_id))]

    def take(self, conversation_id, requested_event_id):
        found = self._take(keys=[self._key(conversation_id)], args=[requested_event_id])
        return None if found is None else PendingApproval(**json.loads(found))

    def clear(self, conversation_id):
        found = self._clear(keys=[self._key(conversation_id)])
        return [PendingApproval(**json.loads(s)) for s in found]
```

Pass it as `RunRecorder(anchorer, approvals=RedisApprovalStore(redis.Redis(decode_responses=True)))`, or as `ApprovalOptions(pending=...)` on the LangChain handler. A Redis entry has no expiry, so a request that nobody answers stays until a `take` or a `clear` removes it.

#### How long a store call can take

The helper waits at most `approval_timeout_ms` (default `APPROVAL_STORE_TIMEOUT_MS`, 30 seconds) for each store call, and holds the run's lock while it waits. Every other call on that run waits too, so a slow store slows the agent: a store that never answers costs 30 seconds at each call that reaches it, `put`, `take`, `list` and `clear` alike. The `a`-prefixed calls wait for the store outside the lock. A read past the limit holds nothing: the run opens as if no request were pending, with a warning. A `put`, `take` or `clear` past the limit is a warning, and the call keeps running on its worker thread and can still land.

#### One invocation, one process

An `AgentRun` keeps the invocation's position, the next `run.seq` and the last event id, in the memory of the process that opened it. Every record of one invocation must come from that one `AgentRun`. Running one invocation across several workers is not supported: do not share a `root_run_id` between processes, and do not hand an `AgentRun`'s work to another process. A resume is a new invocation, so it can run anywhere that reaches the store.

## Trace a LangChain agent

```bash
pip install "sanning-anchor[langchain]"
```

```python
from sanning_anchor import AnchorCallbackHandler

with AnchorCallbackHandler(anchorer) as handler:
    agent.invoke(inputs, config={"callbacks": [handler]})
```

The handler supports LangGraph 1.x. It does not import LangGraph: it recognises
an interrupt (`GraphInterrupt`) and a resume (`Command`) by the names of their
classes, and the `langchain` extra installs `langchain-core` only, so install
LangGraph yourself when you use it. It is tested with LangGraph 1.0
(with `langchain-core` 0.3.67) and LangGraph 1.2 (with `langchain-core` 1.7).

Every chain, model, tool and retriever step is anchored as an `agent.*` record of
the `sanning.agent/1` vocabulary, with LangChain's `run_id` and `parent_run_id`
tree committed alongside a per-invocation `seq` and `prev_event_id`. A missing
record leaves a hole in `seq` and a moved one breaks the chain, so the trail is
deletion-evident and reorder-evident. An invocation opens with `agent.run_opened`
(which lists in `capture.not_captured` what this adapter cannot write), runs as a
root step, and closes with `agent.run_closed`. Every start has an end that names
it in `run.started_event_id`, and a tool call carries `gen_ai.tool.call.id` on
both: the model's id, or one this adapter assigns from the run id.

A moment LangChain reports as one event is one `agent.step.occurred`, with no
start, no end and no outcome, inside the run LangChain names: an agent action
(`run.source_type` `langchain.agent_action`), an agent finish
(`langchain.agent_finish`), and a retry between two attempts (`langchain.retry`,
inside the model call it retries). It commits the event as LangChain handed it.
A customer's own event from `dispatch_custom_event` is not recorded.

Four things decide whether your integration is correct, so they sit here rather
than in a guide:

- **The `with` block raises on a gap.** Leaving it out anchors what it can and
  walks past what it cannot, and you find out when an auditor asks. Leaving the
  block cleanly raises `IncompleteTrailError` for a gap; leaving it on your own
  exception only logs the gap, so it never replaces your error. A bare
  `handler.close()` reports gaps in `handler.gaps` and does not raise, because it
  runs in your `finally`; `handler.close(raise_on_gaps=True)` raises once the
  closing records are written, as `assert_complete()` does. Use
  `raise_on_gaps=True` on the handler to stop the agent instead: the lost record's error
  raises out of `invoke` or `ainvoke` at the step whose record was lost, so a
  tool whose start record is lost does not run. A callback writes every record
  it has, then raises the first one lost, so a lost tool end does not skip the
  tool's decision and file records. A lost record is any record of
  this handler's that is not in the trail: one the plane refused, one the
  handler could not build (the `chain` key function raised, the payload would
  not serialise), one a chain-store failure cost, and a step whose callback
  raised before its record was attempted, which is recorded as `unbuilt`. A
  lost file record (a file a tool returned) raises at the end of that tool's
  step, once every file it returned is recorded, so the next tool call does
  not run. When several are lost, the first one's error is raised. Any
  other error inside the handler (one after the step's record was attempted)
  is logged and the agent continues. An anchorer built with `fail_closed=True`
  stops the agent the same way on any lost record, without `raise_on_gaps`,
  and the handler then stays stopped: every later step raises the same error,
  and a new run on it raises an error that says to construct a new handler.
  With a buffer, a record is lost only once a later drain is refused for good,
  so the agent stops at the step after it.
- **A handler answers for its own records.** One `Anchorer` can serve a
  handler per request: `handler.gaps`, `chain_gaps`, `is_complete` and
  `close()` count only the records that handler wrote, so one request's lost
  record never makes another request's trail incomplete. The handler never
  closes the anchorer; close it yourself when the process is done with it.
- **The object the framework handed each callback is committed**: a chain's
  inputs or outputs, a model call's messages or prompts, a tool's input or output.
  It stays with you. `on_event` watches each record's outcome and cannot change it.
- **A file a tool returns gets its own record**, committed to the file's own
  bytes, with no setup: its `event.content_hash` is the file's SHA-256, and
  the bytes go to the log store as the record's content, like any other
  content. `metadata.artifact` names the file and carries no hash. A file the SDK cannot read becomes a
  `agent.file` record with `outcome.status` `failed` and `artifact.reason`, because silence is how
  files go unrecorded on a run that reports success.
- **A LangGraph pause and resume.** When a node calls `interrupt()`, LangGraph ends
  the run and reports the root as completed. The handler reads it as it is: the
  node's `agent.step.ended` and the root's carry `outcome.status` `interrupted`,
  and the closing record observes `interrupted`. `interrupt()` does not say who
  decides, and a resume value is any JSON, so the approval records need two
  things from you:

  ```python
  from sanning_anchor import AnchorCallbackHandler, ApprovalOptions

  handler = AnchorCallbackHandler(
      anchorer,
      approvals=ApprovalOptions(
          actor="human",
          # Read the resume value as an answer; raise for a value that is no verdict.
          verdict=lambda resume: "approved" if resume == "yes" else "rejected",
      ),
  )
  ```

  The handler writes `agent.approval.requested` before the interrupted node ends
  and keeps that record's `event_id` with the conversation (LangGraph's
  `thread_id`, never generated). The invocation that resumes the thread writes
  `agent.approval.resolved`, naming the request in `run.started_event_id`; the two
  are in different runs and are tied by `gen_ai.conversation.id`. Pending
  approvals are kept in this process by default. When the resume can arrive in
  another process, pass `ApprovalOptions(pending=...)`, an `ApprovalStore` from
  `sanning_anchor`: `put(conversation_id, pending)`, `list(conversation_id)`,
  `take(conversation_id, requested_event_id)` and `clear(conversation_id)`. Its
  contract, which includes that `take` is atomic, and an example on Redis are
  in "A store that outlives the process", under "Record an agent run" above.
  The handler calls the store from synchronous callbacks, so an
  `AsyncApprovalStore` is refused with `TypeError` at construction. The store
  holds one entry per interrupt. An interrupt in a subgraph or a nested runnable
  reaches the handler at each chain level it passes through, and one interrupt id
  is one request: the outermost level's request replaces the inner ones, and the
  resume answers it. A resume answers the one request pending on the thread. With
  two or more pending (two interrupts), it cannot tell which one it answers, so
  the answer is an `unbuilt` hole and the requests stay pending; a single request
  whose decider is not `approvals.actor` is an `unbuilt` hole too. Input on the
  thread that is not a `Command(resume=...)` makes LangGraph discard the
  interrupted task, so the handler removes the thread's pending requests with
  `clear` and logs a warning naming each one; they stay unanswered in the trail.
  This holds when the thread id first appears on a child run too, and a resume
  never removes anything. After `close()`, a callback writes nothing: a resume
  then is an `unbuilt` `agent.approval.resolved`. A resume with no pending
  approval, or whose store read runs past the limit, writes no answer and names
  both approval types as not captured. Only a LangGraph `Command(resume=...)`
  answers; a state dict with a `resume` key does not. A `verdict` or `reviewer`
  that raises costs the resolution: it is an `unbuilt` hole (`is_complete` is
  false), and the run's other records are written. A resume takes the request it
  answers out of the store whether or not its answer is written: after `close()`,
  when the answer cannot be built, and when `verdict` or `reviewer` raises. A
  missing answer is a hole the trail shows, where a request left behind would let
  a later resume write an answer nobody gave. It takes a request only when exactly
  one waits on the thread and `approvals.actor` decides it. A store that raises
  costs the resolution too, and a request it could not remove stays for a later
  resume to answer.

  Run one resume per thread at a time. Two processes that resume one thread at
  once can both read the request before either takes it, and each writes an
  answer to it. A slow store slows the agent: the handler calls the store from the
  callback while it holds the run's lock, so a store call that does not answer
  holds every other callback of that root run, for up to 30 seconds
  (`APPROVAL_STORE_TIMEOUT_MS`). One invocation must run in one process. Running
  one invocation across several workers is not supported. A resume is a new
  invocation and can run in any process that reaches the store.

  A `thread_id` is an id: 1 to 128 characters of `A-Z a-z 0-9 _ . : -`. One
  outside that grammar, such as an email address, is never rewritten or left
  out, so every record of the run is refused and reported in `gaps`, and the
  agent still runs. Use an opaque `thread_id`.

  When `interrupt()` is called inside a tool, the tool call ends `interrupted`
  in the invocation that started it, not `failed`. On resume LangGraph runs the
  tool again as a new tool call, with its own start and end, and the answer
  writes no end for the old one.

  The approval's subject, `approval.subject_event_id`, is the `agent.step.started`
  of the node that paused for the answer, not the start of a tool call. A verifier
  warns `ran_after_refusal` when a tool call ran after its approval refused it,
  and that check does not cover these runs: the re-run after a resume is a new
  operation that nothing links to the refusal. The records still show both.

  What Sanning can see after an answer depends on how you built the agent. In
  `private` it does not receive the verdict, so it can only look at what follows
  the answer ([section 7 of the vocabulary](https://github.com/sanning-io/specs/blob/v1.0.0/specs/agent-events.md#7-the-data-modes)):

  - When an approval node routes on the answer, an approved run shows a tool call
    and a decision (where you name a decision tool) after the answer, and a rejected run shows neither.
  - When `interrupt()` is called inside the tool, the tool runs again on both
    answers, so the records look the same whichever way the answer went (unless
    the tool raises on a rejection, which ends the call `failed`).
- **Decisions from a named tool.** State each decision in a tool call, and name
  the tool and the decision:

  ```python
  from sanning_anchor import AnchorCallbackHandler, DecisionTool

  handler = AnchorCallbackHandler(
      anchorer, decisions=[DecisionTool(record_conclusion, "credit_verdict")]
  )
  ```

  When `record_conclusion` ends `completed`, the handler writes an
  `agent.decision` named `credit_verdict`, whose value is what the tool returned.
  Pass the tool object: a tool that does not exist, a tool named twice, or a name
  that is no label is refused when the handler is constructed. The tool is
  matched by name: a tool with the same name triggers it. A call that ends
  `failed`, including a `ToolMessage` with status `error` (what
  `handle_tool_error` and `handle_validation_error` produce), writes no
  decision. **Name the
  decision for what was decided, and put the outcome in the value**:
  `credit_verdict` with the value `declined` is right, `credit_declined` is not.
- **An id that fails the grammar is refused.** An id is 1 to 128 characters of
  `A-Z a-z 0-9 _ . : -` (a tool call id, 1 to 256). The handler checks each id it
  writes and refuses a record whose id fails, naming the field and never the
  value. With `fail_closed=True` on the anchorer, or `raise_on_gaps=True`, the
  callback raises and the agent stops before its work. By default the agent keeps
  running: the record is an `unbuilt` hole (`is_complete` is false) and
  `handler.recording_status()` lists it under `refused` beside the anchorer's own
  status.
- **Transient failures are retried; a 4xx is not.** The plane has said the
  envelope is wrong, and repeating it is a slower failure rather than a
  recovery.
- **Show which policy a step applied.** Have the tool that reads or applies
  the policy return the file as its artifact, and the handler writes a
  `agent.file` record committing to the file's bytes, on that tool's run. The trail then shows which policy a step actually read, rather than
  which one was configured at startup. An auditor holding the policy runs
  `sha256sum` and compares it with that record's `event.content_hash`:

  ```python
  @tool(response_format="content_and_artifact")
  def read_underwriting_policy() -> tuple[str, dict]:
      """Read the underwriting policy in force."""
      return "Loaded underwriting policy v3.", {"path": "policies/underwriting-v3.md"}
  ```

  Hashing documents named at startup would record a declaration, not what any
  step read, so there is no option for it.
- **The closing record**. An `agent.run_closed` record is
  written once per root run, automatically, when `close()` runs -- no option
  gates it. It states how many records that root run anchored (the anchorer
  accepted them) and their ids, even `0`: a root run that anchored nothing
  still gets one stating the zero. Its outcome is `completed`, `failed`,
  `interrupted` (a LangGraph node interrupted the run) or `unknown`, with a
  reason code (`error` or `interrupted`) when it did not complete. An operation
  with no end when `close()` runs gets no end written, and a warning names it;
  when the root's own end is among the records the closing record lists, such a
  run reads `interrupted`, with no reason, in place of `completed`, and a
  `failed` stays `failed`. A root end that is not among them reads `unknown`.
  `close(outcome=..., reason=...)` states how you say it ended, with the reason
  one of `error`, `timeout`, `cancelled`, `interrupted` or `policy`: free text is
  refused. Once the handler is closed, every later
  record is refused, so nothing lands after a root's closing record.
  A `close()` that returns before the closing records are written raises
  `ClosingNotDeliveredError` (an `AnchorError`, from `sanning_anchor`),
  whatever `raise_on_gaps` says: the second of two concurrent calls waits at
  most 120 s for the first, and one called from inside an `on_event` hook does
  not wait at all. That includes one called from inside a closing anchor call
  (a hook on a closing record, a custom anchorer writing one): the closing
  that call is part of cannot be confirmed from inside it, so it raises every
  time, and retrying in a loop there only holds up the claiming `close()` and
  never succeeds. The hook guard logs it from a hook. From a custom anchorer
  the error leaves `anchor()`, and that root's `run_closed` comes back
  `unbuilt` (`complete=False`) unless the anchorer catches it.
- **The file role**. A tool's returned object can name
  `role` (`"input"` or `"output"`), `source` and/or `destination` alongside
  its `path` or `bytes`, and all three land on the artifact record
  unchanged. Absent unless the tool names them.
- **A file above `artifacts["max_bytes"]` is recorded unreadable, never truncated.** The
  default is 25 MiB (`DEFAULT_ARTIFACT_MAX_BYTES`).

- **The promoted fields name the model, the tool and the step**. Beside the run linkage (`run.run_id`, `run.parent_run_id`,
  `run.root_run_id`, `run.seq`, `run.prev_event_id`), each record carries, where
  LangChain hands it over: `run.name` (the step, by LangChain's own naming
  rule), `run.client` (the client class, such as `ChatOpenAI`), and under
  `gen_ai` the OpenTelemetry GenAI names, pinned to
  [v1.41.0](https://github.com/open-telemetry/semantic-conventions/blob/v1.41.0/docs/registry/attributes/gen-ai.md):
  `gen_ai.request.model`, `.temperature`, `.max_tokens`, `.seed`, `.top_p`;
  `gen_ai.provider.name` (the service that served the call, in OTel's
  well-known values plus `openrouter`; see below); `gen_ai.response.model`,
  `.id`, `.finish_reasons`;
  `gen_ai.usage.input_tokens`, `.output_tokens`, `.reasoning.output_tokens`;
  `gen_ai.tool.name` (the serialized tool's own `name`, never the run name a
  caller sets) and `gen_ai.tool.call.id`; `gen_ai.prompt.name`; and
  `gen_ai.agent.version`. `openai.response.system_fingerprint` sits in
  OpenAI's own namespace. Every record carries `otel.scope`: `sanning-anchor`,
  its version, and `https://opentelemetry.io/schemas/1.41.0`. v1.41.0 is the
  last core OTel release where these names are current; from v1.42.0 core
  marks them moved to
  [open-telemetry/semantic-conventions-genai](https://github.com/open-telemetry/semantic-conventions-genai),
  which has no release yet, and Sanning moves the pin deliberately once it
  does. A field LangChain does not hand over is absent, never empty: no
  response id when the provider put none on the message (LangChain's own
  `lc_run-…` id is never written as the provider's), no token counts when
  neither `usage_metadata` nor `llm_output` has them, no fingerprint from a
  non-OpenAI-compatible provider.

  ```python
  handler = AnchorCallbackHandler(
      anchorer,
      record_names=False,          # keep run.name and gen_ai.tool.name out
      agent_version="2026.10.1",   # gen_ai.agent.version on every record; a label, else ValueError
  )
  agent.invoke(
      inputs,
      config={"callbacks": [handler], "metadata": {"gen_ai.prompt.name": "underwrite-v3"}},
  )
  ```

  `record_names=False` exists because a record's metadata is visible whenever
  the record is, even in a pack whose content is withheld, and a tool's name
  can say more than you meant (`lookup_customer_ssn`). It omits both names and
  nothing else; they stay in the committed content, hashed and withheld like
  the rest.

For the event vocabulary and worked examples, see
[Trace a LangChain agent](https://docs.sanning.io/guides/langchain).

## Hand over a pack

When a compliance person asks for one agent's evidence over one period, the SDK
assembles it in one command, with no Node installed:

```bash
export SANNING_API_KEY=ANCHOR_READ_KEY   # the key needs the `anchor:read` scope

sanning-anchor bundle \
  --agent claims-triage \
  --from 2026-06-01 --to 2026-06-30 \
  --logs ./logstore \
  --out claims-triage-2026-06.zip
```

Replace `ANCHOR_READ_KEY` with a key from the console carrying `anchor:read`.
There is no flag for it: a credential in argv lands in shell history, and this
is a command people paste into tickets. A key missing the scope is reported as
a scope to widen, never as an absence of evidence.

| Flag | What it names |
|---|---|
| `--agent` | The agent's `agent_id`, as committed in each event's subject. |
| `--from` | Period start, inclusive: a whole UTC day written `YYYY-MM-DD`. A time is refused with a usage error. Required for a period pack. A case pack takes no dates: `--case` with `--from` is refused with a usage error. |
| `--to` | Period end: a whole UTC day written `YYYY-MM-DD`, and that day is included. A time is refused with a usage error. When it is today (the UTC date), the period ends at the end of the last sealed stamp interval instead, and a day after today is refused. Required unless `--case` is given. |
| `--logs` | Your `sanning.logstore/v1` store root: the local directory holding `content/` and `records/`, or `s3://bucket` or `s3://bucket/prefix`. |
| `--out` | Where to write the pack. A `.zip` suffix is appended when absent. |
| `--base-url` | The control plane. Defaults to `https://api.sanning.io`, or `$SANNING_BASE_URL`. |
| `--allow-unstamped` | Assemble even when records in the period are anchored but not yet stamped. Without it the verb refuses. Takes no value. |
| `--case` | Select a case's records and declare the pack about it. The records are those the plane returns for the case id (`case_id`, in clear), each kept only when its own signed `context.case_id` is the case; no window is derived, and `--from` and `--to` are refused with it; see [One case, no window](#one-case-no-window). |
| `--handoffs-only` | With `--case`, pack only the case's hand-off records: the minimum-disclosure selection for handing another organization your side of a case. |
| `--report-file` | Case file only: a file to put under `report/`. Takes a path, and may be given more than once. |

`sanning-anchor --help` prints that reference, the exit codes, and the offline
command that checks what the verb produced.

**The window is the plane's clock, not yours.** `--from` and `--to` are whole UTC days, matched
against each record's `received_at` (Sanning's receipt time), which the plane sets when it accepts the
envelope. That instant can be *earlier* than the local one you captured just
before calling `anchor()`: 433 ms earlier on a measured production run. A record
anchored within a moment of 00:00 UTC can then belong to the neighbouring day, and the
pack for the day you expected is short by that record while the command exits `0` and
warns about nothing, which is the one outcome a pack's reader cannot detect. Compare the
pack's event count against what you anchored, and build the neighbouring day too when they differ.

**A period that runs to today ends at the last sealed stamp interval.** With `--to` set to today's UTC date, the pack ends at the end of the last sealed stamp interval before the build, not at midnight: every record in it has a stamp, and two builds in the same interval hold the same records and state the same period. The pack states that end as a time, and the signed text keeps ISO 8601 (`2026-10-14 → 2026-10-20T15:00:00.000Z`). "Today" is the UTC date the control plane reports, which at 00:30 in London in summer is still the day before: a `--to` after it is refused. This needs a control plane that answers `GET /api/v1/user/records/sealed-through`.

**Pass `prefix` to one of `S3ObjectStore` and the `ObjectLogStore` wrapper,
never both.** Each of them prepends it, so the same value on both writes
`ts/ts/content/...` while every reader looks under `ts/content/...`, and the
writes and the reads disagree. `bundle` refuses correctly, with `no record
object in your log store`, and that message does not name the cause.

That writes **one zip**: a signed `sanning.stamp.evidence/v2` `bundle.json`
beside `logs/<event id>.json`. Proofs come from the Sanning
index; the raw bytes come from **your** log store and never left it. The verb
**reads the whole pack offline before it writes anything**, the way the
kernel's `verify` reads it, and exits with the code `verify` gives that pack. A
pack that would read failed at the auditor is never produced (exit 1, no file).

**A stamp settles after it seals.** For the first minutes of its life an
interval stamp has not reached the public record. A pack built then is written
and reads incomplete, as `verify` reads it, and the verb exits `2` and prints
the kernel's lines. Running it again once the stamp settles writes a new pack
in its place. Your records are anchored, retained and stamped throughout, and
nothing about them is wrong.

It also refuses to assemble a **short** pack, in two cases, because a recipient
cannot tell a short pack from a complete one:

- Records whose **record object is missing** from your store make
  `subject.agent_id` unknowable, and one of them may be this agent's.
- Records that are **anchored but not yet stamped** have no inclusion proof, so
  a pack built now omits them and says so nowhere inside itself. The stamper
  seals on an interval, and running again once it has is usually the whole fix.
  `--allow-unstamped` assembles anyway, and then the summary tells you the pack
  is short so you can say so in the cover note. Under `--case` it refuses, exit `2`,
  when a record it would leave out was signed at or before the last record the pack
  holds (a delivery retry stamped later), because the pack would claim the case's
  records inside a period it does not cover; run again once the stamper has sealed
  it. A record signed after the last held one can still be left out.

No signing key is required. Without one, the container is sealed with a
one-time assembly key, and every event inside already carries its agent's own
signature. With `SANNING_SIGNING_SEED`, the pack carries a signed declaration
of what it holds.

### One case, no window

`--case` selects a case's records, and takes no `--from` or `--to`:

```bash
sanning-anchor bundle --case case-4b19de \
  --agent assessor \
  --logs ./logstore --out case-4b19de.zip
```

- **The pack's records are the ones the plane returns for the case id, kept on their own signed `context.case_id`.** The SDK sends the case id, in clear, in the projection beside every record of a type the plane indexes (`index`). `--case` asks the plane for the records filed under the case id (`case_id`, in clear, 1 to 256 characters: no SDK writes a case id longer than 128, and 256 is the plane's query bound only), pages to the end, and keeps each one whose own signed `context.case_id` is the case. It reads nothing else and derives no window. A case pack takes no dates: it holds every record of the case, however long the case runs.
- **The case id only finds candidates.** It is the producer's own word and is not signed, so it selects nothing on its own: a row filed under it whose signed record names another case is left out and counted on the summary.
- **Records sent without a projection are not found.** A custom one-argument submitter would send none. A custom `client` must accept the `index` keyword argument that carries the projection (`submit(envelope, index=None)`): the `Anchorer` reads the signature of `submit` at construction and raises `TypeError` unless it has a parameter named `index` or takes `**kwargs`, rather than drop the projection in silence.
- **A record in the window that names no case refuses a declared pack** (the signing seed is set), and an undeclared pack leaves it out and says how many. Pass the case id when you anchor.
- **The pack's period is the span of the records it holds**: the earliest to the latest `signed_at` among them, read from each signed envelope. The pack's records run oldest first by that signed time, never by a time the plane's list sends. It is not a window, so there is nothing to pad. The declaration's `period.end` is the exclusive bound, one millisecond after the latest record.
- **A case pack holds every record of the case, however long the case runs.** `--from` or `--to` with `--case` is a usage error: a case pack takes no dates. The control plane reads the whole case, and a plane that does not say how much of the case fell outside what it read, or says some did (a record dated after its clock, or a plane that predates the whole-case read), is refused: the verb exits `4` rather than build a short pack. An empty selection exits `4` and writes nothing.
- **A case file** (several `--agent`) selects the same way: each pack states its own records' span, and the case file's `period` line is the span of all of them.

### Several agents, one case: the case file

Give `--agent` more than once, with `--case`, and the verb writes a **case file** (`evidence-bundle.md` section 5.6): one pack per agent, each built, declared and verified exactly as a single pack is and sealed by that agent's own key (or the organization's evidence key, below), unpacked under `packs/<agent>/` in one zip beside `contents.json` (an unsigned index of every file and its SHA-256) and `HOW-TO-VERIFY.txt`. Nobody signs the case file itself.

```bash
export SANNING_API_KEY=…
export SANNING_SIGNING_SEEDS=assessor=SEED_A,checker=SEED_B
sanning-anchor bundle --case case-4b19de \
  --agent assessor --agent checker \
  --logs ./logstore --out case-4b19de.zip
```

Replace `SEED_A` and `SEED_B` with each agent's 64-hex signing seed. `SANNING_SIGNING_SEEDS` holds one `<agent>=<seed>` entry per `--agent`, and `SANNING_SIGNING_SEED` is refused beside it (unless the organization kind is set). To seal every pack with your organization's evidence key instead, set `SANNING_SIGNING_KEY_KIND=organization` and put that one key in `SANNING_SIGNING_SEED`: it seals the wrapper of every pack and authors every declaration, each pack's `issuer` is `{ kind: organization }`, and each record inside stays signed by its own agent. `SANNING_SIGNING_SEEDS` is refused beside the organization kind. `--logs` is given once for every agent, or once per `--agent` in the same order. A case file exits with the code the kernel's `case` gives the file it wrote, and writes nothing when that case would read failed; a case reads its worst pack. Every agent named gets a pack in the file, or nothing is written:

**The organization's evidence key is registered on first use.** With `SANNING_SIGNING_KEY_KIND=organization`, the first `bundle` that declares, a single pack or a case file, registers the key before it sends any declaration: it asks Sanning for the organization's evidence key and, when there is none, signs a challenge with the seed and registers its public key. It prints one line saying so, and Sanning emails every owner of the organization. A later run finds its own key and goes on. Make the seed with `openssl rand -hex 32` on the machine that builds the packs; it never leaves that machine. `SANNING_API_KEY` is then a key with exactly `handover:enroll` (the Build evidence permission), `anchor:read` and `anchor:write`; an agent's API key never carries `handover:enroll`. A run that sends no declaration (no seed, the agent kind, or a pack or case file that is not complete yet) never asks. `bundle` exits `4`, sending no declaration and writing nothing, when the organization already has a different evidence key (registering never replaces one: an owner or admin revokes it in the console, on the Signing keys page, and the message prints the first 16 hex characters of both keys), when the key can never be the evidence key (Sanning holds it for another identity, or it was revoked: make a new seed), when the API key lacks `handover:enroll`, and when Sanning refuses the registration for any other reason, named by the plane's code. When Sanning cannot be reached, after retries on a timeout, a 429 or a 5xx, it exits `2` and sends nothing.

| Agents' packs | Exit | Written? |
| -- | -- | -- |
| All verified | `0` | Yes. Each agent's declaration is anchored. |
| All verified, sandbox | `3` | Yes. Each agent's declaration is anchored. |
| Any incomplete (a stamp not confirmed yet included), none failed | `2` | Yes, with the incomplete packs inside and no declaration anchored. Running it again later writes a new case file in its place. |
| Any pack failed | `1` | No. The output names the agent and prints the kernel's lines. |
| No pack fails alone, and the case fails (through a hand-off) | `1` | No. The output says the case file would read failed and prints the kernel's lines. |
| Records not stamped yet, or the record index could not be reached | `2` | No. |
| Any agent's run could not run, or the file cannot be assembled or written | `4` | No. |

`contents.json`'s `absent[]` is written empty. `--report-file <path>`, given any number of times, adds files under `report/` beside a `report/README.txt` saying no record commits to them.

Every declared pack (`SANNING_SIGNING_SEED` set), single or in a case file, declares `sanning.declaration/v2`: each record is signed `handoff` (a record `envelope-spec.md` section 4.1 governs, claimed in `handoffs[]`) or `step`. Each hand-off record's message travels as `logs/<event id>.json`, exactly `JCS(message)`, the bytes its `message_hash` commits to. So a full pack reads cleanly as a case, and `--handoffs-only` is the minimum-disclosure selection for handing another organization your hand-off records alone.

## Hand-offs between agents

`create_handoff(anchorer=..., case_id=...)` records a message that passes between two agents, over any transport: the sender's `send` writes `agent.handoff.sent`, the receiver's `receive` verifies what arrived and writes `agent.handoff.received`. Both are `sanning.agent/1` records, built by `build_agent_record` and refused before signing unless they read `verified`: each carries the message's part counts, and the receiver's carries the sender's `event_id`. A receiver that holds the bytes of a file part names its position in `held_parts`, which the record lists as held and not checked. Two additions, both offline:

- **How `gen_ai.provider.name` is decided**. It is a signed
  claim about which service served the call, so it is written only from an
  endpoint this adapter positively observed, in the client library's own
  precedence. First, the base-URL field in the client's `dumpd()` kwargs:
  `openai_api_base` (`ChatOpenAI`), `anthropic_api_url` (`ChatAnthropic`),
  `groq_api_base` (`ChatGroq`), `xai_api_base` (`ChatXAI`), `endpoint`
  (`ChatMistralAI`). These clients resolve their own LangChain-level
  variables and the LangSmith gateway into that field at init
  (`OPENAI_API_BASE`, `ANTHROPIC_API_URL`/`ANTHROPIC_BASE_URL`,
  `GROQ_API_BASE`, `XAI_API_BASE`, `MISTRAL_BASE_URL`), so the field is what
  the client will call. When the field is unset, the variable the underlying
  SDK reads decides (`OPENAI_BASE_URL`, `GROQ_BASE_URL`), then the SDK's
  documented default. The provider is that endpoint's host: a `ChatOpenAI`
  pointed at OpenRouter says `openrouter`. In every other case the field is
  absent: a client class not listed (`ChatDeepSeek` serializes as
  `not_implemented`, with no kwargs), a host this package does not know (a
  local server, a proxy, the LangSmith gateway). `run.client` still records
  the class. The table is pinned by captures from the published clients in
  `tools/langchain-callback-conformance/provider-captures.json`. An endpoint
  chosen in code, such as a pre-built `client=`, is not in the serialized
  form; set the endpoint with the client's `base_url` instead.
- **`receive(expected_sender=...)`** refuses a message whose signed sender key is not the one you name, with `HandoffUnexpectedSenderError`, before anything is recorded. Either case of a key is the same key.
- **`handoff.verify(attachment=..., wire_bytes=..., expected_sender=None)`** reads a message before you decide: it runs the checks `receive` runs and returns a `HandoffVerifyResult` (`message`, `message_hash`, `message_bytes_hash`, `sequence`, `content_type`, `sender_public_key`, `sender_record`, `sender_run_records`), and records nothing. A message that is not the one the sender committed to raises `HandoffAlteredError`; call `receive` with the same input to record the tamper. Then `receive` records your decision.
- **`handoff.confirm(sent=..., received_record=...)`** lets the sender check the receiver's own signed record (`received.received_record`, sent back over your transport) with the kernel's `verify_envelope` and `read_handoffs`. It returns a `HandoffConfirmation` with `confirmed`, `reasons`, `outcome`, `receiver_public_key` and `readings`, and `reasons` names every check that failed. A receipt is untrusted, so nothing about it raises.

`outcome` is a required keyword argument of `receive`: the agent decides, `accepted`, `rejected` or `failed`, then `receive` records that decision, before your agent acts on the message. There is no default: this SDK never signs a decision on your behalf. Omitting `outcome` is a `TypeError` from Python itself, since it is a required keyword argument; passing it anyway with `None` or a value outside those three words raises `HandoffOutcomeRequiredError` before anything verifies or is written. The spec has no word for "received, not yet decided", which is a real limitation [Hand off between agents](https://docs.sanning.io/guides/handoff) states in full, along with the refusal table. Both SDKs return the same reason names, graded against one recorded cross-language run.

## Agent records (`sanning.agent/1`)

An `agent.*` record follows the [`sanning.agent/1` vocabulary](https://github.com/sanning-io/specs/blob/v0.1.0/agent-events.md). Build one with `build_agent_record`: it reads the record against the vocabulary's schemas, offline, and raises `InvalidRecordError` for a record that does not read `verified`, with the spec's reason code in `reason` and a JSON Pointer in `at`. `build_envelope` runs the same check, so a record that breaks the schema is never signed. Every record the SDK builds, of any type, carries a fresh random `context.salt`, which the builder writes and no builder argument sets. Below `full`, Sanning does not receive it. A record you build yourself and pass as `build_record`, or to `build_envelope`, is signed with whatever well-formed salt it carries, and the spec makes no finding on a weak one. `sanning_anchor.salt.fresh_salt` is internal and not public API. `build_event_record`, and so `Anchorer.anchor` called with an `event_type`, builds `event` (the default), `checkpoint` and `declaration`. It refuses an `agent.*` type with `event_schema_missing` at `/extras/event_schema`, because only `build_agent_record` builds one, and any other type, such as `claims.decision`, with `event_type_not_in_set` at `/event_type`, because a verifier reads it `failed`. `build_envelope` refuses a hand-built record of such a type the same way. To sign and chain an `agent.*` record, pass `build_record` to `anchor`: it is called `(subject, chain_key, previous_hash)` under the chain lock and must return a record whose `event.content_hash` is the hash of the call's `content`. `recording_status().refused` lists each refused record by event id, type, `reason` and `at`, including a record `build_record` returned that is not one it may sign.

```python
from sanning_anchor import agent_content, build_agent_record, decision_content

content = agent_content(decision_content(name="quote_issued", value={"rate": "3.50"}))
record = build_agent_record(
    event_type="agent.decision",
    subject={"type": "agent", "agent_id": "claims-triage"},
    content=content,  # content.bytes are the JCS bytes content_hash commits to: retain them
    metadata=metadata,  # run, otel and decision, as the schema names them
)
```

`agent_content(value, scrub_credentials=True)` replaces the whole value of every credential-shaped key with `"[scrubbed]"` before hashing, and the record built from it says so in `context.content_scrubbed`. `read_agent_record(record)` returns the reading without raising.

## Verify a pack

Verification lives in `sanning-proof` and needs no account, no key and no
network. The case reader reads one pack or a whole case file, and `bundle`
prints it as its next step (the `case` command reads a v2 pack from
`sanning-proof` 0.13.0), over the zip itself:

```bash
sanning-proof case pack.zip
```

The library call grades one bundle on its own:

```python
import json, pathlib
from sanning_proof import verify_evidence_bundle

pack = pathlib.Path("pack")
verdict = verify_evidence_bundle(
    json.loads((pack / "bundle.json").read_bytes()),
    content={p.stem: p.read_bytes() for p in (pack / "logs").glob("*.json")},
)
verdict.status  # "verified"
```

Whoever receives your pack does not need this SDK. For what a verdict proves,
and the four things it does not claim, see
[Verify](https://docs.sanning.io/verify/what-a-verdict-means).

## Parity with the TypeScript SDK

`sanning-anchor` and `@sanning/anchor` produce **the same signed bytes** for the
same event, and **the same signed pack body**, byte for byte, for the same
pack, so a mixed fleet hands over one pack. Both are gated against the same
pinned corpus for the envelope, and against an oracle that imports neither SDK
for the evidence pack, so neither language can pass by agreeing with the
other.

The LangChain adapters commit `JSON.stringify(payload)`, which `json.dumps` is
not, so this package reimplements it against a cross-language corpus generated
from the real `JSON.stringify`.

**One case refuses rather than diverges:** an integer outside
±(2<sup>53</sup>−1), a set, a reference cycle. JavaScript would round the first
one, and two different 64-bit trace ids can round to the same double, which is
a false integrity verdict rather than a formatting difference. So it fails at
**anchor** time, while you can still fix it, rather than at verification, when
the record is already sealed. Convert the value before anchoring it.

## Development

```bash
pip install -e ".[dev]"
black --check src tests
pytest -q
```

MIT licensed.
