docs/internal/agenthub-link.md

AgentHub link layer

The link layer supplies authenticated TLS roles and the bounded mux used by direct and routed composition. It does not choose invitation state or application authorization.

The circuit contract freezes circuit v1. It implements a transient directory provider, bounded bootstrap worker and exact TLS retirement, with bounded internal fixture composition and joined service/relay settlement. Fixed-attachment sessions, retained recovery, production endpoint carriers, remote availability/selection, routed endpoint authorization and restricted routed pairing are implemented on that foundation. The circuit contract describes the current ownership boundary; service tests own composed runtime regressions. Normal-peer and other TLS-role policies are unchanged.

TLS roles

Each role has an exact ALPN and provider profile: client entry, peer, circuit, endpoint, and pairing. Constructors enforce the local side, remote role, certificate chain shape, identity pin, authority generation, key usages, security time, and no session resumption. Wrong-role, wrong-pin, expired, and revoked credentials fail before a connection becomes usable.

Pairing has two typed forms. InitialPairingClient checks the independently entered target CandidateCheck against a strict operational chain before it releases the joining authority certificate. InitialPairingServer accepts a strict authority/operational chain without a prior pin and returns InitialPairingConn. That type exposes exact authority IDs and SPKIs but no generation, because TLS does not prove lineage generations. Claim and Context must supply signed lineages before callers trust their generation fields. Prepared status polling and exact-Q Claim retry use exact-key InitialPairingClient. A Prepared row that lost Context has no authenticated target-clock deadline, so local Cancel remains durable but is not transmitted. After Context installs signed target trust and its exact deadline, joining-side recovery and Cancel delivery use exact-pinned PairingClient. The pairing engine owns claimant-lock evaluation, exact durable-Q matching, and pairing session state. The target checks every inbound recovery authority against durable Q. PairingServer remains a separate closed exact-pinned constructor with no current service public-entry consumer. The service connects InitialPairingServer to the one-address public accept owner and owns the generic-pre-TLS to authenticated pairing/session budget transfer. Neither TLS form can produce ClientEntryConn or enter client gateway framing. PublicPeerServer selects the exact ez-agent-hub-peer/1 ALPN on that same connection. The peer verifier checks a strict authority/operational chain, current security time, and the active local Peer's exact head key and generation through HubStore.CurrentInboundPeer. Multiple active matches reject authentication rather than selecting the first row. Head-or-genesis relationship resolution also rejects a cross-match between one relationship's head and another's genesis. The selected connection is a typed PeerConn, never a pairing or client connection. ALPN alone grants no authenticated reservation.

Role-specific exporters are exposed only by their corresponding typed connection. The invitation carrier uses EXPORTER-AgentHub-invitation-v1; peer, circuit, hop, and pairing exporters remain separate and are not interchangeable.

Authenticated lifecycle ownership

hoptls owns the shared handshake material loader, per-load credential cleanup, transport close, cancellation callback join, and absolute control deadlines. Calling a typed handshake constructor transfers the supplied raw transport on every outcome. The constructor closes handshake failures, and the returned typed connection owns successful transport closure. Callers must not retain a second raw-connection close defer after that transfer.

hoptls.OwnershipTransferTarget is the narrow accounting handoff used by Lifecycle.Transfer. A compatible target atomically replaces the exact pre-authentication staging lease before the old owner closes. Failure consumes the rejected target, preserves the old lease, and starts no authenticated owner. The callback may perform only bounded local accounting work because the lifecycle mutex is held. This interface moves capacity only. It does not select a TLS role, authenticate a peer, or grant transport ownership. OwnershipTransferSource lets an entry reservation expose that nested staging lease while its wrapper keeps separate scheduler and source-count cleanup.

TLS staging charges are explicit. TLSOwnedStagingBytes is two TLS 1.3 record workspaces of 5 + 16,384 + 256 bytes plus two maximum 120-byte canonical SPKI copies. It excludes general crypto/tls metadata, allocator classes and goroutine stacks. Existing coarse service budgets remain in force around this narrow aggregate. Public pre-TLS adds the four-byte one-address prefix. An established gateway tunnel separately owns two 32 KiB pump buffers and an 8 KiB bounded pipe, exposed as endpoint.TunnelOwnedBytes. The 64 MiB JSONL value and queue limits are unchanged.

service.StagingAccounting composes these charges with current budget closers. PreTLSOwner wraps the generic source-keyed lease, AuthenticatedTransferTarget wraps a role budget already reserved after authentication, and AuthenticatedOwner covers supplemental keyed storage such as a selected tunnel. gateway.EntryReservation now exposes the original pending owner through OwnershipTransferSource while its Close still retires generic admission capacity. Ordinary admission/gateway transfer first calls TransferOwnership, then combines the actual transferred owner with ordinary source capacity. Detached peer adoption transfers before detach and passes only the resulting owner to AcceptOwned, which retains it until manager retirement.

Outgoing normal peers use peer.Manager.ReservePreTLS before PeerClient allocates TLS staging. A copied PeerTarget supplies local expected identity, not a source IP or an authenticated remote SPKI. Service composition reserves a separate finite peer-preparation owner through reservePeerPreTLS; Manager.Reserve then returns an authenticated transfer target. The manager transfers onto the actual TLS-authenticated peer before arbitration and retains that charge until attach has joined and retired the exact link. A denied reservation emits no TLS bytes. Failed TLS closes the pre-TLS owner after transport retirement; failed transfer consumes its target and retires the previous owner once.

Pairing TLS also reserves before the typed constructor. Outgoing short checks and exact IDs without an available trusted SPKI use the independent sixteen-owner pairing preparation pool. They do not invent a public source IP or share the public 128-pending/eight-per-source reserve. A routed selection with a verified head SPKI charges that expected key before opening its carrier. Restricted targets charge the authenticated immediate entry source before OK, then transfer onto the actual joining authority SPKI after TLS. All authenticated roles share the same SPKI aggregate.

The outgoing initialPairingClient and request-bound pairingClient service helpers return a separate staging owner. Their caller joins the engine before closing it. openRoutedInitial requires an explicit staging-owner handoff when production accounting is installed; its supervisor releases the raw carrier before closing that owner. Routed recovery follows the same order. Restricted targets retain the charge in their target reservation until the carrier has joined TLS/engine and raw workers and calls target Close. Cancellation and TLS Abort stop I/O but do not release a successful staging reservation. This keeps held decisions and overlapping same-key carriers charged through exact retirement. Manually constructed nil-accounting fixtures remain supported; production Start always creates the accounting owner.

gateway.Server.ReserveTunnel charges the authenticated outer client before both direct and routed endpoint preparation. The gateway retains it through joined preparation and all three tunnel workers. The origin endpoint engine charges the inner client independently; it never substitutes the outer client. Established endpoint-access tunnels keep the 1 MiB outer frame maximum and charge each opaque body plus its owned copy before allocation. Their finite 12 MiB control-class pool is independent of application DATA pressure and also contributes to the shared role/SPKI staging ledger. These hooks add no wire fields. Circuit bootstrap separately charges its verified expected remote SPKI before TLS allocation and retires the charge after TLS and cancellation bridge join.

Closed private policy types supply each constructor's exact certificate forms and ALPN. Those same hooks bind each exporter's exact domain and required negotiated ALPN. The invitation adapter binds either the closed client-entry hook or the closed endpoint hook; their shared label does not permit cross-role substitution. Role is diagnostic metadata, not a policy selector. The public listener still dispatches exactly one advertised ALPN; it cannot reserve privileged capacity or fall back to another role based on that advertisement. Candidate admission and initial pairing share one private first-contact client implementation, including target checks before certificate disclosure, fresh credential validation and transport ownership. Their typed public constructors retain distinct local credential forms, ALPNs and result types. The shared implementation enforces each role's local credential profile, requires a successful client handshake signature and aborts before a signing failure can flush the certificate. A target that omits the client-certificate request is rejected. Both flows also use the same fresh-material loader as pinned TLS. Callback-level policy tests cover both flows without a network handshake; focused real-TLS tests cover disclosure ordering, mutual authentication, signer release, transport ownership, roles and exporters.

The pre-auth worker uses hoptls.Lifecycle for its generic reservation and cancellation. Before a typed handler adopts the authenticated transport, DetachTransport joins and retires that callback and all transport-close authority. Capacity retained by the entry worker remains live until the handler joins, but cannot close the handed-off transport. The peer manager alone adopts the peer reservation through AcceptOwned, its sole inbound adoption API; entry does not also transfer it into its lifecycle. Outbound reservations reach the same attach owner. Direct endpoint preparation uses the same detach boundary before application or invitation handling.

Each composed transport has one active phase cancellation owner. Gateway selection retires before admission handling; invitation reading retires before processing and resumes only after that worker joins. Endpoint opening retires before active proxy handoff. Pairing supplies graceful TLS Close; entry cannot race it with an immediate raw abort. Application and peer owners retain immediate Abort. Cancellation never prematurely releases capacity. There is no shared connection worker or I/O lock. The endpoint invitation scheduler lease remains separate and live through the ceremony. TLS Close and Abort retain the existing underlying transport-close owner.

Store providers return independent in-memory signer loads. Signers implementing CredentialReleaser are erased at handshake exit, including rejected fresh selections and failures before certificate disclosure. Other provider signers are borrowed. This does not delete credential files or alter renewal, security time persistence, or authority selection. Returned exporter material remains owned and cleared by its typed protocol consumer.

Hub operational, endpoint, peer, pairing and circuit providers capture exact credential references and public trust under a short RAM read lock. The capture includes local authority head and generation, peer request/ceremony/activation epoch, pairing request and deadline/retention/phase, and endpoint publication, retirement and binding generation. It owns public copies, not a complete retained Hub snapshot or pairing retry secrets. File reads, strict certificate/key validation and lineage verification happen after the lock is released. A final RAM check must still match the captured token before any material is returned. Changed references, authority transitions, relationship replacement, retirement, uncertainty rejects the load and erases its key. An advanced semantic floor rechecks the loaded certificate's validity interval and any pairing cutoff at the later durable second. Unchanged credentials remain usable while valid; expiry or an exact authority, credential or relationship change still rejects stale work. No loader retries by adopting the replacement head or relationship. An unrelated committed revision does not invalidate an unchanged credential token.

Each Hub signer checks that same token immediately before and after Sign. Only its per-load key-lifetime mutex spans signing, never a request-facing store lock. A failed post-sign check clears the signature allocation and returns no signature. Circuit signers also recheck their exact directory lifetime borrow outside store locks. File loading and blocked signing therefore cannot prevent passive status or a local revoke/retire operation from progressing. This does not change TLS role profiles, current-security-time checks, pairing deadline equality or its bounded cancelled-row recovery exception. Unpublished endpoints remain eligible for invitation TLS; changing their publication state invalidates work already in flight. Client-store locking is unchanged.

Pairing certificate validation uses covered security time, including the conservative restart clamp. Signed and persisted pairing decisions use semantic execution time and recheck their final commit cut. Temporary handshake, authentication, queue, challenge, worker and carrier deadlines instead use one unclamped runtime clock shared by the direct and routed owners and dispatcher. The restart offset never adds elapsed seconds to those limits. A target approval cutoff bounds the held carrier by its remaining semantic duration, translated onto runtime time and capped at the existing 300 seconds. Equality still refuses new approvals and incomplete exchange; retry does not move signed deadlines.

TestHubTLSBlockedFileLoadRechecksExactToken and TestHubTLSBlockedSignatureRechecksExactToken cover exact reference, head, relationship and endpoint substitutions. The durable revocation and credential transition regressions hold real validator/signer calls behind channel barriers, assert RAM lock availability without timing thresholds, and check stale-key and signature erasure. Circuit regressions cover invalidation during file loading, signing and the final directory recheck.

authorization.Registry remains the sole admission/endpoint epoch and check-to-registration barrier. Replacement and shutdown detach all matching leases under that barrier, then use hoptls.AbortAll to abort each detached transport independently and join every completion outside the lock. No fixed worker pool or sequential abort loop can leave unrelated revoked transports open behind one blocked closer. Repeated registry shutdown calls join the same completion. Its closed registration policies share exact client, ACL, time, and registration checks. Admission queues first-use history after registration, without waiting for disk acceptance. Endpoint registration does not: BeginWork, one AF_UNIX dial, open_ok, and asynchronous MarkFirstUse retain their order. History never grants rights or holds the registry mutex. The peer manager still owns reciprocal readiness, arbitration, relationship removal, drain, mux and channel leases; its serving worker uses the shared transport/capacity lifecycle without adding another peer registry. Drain, removal, and shutdown signal each link's cancellation callback rather than performing transport I/O under the manager lock. The link worker joins that shared abort before releasing its capacity or signaling completion.

Circuit-only proof and retirement

For A through B to C, only A/B and B/C require Peer relationships. Each circuit endpoint resolves the other stable root from immutable attachment metadata in its own verified learned directory. ResolveCircuitAuthority reserves 4 MiB before scanning or waiting for the directory lock, compares complete ordered signed-content digests, and requires the maximal head selected by LearnedState. Missing, stale, forked, incomparable, shared-head or resource-limited evidence fails. No remote lineage is accepted and no trust or access row is changed.

The attempt retains one immutable lineage and one publication channel token. Any publication, including an unrelated update or ABA restoration, invalidates it; shutdown also fails closed. Its fixed owner admits one lifetime borrow, one Head read and one Recheck read. Close seals admission, joins those slots, clears the proof and returns its charge. Store providers check the borrow before loading and before returning fresh operational credentials, erasing a failed load. The first head SPKI is reduced to fixed comparison material and cleared before the second read; the final rechecked copy transfers directly into the TLS pin, so provider head copies never overlap. Bootstrap holds the borrow through TLS constructor return and credential release. No directory or store lock spans network I/O.

Circuit providers read fresh covered RAM security time and the authenticated local store lineage. Their sequential local projection checks root, ordered predecessor, head, generation and credential consistency without allocating another ancestor evidence graph. Certificate validation and signer-reference rechecks remain the same as other operational TLS roles. The provider never calls loadHubPeer. Normal-peer providers retain active eligibility and exact accepted-head policy. Bootstrap compares the local lineage snapshot with LocalCircuitAuthority from the actual handshake and compares the TLS peer with the exact borrowed head. Typed persistence/uncertainty causes remain inspectable by the local service owner. Semantic uncertainty records the first exact cause and freezes fresh trust use without closing passive control or unrelated established sessions. Returned bootstrap messages redact nested diagnostics.

The circuit adapter reads only the current five-byte TLS header and record body, with a 16,640-byte payload maximum and independent 256 KiB absolute wire ceilings. It clamps TLS deadline changes to Attachment.ReadyAt() + 10 seconds. ReadyAt is the relay's immutable local publication time, not the bootstrap worker's start time. Already-expired attachments fail before proof or TLS work. HELLO and CONFIRM use the frozen codec; each endpoint rechecks its selection immediately before writing confirmation. Circuit-only CloseBootstrapWrite sends close-notify without relay FIN or transport close. The ordered exchange requires authenticated TLS EOF with no further plaintext, rejects transport EOF, joins the explicit cancellation bridge, clears bulk deadlines and checks the exact record boundary before disabling adapter close authority. It retains no prefetched raw tail. Ordinary Close/Abort/exporter behavior is unchanged.

The raw result installs its cancellation owner before return. Single-use Take joins that owner and transfers the original bulk, control material, lifecycle parent and reservation to SessionInput. Terminal entry Wait additionally joins Attachment.Wait before settlement release; origin Wait leaves that join to relay. No detached settlement waiter exists. Custom contexts use one explicit Background-rooted bridge, joined before transfer or release. Service/settlement composition and its real-attachment integration tests implement this. The fixed session consumes Take with NewSessionStarter(SessionConfig{Clock: MonotonicSessionClock{}}) and Start. Its fixed six workers plus two surrounding owners and one reusable session timer implement reliable opaque bytes and HMAC-protected controls above unchanged relay lanes. Session EOF requires delivery through authenticated FIN; TLS, lane EOF and peer loss alone never establish it. Entry Wait joins local Attachment.Wait; origin leaves relay settlement to its supervisor. Circuit implementation evidence owns queue/cursor limits, joins, locks and the retained-state split. The session layer itself has no endpoint dial, application handler, recovery/replay/ATTACH implementation or grace timer; those belong to the recovery and endpoint consumer owners.

Mux

The one-hop mux has bounded OPEN, OPEN_OK, OPEN_ERROR, DATA, WINDOW_UPDATE, FIN, RESET, PING, PONG, and GOAWAY frames. Per-channel state and credit are validated before mutation. Independent protocol controls have their own finite queue and do not need DATA credit. Aggregate budgets and per-channel limits are finite, and closing a channel joins blocked writers without affecting others.

Each reciprocal-READY normal peer link creates exactly one mux.NewPeer session on its fresh peer TLS connection. The smaller authenticated authority head ID uses mux client parity (odd OPEN IDs); the larger uses server parity (even OPEN IDs), regardless of who dialed. This does not change the normal-peer link's nonce arbitration or choose a preferred dial direction. Pairing TLS and provisional links never enter mux. Link exposes no raw connection or session for application traffic. ReadyLink.ClaimDirectory(ctx) takes a managed worker lease for exactly one directory pair on the physical connection that emitted READY. There is no relationship-level directory claim. Its scoped channel operations pin both OPENs to that link and enforce control then bulk with exact setup AHDS plus version 1. Generic channel operations reject that reserved setup. Reclaim, extra channels, wrong order and new work on a draining link fail closed. Draining signals the directory engine to stop; removal/shutdown also close transport. The directory owner releases its worker lease only after joining the engine, so the manager's existing removal/shutdown join covers the synchronization workers as well as both mux channel leases. The service composes this lease after reciprocal READY; it adds no separate peer manager or pairing carrier.

Typed lease channel operations use the manager's existing registration, relationship-request, generation, removal and shutdown barriers. Hold remains an idempotent internal relationship lease; callers must not use it in place of a channel owner. An outgoing lease starts before OPEN and ends only after the two-way terminal RESET barrier or transport failure; a cancelled or failed OPEN releases it. An incoming proposal owns only bounded mux pending state until the manager rechecks the same selected link under the store barrier and commits OPEN_OK. The returned channel retains its lease through the terminal mux barrier. Both directions work on an outbound-established peer link. A GOAWAY or duplicate loss stops new leases; existing channels finish or the normal-peer five-second drain deadline aborts the link. Local removal closes the session and joins the link worker immediately. Manager shutdown joins mux workers before closing the store.

Mux Channel.FlushWrite(ctx), also exposed by the neutral paired routing.Lane, is a local physical-write barrier for preceding admitted DATA. The sole lane writer must exclude new writes until it returns. It waits for queued and in-flight DATA to commit, not for peer consumption or an acknowledgment. Its context cancels only the wait, never the shared transport syscall. Relay uses one bounded wait in its existing control writer to attempt an established ATTACHMENT_ABORT before ordered RESET. If the control lane is unavailable, RESET remains the fallback. No queue, wire field, worker or mux charge is added; ordinary RESET still discards uncertain queued DATA.

Peer mux OPEN setup has one mandatory leading octet: 01 for control and 02 for bulk. OpenClass adds it; Incoming.Class reports it and Setup returns only the remaining application bytes. Empty and unknown class values are fatal protocol errors. The ordinary non-peer mux constructor retains its unclassified setup contract. Directory updates belong on control channels and snapshot chunks on bulk channels. Their message bytes and setup payloads are not specified here. Circuit ACK and other mapped controls use control channels; normal ciphertext DATA uses bulk. A channel's class cannot change.

NewPeer uses PeerConfig: 128 active and 128 terminal channels, 16 pending OPENs, 4 KiB setup per OPEN and 128 KiB setup aggregate, 2 MiB queued outbound payload, 8 MiB aggregate receive capacity, 64 KiB initial receive credit per channel and 64 KiB DATA fragments. The service reserves 12 MiB per exact peer mux before creating its workers/parser, through their joined retirement. The local Hub additionally counts up to 17,152 real channel liabilities, including the mandatory 8,192-channel target, through Config.ReserveChannels. Required directory control, directory bulk and route control count as three. Pair reservations charge both lanes before OPEN, including missing siblings, without charging materialized lanes twice. Admitted channels retain their channel charge through rejection/RESET settlement; transport failure keeps that charge until mux workers join. Never-admitted OPEN refusals use the existing 128-record terminal metadata headroom within the fixed 12-MiB exact-peer reservation, not a new Hub channel liability. Optional channel budget denial therefore emits the unchanged OPEN_ERROR/resource-limit followed by RESET without discarding established channels' queued bytes. Refusals admit no setup or receive credit. Peer RESET settlement refills this headroom; exceeding the terminal bound or native control queue still fails the link. Required-stream admission failure and required-stream retirement keep their fail/drain policy.

The local rendering of OPEN_ERROR/resource-limit explicitly says "capacity limit reached; new channel refused", rather than the generic "open rejected". The existing wire code supplies that coarse cause, not the remote configured cap or current usage. Local operators can inspect the private limits/usage sample for those values. ChannelOwnerBytes = 1024 is bytes per charged channel, not a 1,024-channel Hub cap; the three required channels per peer are counted within the configured Hub-wide channel limit.

Optional OPENs wait for all three required channels to commit. The 128 KiB control-class DATA partition protects 16 KiB directory, 1 KiB routing and each of up to 32 relay pairs' 4 KiB shares. Two active control and pending OPEN slots and 8 KiB setup remain protected from optional admission. Bulk may use at most 2 MiB minus 256 KiB; control DATA may queue at most 256 KiB. Native protocol controls have independent 256-frame/256-KiB bounds. One physical frame is separately bounded. After at most eight consecutive protocol or control-class frames, a runnable bulk DATA or FIN gets one turn. After at most four native protocol controls, a runnable mapped peer-control DATA or FIN gets a turn, independently of the bulk bound. Native controls still receive first service and alternate queued responses with WINDOW_UPDATE work. All three runnable classes progress within nine selections; continuous credit traffic cannot starve SUMMARY, DELTA or REPAIR. A saturated bulk queue cannot prevent bounded control admission; control work cannot starve a runnable bulk channel. Credit pressure still backpressures each channel and a blocked physical TLS write can delay both classes by at most the in-flight frame before the transport deadline or abort. Protocol control queue exhaustion fails the session rather than dropping an obligatory control frame.

The endpoint and application boundaries remain above mux. Shipped direct pairing uses InitialPairingClient/InitialPairingServer through the existing public accept owner and the pairing session engine. Pairing TLS never enters mux or carries normal peer traffic. Relayed route setup has a frozen relay contract and independent literals. The implemented transport and circuit handoff describe real TLS topology/pressure fixtures and the structural/live-owner standard. A hard total Go-runtime ceiling is not implied by that proof. This does not enable circuit authentication or remote access.

Typed required consumers

One joined dispatcher per exact physical link alone calls Session.Next. Directory and route inboxes retain at most two and one proposal references, respectively, within the existing eight pending OPENs. Only typed leases can accept them. Generic NextChannel and AcceptChannel fail closed; generic OpenChannel rejects reserved AHDS and AHRT identifiers. Unknown identifiers receive the existing rejection code, not a generic application inbox.

ReadyLink.ClaimRoute(ctx, RouteIdentity) validates both verified stable roots and exact authenticated heads. The smaller unsigned stable root opens control with AHRT\x01; directory still uses head ordering with AHDS\x01, control then bulk. Mux parity is also head-based. A successor can therefore reverse directory roles without changing the route opener. Route peer setup is exactly 01 41 48 52 54 01, with no suffix or alternative class.

Channel.CommitmentTime() records the existing local readiness boundary: successful OPEN_OK write for an incoming channel, or received OPEN_OK for an outgoing channel. Queue insertion and writer selection do not commit an incoming OPEN. Failed OPEN_OK writes leave the timestamp zero. Route initial exchange uses this immutable timestamp plus ten seconds, separately from claim-to-OPEN setup time and without restarting the allowance at caller scheduling.

Claims perform no channel I/O. Production composition must claim both consumers synchronously before starting either owner. A claim cannot move from retired L1 to replacement L2. RouteLease.WithAdmission and Manager.ReserveRoute use peer gate, store barrier, manager mutex, then table mutex. No I/O, budget allocation, service callback or join runs under these locks.

Production now reserves the full route runtime before claims and registers its budget release through ReadyLink.RegisterRouteRelease. Exact finalization runs that callback outside locks after dispatcher and managed holds join. RouteLease.BindTable atomically binds one exact contribution; physical retirement synchronously calls MarkUnusable before returning, closing captured Changed generations and invalidating admissions. Stale L1 retirement cannot mutate L2. READY rejection calls ReadyLink.Drain even before any claim exists, so dispatch cannot start on an uncharged rejected link.

Production activates the route claim in READY. The existing engine supervisor then owns its coalesced Wake, nonblocking Step and Shutdown, including bounded admission deadlines and cancellation. There is no admission worker per link or ticket. A route Channel has an explicit caller-owned hold, with idempotent ReleaseHold only after Settled; the engine releases it after reader/writer join. Setup rollback does the same synchronously. Directory and optional-channel baseline settlement owners are unchanged. The routing integration status and service boundary record the implemented composition.

Closed relay paired admission

The capacity numbers and layout proofs in this section are superseded by the production capacity ownership map. The paired-admission and joined-release rules remain unchanged.

The relay owner freezes the next typed consumer before implementation. Both attachment lanes reserve at the SAME candidate/link admission point under peer gate, store barrier, manager mutex, directory admission mutex and table mutex. The closed Table.ReservePair extension revalidates the exact suffix and candidate revision while committing both lane/window/pending/terminal reservations and the managed hold. Routing's channel-free Admission cannot be followed by a generic relationship opener. The single-use pair opener accepts no new link, class or setup arguments.

Relay alone allocates one global-pool attempt-owner and charges its service budget before pair admission. PairSpec carries its neutral opaque owner capability and Incoming/Outgoing role. The typed relay claim pins the trusted issuer/service scope; peer validates the capability and reserves only pair-local ticket/link/mux/control-share/terminal liabilities. Both pairs at a transit use that same owner; ticket-to-pair transfer never allocates a second owner or releases its service lease. Owner and incident claims remain charged until all joins and settlements finish. Peer calls no service budget callback. The fixed 64 KiB relay allocator/issuer metadata is process-lifetime structural storage, not a lease sponsored by whichever service starts first. Per-service attempt charges are 96 KiB data and 8 KiB control, capped by the shared 32 slots.

Relay OPEN application setup is AHRA\x01, lane, attempt[16], endpoint[32], mode, receiver position, full entry-to-origin path and bounded opaque circuit setup, exactly as specified by the relay page. Control uses class 01, bulk class 02. No mux frame, class, directory byte or route-control byte changes. The sole dispatcher adds a closed relay inbox with at most six proposal references within the existing eight pending OPENs. Generic APIs reject the reserved AHRA prefix. READY claims relay before launching workers, but optional relay admission remains gated until all three required channels commit.

Assembly permits at most three pending pairs and eight incident pairs per exact link, incoming and outgoing combined. Both lanes associate by exact link and byte-identical metadata except lane/class. Hop OPEN_OK is not route OK. The downstream-first explicit response belongs on the control lane. Cancellation rolls back both lanes through settlement, including late OPEN_OK/route OK. Transferred pair holds cease to be ten-second setup tickets without losing managed ownership. An established attachment never reopens on a replacement link or follows a new preferred suffix.

Within the existing 64 KiB mapped-control payload partition, directory retains 16 KiB and routing 1 KiB. Relay reserves and caps 4 KiB per owned control lane, at most eight lanes or 32 KiB per link, leaving 15 KiB for required writers. Pair reservations preserve two pending slots and 8 KiB setup for required work; relay's six slots hold at most three complete pairs. Relay admission also checks the combined channel/pending/terminal liabilities against a conservative 32-slot ceiling. Ordinary admissions also preserve an existing pair's combined terminal liabilities. Unavoidable rejected-OPEN records retain the exact-session failure policy; they cannot be evicted to admit an attachment. The existing native/mapped/bulk progress rules remain. Control and bulk use independent rotation cursors, so bulk selections cannot reset the mapped-control rotation. Each eligible mapped lane gets a turn within nine times the number of control lanes in a stable runnable set. These are scheduling bounds, not delivery promises through a stalled physical writer.

The mux implements these reservations, not relay authorization or service composition. Session.ReservePair(ctx, controlSetup, bulkSetup, deadline) reserves an outgoing pair without allocating IDs or doing I/O. Incoming.ReservePair on an undecided control proposal reserves the complete incoming pair, including its sibling. Both setups exclude the mux class byte. The typed owner validates frozen relay setup shape, path, capability and exact-link provenance before admission; mux only owns bounded copies and exact class/setup association. Matching bulk proposals consume their already reserved sibling and still pass through the sole Next dispatcher. Spliced or duplicate proposals cannot borrow that slot.

PairReservation.OpenControl then OpenBulk are single-use tracked operations; bulk requires committed control. Incoming owners use AcceptControl and AcceptBulk(ctx, incoming) with the exact associated proposal. All operations use the fixed absolute local setup deadline. Outgoing reservations require a nonzero deadline at most ten seconds away. Incoming reservations use the earlier of that inherited deadline and Incoming.ProposalTime().Add(10*time.Second). ProposalTime records the original OPEN decode boundary before queue, dispatcher or admission waits; those waits do not restart the receiver's setup allowance. PairReservation.SetupDeadline() exposes the immutable effective deadline for relay supervisors, downstream admission and origin callbacks to inherit. Expired valid deadlines return context.DeadlineExceeded without reserving anything, including when a queued incoming proposal has exhausted its allowance. Zero or over-ten-second future deadlines and malformed local setup remain ErrInvalidConfig. These are local API errors, not new wire codes. The watchdog aborts incomplete pairs, including unused reservations, but does not free their owner capacity. Incoming OPEN_OK writes and outgoing OPEN_OK receives also check the deadline at actual commitment, so delayed watchdog processing cannot establish a late pair. Timely commitment observed later stays timely. Abort forbids new lane use and resets allocated lanes while retaining all liabilities. After joining lane I/O, the owner calls idempotent Close; release waits for both allocated lanes' Settled. Transport teardown settles and releases all mux reservations; the peer/relay owner still joins its workers before releasing its separate hold and budget lease. Mux creates no pair worker or timer. Reservation and all transitions use only the session mutex; reserve before admission barriers and perform no lane I/O or settlement waits under them.

Each pair also protects four native frame slots and the two OPEN payloads plus two RESETs, len(controlSetup) + len(bulkSetup) + 82 bytes, inside the existing 64-frame/64-KiB native queue caps. Unused native headroom remains owned by the pair. The 4-KiB mapped-control cap includes admitted bytes, while one selected physical frame remains separately covered. Reservation fails locally if any channel, pending/setup, terminal, mapped-share or native-queue liability cannot fit. No partial pair or ID allocation follows failure.

mux.PeerMemoryReservationBytes publishes the unchanged 6-MiB charge for service budget integration. TestPeerMemoryReservation proves live mux storage on the concrete Go layouts: 4,628,512 bytes of buffers and bounded copy transients, including the explicit 8-KiB dispatch/parser allowance, 160,376 bytes of metadata including a 128-KiB allowance, and 524,288 bytes for four worker stacks. The total is 5,313,176 bytes, leaving 978,280 bytes. Buffer accounting includes both 2-MiB receive/outbound aggregates, pending setups, native payload, two setup copies for each of eight reservations, decoder and physical-frame staging, and a serialized per-channel copy transient. Metadata counts up to 64 retained channels and Incoming objects, eight reservations, slice storage, maps, runtime channel objects, closures and alignment. This is a live-owner storage proof, not a bound on allocator arenas, unreclaimed GC garbage, caller-retained retired handles or TLS transport storage. Those are not a second mux queue. Required nineteen-channel relay occupancy uses only 1,245,184 receive bytes; no aggregate cap, fragment size, service charge or wire field increased.

FIN is lane-directional. Bulk FIN drains accepted bytes and leaves control live. Transit forwards control FIN only after the corresponding bulk FIN drains. RESET/loss aborts the attachment, not clean circuit EOF. Origin handoff is a revocable, joined owner with bounded lanes. A missing production origin handler denies; relay never calls the direct endpoint preparer. Origin Admit runs in the charged supervisor and must return on context cancellation/setup expiry, with zero fully unwound acceptance or an immediately abortable/joinable acquisition. The borrowed offer cannot outlive Admit; a taken provisional attachment stays revocable under relay ownership. No uncharged callback worker hides blocked Admit, and acquisition Wait cannot wait on its calling relay supervisor. relay/types.go publishes shared interface declarations before codec/pair/pump/setup compilation; service wiring follows the relay owner. The circuit owner now defines TLS transcript and authenticated ACK/control bytes, not this link layer.

Checks

Role tests cover exact ALPN/exporter labels, first-contact disclosure order, strict unpinned operational chains, provider reload, exact recovery pins, security-time expiry, cancellation, and no resumption. Mux tests cover credit, fairness, liveness, malformed frames, half-close, and concurrent shutdown.

AgentHub is unreleased. One public generic pre-TLS pool protects accepted physical ingress before authenticated role selection. Nested endpoint TLS and outgoing peer/pairing TLS use independent finite preparation pools so they cannot consume the public reserve. All physical descriptors still share one 2,048-owner ceiling. These limits are not DDoS prevention; firewall and network source policy are out of scope. Dedicated TLS roles do not imply separate public ports.

Direct normal-peer control

Each link starts a fresh ez-agent-hub-peer/1 TLS session. Before any channel bytes, both sides exchange two symmetric 40-byte frames: AHCOMT01 carries SHA-256 of the side's fresh 32-byte nonce, then AHPEER01 carries that nonce. A mismatched commitment, wrong prefix, short frame, or self-connection fails closed. Each exchange has a five-second deadline. A peer cannot choose its nonce after reading the other side's reveal. It carries no address, pairing secret, or routing claim. Both sides compute SHA-256 over the concatenation of lower authority ID, that ID's nonce, higher authority ID, and that ID's nonce. IDs are 32-byte binary authority heads, not printable strings. Before link registration, both sides exchange a third 40-byte frame: ASCII AHVOTE01 followed by the 32-byte score of their locally preferred link. A confirmed healthy link is preferred; when there is none, provisional links prefer the smaller nonce-bound score. Unknown scores and malformed votes fail closed. In the fourth phase, the side with the lower binary authority head ID sends AHWIN001 followed by its 32-byte chosen score. The other side must know that score and must not have confirmed a different healthy link; it echoes the same 40 bytes before either side registers the candidate as ready. An absent or mismatched echo fails closed. Both sides retain provisional links only until confirmation or failure. Once ready, a healthy link cannot be displaced by a later lower score, including one ground by an authenticated peer. A cross-dial that has not yet converged may fail closed and retry rather than admit conflicting links. The winning link enters the typed mux immediately after reciprocal READY. Only mux frames follow; malformed or unclassified OPEN fails the link. Both sides may open channels on an outbound-established connection. Channel owners must use the manager's leased APIs, not add another reader or link arbiter.

Renewal compares the complete stable authority SPKI fingerprint and generation, not the operational certificate instance. Strict same-authority renewal is automatic. An unexpected authority fails TLS. The manager may then use the existing AHLQ bytes on that relationship's saved public address to obtain a complete verified signed lineage extending the exact old head. This bounded query shares the outbound worker's reservation and five-second deadline. The Peer manager stages only its first unseen successor; later records require separate proposals after that successor is approved. Transport lineage conversion does not apply local consent or fork policy. Fresh successor TLS stays rejected until local approval commits. No address is inferred from a remote connection or proof. A nonterminal TLS or lineage-query failure continues through the local address list in the same attempt and reservation, rechecking cancellation and current relationship eligibility before each address.

Both AHLQ transfer and learned-directory successor extraction use the records owner's complete-lineage witness normalization. Equivalent signed-content overlaps become copies of the exact accepted prefix before selecting the immediate successor. Durable staging uses the same mechanism against its first pending, denied or collision observation. A signature variant is redelivery, not a fork; stale pending revisions may refresh without replacing decision evidence. A colliding head remains non-authorizing until its other owner is removed, the exact retained branch is restaged, and a current explicit decision approves it. Genuine incomparable successors still terminally remove the Peer and matching Pairing through the existing removal barrier.

On approved succession, new holds immediately fail the old-head store check. The one-second scan marks superseded links draining and removes them from selection. Existing holds may finish for at most five seconds after that scan; links with no holds close immediately. The relationship request and retained verified history must remain unchanged. Removal still closes every generation immediately. Fresh links must authenticate the newly accepted head on both sides and complete the same arbitration transcript.

peer.Manager.Hold returns the sole ready non-draining link and an idempotent release function. It resolves the requested head or genesis through the store before selecting a link, rejecting ambiguous head/genesis cross-matches. Under the final store read barrier, that original ID must still resolve uniquely to the selected relationship and request, and both TLS authority heads must still match their generations. Managed channel holds remain owned through the mux terminal barrier; a raw Hold is only a relationship lease for manager tests and does not grant transport I/O. On duplicate loss, no new holds enter the loser. Existing holds finish or expire after five seconds; a loser with no holds closes immediately. The inbound TLS verifier captures the current relationship request before selecting its local peer credential. Registration checks that same request again under the store barrier. A previously authenticated, provisional connection cannot register after remove/re-pair with the same authority key. Local removal closes all committed and provisional links for the relationship genesis, including draining links with older TLS heads, and joins their workers before the control response. Drain expiry uses one five-second deadline even if a holder never releases. Shutdown cancels and joins the manager before the store closes. Only one outbound establishment per relationship is in flight. Failed attempts start their bounded randomized backoff after completion, not at dial start. Removal cancels and joins the attempt. Registration, holds, and removal use a per-relationship gate so arbitration and one peer's removal do not lock out unrelated peers. A connection's remote socket address is never a dial target.

The optional service.Options.PeerSchedulingClock is installed before peer workers start. It controls only the scan ticker, retry eligibility and the attempt-completion timestamp used for randomized backoff. Nil keeps the real one-second ticker and existing retry policy. TLS/security time and dial, exchange and drain deadlines remain on their original clocks. The read-only peer.Manager.NextRetryDeadline exposes a recorded deadline only after its attempt joins and while no replacement attempt owns that relationship. Opt-in paired-service fixtures advance to that deadline and let the ordinary scan perform admission and real TCP/TLS dialing; they do not reset retries or install links. Other paired fixtures retain real scheduling coverage.

Normal-peer regressions use bilateral direct pairing and authenticated peer TLS. The manager logs confirmed authenticated normal-peer links, with remote authority ID and inbound/outbound direction. On exit it logs that same ID and direction with removed, shutdown, or transport. Failed arbitration and retrying TLS handshakes do not produce lifecycle events.

Delivery is asynchronous and best effort. One process-wide dispatcher has four workers and a 128-event queue, shared across all peer managers. Enqueue never waits for a callback or the default stderr logger; a full queue drops the new event. Delivery can be concurrent or out of order. A blocked sink can occupy a worker indefinitely. If all four workers block, delivery stops and the queue eventually drops all new events, but repeated managers cannot create more consumers. At most 132 events retain sink references, including in-flight calls; this is an event-count bound, not a bound on memory captured by injected callbacks. Sink panics are recovered without retiring a worker. Establishment callbacks, link completion, removal joins, terminal fork callbacks/audit, and shutdown do not wait for diagnostic delivery. Shutdown neither flushes the queue nor joins the sinks, so callbacks may run after manager closure and must not access resources torn down then. Missing diagnostics are not evidence that a link did not establish or close.

An outbound normal-peer TLS attempt that returns the typed hoptls.ErrIdentity also emits normal peer TLS rejected remote=<accepted-head-id> direction=outbound reason=identity. Here remote is the locally accepted authority head, not the identity presented by the rejected connection. This is positive evidence of a local TLS identity rejection, including an authority mismatch, not proof of a specific successor or of rejection by the other Hub. Generic handshake errors, timeouts, TCP failures and lineage-query failures do not emit this diagnostic. Silence does not prove rejection. The diagnostic contains no raw error, records, SPKIs, addresses or secrets.

Rejection diagnostics are suppressed after the first event per relationship request and accepted head/generation. Confirmed link success or a changed request/head/generation resets suppression; removal discards it. The suppression flag lives in the existing bounded retry row and adds no workers, timers or dial slots. Queue overflow does not reset suppression or retry the diagnostic. A rejected attempt retains its existing slot through synchronous lineage discovery and continues to the next eligible local address. Diagnostic sink panics cannot escape into transport handling, and emission or suppression never decides whether to query, retry or accept. Pairing TLS never produces these peer-link events. Manual opposite-direction net.Pipe connections test manager arbitration, not two service scans or the public accept path. Separate public-TCP tests cover healthy and malformed duplicates, a real outbound TLS dial that fails arbitration before a bounded retry, removal during a paused outbound dial, and shutdown with a provisional inbound exchange. Focused codec checks pin the 40-byte arbitration frames and the nonce-bound score transcript. The current pairing contract persists exactly one direct joining address and no target address, so these fixtures cannot create two persisted addresses or two simultaneous service-initiated cross-dials.

Public-TCP regression also covers replacement operational keys without a proposal, reject-before-approve and accept-after-approve succession, rejection of new holds on superseded links, bilateral removal, fresh pairing and a new live peer. Old pairing approvals and transition decisions cannot revive the removed relationship.

A second verified incomparable immediate successor of the exact accepted Peer head commits a terminal removal before transport cleanup. The relationship's removal barrier excludes new registration and holds while the manager cancels retries, closes all owned links including provisional and draining links, and joins their workers. Automatic lineage queries retain their initiating dial worker and slot. Explicit queries reserve one of the same eight slots and register under the relationship removal barrier. A committing query closes its control connection before cleanup, cancels all relationship workers, and joins every worker except itself before reporting the fork. Cancelled workers do not schedule another retry. Saved-client entries keep their separate nonterminal fork policy. An active Peer fork has no branch-selection command: terminal removal requires fresh bilateral pairing. Two active relationships cannot own the same accepted head; convergence fails at staging, approval, and pairing activation rather than merging Hub identities. Removed history and unaccepted proposals do not reserve heads.

The shipped service attaches synchronization only after reciprocal READY selects a link. The peer manager invokes Ready(*peer.ReadyLink) with an opaque in-memory capability for that physical link. The capability exposes only relationship genesis, authenticated local and remote authority heads, exact-link cancellation, and ClaimDirectory(ctx). Retaining it owns no worker or transport. Claim performs admission without channel I/O, under the existing store, relationship gate and manager barriers. The service claims synchronously before scheduling setup. A delayed L1 callback can claim L1 only while it is still selected and eligible; otherwise it fails closed. It never selects L2 through the durable relationship.

peersync.EstablishPair(ctx, lease) consumes that lease, chooses opener or accepter from its authenticated heads, and opens or accepts the control/bulk channels on the same exact link. Setup and engine cancellation use the lease's link-drain signal. Link replacement, terminal fork, local removal, draining, and shutdown stop new channel work and join setup or the engine before mux and peer reservations are released. This adds no second registry, persisted connection ID, routing API, or wire field. Pairing TLS, unconfirmed candidates, and duplicate losers never receive a directory pair. Control parser/write reservations use the service's separate bounded control reserve; saturated bulk DATA cannot consume those charges.

A failed directory pair consumes its one-pair-per-link claim. The owner drains that exact physical link (not the relationship), so the normal-peer reconnect owner can open a new pair with new connection-local IDs; other channel leases follow the manager's existing bounded drain. This applies to setup failure and terminal engine error, including local resource rejection. A local removal or fork still uses the stronger terminal relationship barrier.

Directory bytes belong to the daemon-wide directory owner, not the physical link. Each engine borrows the same reserved immutable encoding, and a reconnect with matching retained count/digest exchanges summaries without transferring a snapshot. Replacing or draining a link releases its handles only after its workers and writes join; it does not erase learned records. Verified transitive lineages can stage an exact successor for any active relationship, including an address-free Peer. Only an explicit local revision-bound decision changes its pin. A verified incomparable branch uses the existing terminal removal barrier.

Directory pair setup has one ten-second deadline covering both control and bulk channels on both opener and accepter paths. An authenticated peer that opens no channel, or only control, cannot hold the directory worker indefinitely. Failure closes any partial pair, releases its connection-bound lease and drains that physical link for normal-peer reconnect/backoff. Cancellation and setup expiry remain context errors, not signature failures. Successful setup cancels only its setup timer; the engine retains the pair until its joined shutdown.

Directory frame completion has a separate absolute ten-second read deadline starting at the first byte of a control or bulk frame. It covers partial length prefixes and bodies; progress and mux keepalives cannot extend it. Fully idle channels have no frame deadline. A timeout follows the existing joined directory failure and link-drain path, preserving manager-owned reconnect and cancellation. Historical directory relationship evidence never grants link eligibility.

After a complete directory bulk snapshot passes its count/digest precheck, peersync transfers the reserved inbound buffer to LearnedDirectory.StageOwned. The engine drops its data reference and release callback; the directory consumes that ownership on success or failure. This avoids two full compact buffers while retaining parser charges, manager-owned channel leases, and joined cleanup.

JoinCancellation owns cancellation-callback joining independently of the protocol's close action. WatchCancellation uses it with immediate Abort; pairing uses it with its existing graceful Close. Stop is idempotent and waits for an already-running action without serializing other connections. This shares cancellation ownership without changing pairing's close behavior or its typed message/recovery model. Independent candidate checks are captured before asynchronous TLS work; role-correct matching belongs to identity.

Carrier close and abort composition

This is a downstream implementation contract, not a change to current hoptls source or TLS bytes. Normal hoptls.Conn.Close calls tls.Conn.Close; current Conn.Abort instead calls tls.NetConn().Close. Raw Session and AHRP carriers distinguish graceful Close from immediate Abort. The hoptls owner must preserve that distinction before those carriers are enabled.

Use the existing narrow capability shape interface { Abort() error } for immediate raw transport shutdown. Conn.Abort calls the existing hoptls.Abort helper on tls.NetConn, so an Abort-capable carrier is interrupted without close_notify, queue drain or grace renewal. The helper's ordinary Close fallback remains only for transports without that capability, such as net.TCPConn and net.Pipe. Keep normal Conn.Close as tls.Conn.Close, including its existing TLS close_notify bytes and deadlines. It eventually calls the raw carrier's bounded graceful Close, which drains output already reported written before FIN/join. No new exporter, TLS alert or ceremony message is required.

Preserve the capability through any once-close wrapper in hoptls.Lifecycle, handshake material owners and roleConn. A wrapper must forward raw Abort as nonwaiting and keep its ordinary Close as the joined graceful path. Abort does not consume the later join/release obligation. An Abort-capable raw carrier is NOT an authenticated TLS connection merely because it has that method; OwnConnection's current optimization for typed authenticated transports cannot be used to skip pre-authentication ownership for the new raw carrier. Keep one explicit pre-auth owner through callback join and DetachTransport, then one explicit authenticated owner. Never duplicate capacity or close authority. Handshake failure and cancellation use Abort before joining, not graceful Close.

Pairing's ordinary JoinInitial/ServePublic close defers still use TLS Close on normal completion. Cancellation actions, failed handshakes, malformed TLS and explicit terminal failure use the existing abort helper, then joined owner cleanup. The service/endpoint owner must also split RunApplication/ServeEndpoint normal return from failure: normal completion permits bounded TLS Close and raw carrier drain; cancellation/revocation/TLS/proxy failure aborts immediately. Current RunApplication's unconditional deferred conn.Abort and runGateway's first-pump-result cancellation are not sufficient production graceful-close composition. Do not cancel the terminal parent merely because one clean output pump returned; seal/drain and join the other direction within the existing close bound. Do not swallow a real caller loss or a delivery error as normal. Direct transports keep their current bounded shutdown behavior. Circuit bootstrap has its separate retirement contract and is not changed by this work.

Raw carrier Close/Wait cannot join the engine or gateway worker that invokes it. They join raw pumps/API calls and their role-specific Session/native settlement only. The outer service owner joins TLS/engine/gateway workers before finally releasing its remaining budgets and incident claims. Durable downstream tests must exercise successful queued close_notify/application output plus FIN, blocked-close cancellation through Conn.Abort and wrappers, partial writes with nonnil errors, concurrent Close/Abort, and no self-dependent settlement join.

The carrier close split is implemented: hoptls wrappers forward narrow Abort independently of ordinary raw Close, including failed or cancelled TLS handshakes, and expose TLS CloseWrite without retiring reverse reads. Joined lifecycle Close releases reservations only after its transport owner joins. The shared endpoint engine and proxy preserve that split for direct and routed applications. The client Tunnel and gateway's unbuffered directional pipe retain reciprocal TLS output after reverse EOF; normal drain and failure interruption use different paths. Focused regressions cover these owners without changing TLS roles, identity checks, exporters or application bytes.

AgentHub's TLS raw wrapper rejects transport EOF without close_notify, even at a complete record boundary. Go's ordinary TLS EOF tolerance is not used as proof of authenticated application closure. The wrapper returns a distinct error wrapping io.ErrUnexpectedEOF; genuine TLS close_notify still returns EOF. The clean/abort/record-boundary-loss regressions exercise this distinction.