docs/internal/agenthub-contracts.md

AgentHub current contract inventory

AgentHub is an unreleased first implementation. Current composition includes one public address, claimant-locked admission, endpoint authorization and ordinary EzAgent JSONL/TUI; bilateral pairing and explicit stable-authority decisions; signed local/learned directories, routing, relay and circuit sessions; retained recovery and production direct/routed application opening. Circuit possession and signed lineage grant no application access or successor consent.

The private contract and configuration are approved. All 79 ordinary operations plus transport cancellation, online/offline adapters, result accounting and the command-dashboard consumers are implemented, as are saved-Hub re-admission, endpoint eligibility/history, bookmarks and the native terminal lifecycle. Capacity, semantic-state, private-result and composed topology/process work is implemented too. The test guide describes commands, isolation and validation ownership. This inventory describes supported behavior, not completed validation runs or release signoff.

The direct-handshake review owns the client operator transcript. The pairing-handshake contract owns bilateral administrator ordering and exact pairing messages.

Layer owners

LayerContract and owner
Identity and recordsCanonical SPKI identities, human checks, certificates, and signed public records: identity, records
Local directoryBounded, scoped verification of committed public catalog selections: directory; store.DirectoryCatalog selects active Peer and matching Pairing evidence under the Hub revision, and validates every candidate before commit. The shipped peersync engine owns directory control/bulk mux composition and exchanges compact values over manager-owned channels; service feeds it only committed selections and retains RAM-learned state. The gateway consumes verified learned listing; routing remains separate. See directory contract.
Invitation and storePrivate claimant-locked lifecycle and strict v1 Hub/client state: invitationwire, invitation, store
Pairing messagesClosed authority-pairing request, frames, transcript authentication, and literal vectors: pairingwire
Configuration and controlClosed version-1 YAML: config; private typed JSONL: pkg/ezhubapi; same-user AF_UNIX: controlsocket; typed online/offline administration: admin
Gateway and applicationOne public outer gateway, bounded learned list, private-descriptor merge, and ez-agent-jsonl/v1 endpoint codec: gateway, clienttransport, internal/frontend, application
LinkClosed role-specific TLS, peer lifecycle and arbitration, and one-hop mux: hoptls, peer, mux
RoutingRoute-control v1 and its literal fixtures own bytes. The accepted worktree composes codec, RAM table/lookup, stream runtime and typed peer claims in production READY. Exact binding, synchronous invalidation, shared admission supervision and explicit joined channel-hold release fit the resource proof. Real signed/TLS topology and ownership evidence covers the composition. Routing Admission remains channel-free. Routing alone does not change remote gateway availability; the production endpoint carrier supplies the selectable remote path.
RelayRelay v1 and independent literal corpus own bytes and semantics. relay, paired routing admission and typed peer/mux composition implement exact AHRA control/bulk pairs, downstream OK/error, immutable forwarding and joined rollback/FIN/RESET. One local owner/lease covers both transit pairs. Process-fixed pool/issuer storage, per-Hub Setup storage and admitted attempt owners are charged separately; current capacities belong to service/configuration. Production installs endpoint and restricted-pairing origin consumers. Relay status and circuit handoff record real TLS topology/pressure evidence and the frozen structural/live-owner standard. Reliable DATA/ACK, retained recovery and remote gateway availability are not delivered by relay.
Circuit bootstrapCircuit v1 owns frozen bytes and limits. directory/records select one charged maximal nonconflicted local authority proof and invalidate its publication token conservatively. store uses one guarded transient borrow, fresh local credentials and persisted security time without direct-Peer lookup. hoptls exposes exact handshake-local authority and circuit-only close-notify. circuit.NewBootstrapper(BootstrapConfig) binds HELLO/confirm, rechecks before confirmation, joins cancellation, retires record-bounded TLS and transfers one raw result. Entry terminal settlement joins the attachment; origin leaves settlement to relay. Neighboring Peer policy, endpoint TLS/ACL access authority, service caps and public/private JSONL are unchanged. NewEntry reserves before one exact relay Start. NewOriginHandler denies without a consumer, reserves before Take and waits for Ready outside Admit with an independent acquisition lifecycle. service owns finite endpoint leases and counted fixture invocations; entry shutdown joins through Take. Optional relay OriginSettlement runs once after acquisition and both lane settlements on every terminal path. Capacity stays charged through the circuit and settlement gates, including the joined entry invocation bridge. Real signed A-B-C successor fixtures assert unchanged security state and raw-byte transfer, with only neighboring pairing. Production composes retained recovery and endpoint origin consumers without changing the circuit-only authority boundary.
Fixed-attachment circuit sessionscircuit.NewSessionStarter(SessionConfig{Clock: MonotonicSessionClock{}}) validates only; Start consumes and zeros its owned SessionInput on every outcome and rejects a public Role differing from Take's immutable local-role anchor before session allocation. Local RESET has one nonwaiting terminal-control admission through the existing relay writer/abort slot and shared abort-forward deadline; context-aware control close wakes on cancellation. No wire or worker/timer bound changes. One 4,096-slot pool retains 2 MiB unsent, 8 MiB unacknowledged and 2 MiB RX; cumulative authenticated ACKs release only emitted covered data, with deferred in-flight ACKs pinned until Commit. Six fixed workers plus two surrounding owners and one reusable session timer implement liveness, final-cursor FIN/ACK/FIN_ACK and terminal join. Entry Wait joins relay settlement; origin leaves it to relay. Public Read/Write users join before payload/material erasure. Real signed/TLS one-relay and two-relay service fixtures exchange exact binary duplex bytes beyond retained budgets, exercise pressure/control isolation, fixed preference changes, failures, malformed Start and charged joins. Circuit implementation evidence owns exact limits and the destructive-state split that recovery needs. Retained recovery and production endpoint TLS/ACL composition use this same byte edge.
Authority proposalsDurable non-authorizing lineage staging and exact decisions: store; local presentation: admin, pkg/ezhubapi; saved-client decision flow: clienttransport, internal/frontend
ServiceListener, limits, authorization epochs, audit, and local control: service
Direct clientTrust prompts, saved targets, endpoint access, typed JSONL handoff, and existing TUI: internal/frontend, cmd/ez-agent, pkg/tui
Common ceremony mechanicsClient binding, exact replay, confirmation and erasure: invitation.sessionCore; dispatched client/pairing processing ownership: invitation.Attempt.BeginProcessing; joined transport cancellation: hoptls; revision, durability, uncertainty and durable erasure: store. Separate closed hooks keep client ACK/status credentials distinct from pairing's bilateral approvals and exact-Q recovery.
Common trust presentationClosed independent-evidence match and canonical public records: identity; endpoint status and ordinary-open/fresh-authorization projection: clienttransport.ProjectEndpoint; confirmation rendering: internal/frontend. The private local-control wire is the typed EzHub JSONL API; public EzAgent JSONL and inter-Hub wire shapes remain unchanged.

Dependency direction is identity/records, stateless invitation and pairing bytes, durable store operations, invitation and pairing sessions, gateway/client transport, then service composition. Lower layers do not import ceremony state or presentation. Package source maps and the owning pages carry the detailed import boundaries.

Shared rules

  • Closed codecs and documents use their explicit version-1 literals, reject unknown or malformed fields, and bound lengths before allocation.
  • Public records contain no invitation root, selector, request, proof, claimant lock, or private profile. Invitation state is private store state.
  • One public Hub address serves first contact, admitted clients, and later peer roles. No response redirects to another host or port. Private control and application sockets remain separate.
  • Generic pre-TLS capacity transfers into authenticated role budgets only after closed TLS and valid state selection.
  • Saved addresses come only from deliberate local input and become pinned only after identity and lineage verification. Wire data, DNS inference, and routes cannot create or replace them.
  • Bilateral pairing activation creates durable peer eligibility only. Pairing TLS closes after bounded pairing exchange. The peer.Manager creates fresh normal-peer TLS, reconnects, and arbitrates duplicates.
  • Prepared recovery pins the saved exact target key without trusting its asserted generation until signed Context verifies it. Recovery preserves Q and polls before retrying Claim. The seven-day deadline gates approvals; only an already committed Completion may be retrieved afterward, before the existing retention cutoff. No new ceremony may start against a local non-removed Peer. Both sides must remove before re-pairing.
  • AgentHub changes transport framing, not EzAgent JSON values or service semantics. Application open chooses no CWD, root, or leaf. Remote recency is local TUI convenience state; session concurrency stays service-owned.

Identity, record, invitation, exporter, ALPN, gateway, application and configuration literals live under internal/agenthub/testdata/trust. Local-control literals live in pkg/ezhubapi/testdata/control.json. Package tests own runtime detail.

The separate routing corpus contains actual setup/frame bytes and line, diamond, expiry and exact-link replacement walkthroughs. These reserved route identifiers do not change mux class or directory bytes. The routing page owns the lease-bounded lookup boundary, channel-free routing Admission, typed failure scopes, daemon-wide revision exhaustion, lock order and count/byte proof.

Convergence and review boundary

The four current mechanism owners are signed-record semantics in records, authenticated lifecycle in hoptls with the existing authorization/manager barriers, ceremony progression in the owners above, and closed typed role policy at each role entry. Invitation sessions, request preparation, card creation and store approval and client installation no longer infer policy through public generic purpose factories. All production and test callers use the closed hooks. Public ALPN dispatch and local-control operation dispatch remain exact parser boundaries, not fallback.

Independent short and complete evidence must agree before protected disclosure or durable approval. Candidate checks remain diagnostic unless independently supplied. Offline, revoked, conflicted and unavailable endpoints remain distinct and cannot open an ordinary application. Explicit fresh Add agent reauthorization requires the published, available, nonconflicted carrier and independent endpoint check even when a revoked private descriptor exists.

The boundary includes the public Cancel-retry projection retirement and learned-origin handoff checks. It also covers suppression of prepared-origin Cancel delivery without a target-clock deadline, decision registration ordered against durable cancellation, the post-Challenge approval-time reload, terminal verified-pool ownership, order-independent forwarding of shared-head binding ambiguity and sole typed-TLS transport closure after constructor handoff. The final timing correction refreshes the boundary clock after decision-owner joins and again under the store snapshot lock for each local pairing approval or cancellation transaction. The initial connection transfers its sole cancellation owner to the shorter five-minute decision context, bounds continuation writes by that context, and leaves accepted or locally approved state for fresh recovery when the cutoff wins. Prepared cancellation without an authenticated target deadline performs no dial.

Daemon pairing recovery scheduling is removed; the service supplies one private exact check requested by an open local pairing view. The view owns immediate checks, repeat pacing and joined close; passive status and restart never dial from pairing rows. Authorization cutoff, Completion-only retention and durable active Peer access are unchanged. The owning contracts and test guide describe preservation and validation requirements; the current composition and validation boundaries are described below.

Current composition and supported fixture APIs

Production exports belong to the composed owner and its current consumers. Unused alternate protocol constructors, role fallbacks and convenience wrappers are not reserves for future components. Supported standalone fixtures remain valid consumers when they protect an observable contract; a production-only lexical reference search is not enough to remove them.

FamilyCurrent consumer and owner
Prepared client, saved-Hub and client transportClient-only startup, claimant-card preparation, explicit saved-target recovery/re-admission and exact selected approval TLS. Client flow owns the trust cut. No client-ID-only endpoint credential fallback is part of application opening.
Closed TLS roles, exporters and fresh store providersInitial/exact recovery pairing, normal peer lifecycle, client entry, endpoint TLS and circuit bootstrap. Link owns role separation and joined transport transfer.
Pairing sessions/wire/storeService initial and restricted routed pairing, signed Context, both approvals and exact-Q status-first recovery. Pairing handshake owns bytes and consent.
Signed records and directoryCurrent public catalog, learned compact synchronization, conflict handling and routing evidence. Records and directory own verified selection, not client recognition or Peer trust creation.
Mux, routing, relay and circuitsManager-owned exact physical links, required directory/routing consumers, paired relay lanes, authenticated Sessions and retained replacement. The layer table above names byte and ownership contracts.
Endpoint credential staging and renewalPrivate online/offline administration and composed renewal fixtures. Storage and identity own issuance/activation and current credentials.
Test-only lifecycle/filesystem/timing hooksThe deterministic seams below support staging, persistence uncertainty, cancellation and ownership regressions. They are not alternate accepting runtime paths.

Validation boundaries

The test guide defines validation ownership and focused selection. Package, process and deployment-host checks cover distinct behavior. Literal old_reset is unreachable under the accepted G1-reader-join-before-G2 invariant. The reader barrier and independent post-join stale-token assertion remain mandatory. The supported maxima and supported regressions remain unchanged.

The private API approval does not extend to public EzAgent or inter-Hub wire changes. Current best-effort broad pressure feedback does not promise an exact origin-queue subtype or reliable diagnosis after notice loss. Strengthening that behavior needs separate wire/lifecycle approval, not an inferred capacity contract. Unclaimed pairing cards may be cancelled by exact local row ID; client admission cards retain their separate lifecycle.

Transport detachment joins before typed handoff, with no second concurrent cancellation owner. Peer adoption transfers its reservation alone. Static context and claimant presentation use closed hooks; endpoint invitation TLS scheduling stays endpoint-owned. Complete identity presentation validates SPKI and provenance. Structured JOIN/pairing input holders consume and clear owned material. These implemented boundaries do not alter pairing/client protocol bytes.

Retained deterministic fault-injection seams

The structural removal claim is limited to the audit-listed parallel protocol APIs. The repository still exports peer.Manager.SetLineageStageHookForTesting and the Hub/client store SetTransactionHookForTesting methods. These predate this correction and remain deterministic integration-test seams for staging revision races and filesystem failure/uncertainty. They do not provide another protocol constructor, claimed-content installer, authorization path or role fallback. Runtime composition does not call them. Their comments constrain concurrent use; test cleanup removes the hooks or closes the owning fixture. No future production consumer is claimed for them, and the tree is not described as free of all test-only exports.

Timing and observation seams

Production endpoint opening and peersync partial-frame completion remain fixed at ten seconds. Neither engine exports a duration override. Private endpoint.Engine.openingDuration and peersync.Engine.frameDuration accelerate component tests only. These short tests certify cancellation, timeout classification and joined cleanup, not elapsed production timing. The peersync non-sliding test observes the default ten-second absolute deadline at the first byte. Managed service partial-frame coverage uses the real default duration; there is no service duration override.

invitation.AdmissionController.DisableClaimPacingForTesting is a retained policy-changing test seam, not a runtime configuration option. Its entire caller inventory is invitation/limits_test.go, clienttransport/saved_integration_test.go and pairing/engine_test.go. The mutex and first-reservation guard make the choice immutable before use, even after the first lease closes. Default construction retains the two-second interval. TestSchedulerBoundsLaneFIFOAndRetainsCancelledWorker covers ordinary pacing; TestDisabledClaimPacingStillWaitsForActiveAttempt covers the guard, FIFO, worker exclusion and unchanged processing deadline with the bypass. Bypassed fixture results must never be used as production-pacing evidence. Frozen predecessor comparisons must use ordinary pacing in both lanes or explicitly classify their policy difference.

clienttransport.approvalTestPolicy is a private context-key seam. It injects loss only after an authenticated pending response and replaces reconnect waits with cancellation-aware barriers. It certifies recovery after carrier loss, not production idle expiry or elapsed retry timing. Gateway timeout cases own idle-expiry failure production. directory.selectOutbound's private afterAuthorities callback injects cancellation between collection phases; it does not change selection or limits. records.SignedFrameSelection.observeParse is a private strict-parser observer. Its counts establish parser-call reuse, not zero allocations or whole-process memory use.

The lifecycle matrix is an overlapping test index, not exhaustive certification. Once-guarded release observers establish release before return, not the count of native Close calls. TLS role-pair probes do not establish composed service-budget ownership; only explicit pre-certificate probes observe disclosure. Maximum charged reservations are accounting evidence, not RSS measurements. Skipped capacity probes provide no preservation evidence.

Private administration migration

All 22 administration operations use concrete pkg/ezhubapi requests/results. The service authenticates owner-private AF_UNIX before hello and shares one Server; the dashboard and pairing view share one concurrent Client. Only socket absence permits offline locked administration through the same typed handler. admin.CommittedResult is internal definite-commit/audit processing, completed before wire delivery. Cancellation ACK follows exact handler retirement; EOF and shutdown cancel and join owners. The predecessor package is deleted, without an alias, generic-parameter adapter, dual listener or U32BE local administration.

Local administration owns the new private contract and replaced control.json corpus. Other fixture bytes, public EzAgent JSONL, inter-Hub protocols, durable formats and schemas are unchanged. Exact-link READY ownership is preserved.

Add Hub now maps definite Prepared and Context commits to Prepared/Accepted with exact nonsecret IDs and actual checkpoint revisions. Uncertainty fabricates neither outcome; precommit failure creates no row or view. Alias warnings retain durability, and either checkpoint opens or wakes one client-owned view with an immediate exact check. The service tests exercise this composition; library literals alone are not business acceptance. Current direct/routed consumers use the single typed private transport above. The typed library tests own codec and transport regressions.

Payload/configuration integration boundary

Maximum escaped 64 MiB JSONL values now have separate wrapper, parser scratch and active encoder headroom, with real direct and one-relay bidirectional evidence. Protected finite YAML limits feed production owners; exact-token replacement, restart-required state and independent configured/effective/structural values have internal domain APIs. Entry-Hub locally detected resource pressure uses the approved best-effort terminal/resource_limit gateway/client/frontend/TUI path. Received circuit resource RESETs remain generic terminal failures, while remote mux resource resets remain transport failures eligible for normal attachment recovery with the fixed 65-second grace. Existing RESET bytes do not authorize remote pressure propagation or new inter-Hub lifecycle semantics. Best-effort notice loss remains generic failure and exact origin-queue subtype is not encoded.

Private DTOs, online/offline adapters, atomic usage/peak sampling, result ownership, viable configuration minima and command consumers are implemented. Current capacities and compiled/default arithmetic belong to configuration and service production ownership, with regressions in service, store and the typed library. Supported maxima have not been reduced. Codec/ownership checks, signed population controls and maximum live profiles have distinct validation scopes.