docs/internal/agenthub-storage.md

AgentHub authoritative storage v1

Committed RAM and WAL format

Hub persistence preserves recognized version-1 state.yaml as generation zero's checkpoint. It adds an independent proactive security-time.v1, a bounded semantic WAL, and an atomic state-head.v1 selector. New generations use state.checkpoint.%016x.yaml and state.wal.%016x.v1. The selector, not directory enumeration, chooses the checkpoint/WAL pair. Checksums detect corruption. Owner-private regular nonsymlink files remain the trust boundary. Complete older valid images cannot be detected without an external anchor.

The binary envelope is closed and versioned. Integers are unsigned big-endian. Version is 1. Hashes are SHA-256 over the domain followed by the specified bytes. Every domain below ends in one NUL byte.

File or frameMagicFields after magicBytes
Security horizonAHSTIME\0version u32, reserved-through u64, checksum52
State selectorAHSTHEADversion u32, generation u64, checkpoint sequence u64, revision u64, floor u64, checkpoint digest, WAL-header digest, checksum140
WAL headerAHWALHDRversion u32, generation u64, base sequence u64, revision u64, floor u64, checkpoint digest, base prefix digest, checksum140
Batch headerAHWALBATversion u32, total length u64, sequence u64, base revision u64, final revision u64, final floor u64, operation count u32, reserved-zero u32, prior prefix digest, checksum124
Mutation headernonekind u16, version u16, flags-zero u32, expected revision u64, result revision u64, floor u64, payload length u32, reserved-zero u3240
Commit trailerAHWALCMTversion u32, sequence u64, repeated total length u64, batch digest, checksum92

Each mutation has a 32-byte checksum after its payload. Digests and checksums in the table are 32 bytes. Total batch length includes the complete header, records, record checksums, and trailer. Unknown kinds, versions, flags, reserved fields, impossible lengths, and complete invalid checksums fail closed. Only a genuinely incomplete final uncommitted batch may be ignored.

HashDomainCovered bytes
Horizon checksumAgentHub/security-time/checksum/v1first 20 horizon bytes
Checkpoint digestAgentHub/hub-checkpoint/digest/v1exact checkpoint bytes
Selector checksumAgentHub/hub-state-head/checksum/v1first 108 selector bytes
WAL-header checksumAgentHub/hub-wal/header/checksum/v1first 108 header bytes
WAL-header digestAgentHub/hub-wal/header/digest/v1complete 140-byte header
Batch-header checksumAgentHub/hub-wal/batch-header/checksum/v1first 92 header bytes
Record checksumAgentHub/hub-wal/record/checksum/v1mutation header and payload
Batch digestAgentHub/hub-wal/batch/digest/v1complete header and all records including checksums
Commit checksumAgentHub/hub-wal/commit/checksum/v1first 60 trailer bytes
Initial prefixAgentHub/hub-wal/prefix/base/v1checkpoint digest then u64 sequence, revision and floor

Each batch names the preceding committed prefix. Its digest becomes the next prefix. Healing retains the prefix at captured sequence N, so later complete batches can be copied byte-for-byte to the new generation. Old and new pairs must be durable and equivalent through K before selector replacement. Successful directory sync must precede append K+1. Uncertain selection stops appends until strict recovery. Readback alone is not durability proof.

Healing copies committed suffixes outside the writer in chunks of at most 1 MiB and fsyncs each caught-up boundary before trying cutover. The writer copies at most a 64 KiB remainder before selector replacement. A larger remainder returns to catchup, with at most 64 attempts per maintenance call. Sustained churn may defer healing; it never permits an unbounded tail copy under the writer. Checkpoint encoding, tail catchup and their hooks leave committed reads and later WAL mutations available.

The security horizon uses a 60-second UTC-minute quantum, 20-second renewal lead, and 5-second maintenance poll. Renewal uses max(wall, semantic floor), never the restart clamp. The target is the strict next minute after the greater of that basis and the current horizon. If the initial reservation is already inside the renewal lead, startup applies the due renewal before opening listeners. This prevents a short first reservation from expiring before the first maintenance poll; the same minute quantum and renewal rule apply. Restart clamps RAM time to the old horizon without repeatedly extending it. Traffic cannot enqueue, wake, or flush a persistence owner. The existing rollback check remains against semantic time.

Group commit keeps exact global revision consent. Same-base requests conflict; only sequential revisions or explicitly ticketed internal history may share a batch. The group window is 2 ms, with 64 ordinary operations and an 8 MiB target. One larger legal operation may use a batch alone, bounded by MaxStateBytes plus 1 MiB. The queue is bounded by 256 operations and twice the maximum batch bytes. Healing triggers at twice MaxStateBytes, 8,192 records, one hour, graceful shutdown, or explicit maintenance. Hard WAL bounds are four times MaxStateBytes and 65,536 records. These do not lower semantic population limits. Closed mutation schemas and their numeric IDs are documented with their owner before their payload codecs are implemented. There is no arbitrary-state or generic patch fallback.

Graceful close reports recovery or final-healing errors to the service's first-error owner. It still joins all storage workers and releases the lifetime lock. The service records that result before closing the snapshot budget; neither Close nor Wait reports a clean shutdown after failed final healing.

Semantic payload version 1

The following numeric kinds are closed schemas, not a state-diff format. Every payload is one UTF-8 canonical JSON object. Fields appear in the order below; there is no whitespace, unknown/duplicate field, alternate number spelling, or trailing byte. Integers are unsigned decimal; fixed IDs, digests, secrets and frames use the existing lowercase hexadecimal representation. Optional values are explicit null. Arrays retain the state's canonical key ordering; notice arrays retain increasing revocation age. An absent result is a validated purge, never a free-form deletion. Replay verifies the exact old key and SHA-256 digest of its canonical domain row, all revision/counter/deadline transitions, signed frames and immutable file references. It never signs or generates randomness. All digests in payloads use AgentHub/hub-wal/domain-row/v1 plus NUL and the exact canonical JSON row. Each payload is at most 68,157,152 bytes. A framed single-operation batch is at most 68,157,440 bytes. Encoding rejects either limit before admission. Collection bounds remain the existing semantic limits.

Payload string sizing matches default encoding/json escaping exactly, including six bytes for each &, <, and >. Checkpoints retain their existing HTML-escaping-disabled canonical encoder and matching separate size mode.

Kind/versionSchema, in field orderAdditional bounds and constraints
1/1floorOne u64; floor-only reservation, result revision equals expected or expected+1 for explicit issuance reservation
2/1previous, credentialExact operational credential replacement; selected issuance floor and activation in this same record
3/1endpoint, previous, credentialExisting endpoint certificate replacement; unchanged key and ID
4/1previous_origin, endpointOne new withdrawn, unretired endpoint, empty ACL/notices, access/binding revision 1
5/1endpoint, previous_origin, previous_publication, publication_revision, published, retired, publicationOne publication/withdrawal/retirement, unchanged binding and access
6/1endpoint, client, approval, previous_access, previous_row, revoked, access, row, tag, evicted, revocation_listOne exact epoch revoke; evicted notice only at the 1,024-notice bound; no secret bytes
7/1client, approval, previous_row, revoked, rowOne exact admission epoch revoke
8/1endpoint, client, approval, observedFirst-use observation for this exact unrevoked/unexpired epoch only
9/1input, previous_origin, binding, publication_revision, publicationExplicit confirmed higher-binding repair with exact old generation and observed maximum
10/1previous, authority, operational, endpoints, invitations, pairingsAuthority succession; every retained endpoint moves in ID order, unchanged identity/credential/ACL/access/publication state; only succession cancellation of invitations/pairings
16/1endpoint, previous_alias, previous_socket, alias, socketExact local endpoint presentation/application configuration; unchanged signed/public/authorization state, alias <=256 bytes and absolute NUL-free socket <=4,096 bytes
20/1invitationOne newly created unclaimed invitation, with deterministic deadline cleanup recomputed from the prior state and record floor
21/1invitations, admissions, grantsExisting client invitation claim/ACK/diagnosis/completion/approval only; every invitation has a nonzero prior digest. Exactly one non-deadline invitation; any grant must match its purpose, subject, claimant/SPKI, profile, receipt, secret, approval time, expiry and newly allocated revision. Other invitation changes are exact deadline cleanup.
22/1invitations, pairingsExact equality to recomputed deadline expiry/purge only, up to 4,096 invitations and 256 pairings; cannot disguise a valid cancellation or another row patch
23/1invitationsExact explicit cancellation/removal; at most one non-deadline cancellation
30/1pairings, invitations, peers, forkPairing prepare/claim/context/approval/activation/diagnosis/cancellation/removal and linked invitation; all non-deadline results share one exact request/genesis relationship, with the invitation's claim request, target and claimant bound to that pairing. An unclaimed invitation cannot accompany an unrelated pairing or peer change. Fresh bilateral consent may activate a different request epoch in the removal second, but cannot backdate activation or resurrect the removed request.
31/1pairings, invitations, peers, forkExact peer lineage proposal/decision/collision/fork with its linked pairing; at most one non-deadline relationship

Nested closed payload structures have these orders. Invitation change is row_id, previous, invitation; Pairing change is request, previous, pairing; Peer change is genesis, request, previous, peer. A zero previous digest means creation, and only the creation-capable kind permits it. Admission approval is client, previous, authorization. Endpoint grant is endpoint, client, previous_access, previous, authorization, access, notices, revocation_list. Authority endpoint result is endpoint, previous_binding, binding_generation, binding, publication_revision, publication. Repair input is EndpointID, ExpectedBindingGeneration, ObservedConflictGeneration, NextBindingGeneration, ConfirmStoppedClone. Fork proof is genesis, request, incoming, containing the exact closed Trust witness from peerForkProof. It is checked again during replay and grants no bypass.

Exact resulting domain rows use all and only the current version-1 fields in their declaration order in types.go: Credential, LocalAuthority, Trust, Resolution, Authorization, EndpointAuthorization, Notice, Endpoint, Invitation, Pairing, Peer, PeerTransition, PeerForkEvidence, PeerCollisionWitness, PairingConflict and Address. This pins the order as part of this codec, independently of YAML mapping order. Embedded claimant locks keep their closed identity codec. Their existing scalar/frame/string/array bounds apply. The compact payload preflight counts exact output bytes before encoding or queue admission, including default-named repair fields. Payload bounds are 3,090,112 JSON nodes and depth 36, allowing closed operation wrappers around a legal state row. The resulting checkpoint keeps the unchanged 3,000,000-node and depth-32 bounds. Private keys and certificates are referenced by immutable credential names/digests only, never copied into WAL payloads.

Kinds 6, 7 and 8 have narrow constructors and replay validators. They cannot replace an endpoint or authorization row. Other kinds build only the listed domain results and must reproduce the complete prepared candidate exactly. The full transition validator remains mandatory for these wider operations. Unrepresentable combinations fail before any file creation or WAL append.

Operational issuance, endpoint registration and authority succession prepare inert credentials and commit their selected floor and activation in one WAL record. They do not require a prior ReserveSecurityTime transaction. The existing explicit endpoint-renewal reservation API retains its exact previous issuance check. WithFinalCutSecurityTime supplies a RAM-only execution clock for time-dependent operations. Preparation samples it under semantic ownership; the writer samples again immediately before append, after immutable file work and the preappend hook. Stale prepared work fails rather than changing its timestamps or signatures. Publication, binding repair, configuration and non-fork peer-lineage decisions have no time deadline and do not require a floor-only write just to accept their context. Callers without a context clock retain the deterministic explicit-time API; production executors must attach their live clock at the boundary.

A valid security-second advance retains conflict classification with a distinct internal cause. A cleanup, cancellation or persistence error joined with it is not a pure time refusal. The store never rebases or retries the candidate. The joining Prepared owner may rebuild one unpublished candidate under the same revision fence.

The prepared batch owns only immutable files it created with O_EXCL. A pre-append failure, including the final time check, removes those exact files and syncs their parent directories. Collisions never transfer ownership of an existing file. Cleanup ownership ends immediately before the first WAL write; append/fsync uncertainty and even a definite append rollback retain all staged credentials. Successful replacement also retains valid superseded credentials. TestWALFinalCutRemovesOnlyPreparedCredentials covers operational issuance, endpoint registration/renewal and authority succession, including clean retry and strict WAL replay. Collision/partial-file and append-started tests cover the other cleanup ownership boundaries.

Startup cleanup recognizes only state.tmp- plus 32 lowercase hex characters, state.tmp-head- plus a canonical decimal uint32 from os.CreateTemp, and security-time.tmp- plus 32 lowercase hex characters. Recognized leftovers must be owner-private regular nonsymlink files. Near-matches are untouched; unsafe recognized entries fail startup. Cleanup syncs the root directory after any removal, including when a later unsafe entry makes startup fail. TestStartupCleansExactAuxiliaryTemporaries and TestStartupRejectsUnsafeAuxiliaryTemporaries exercise these rules.

Pairing authority identities are short-lived preparation material, not lifetime authorization tokens. Authority credential and complete trust are rechecked after loading. Local approval signing runs outside the semantic and RAM owners, with exact authority, credential, request epoch and revision checks before and after signing. A stale frame is cleared and never enters a candidate or reply. Inbound peer resolution retains the initially selected request/activation epoch through credential loading and clears owned credentials on epoch or pin mismatch.

Test fixtures use CommittedSnapshotForTesting through testkit.ReadHub to inspect an independently owned committed copy, without reading stale state.yaml, acquiring a second file lock or healing on each query. This API is not durability evidence. Crash/replay and strict Close/reopen tests remain the proof of persistence. testkit.WriteHubFixture acquires the real lock on a closed isolated Hub before replacing generation-zero fixture data; it is setup, not a production mutation or a corruption helper. Corruption tests edit the actual selected files. Private bulk fixture edits stay in test-only checkpoint helpers rather than expanding the closed WAL schemas.

The store owns durable Hub and client trust state. It reads and writes one strict version-1 YAML shape per store and never migrates or rewrites an unrecognized document. The package source map is the implementation guide.

Protection and layout

paths.Resolve supplies private hub, client, config, and runtime roots. State and credential files are owner-only regular files. Open acquires the store lock, loads the selected bounded checkpoint and committed WAL prefix, validates their closed shapes and relationships, then exposes purpose-specific projections. DirectoryCatalog returns the cached immutable public-only catalog and the current private store revision under the same read lock; DirectoryCatalogAtRevision rejects stale bases. A commit builds and verifies a changed public selection before writing, then installs it only after definite durability. An identical public selection reuses the committed catalog. Open/recovery rebuilds from a complete strict snapshot. Poisoned stores publish no catalog result, including the old cached one. No catalog file is persisted. Explicit local floor-only ReserveSecurityTime updates copy the immutable header and commit one typed WAL record without advancing the administration revision, cloning all rows or rebuilding the public catalog. Equal-floor reservations do not write. TLS uses the independent proactive horizon and can neither request a floor reservation nor flush the WAL. Its credential selection still validates the selected credential outside RAM locks. Disk failure or horizon exhaustion may refuse new TLS. Passive diagnosis can still describe the last known committed state without claiming a pending result. Semantic uncertainty refuses authorization, catalog use and new mutations. Storage latency still bounds durable administration completion; it does not retain a request-facing RAM or registry mutex during that wait.

Control mutations and automatic selector healing share this poisoned diagnostic mode. The store notifies the service of semantic uncertainty, which records the cause without cancelling its global context or closing the control listener. Passive status/browse stays available; unrelated established sessions survive. Only the affected authorization epoch or endpoint scope is detached when its operation may have committed. Horizon renewal errors are separate and never make the service fatal.

Production pairing operations carry a narrow live security-time callback in their context. The store invokes it at preparation and again at the final WAL append cut before applying any approval, cancellation, retention, or recovery result; test callers without that callback retain explicit deterministic timestamps. The callback must not call into the same store. Active Peer trust must match its active Pairing.RemoteTrust, request, digest, and completion; the store projects only the original ceremony, both approval frames, and retained current authority lineages. Pending and denied successors, collision witnesses, terminal fork evidence, recovery rows, removed relationships, and dial addresses stay private. A terminal fork or removal drops relationship evidence in its commit revision, while a fresh pairing has a new evidence epoch. Signed approvals remain historical proof after key succession and deadline expiry, not a renewed activation decision. Atomic replacement and credential ordering are implementation details covered by store tests.

Exact endpoint approval credential selection

store.SameEndpointApproval owns authorization-epoch identity for credential disclosure, application preflight and frontend revalidation after a human pause. It ignores aliases and usage history, but compares the complete grant and rejects recognized revocation. Client transport and frontend do not own parallel copies.

ClientStore.EndpointApprovalTLSCredential in store/endpoint_approval_tls.go borrows the approval chosen for application startup and one fixed effective security-time sample. There is no ID-only endpoint client provider. It selects the device reference and endpoint pin only from a snapshot matching the exact endpoint ID/SPKI, profile, authorization revision, secret and receipt, with no recognized revocation. Existing receipt validation uses invitationwire.DecodeReceipt through the store's receipt adapter and enforces access expiry, including equality and the durable floor. After initial admission, post-I/O and signing checks use the later of that sample and the persisted floor. A floor-only update cannot invalidate an unchanged, unexpired grant. Receipt expiry refuses at equality; device certificates retain the identity profile's inclusive NotAfter boundary. Signing contention waits within the caller's cancellation/deadline and the existing default TLS handshake allowance. Each file-lock retry reloads and revalidates the same approval; it neither extends grant deadlines nor adopts a replacement grant.

Client read callbacks own a copied snapshot, not a continuously held file lock. After credential-file loading, the exact approval and device reference are therefore checked against another current snapshot before the credential can return. Same-second mutations are checked even when the security floor does not advance. Mismatch releases the loaded signer, clears the loaded certificate and returns a fixed credential refusal. Labels and first-use history are not approval identity. The returned signer checks that same endpoint approval and device reference under the client mutation and file locks, holding both through the key operation. A committed revocation, missing descriptor or replacement grant therefore refuses a previously loaded signer. It does not rebase onto a fresh grant; explicit onboarding and a newly selected approval retain their separate paths. The caller owns the borrowed approval until credential release, which also drops the signer's reference to it. This selection introduces no durable fields or wire changes.

Durable documents

Hub state contains revision and security-time metadata, authority and operational credentials, admissions, endpoints, invitations, pairings, and peers. Invitation rows carry the immutable claimant lock and only the secrets required by their current phase. Endpoint rows carry signed identity, current hosting binding, current publication, and current revocation-list frames beside private publication and access counters, ACLs, and age-ordered notices. The strict current shape has no compatibility reader for unsigned endpoint rows. Validation checks each signature and exact endpoint, current authority/binding digest, origin revision, state, access revision, and canonical lexical notification tag set. The authority origin counter must equal the greatest retained current signed publication revision, or zero when no endpoints exist. Retired endpoints remain retained, so every origin allocation has a current publication. Load and recovery reject an inflated unsigned counter rather than allowing it to select a later signed revision. Registration signs a withdrawn publication at its allocated origin revision and an empty revocation list at access revision 1. Publication changes (including retirement after withdrawal) advance the origin revision and replace the signed publication. Grant, re-grant, and revocation replace the complete signed revocation list at the new access revision. At 1,024 notifications, revocation evicts the oldest private notice before signing the replacement set; the revoked ACL remains revoked. Prepared authority activation advances and re-signs every retained endpoint's binding and publication, including withdrawn and retired endpoints, in one candidate transaction. It preflights the domain and origin revision capacity, every binding generation, and every retained endpoint key before authoring replacement frames. Endpoint ID order assigns distinct consecutive origin revisions; each binding gains one generation and names the new current authority head and generation. Publications keep their published or withdrawn state, including retired endpoints, and bind the replacement digest. The transition validator requires all retained endpoints to advance together with both publication and retirement state unchanged, even when a state-changing candidate has valid replacement signatures. It rejects additions during succession. A signing or precommit failure leaves the old snapshot selected; uncertain persistence emits no success, and restart loads whichever complete strict snapshot was selected. Signing occurs before persistence, never on load or after commit.

Explicit endpoint conflict repair is a separate narrow transaction in store/repair_endpoint.go, not an authority transition or an ordinary publish. It checks the exact store revision, endpoint ID and retained binding generation, requires stopped-clone confirmation, and takes exactly max(local_binding_generation, observed_conflict_generation)+1 with checked overflow. A one-use validation callback checks the operator's displayed evidence outside store and registry locks before credentials are loaded or signatures are prepared. The semantic owner rechecks the exact revision and binding generation. The callback returns only the verified maximum binding generation, releases its directory ownership, and retires before returning.

Repair validates the existing endpoint signer and the existing current local authority signer against the verified lineage head, not the original retained pin. It signs the higher dual-signed binding and a matching published record, advances the local origin/publication revision, and commits once. Its transition validator allows changes only to those records/counters, publication state and the store revision. ACLs, access revisions, revocation lists, credentials, endpoint identity, authority trust and unrelated rows must remain identical. Ordinary transition validation still requires consecutive binding increments; only this explicit repair transaction can skip conflicting generations. Definite precommit failure leaves the selected snapshot unchanged. Uncertainty publishes no successful repair fields or effect, poisons the store, and requires strict recovery of the complete snapshot on disk. Repair does not promise that new evidence cannot produce a later conflict.

Client state contains revision and security time, the device credential, saved entry-hub trust, endpoint descriptors, and pending requests or credentials. Unanswered rows retain the exact request material needed for retry. After the claimed response is stored, the row retains the narrow recovery state and no longer retains request/root material. There is no alternate pending-row shape.

Saved Hub addresses originate only in deliberate local input and become trusted only after candidate identity and signed lineage verify. Aliases and success order are local metadata. Ordinary successful exact-pinned connections advance entry/address recency; admission and failed connections do not. Wire content, DNS inference, and route advertisements cannot create or replace addresses. Ambiguous aliases require selection.

Endpoint descriptors retain the exact endpoint identity, profile, receipt, authorization revision, revocation state, and required secret. Remote TUI CWD and leaf recency is separate convenience state in local tui.yaml; it never selects or authorizes an endpoint. See pkg/tui.

Bounded durable administration projections

store/browse*.go owns concrete list/get methods for endpoints, admissions, endpoint ACLs, endpoint notices, invitations, pairings, peers, peer addresses, peer successor proposals, local authority history/resolutions/rejections, and the corresponding peer authority families. admin/browse.go forwards these through concrete Manager.List*Context and Manager.Get*Context methods, and admin/browse_control*.go converts them to the 30 closed private JSONL request/result pairs. The exact keys, fields and revision rules are defined in the local control contract. Retired, revoked and terminal retained rows remain reachable beyond legacy status samples. Each page scans a retained immutable committed generation, with only a short cancellable RAM borrow to select it. It retains at most limit+1 candidate key/index pairs in a backing array of limit+2 slots, and derives/copies at most limit public rows. Limit defaults to 16 and cannot exceed 16. There is no whole-store clone or retained cursor snapshot. These bounds describe owned projection storage, not total allocator overhead.

Exact endpoint detail performs no filesystem reads. Startup validation and credential activation capture validated expiry in RAM-only metadata, bounded to one entry per endpoint and bound to the exact committed credential reference including its certificate digest. Publication is atomic with the credential's commit; definite failure or uncertainty never publishes pending expiry. Detail captures the row and metadata together under a short RAM read lock and parses the retained public binding. Certificate removal or substitution cannot change that committed diagnostic value. No persisted field is added. It returns neither filenames, PEM, private keys nor signed proof buffers. Mutable nullable fields are copied; admission and ACL projections omit SPKI, receipts, access secrets and notice tags. Invitation diagnosis returns only retained role-derived public claimant identities and request IDs. Selectors are exposed only in exact actionable ACKed/unacked client detail, never pairing or erased detail. Notice rows expose the domain-separated digest rather than a usable notice tag. Pairing detail includes the retained direct joining address and complete public conflict tuple.

Alias/token composition remains with the independent service sidecar owner after the durable store lock is released. Durable pairing projections do not manufacture a token or claim the samples form a transaction. The adapter samples the canonical sidecar token independently for pairing detail, status, and alias writes. Authority-history families and all private JSONL browse adapters are now implemented, as are the durable consumers in the existing command dashboard. See the service adapters and command guide.

Store query tests own strict-reopen coverage for every family, including the full 1,024-notice window, compromised/conflicted invitation diagnosis, direct pairing terminal rows, removed fork evidence and collision witnesses. Its narrow test-only producer can create the authenticated-remote retained conflict format under normal snapshot/transition validation and persistence. No production store operation creates that source, and the fixture does not claim remote authentication/ingestion. Validation selection follows the test guide.

Transactions and deadlines

Production callers use narrow operations for invitation phases, authorization, publication, retirement, security time, saved entries, lineage, credentials, and pairing foundations. Whole-snapshot mutation remains private.

MutationOutcome distinguishes no mutation, definite precommit failure, uncertain persistence, and durable commit. Callers never treat uncertainty as authorization success. Authorization changes acquire exact scoped authorization gates shared with matching registrations. Unrelated scopes remain independent; matching leases detach before transports close.

Hub ReserveSecurityTime and floor-only invitation deadline processing return Durable with the unchanged revision after definite persistence. The revision tracks semantic administration changes, not each persisted clock second. TLS selection, quiet-clock advancement, and unchanged invitation status polling therefore cannot invalidate a reviewed card, exact detail, or approval request. Explicit mutations check the expected pending revision under semantic ownership. A changed invitation, pairing, deadline cleanup, authorization, or authority advances the revision and rejects stale consent. Requests are never silently rebased. An overtaken explicit ReserveSecurityTime second conflicts even at the same revision, so its caller must resample the committed floor. TLS reads the independent proactive horizon and does not invoke this reservation API. Deadline processing reports domain changes separately from floor advancement; floor-only persistence copies the immutable header and cannot install other candidate edits. Failure and WAL commit uncertainty retain their existing fail-closed behavior. This rule is Hub-specific; client-store transactions and explicit credential-issuance reservations retain their own revision rules.

Every mutation supplies an expected revision, validates candidate state under semantic ownership, and durably commits before publishing the result. Pairing mutations run full snapshot and credential validation at that commit boundary, not again in each operation callback and encoder. Serialization still checks size and parser bounds. Transition comparisons and peer relationship matching reuse already-validated unchanged identities rather than repeating signatures. This avoids exhausting the fixed pairing evaluation budget on retained history; no processing deadline or validation requirement is relaxed. Security time never moves backward. At an exact deadline, cleanup and floor advancement commit before the caller receives the deadline error. Retries and restarts never extend retained deadlines.

Secret-bearing projections have explicit ownership and idempotent close paths. This covers mutable buffers owned by AgentHub, not immutable strings or opaque library intermediates. Exact projection types and cleanup mechanics belong to internal/agenthub/store and its tests.

Version and future owners

FormatVersion is 1. Unknown versions or fields, aliases, duplicate keys, nulls, coercions, and trailing YAML documents fail closed. Configuration is a separate version-1 document.

The reviewed pairing-handshake contract defines the strict version-1 pairing rows. A target creates a Pairing-purpose invitation using CreatePairingInvitation with an Authority claimant lock and explicit Direct or Routed mode. The joining Hub calls PreparePairing before sending a Claim; its target generation is only an assertion until CommitPairingContext verifies and stores signed target lineage. Target DiagnosePairingClaim checks the canonical request's target ID, SPKI, and generation against the current trust head before classifying a root-verified Claim. AcceptPairingClaim atomically advances the invitation and creates a signed-lineage pairing. Recovery uses PairingStatus with authenticated current authority head IDs and exact request, not a token. The remote argument is the TLS-authenticated head ID, not the lineage genesis ID used to key other pairing mutations. ApproveJoiningPairing signs and stores pending evidence; ReceiveJoiningApproval verifies the remote slot; FinalizeTargetPairing signs the final target slot and activates with no reverse address; CompleteJoiningPairing verifies Completion and atomically promotes only the locally entered direct address. PeerTargets copies only active, non-removed Peer heads and their locally stored addresses for direct reconnect; an empty address list remains eligible for inbound links. WithPeerConnectionBound checks both authority heads, generations, and the relationship request captured before peer TLS selection under the read lock through registration. Removal and re-pairing cannot admit a provisional link from the previous relationship. WithPeerConnection remains an eligibility check without that request binding. The manager keys removal by stable genesis, independently of the current TLS head. CancelPairing and RemovePeerContext own deliberate local terminal decisions. Authenticated claim diagnosis uses DiagnosePairingClaim and ApplyPairingClaimPolicy, with shared invitation terminalization. There is no separate claimant/evidence terminal writer. AdminStatus returns bounded, secret-free local Pairing and pairing-Invitation summaries for the dashboard. A conflict with identical first and second authority IDs and request IDs records a valid same-request Claim carrying a different complete signed lineage; the diagnosis transaction compares the canonical frames before committing that terminal state. The exact seven-day deadline stops new approvals and incomplete exchange. An Active target can still return its committed Completion to exact authenticated StatusRequest until the existing RetentionUntil. Joining LocalApproved evidence survives the approval deadline only for that convergence path and is purged at retention equality. Other expired incomplete pairings retain only a non-authorizing tombstone through that same cutoff. Deadline processing, authority transition, and erasure share the same validated snapshot. Pairing compaction clears removed prepared roots and selectors in both the live slice and its truncated backing tail. There is no committed BothApproved state or compatibility parser.

Endpoint credential staging and the context-aware renewal reservation/activation path now back the private renew_endpoint operation without changing endpoint identity, binding, publication, or ACL epochs. Their named ownership is recorded in the contract inventory.

Authority proposals and exact local decisions

The current format includes a nullable transition on Peer and saved client Entry rows. It holds one bounded public proposal with old, candidate, an optional second signed fork, revision, and status. Saved-client status may be pending, approved, denied, or quarantined; Peer proposals use only the first three. A terminal Peer instead has transition: null and two nonsecret verified successor record digests in fork_evidence. Each Trust value must pass complete lineage verification and its existing 64-transition bound. Active peer and client Trust must pin its verified head. Unapproved records never enter it.

StagePeerTransition accepts exactly one signed immediate successor of the accepted Peer head, with the same genesis, exact record prefix, parsed predecessor and generation +1. Full lineage signature and new-key possession verification is shared with saved-client trust, but the one-step Peer rule is not applied to saved-client entries. Staging binds the successor to the stable peer genesis plus the current pairing request. It takes no address, so a future verified delivery owner can stage an address-free peer without granting dial authority. DecidePeerTransition requires the current global revision, the proposal revision equal to that current store revision, genesis, request, exact staged old and candidate Trust, and both heads. An intervening store write requires restaging identical pending evidence under the current basis before approval. Approval rechecks the signed one-step relationship inside the write transaction and atomically updates Peer.Trust and the matching active Pairing.RemoteTrust. Ceremony, signed approvals, activation, request and local addresses stay unchanged. Historical ceremony keys remain verified dependencies, not current TLS pins. Complete Hub snapshots require distinct accepted heads among active, non-removed Peers as well as distinct genesis IDs across all Peers. Pending successors do not reserve a head. Staging rejects an already active owner, and approval checks again under the writer lock before installing the candidate. Pairing activation passes the same complete-snapshot validation. Removed rows and historical signed evidence do not own a current head. Denial persists without advancing trust.

Before applying these exact durable checks, observation staging uses records.NormalizeAuthorityWitnesses to verify complete candidate evidence and copy semantically equivalent overlaps from accepted Trust. Both proposal owners then use the same mechanism to retain the first candidate's exact witnesses. Pending Peer redelivery may refresh only its stale revision, not the evidence shown to an administrator. Equivalent denied delivery remains denied; saved clients do not quarantine it and Peers do not attempt terminal equal-digest forks. A longer same-branch proof still cannot replace an existing decision. Trust-history validation itself remains byte-exact.

A first verified successor whose head is already owned rejects staging with a conflict, but commits a bounded collision_witness and a new store revision. It contains the accepted head and generation plus one signed immediate public record. The containing Peer binds genesis and pairing request. Loading a snapshot re-verifies the witness against that exact accepted prefix. It is not a proposal, appears in no approval queue, and reserves no head. Repeating the same collision has no side effects. After the owner is removed, the same successor may be explicitly restaged and approved; approval clears the witness. Equivalent witness delivery follows the same rule and restages the first exact collision record. Other-owner removal alone grants no authority and creates no approval. Denial preserves both that witness and the accepted Trust.

A second verified incomparable immediate successor of the exact accepted Peer head terminates the relationship, whether the first observation was a proposal or a rejected collision. The writer commits removal of the Peer and its matching Pairing, advances security time and revision, erases the proposal and witness, and retains two verified successor record digests in fork_evidence. Generic transition validation binds the first digest to the prior proposal or witness and the second to transaction-local signed successor proof. That proof must verify against the same relationship and accepted Trust; it is never installed or serialized. Neither branch can be approved. A fresh pairing clears all old relationship evidence. Convergence never advances either accepted head.

StageHubTransition, DenyHubTransition, and AdvanceHubLineage implement the same saved-client decision boundary. The latter requires an exact pending proposal and a pre-commit caller decision. Entry addresses, grants, aliases and successful-use metadata are not transition state. After staging semantic redelivery, a caller must use the retained candidate from the current proposal projection for denial or approval, not its incoming variant. The decision APIs deliberately do not normalize decision evidence. Saved-client recovery performs this revision-checked reload before presentation and carries owned local resolution policy into the staged observation. A valid nonempty resolution remains bound to its retained predecessor and chosen successor through staging, explicit decision and restart.

An identical delivery cannot erase a denial. A pending or denied proposal is not silently replaced by a longer same-branch proof. This first bounded design retains one proposal per relationship; it has no reset-denial or fork-override operation. Fresh peer pairing after bilateral removal has a new request and no inherited transition consent. Old requests and proposal revisions cannot act on it. All projections clone evidence. Missing, cancelled, failed or stale decisions leave the accepted pin alone. Uncertain commits publish no live authorization or success effects and poison semantic use; the owning service retains passive diagnosis and unrelated established sessions rather than shutting down. Uncertainty is not a promise to roll back an appended batch. On restart the store strictly loads the selector's complete checkpoint and committed WAL prefix. It may contain the old pending proposal or the atomically approved Peer/Pairing trust and proposal. A valid committed approval is authoritative on restart, not a rollback violation. The failed request still has no successful response or audit.

Fixtures and checks

internal/agenthub/testdata/trust/storage contains current hub/client snapshots and credential files. The storage generator, -check, and check-storage.rb check closed shapes, credentials, deadlines, and YAML restrictions. Fixture scope and the aggregate check command are in the fixture README.

Client notice recognition

The gateway sends only the endpoint-signed current replacement window of opaque revocation tags and its access revision. The client derives the tag from its private descriptor secret; neither the secret nor the ACL is listed. On a match, ClientStore.RecognizeEndpointRevocations checks the current descriptor's exact SPKI and secret inside a revision-checked transaction, then saves the recognition time. A concurrent new approval cannot inherit a match calculated for the old secret. A later list with no tag does not clear the recognition; only a newly approved invitation replaces the descriptor and its secret. The origin ACL still enforces access if the client missed the entire notification window. Learned state and public revocation tags are never persisted by the Hub.

ClientStore.DescriptorIDs returns a bounded, independently owned, secret-free projection of every saved endpoint approval, independent of public discovery. The chooser uses it with owned LookupDescriptor rows so missing endpoints can remain visible offline and recognized revocations can remain visible after tag expiry or restart. A concurrent removal may make a subsequent lookup return ErrMissing. New approved installation replaces the old descriptor and its revocation marker; directory disappearance never changes private authorization.

Closed ceremony transaction policy

CreateAdmissionInvitation, CreateEndpointInvitation and CreatePairingInvitation select closed creation policies before any durable row is installed. Each validates the exact encoded J, mode, subject eligibility and claimant role. PrepareAdmissionRequest requires the local address; PrepareEndpointRequest has no address input. Both retain the same pending-row format, exact request/root ownership and unanswered cutoff.

ApproveAdmissionInvitation and ApproveEndpointInvitation share exact-row selection, ACK and cutoff checks, receipt binding, persistence outcome and terminal erasure. Their private policies separately select the authorization revision and install the admission or endpoint ACL output. Endpoint approval still replaces the complete signed revocation list and erases the replaced secret. A wrong hook, stale store or row revision, failed persistence or uncertainty cannot install or disclose an approval. Pairing's separate transactions retain bilateral approval and Completion-only recovery; they never invoke a client approval policy. The existing operate/mutateContext commit path remains the sole transaction owner. No new format, migration or common untyped row exists.

Client credential and result installation also uses closed InstallAdmissionCredential/InstallEndpointCredential and InstallAdmissionApproval/InstallEndpointApproval hooks. Common mechanics validate the exact pending request or credential, receipt and times, process cutoffs and erase replaced pending material. Admission policy alone validates and merges authority trust and the locally entered address, then updates the saved entry receipt. Endpoint policy alone installs the private descriptor and approval secret. Wrong-role material cannot invoke the other policy, including on replay. The generic purpose-inferred installers were removed, not retained as compatibility entry points.

Whole-state snapshot reservations

store/accounting.go and state/reservation.go admit owned snapshot capacity before protected reads, YAML decoding, working-copy creation, immutable-file staging and encoding. Every store uses a finite fallback budget even without a service adapter. state.Reserver.Reserve(context.Context, int64) returns a release callback or a prompt rejection. state.ErrResourceLimit, also exported as store.ErrResourceLimit, is admission failure, not corrupt authoritative data. Callbacks must not wait for another store owner or reenter their store.

The parent service can call HubStore.SetSnapshotReserver or ClientStore.SetSnapshotReserver with its Budget adapter. Hub transfer admits the retained snapshot before retiring the prior reservation. Existing read copies retain their original budget until their own Close. The OpenHubReserved, CreateHubReserved, OpenClientReserved and CreateClientReserved constructors also admit startup work through that adapter. Their original counterparts use the finite fallback. No service package import is required.

ParseHubReserved and ParseClientReserved keep the typed-state reservation until HubState.Close or ClientState.Close. MarshalHubReserved and MarshalClientReserved return SnapshotBytes, whose Close clears the encoded bytes and retires their charge. Internal writes always use the reserved result through filesystem write completion, including uncertain post-rename failure. The raw public marshal functions transfer byte ownership to their caller; callers needing aggregate ownership beyond that transfer use the reserved form. State bookkeeping stays outside the data structs and leaves value comparisons, version-1 fields and canonical bytes unchanged. Whole-state owners must be closed, must not be shallow-copied, and cannot be used after close. Closing invalidates borrowed aliases; it does not claim to force Go garbage collection.

ResolveSnapshotLimits computes conservative explicit-capacity bounds:

  • Let B be the 64 MiB document ceiling, N the 3,000,000 node ceiling, and E the largest pointed-to or slice-element type in the closed Hub/client model. A typed state has bound T = B + N*E.
  • Mutable typed data and immutable-file staging have ceiling O = 2*T + 128*MaxInvitations + 256, covering independently owned typed data, mutation backing-array overlap, the private selector index and accounting entry. One state owner reserves StateBytes = O + ValidationBytes. Installed old state and new candidate retain separate charges until installation or discard completes. Their validation headroom covers internal domain, credential and transition checks before encoder admission, including post-parse credential checks during open/recovery. Both stores use the unchanged O/2 typed-data preflight before working-copy allocation; validation scratch never enlarges that bound. Hub persistence uses an already-validated canonical encoding path. Client persistence also calls the public reserved marshal, so its repeated domain validation has an additional explicit validation-plus-encoding charge through write retirement.
  • `ValidationBytes = 2T + 128N + 32*records.MaxDependencyBytes
    • 4*state.ReadCapacity(64 KiB) + 4096`. The state-derived term covers frame clones and parsed content. The node-derived term covers collection and trust maps, key/value capacity and growth overlap. The record term covers bounded dependency copies, parsed frames, verifier memo tables and lineage key slices for sequential verification. Credential scratch covers bounded key/certificate reads and growth overlap, including the retained authority certificate. These are declared owner capacities, not estimates of opaque crypto-library heaps.
  • A protected read reserves 4*(B+1)+512 for returned capacity and read-buffer growth overlap. Missing files, rejected reads and cancellation retire it.
  • YAML decoder admission for input length b is 4*(b+1)*(sizeof(yaml.Node)+128) + 32*(b+1) + 512*min(N,4*(b+1)). A streaming strict-profile pass bounds node count, depth and closed collection lengths before document-tree construction. Native UTF-8 block/flow syntax, quotes and scalar bodies borrow input. BOM-marked UTF-16 retains support through bounded text conversion within decode admission; key decoding is capped at 256 bytes. Neither path constructs a document tree during preflight. Then one full-document YAML decode supplies the format/version check and strict shape/typed conversion. Unsupported versions do not trigger a second decode. Input-derived scanner/token headroom remains conservative for malformed syntax; conversion maps, JSON and typed staging coexist with the single tree. Failure/cancellation retain no result.
  • Encoding preflights exact pretty-JSON length s, node count n and depth without creating proportional storage. It reserves 16*(s+1)+128*n+4096 for compact/indented buffers, growth overlap and scalar copies. Its maximum is 1,457,745,936 bytes. No YAML validation tree is created by the encoder. Byte, node and depth rejection precedes encoder allocation. MarshalHubReserved and MarshalClientReserved first check context, then run allocation-free ownership and canonical preflight for the closed model. They reserve ValidationBytes + 16*(s+1) + 128*n + 4096 before domain validation. A rejecting or canceled reserver therefore wins over a domain validation error for a candidate that passes preflight. The full charge stays live through validation, encoding and caller retirement of SnapshotBytes. Validation errors, encoding errors and cancellation retire the charge without returning bytes. The raw marshal wrappers use the same admitted path, then transfer byte ownership to their caller.
  • Immutable-file staging reserves its actual bounded data/path and map/sorted descriptor capacity before copying, with OverlayBytes as its ceiling. Valid 16 KiB keys, 64 KiB certificates and the maximum endpoint collection remain supported.

The combined MinimumBytes is 3*StateBytes + OverlayBytes + ReadBytes + DecodeBytes + ValidationBytes + EncodeBytes. It includes retained old/candidate/recovery owners, immutable staging and a public validation-plus-encoding envelope. The extra public validation term permits exported reserved serialization of caller-owned values without relying on a registered state owner. Additional simultaneous independent read copies require another StateBytes each. On amd64, E is 408 bytes and T is 1,291,108,864 bytes. OverlayBytes is 2,582,742,272, ValidationBytes is 3,034,381,328, StateBytes is 5,617,123,600, ReadBytes is 268,435,972 and maximum DecodeBytes is 78,845,412,480. Maximum EncodeBytes is 1,457,745,936 and MinimumBytes is 103,040,088,788 bytes. The large decoder bound is deliberately visible to service-default resolution; attaching a smaller service budget without resolving this headroom would reject some supported input. The fallback admits eight combined envelopes. These calculations bound declared owned capacity, not total Go allocator use, GC retention, goroutine stacks, unrelated catalog/TLS owners or process RSS. The byte, node and collection ceilings are independent bounds, not a claim that one document can contain every semantic collection maximum simultaneously.

Accounting regressions cover the 64 MiB Hub/client byte ceiling, exact 3,000,000-node canonical preflight, encoding escapes, admission refusal, interrupted writes before/after rename, recovery, cancellation, ownership transfer, concurrent owners and exactly-once retirement. Padded codec documents prove the byte boundary only. Populated semantic evidence comes from store/semantic_maximum_test.go and store/semantic_peers_test.go. They construct real keys, canonical SPKIs, signed endpoint records and approvals, with real endpoint credential files. Every admission/ACL digest hashes an exact canonical invitation receipt. The endpoint secret is identical in its receipt, ACL, notice tag and signed revocation list. Three current approved invitations retain full receipt linkage in the combined profile; bulk rows represent post-retention-cleanup state. Each supported profile loads, completely paginates its collections, mutates, persists and reopens without truncation. The opt-in combined profile holds 4,096 admissions, 4,096 invitations, 1,024 endpoints, 65,536 ACL rows, 1,024 notices and 256 ACTIVE pairings/peers. Its 256 remote lineages contain one transition each, with 128 pending successors and 128 signed actual-head collision witnesses. Separate evidence covers a 4,096-row endpoint ACL with 1,024 signed notices, 256 full 64-transition peer lineages, one chain with 64 resolutions and 256 rejected-successor digests from branches verified when constructed, and a saved-client entry with 16 addresses. Persisted resolution rows retain only digests. Reopen checks their count, ordering and exclusion of the chosen successor, not the discarded branch signatures. The store tests own these profiles and their opt-in selectors; the test guide owns recurring commands.

Exact semantic envelope

  • Canonical persisted output must fit 64 MiB, 3,000,000 YAML nodes and depth 32. These checks precede encoding and working-copy allocation. Streaming input node/depth/collection checks precede document-tree decoding; Hub/client domain validation also preflights before signature verification and credential reads.
  • Admissions and invitations each allow 4,096 rows; endpoints allow 1,024; pairings and peers each allow 256. ACLs allow 4,096 rows per endpoint and 65,536 total, not 4,096 times 1,024.
  • Each endpoint allows 1,024 notices. Every notice must reference its matching revoked ACL epoch and the signed revocation list. Thus notices consume ACL capacity too. The combined fixture has 1,024 notices total, not per endpoint.
  • Trust permits 64 transitions, 64 resolutions and 256 rejected successors, within the same document envelope. A full accepted lineage cannot append a pending successor. ACTIVE peers cannot retain terminal fork evidence; signed pending proposals and collision witnesses are non-authorizing evidence.
  • Address lists have a structural bound of 16. Current ACTIVE direct-initiator pairings require exactly one address, target/routed pairings require zero, and the matching Peer retains the identical list. A saved client entry can reach 16 addresses. No new address or pairing wire semantics were introduced.
  • Alias and socket strings retain their 256-byte and 4,096-byte limits. Satisfying each field limit does not guarantee a combined document fits. The combined fixture expanded to individually legal maximum sockets exceeds 64 MiB and is rejected before encoder admission, never truncated.
  • Persistence also requires a representable verified public catalog under the unchanged directory limits, including 16 MiB of distinct selected frames. Private ACLs and invitations add no public frames. A valid signature alone does not override catalog, dependency, document or ownership limits.

Service.Start installs the snapshot reserver before protected Hub/client loading. Its separate finite snapshot pool defaults to MinimumBytes plus one configuration-operation envelope and one projection-sized spare margin, currently 103,191,088,584 bytes on amd64. These are admitted capacities, not allocated startup memory or RSS. Production configuration/session output projections and audit readers charge CONTROL, not snapshot headroom. Configuration replacement and Hub mutation serialize at the same administration lock. The direct-call composition fixture is synthetic upper-bound admission arithmetic; the separate EzHub-server fixture proves actual lock cancellation and retained output owners. Process-local snapshot and config fallbacks remain independent finite pools. Cancellation retires failed owners; pre-rename interruption preserves the old commit, while post-rename uncertainty requires recovery before reads. ResolveResourceLimits and Service.ResourceLimits return copied effective limits and the explicit calculations.