# Bundle v2 wire format

This guide describes the v2 export, verification and import format, including
explicit untrusted recovery. Trust roots and import authorization are configured
separately; the file format does not establish trust in a signer.

## Restricted canonical JSON

Canonicalization ID: `op-sys.restricted-json.v1`. This is deliberately **not**
RFC 8785/JCS: object keys sort by Unicode scalar value, not UTF-16 code units,
and floating-point numbers are not supported.

- Values are JSON objects, arrays, Unicode scalar strings, integers in
  `[-9007199254740991, 9007199254740991]`, booleans and null. Object keys are
  strings. Duplicate keys, floats/exponents, NaN/Infinity, surrogates and
  non-JSON values are rejected.
- Input is UTF-8 without a byte-order mark. Canonical output is UTF-8 without
  whitespace or BOM. Strings are not Unicode-normalized; canonically equivalent
  Unicode spellings therefore remain distinct bytes.
- Object keys sort lexicographically by Unicode scalar value. Array order is
  preserved. Integers use shortest decimal, with zero encoded `0`, never `-0`.
- Quotes and backslashes are escaped. Backspace, tab, LF, form feed and CR use
  `\b`, `\t`, `\n`, `\f`, `\r`. Other U+0000–U+001F use lowercase
  `\u00xx`. All other scalars, including `/`, U+2028 and U+2029, are literal.
- Control input and canonical output are bounded by the existing 8 MiB control
  ceiling, lowerable by callers but never raised. Nesting is at most 32 edges
  from the document root. Raw parsing also rejects recursion overflow. This is
  a bounded format, not a claim of allocation-free parsing or constant memory.

Ordinary tests contain exact Unicode/escape/order bytes, adversarial decoding,
a deterministic 200-value cross-serializer corpus, and the frozen public
`tests/fixtures/bundle-v2/canonical-signed.json` vector. The latter is generated
and checked with the independent native test crypto provider and a separate
serializer/framing path. Its RFC8032 seed is public test data, never a real key.
Native CI on each supported platform remains required.

## Manifest and envelope

The envelope has exactly `schema`, `manifest`, `signatures`, and `anchors`.
`schema` is `op-sys.bundle.v2`. The manifest has exactly:

- `schema_version`: `op-sys.bundle.v2`;
- `canonicalization`: `op-sys.restricted-json.v1`;
- `signer_policy`: `required` or `unsigned`;
- `files`: ordered objects with exactly `path`, lowercase SHA-256 `sha256`, and
  nonnegative integer `bytes`;
- `ledger` and `migration`: objects covered in full by the signature;
- `created_at`: integer UTC Unix seconds, no later than year 9999.

No file may declare `manifest.json` itself or collide under the existing
portable path rules. The bounded archive reader must independently check the
exact entry set, sizes, complete streamed bytes, hashes and ledger semantics;
parsing this contract does not perform those checks.

A required envelope contains exactly one signature record. An empty signature
list gives `bundle_signature_missing`; multiple/duplicate signatures are
rejected, not interpreted as an alternative-signature policy. A deliberately
unsigned envelope contains neither signatures nor anchors. Unknown fields or
canonicalization IDs are rejected, not silently ignored. Anchor lists are
bounded to eight proof records; their proof/trust validation is a separate gate.

The manifest digest is SHA-256 of its canonical bytes. The byte message passed
to the signature API is:

```text
ASCII("op-sys:bundle-signature:v2") || NUL || uint64_be(manifest_byte_length) || canonical_manifest
```

The manifest's schema and canonicalization ID are therefore signed. The signature
API further authenticates its signature header (algorithm, key ID, fingerprint,
embedded public key and signed-at) using its existing length-framed domain.
The v2 signature record adds the exact `canonicalization` ID; it must match the
signed manifest. Embedded public key consistency is not implicit local trust.

## Independent notary proof and archival policy

The proposed local proof format is `op-sys.bundle-notary-proof.v1`, containing
exactly `schema`, `receipt`, and a `signature` record. It is a narrow
signed-notary timestamp contract, not an RFC3161, X.509 or transparency-log
parser. Other proof formats are rejected. It has no built-in trusted root.

The receipt has exactly `schema` (`op-sys.bundle-notary-receipt.v1`),
`canonicalization`, `receipt_id`, `manifest_sha256`, `signature_sha256`,
`recorded_at` and `incident_policy` (`op-sys.pre-cutoff-anchor.v1`). The receipt
ID is 1–128 ASCII letters/digits or `._:-`, starting with a letter/digit. The
signature digest covers the entire canonical v2 signature record, including its
header and canonicalization ID. The independently signed message is:

```text
ASCII("op-sys:bundle-notary:v1") || NUL || uint64_be(receipt_byte_length) || canonical_receipt
```

The notary's authenticated signature time must equal `recorded_at`. Both
manifest and signature digests must match exactly. The verifier must already
have an explicitly accepted notary public-key snapshot and incident policy;
trusting a bundle signer does not authorize it as a notary. The notary and
signer fingerprints must differ. Different keys alone do **not** establish
organizational independence or a trustworthy clock: those are separate owner
review and authenticated-exchange responsibilities. No production notary is
provisioned or accepted by a fixture test.

A receipt must be no earlier than the manifest creation and claimed signing
time, no later than verification time, within the notary's signing interval,
and within the signer's signing interval. It must strictly precede every known
signer revocation/compromise cutoff. The same notary/receipt-ID pair may appear
only once. Any supplied invalid, late, untrusted or duplicate proof fails the
policy; invalid proofs are never silently discarded to get a different result.

A current trusted, nonrevoked/uncompromised signer may verify without a proof,
but that result explicitly says `archival_validity.valid=false`. Expired,
revoked or compromised signer snapshots require a verified pre-cutoff anchor.
In particular, compromise rejects **every unanchored signature**, even one
with an authenticated backdated `signed_at`.

Notary retirement/expiry alone preserves receipts recorded within its accepted
interval. Any known notary revocation/compromise rejects all of its receipts;
there is no recursive self-timestamp exception. A new independently reviewed
basis would be required to recover trust after a notary incident. This is the
fixed incident policy, not a bundle-provided relaxation.

Results distinguish `verified_trusted`, `valid_untrusted`, `invalid`, and
`unsigned` in this v2 component; the archive integration separately labels
v1 as `legacy_insecure`. Mathematical signature validity, local trust and
archival validity are separate. Validated public signer/notary snapshots and
their hashes, exact public proofs, proof hashes and evaluation time support
later inspection. `revocation_freshness=not_online_checked` is always explicit.
The owner must preserve the exact receipt/proof, archive and authenticated
trust/incident history in independently controlled immutable retention. The
local verifier proves neither external retention immutability nor current
revocation freshness, and must not be represented as doing so.

## Frozen public notary interoperability vectors

`tests/fixtures/bundle-v2/notary-archival.json` has SHA-256
`34636d79a4bd6231f06d1739fa5acb9d145d7090b83f3d72e6f8ccff56ef83d4`.
It freezes 32 policy scenarios and 12 exact signing transcripts. Each transcript
contains canonical bytes, digest, domain/length-framed message, authenticated
header-frame digest and native-generated Ed25519 signature. The ordinary
`test_bundle_notary_fixtures` tests pin the complete fixture, independently
re-serialize and verify/re-sign with the native test provider, and compare the
product's policy and public proof/snapshot reporting with the frozen cases.

Cases cover current unanchored trust, signer/notary expiry, signer revocation
and compromise before/at the receipt cutoff, self-notarization, unknown/future
trust, notary incidents, exact manifest/signature binding, early/future/late
receipts, mismatched signed times, duplicate/unknown proofs, signature tampering,
required-signature removal and deliberately unsigned input. Construction and
the separate isolated reference verification use native crypto and stdlib
serialization without importing the product implementation; their evidence
and owner-run procedure belong to the private acceptance packet, not runtime.

The keys, identities and times in these vectors are public examples. A verifier
must apply its own accepted signer interval. Distinct example keys demonstrate
key separation, not organizational independence or the accuracy of a real clock.
These envelope/proof vectors are not complete ZIP or SQLite restore archives,
and do not establish the retention properties of an external service.

## Archive integration

Exports now write this closed v2 envelope, and archive verification checks the
declared sizes, streamed hashes, exact member set and semantic database/metadata
invariants. Default import accepts only `verified_trusted`. Removing a required
signature fails with `bundle_signature_missing`; relabeling a stripped bundle
as explicitly unsigned still fails default admission with `bundle_unsigned`.
No flag or test-only direct-import entry point implicitly bypasses this policy.
Default export requires an existing active signer; use explicit `trust keygen`
or initialization to provision one. `--no-sign` writes an explicit unsigned v2
manifest. Export's singular `signature` result is a deprecated alias and is
not written to the closed ZIP envelope.

V1 inspection is always `legacy_insecure`, even for a mathematically valid
old Ed25519 signature. Malformed Ed25519 signatures are `invalid`, not unsigned.
The trust-tree archive ban is unconditional. The private-keystore ban has only
the narrow discard-only legacy recovery exception described below.
Review binds the v2 schema, admission mode, canonical manifest digest and exact
signature-record digest into the one-shot operation intent. Old manifest-only
approvals cannot authorize it. Restore repeats the small trust evaluation
under its root lock before staging and again immediately before the first
publication, without copying/verifying the database again for either recheck.
Thus a long stage/backup crossing natural signer expiry requires an anchor;
an otherwise valid pre-cutoff anchor still preserves archival admission.
Backup, staged approval consumption, journal,
rollback and writer-fencing obligations are unchanged.

Still pending: the second isolated owner verification of the frozen notary
fixtures, dated recovery-policy acceptance, all standing tests and owner
acceptance. A signer's authenticated `signed_at` remains self-asserted and
cannot by itself prove that a signature predates compromise. No anchor provider,
production key or live-state action is authorized by these fixtures.

The Python SDK exposes `OpSys(...).state.export_bundle(path, sign=True)`,
`verify_bundle(path)`, `import_operation(path)` and
`import_bundle(path, actor=..., approval_id=...)`, each with lower-only
`ArchiveLimits`. Request/decide the returned exact operation through the normal
ledger approval API and close its store before offline import. The SDK uses
the same trusted-v2 and governed one-shot paths; it neither bootstraps trust
from a bundle nor automatically syncs restored state to Cloud. Inspect
`verification_state` and `valid` in SDK verification results; structural
failures raise `BundleError`, and default import rejects all nontrusted states.
Both `import_operation` and `import_bundle` also accept the same explicit
`allow_unsigned=True` or `allow_legacy_insecure=True`, with `override_reason=...`;
repeat the exact options during import. There is no ungoverned SDK bypass.

## Explicit untrusted recovery policy

`op-sys.bundle-recovery.v1` defines a separate recovery operation. It does not
ignore verification failures or authorize changes to live state. Default unsigned
and v1/HMAC admission ends with v2:

- `--allow-unsigned` admits only deliberately unsigned v2. It has no global
  removal date under this proposal; every import still needs a new bounded grant.
- `--allow-legacy-insecure` admits only structurally valid v1, with or without
  an old signature. The compiled window closes at **2026-12-22 00:00:00 UTC**.
  No environment variable or CLI flag extends it. Host-clock correctness is an
  operator responsibility. After closure, retain evidence for a separately
  reviewed recovery plan; do not turn the clock back or edit the cutoff.
- Both require an initialized recipient, normal actor/policy permission,
  non-secret `--override-reason` (1–1,024 characters, at most 4,096 UTF-8 bytes,
  no control characters), and an explicitly approved one-shot grant even if
  normal policy requires zero votes. The exact reason is intent-bound; spaces
  are significant. The approval's display `--reason` is not a substitute.
- Grant lifetime is at most six hours from issuance; a lower policy limit or
  requested TTL still applies (the normal default remains one hour). Schema,
  mode, recovery-policy ID, manifest, exact signature record (including absence),
  reason, actor, target root and workflow context are bound. No existing
  digest-less/manifest-only approval can authorize recovery.
- Invalid/malformed v2 signatures and unknown signed v2 keys cannot use either
  flag. Required-signature stripping remains fatal. Deliberately editing the
  manifest into unsigned form produces different, unauthenticated input that
  needs its own reviewed unsigned grant; it does not authenticate the source.

For a disposable isolated recipient, the public command sequence is:

```bash
op-sys --state-root /private/recovery/recipient init
op-sys --state-root /private/recovery/recipient approval request \
  --action state.import --target-type state --target-id state_root \
  --bundle /private/recovery/input.zip --allow-unsigned \
  --override-reason 'Recover reviewed synthetic data; provenance untrusted' \
  --reason 'Approve the exact synthetic recovery intent' --ttl-seconds 3600
op-sys --state-root /private/recovery/recipient approval decide \
  --id <returned-approval-id> --decision approve
op-sys --state-root /private/recovery/recipient state import \
  --bundle /private/recovery/input.zip --allow-unsigned \
  --override-reason 'Recover reviewed synthetic data; provenance untrusted' \
  --approval <returned-approval-id>
```

For eligible v1 input, replace `--allow-unsigned` with
`--allow-legacy-insecure` in **both** commands. Review the returned operation
digest before voting. Stop all writers; this is an offline restore, not merge
or ordinary ledger opening. Valuable/live state requires separately authorized
target-specific inventory, independently verified backups and restore drill.

Only this legacy path tolerates the exact root `keystore.json` entry, capped
at the control-file bound (8 MiB by default, lower-only). It is streamed for
CRC/hash/exact-member checks, never parsed, staged, copied or installed.
Case/Unicode aliases and every `trust/` entry remain rejected. The original
archive is not edited or deleted: retain it privately as untrusted evidence,
separately from any recovered root. This discard-only import does not migrate,
extend or destroy the independent 30-day local HMAC custody quarantine.

Successful recovery reports `unsigned` or `legacy_insecure`, `trusted: false`,
and a `recovery` object with a HIGH warning, exact reason hash and discarded
entry hashes. An atomic `state.import.insecure` audit records `severity: high`
with approval/digest details, not secret key bytes or the raw override reason.
The approval intent contains only the reason's effect digest; it is not a
secret-storage channel. Publication rechecks grant expiry and the legacy
window immediately before applying. Already-published crash recovery may
finalize after either deadline only with the existing full-byte/journal proof;
it never repeats the restore. Audit failure prevents publication and grant
consumption. Other backup, rollback and replay protections are unchanged.

Reconcile recovered records and promptly re-export v2 from a newly trusted
local signer. That signature attests the new export, not original provenance;
retain its recovery audit and original receipt. Proposed final removal criteria
are owner-confirmed reconciliation, independently verified retained recovery
evidence, no unresolved restore, and the applicable legal retention schedule.
There is no automatic archive/key deletion or cleanup authorization. Before
the dated cutoff, the state/security owner must inventory remaining legacy
artifacts, notify affected holders and decide any separate recovery plan;
legal/dependency and release owners must accept retention/removal obligations.

External Record file chunks referenced by the captured SQLite snapshot are
included under `ledger-files/`, including retained pending contributions. Their
sizes and digests must match the snapshot. Missing or corrupt chunks fail export
or verification. The usual bundle byte/entry limits still apply; a bare database
copy is not a standalone backup of external file content.
