# Connector E2E runtime

The original E2E integration patch has been applied and extended in the core and CLI.
`serve` now selects E2E by default. There is no automatic plaintext fallback.
The old HTTP app transport requires `serve --dev-plaintext`, and refuses a data
directory that already contains a paired E2E binding. Hermes itself still uses
its authenticated loopback `/relay` and `/relay/media` contract.

## Configure the local runtime

Keep the existing `dataDir`, `listen` and optional `logLevel`. Add:

```json
{
  "e2e": {
    "port": 8788,
    "tlsKey": "/absolute/private/path/mailbox.key",
    "tlsCert": "/absolute/path/mailbox.crt",
    "witness": {
      "url": "https://your-separate-witness.example/checkpoint",
      "publicKey": "<the witness Ed25519 public key: 64 lowercase hex characters>"
    }
  }
}
```

The example public key must be replaced. TLS material belongs to the deployment;
the runtime never installs a test certificate or turns off certificate checks.
Missing TLS settings stop startup with `e2e_tls_required`. Missing witness
settings leave pairing/history available but reject actions with
`witness_required`. For more than one binding, set `e2e.binding` to the binding
ID the local `pair` command should use.

The mailbox listener binds only `127.0.0.1`. Publishing a remotely reachable
TLS endpoint and its AuthProvider routing belongs to the deployment. The local
adapter uses `Unbound-Route`, a base64url encoding of canonical public JSON:
`{binding,endpoint}` or `{binding,endpoint,pair_id}` for bootstrap. It selects a
route only. Device/connector signatures, pinned lists and pairing proofs still
provide authority. No QR secret, bearer credential, private key or content is
allowed in that header. This is an explicit local AuthProvider adapter; it is
not an asserted hosted AuthProvider contract.

The private endpoint uses the core's **same SQLite connection**. Its independent
`e2e_migrations` table does not replace the core's schema version. The embedded
mailbox uses a separate `mailbox.sqlite`, containing public routing/list metadata
and ciphertext only. Protected endpoint records use a mode-0600
`e2e-wrapping.key` outside SQLite. Keep that key in the deployment's protected
credential/backup store; losing it does not authorize generating a replacement
for existing encrypted state. The runtime refuses that case. No live credential
was provisioned during this lane's tests.

## Pairing, devices and reconnects

`pair` talks to the running service's mode-0600 console socket, prints the real
one-use QR, compares every SAS group and waits for the signed result. Console
consent cannot arrive over the mailbox. A first console pairing creates an admin
device. An additional pairing still needs the existing owner's membership
rotation; a new device cannot authorize itself. The signed result is returned
to that device through its bootstrap route after activation.

`status` and `doctor` show pairing state, witness selection (URL host only),
and device signing-key fingerprints.
They do not expose public keys, QR secrets or private keys. The app registry
allows 32 devices. Retired endpoint mappings remove their core device/page rows
before replacement registration; lifetime action receipts remain intact. Legacy
registry rows without a current signed endpoint mapping are retired on E2E
activation. Explicit binding deletion also removes its embedded-mailbox routes,
sessions, envelopes, recovery frames and file chunks.

Live authenticated mailbox delivery and reconnect fetches use persisted crypto
budgets. Exhausted live work stays in the mailbox and is fetched in later
windows. Startup drains the durable inbox and missed ciphertext. Sessions are
renewed before their ten-minute expiry. Every epoch starts with
`membership_result`, then device scopes, conversation pages and history pages;
original event/message/conversation identities and app cursors survive.

An authenticated stream gap requests the independent signed recovery exchange.
The connector persists its fresh private key before publishing a proposal. Only
the owner-signed commit activates the new list. Recovery does not fill an old
stream gap, advance an old cursor or authorize another action. Cancellation is
terminal for that plan; a new attempt uses fresh plan/action IDs. Retained IDs
and terminal receipts reject changed retries. Recovery fetches select one plan
and return plan, proposals, then its terminal frame. Exact terminal retries remain
available after rotation without admitting old-epoch app data.

## Core receipts and action proof

All core receipt result content, including legacy receipt/media status rows,
is migrated into authenticated encrypted records before E2E admission. The core
receipt table retains identities, fingerprints, status and an encrypted marker.
Encryption shares the queue/conversation/receipt transaction. Receipt tombstones
are binding-lifetime state; quotas reject new work rather than evict dedup data.
The rest of the endpoint's core event database and Hermes media cache are still
private endpoint plaintext. They are never copied to the mailbox. Logical
SQLite deletion does not promise physical-media erasure.

Secure action acceptance includes the full operation and prompt version in its
fingerprint. The core queue item, encrypted result, prompt CAS and ledger entry
commit together. Before release and dispatch, the ledger mirrors its hash chain
and verifies a fresh signed witness checkpoint. A witness ahead of the local
chain fences a rolled-back host. A socket write is `dispatching`, not an ACK.
Only stock's `inbound_ack` records `acknowledged`. A reopened `dispatching` item
becomes terminal `outcome_unknown` and is never sent a second time. Its encrypted
live status tells the app the result is unknown. Verified restores still require
owner rotation; normal reconnect cannot clear that fence.

Hosted routing to `hermes.unboundchat.net` or
`hermes-android-staging.unboundchat.net` automatically selects the owner's pinned
relay witness at `https://<mailbox-host>/e2e/v1/witness/<binding>`. No local signing
key or extra install/pairing input is needed. `boot_witness_hosted` records this
selection; `doctor` and `status` show `hosted (<host>)`. The relay must have its
witness secret and witness route deployed before releasing a connector with this
default. The pins and complete wire contract are in
[`hosted_witness_v1`](../../protocol/extensions/hosted_witness_v1.md).

Explicit `e2e.witness: {url, publicKey}` always overrides the hosted default.
Unknown origins still require that explicit configuration and log
`boot_witness_required`; embedded mailbox mode has no default. Pairing and
history remain available without a witness, but secure actions are blocked.
A configured or hosted witness that is unreachable also blocks action release:
selecting a default does not weaken checkpoint verification.

The deployment-owned witness is a separate trusted service, never a fake local
signing key in the connector. `HttpLedgerWitness` POSTs a signed request to its
configured URL. The body adds `endpoint`, a fresh hex32 `nonce`, and `time` to:

- `{operation:"mirror",binding,record,previousHash,hash}`; or
- `{operation:"latest",binding}`.

The signature covers `D("ledger-witness-request") || C(body)`. The witness must
check connector authority, freshness and nonce reuse, persist append/CAS order,
and return the `Checkpoint` shape in `ledger.ts`, signed over
`D("ledger-checkpoint") || C(checkpoint.body)`. An exact retry of the current
head returns the same checkpoint for an unchanged signed list; older records
conflict. `latest` must return the fresh durable head. Keep witness records
private: they contain action identities and fingerprints, not action content.
The hosted witness retains only its durable head and bounded admission metadata;
action records are validated transiently and are never logged. HTTP loopback
is admitted for isolated tests; it is not an off-host rollback witness.

## Prompts and media

Stock clarify questions bind the immutable authenticated action, binding owner,
route, body and ordered options to a random `promptVersion`. The version is saved
in the core event before commit, so old history keeps the version actually shown.
Answers compare the live owner/option/version atomically with core acceptance.
Retries reuse the saved result, including its version. Stale versions cannot
create another queue item or consume the live prompt.

Stock approval prompts do **not** include their hidden executable action and
arguments. They remain display-only text over E2E; they get no executable review
record. This follows protocol rev 2's explicit read-only rule. Inferring tool
authority from a displayed card would be unsafe. A future engine adapter must
supply the actual reviewed record before enabling these approvals.

Uploads retain protocol hex16 file/action IDs without an HTTP-header or UUID
translation. The endpoint verifies every chunk/tag and the full file hash, then
adopts the exact verified bytes into the core media adapter. Upload ownership
and immutable intent are rechecked before sending. Outbound files are sealed
before publication; the connector sends the encrypted `media_manifest` and event,
and the app downloads authenticated ciphertext chunks. No new media-download
operation or plaintext app route was invented.

E2E staging supports empty files and up to 100 MiB. Unmodified stock Hermes'
`RelayMediaClient` only supports nonempty files through 25 MiB. A send outside
that smaller engine limit returns `stock_media_size_unsupported` before queue
acceptance. It never reports a successful agent delivery. Existing earlier-epoch
attachments require a new current-epoch transfer identity after rotation; their
old ciphertext is not treated as a current-epoch blob grant.

## Session import

`import` calls the real profile-selected
`hermes --profile PROFILE sessions export - --format jsonl --newer-than TIME`
(with optional source filter). It requires the deployment's installed Hermes
CLI; no console-engine/admin session command is used. Activity selection exports
whole sessions. Requests and `(binding, session, snapshot)` identities deduplicate;
changed snapshots edit stable display rows instead of appending duplicate chat.
Null route/profile/source evidence stays unknown. Exported paths, tool-call text
and attachment URLs are never opened or executed.

Imported transcripts are read-only. `continue_import` rejects `strategy:"exact"`
before any engine command. `strategy:"seed"` saves a stable plan and sends inert
context to a fresh UUID thread through normal secure acceptance. It preserves the
original transcript and import source record. `submitted` means admitted work,
not proven tool execution. Oversized seed context fails explicitly.

## Verification boundary

`test/e2e/full-path.e2e.ts` is discovered through `full-path.test.ts` and uses the
same opt-in environment gate as the stock Hermes fixture. The simulated app uses
only the minimal `crypto.ts` and `protocol.ts` reference modules copied from the
p2 protocol lane into `test/support/`; production imports neither. The sole added
reference line disables checking those frozen files under this package's stricter
TypeScript settings. All live test keys and TLS material are disposable, stay
under this source tree and are removed after the test.

The full path covers real stock Hermes, both SAS confirmations, E2E default/no
plaintext app route, new-thread send/reply, exact prompt version and stale
rejection, upload/download, queued restart, signed recovery/epoch activation,
original history/action identity preservation, encrypted core receipt markers,
and SQLite mailbox canaries. The test uses a separate loopback witness server
with a key the connector never receives. This proves the wiring, not a deployed
off-host service or physical power-loss durability.

Unit coverage also checks 32-device admission, retirement/page cleanup, encrypted
legacy receipts/reopen, transactional rollback, missing/unavailable witnesses,
fresh-head rollback fencing, uncertain dispatch, stock's narrower media boundary,
and whole-session import/dedup/read-only/seed behavior.

The optional phone MCP extension still has no negotiated E2E phone wire; it stays
offline. OpenClaw's direct remote-submit path does not yet provide the shared
secure acceptance/dispatch contract, so E2E actions for it fail closed with
`secure_openclaw_unavailable`. Existing explicit dev-mode tests retain those
adapters' prior behavior. Hosted AuthProvider integration, real phones,
independent crypto review and deployment witness provisioning were not performed
under this loopback-only lane.

## Local check results

Machine guards ran before all test commands. No tests use concurrent mode.
No Git/Beads command, dependency installation, external request, Flutter command,
VM/runner operation or project-memory write was performed.

```text
cd connector && bunx tsc --noEmit
exit 0; no stdout/stderr (the compiler has no success-summary line).

cd connector && bun test
 228 pass
 3 skip
 0 fail
 2287 expect() calls
Ran 231 tests across 32 files. [14.66s]

cd connector && UNBOUND_E2E_HERMES_PYTHON=$HOME/codex-artifacts/hermes-venv/bin/python UNBOUND_E2E_HERMES_SRC=$HOME/codex-artifacts/hermes-src bun test test/e2e
 122 pass
 0 fail
 1890 expect() calls
Ran 122 tests across 10 files. [19.42s]

cd connector && bash packaging/build.sh --target linux-x64
Build complete: packaging/dist (linux-x64); SHA256SUMS written.

cd connector && packaging/dist/unbound-connector-linux-x64 help
or config; 3 doctor found a FAIL. WARN checks alone return 0.
exit 0 (the help text ends with a blank line).
```

The three ordinary-suite skips are the two existing stock fixtures and the new
full-path fixture. The explicit opt-in command runs all three, with no skips.
Bun's path filter also includes `test/e2e-layer`, hence the ten-file opt-in run.
