docs/pkg/service.md

pkg/service — daemon orchestration

pkg/service runs the persistent daemon: startup and readiness, Unix-socket peers, external service processes, capability routing, and shutdown. For executable behavior, see cmd/ez-agent-service; for configuration, see service/config; for stored session state, see service/session; for per-leaf model execution, see service/agent. Other destinations are in the routing table below.

RoleKey files
Daemon lifecycle and readinessdaemon.go, state_lock.go
Socket server and peer dispatchserver.go
Leaf runtime/state operations and coordinationleaf_operations.go, leaf_runtime_operations.go, leaf_sync.go
Capability ownership and pending callsregistry.go, ipc.go
Child service supervisionprocess_pool.go, service_process.go
Progress/replay and loggingprogress.go, logging.go

When is the daemon ready?

A bound socket is not readiness. Its bootstrap server answers only hello_ack{ready:false} while session maintenance runs. The same listener then hands off to the normal server, preserving its inode and queued clients. ProbeDaemonContext distinguishes an unavailable daemon from one still starting; StartDaemonContext joins an existing starting/ready daemon, while StopDaemonContext refuses a bootstrap daemon and verifies readiness again before shutdown.

Startup storage cleanup, interrupted-turn repair, optional vacuum, and content reconciliation are orchestrated here but owned by service/session. Warning failures may still permit readiness; failed cleanup or repair suppresses automatic vacuum.

Interrupted-leaf alert recovery runs during repair, before serving clients. Unlike best-effort turn repair, failure to recover these alerts stops startup so active recovery markers are not mistaken for fresh activity.

Selected incident registrations in audit.go use fixed friendly operation descriptions for stats reads, leaf names, prompt admission, abort, and individual startup phases. Handler entry, panic boundary, and response sites have distinct static file/method/index identities. The descriptions share the internal Go/Ruby operation allowlist; they never come from request text or exceptions. This labeling does not change service behavior or add stack-wide instrumentation.

What does a connection own and lose on cleanup?

Server accepts Unix peers and dispatches typed operations, but JSONL frame schemas belong to pkg/protocol and pkg/ezagentapi. Connections have subscriptions, correlated-response routing, capability claims, and pending IPC calls. Completion records retain their originating connection only to route that request's terminal notification. leafOperations owns and coordinates live leaf runtime independently of the socket; connections do not own leaves or Agents. Cleanup removes subscriptions and transient progress, closes the peer, and releases registry ownership. It does not cancel accepted prompt or replay work. Those runs continue with no connected requesters and remain visible to a later subscriber. Do not send to peers while holding Server.mu: SendToLeaf snapshots subscribers first.

Connection cwd defaults are captured in inbound wire order before context-dependent handlers run. update_cwd changes that default and can switch the subscription; it does not modify a stored root. Leaf-gated switch and replay work runs outside the wire reader. Only requests that use the connection default wait for an unresolved cwd update; explicit-leaf and explicit-cwd work can continue. Subscription versions stop older pending create, switch, or hello replay from replacing a newer selection or a successful feed drop. Failed drops do not advance the version. A new root uses the captured default only when neither cwd nor a fork source is supplied. list_cwd returns distinct CWDs containing non-temporary leaves with turns, including missing paths and unloaded conversations. Temporary leaves, empty leaves and orphan roots do not contribute to the list or its summaries. Running, aborting and background leaves count as active.

leafOperations owns the live-Agent registry, prompt-like admission reservations, progress registry, per-leaf gates, Agent construction, and runtime/state operation policy. It coordinates create and fork initialization, prompt and steer admission, tool-result admission acknowledgements, abort, rewind, deletion, virtual root creation, vacuum cleanup, leaf mutations and cache effects, snapshot and stats capture, replay barriers, eviction, and shutdown closure. Operations also choose each required notification and its order. The server implements a narrow routing interface that looks up recipients and enqueues immutable frames; it has no runtime map and leafOperations has no Server backpointer.

Provider-native thinking (Anthropic thinking/redacted blocks and OpenAI Responses encrypted reasoning) is durable data belonging to the assistant turn that produced it. leafOperations keeps no cache of it: Agents load it with the provider context from SQLite and release the request-local copy when the provider cycle ends. Forks, rewinds, restarts, and idle Agents need no native-state bookkeeping because they follow the durable turns.

The exported Server.PublishLeafSnapshot, Server.AdvanceSentTurn, and Server.NotifyRunCompleted methods forward directly to leaf operations for Go API compatibility. Production Agents receive leafOperations as their event router and run notifier, so these compatibility methods do not restore runtime ownership to dispatch.

Direct prompt admission treats a registered closed Agent as unloaded. Under the leaf gate, it drains that generation's owned subscription resolution before conditionally removing the reference and following normal lazy loading; concurrent admissions share the replacement without requiring a stats or replay read first. A stale reference cannot remove a newer registered Agent.

Prompt failures retain their admission-stage error code and original message. In particular, a request that passes preliminary validation but loses admission to another prompt returns leaf_busy with agent is running. Preliminary ensureAgent busy errors retain their existing leaf_busy: message prefix.

Storage still owns transactions and durable session mechanics. Agent still owns model execution, queues, run lifecycle, and Agent-internal compaction. The capability registry and IPC caller still own invocation claims, watchdogs, and process routing. Read-only command handlers may combine those owners' snapshots, but they do not mutate leaf runtime state.

How are leaf snapshots and stats ordered?

Leaf lifecycle notifications are selected under the same per-leaf gate used for ownership changes and snapshot publication. on_success and on_error still describe each model run. After execution retirement, on_background describes model processing stopped with provider-owned tasks remaining. on_idle describes true quiescence: no execution, queued/in-flight input, terminalization, or pending admission reservation, and no background owner. Last-task removal and provider loss can select idle without a new model turn. Initial leaf loading and repeated snapshots do not deliver duplicate idle notifications.

Selection and canonical snapshot publication share the gate. External macro calls run afterward, without a service/Agent mutex. Callbacks execute in selection order per leaf, so background rejection cannot lose to a later idle callback. A held callback queues later notifications without blocking their callers or model completion frames. It cannot block completion admission or work on another leaf. Background alone is not an editing or admission lock. For add/remove RPCs, the tracked worker enqueues the ownership acknowledgement, then cancels and joins the admission cancellation watcher before invoking the selected notification. Admission is cancellable by disconnect/shutdown, without an implicit elapsed-time maximum; a slow macro cannot turn committed ownership into an acknowledgement timeout or disconnect the shared provider. Notification work remains tracked for cleanup. Admission reservations project running during handoff, including before lazy loading, and prevent both idle delivery and eviction. Idle age starts at true quiescence rather than at the first model stop with owners remaining.

These notifications are not subscriber termination commands. Requester-directed prompt_completed and leaf-wide agent_end remain per-run outcomes, and may arrive after a background notification macro completes. Ownership-only retirement emits the idle snapshot and configured idle macros, not a fabricated model terminal event. Followers must observe the accepted leaf through background activity and owned follow-up runs until idle or deletion.

Provider invocation and provider-setup failures terminate the model run without retiring independently owned background tasks or cancelling unadmitted daemon continuations. Remaining owners keep the leaf in background; a later completion can wake the model without another user message. Failed requests and tool calls are not replayed. Run cleanup still discards queued/in-flight input and rolls back unsent turns. Agent/storage failures, including context-storage reads during provider preparation, retain the ownership cleanup path, retiring an immutable task snapshot and routing kills with reason error outside the gate. Registration cannot race past a claimed error. Cleanup preserves that error and never calls public abort or appends an ABORT record. Explicit abort retains its existing outcome selection and cancels background tasks after provider failure. Shutdown closes admission before provider teardown, retires remaining owners, and suppresses new idle/background notifications and follow-up admission.

leaf_updated and leaf_stats_response hold the same per-leaf gate from capture through response enqueue. Their connection-local itr values therefore preserve capture order, even when RPC handlers or client callbacks run out of order. leafOperations captures stats and invokes the response-enqueue callback before it releases the gate, including when that enqueue fails. Capture failures invoke the handler's error-translation and enqueue callback before releasing any acquired gate. Enqueue failures return directly without a second response. Enqueue does not wait for a socket write or remote acknowledgement. Other leaves use independent gates.

The gate serializes snapshot assembly, not every database or runtime mutation. Durable reads and process-local snapshots still use their own subsystem locks; they are not one global transaction.

Model activation, retirement, and background-presence changes record activity in the existing leaf metadata under Agent.mu. Background ownership mutations and the Agent's presence mirror share that critical section, so model admission and retirement cannot run between them. Ownership callbacks release leafOperations.mu before activity storage writes. Closed Agents reject new ownership; cleanup can still remove their owners without consuming recovery markers. At the idle transition, storage consumes an armed alert_idle and sets alert_time to the current UTC time in one transaction, before another run can enter. Queued work and prompt-like admission reservations defer that transition along with background ownership. Releasing the final reservation records quiescence even when the lifecycle phase label is unchanged. Multiple background tasks keep the leaf active until the last one finishes. Normal shutdown freezes idle conversions before disconnecting task owners. Startup applies the same conversion to leaves left active by either a normal stop or a crash. Snapshot reads do not drive these transitions. The metadata conventions and one-shot behavior are described in session storage.

Both frames project one computed access_source through leaf_access_source.go. An active Agent retains the source captured from its run configuration and selected route; an idle or unloaded leaf uses freshly resolved next-run configuration, including its trusted project overlay. SIWC uses the selected registration from GetOAuthCredentials and requires UsableSubscription; legacy, missing, or incomplete authorization is unavailable, never API-key fallback. Explicit loopback compatible/Ollama routes without API-key authentication are local. A keyless remote route is unknown, not implicitly local or free. API-key routes are api_key. This classification is non-secret display data in RAM, not SQLite schema, editable leaf metadata, authorization, or a price estimate.

Pending questions are daemon-owned leaf state captured inside this same gate. This includes snapshots sent for hello subscription and reconnect, switch, autosubscribe, and ordinary live publication. The internal question owner only supplies a complete snapshot and resolves an exact question_reply; it exposes no generic producer or macro route. A successful reply receives the correlated question_reply_ack. Invalid kind, empty revision, or a reply other than trust or reject receives parse_error without reaching the owner. After the owner accepts a reply, the durable decision invalidates cached project resolution, the operation enqueues the acknowledgement and replying-leaf snapshot, then releases that gate before taking each other leaf gate individually. It fans out a freshly captured complete snapshot to every currently loaded or followed leaf whose physically resolved CWD/config identity and exact bytes still match. A failed acknowledgement does not suppress fan-out; its saved error is returned afterward. Dormant leaves derive the decision on their next snapshot/config sync. Concurrent or duplicate replies are serialized across leaves: exactly one decides an undecided revision and later replies receive question_not_found. If the current project bytes changed before a reply, that error is followed by fresh snapshots carrying the replacement question for matching loaded/followed leaves. If the config was removed or current inspection fails, the exact previously observed revision is used only to select matching live/followed leaves; their fresh snapshots clear the obsolete question without persisting a decision. The owner retains one compact path/fingerprint/revision identity per leaf—not config bytes or revision history— and prunes leaves that are no longer loaded or followed.

rewind_leaf is a leaf operation that coordinates both layers. The leaf gate serializes it with lazy load, eviction/unload, deletion, and prompt admission; a loaded Agent's lifecycle lock then serializes the compare-and-rewind with prompt and run admission. Only idle or unloaded leaves qualify. Non-replay rewind leaves an unloaded leaf unloaded. Replay lazily creates an Agent, reserves the run, and enqueues the correlated leaf_rewound acknowledgement followed by canonical leaf_updated, releases the gate, and only then starts normal stream lifecycle. On failure, the operation invokes the handler's error-translation and enqueue callback before releasing an acquired gate. Admission-reservation rejection keeps its leaf-specific busy message; Agent busy errors keep their original messages.

Snapshot capture takes the leaf gate, then one subsystem at a time. leafOperations.mu is held only for short live-Agent and admission access and is released before entering storage, Agent methods, progress, or routing. Server.mu protects connection and subscription routing and is likewise not held while entering leaf operations or sending frames. Snapshot capture therefore proceeds as gate, storage, live-Agent lookup/runtime, then progress. Enqueue happens while the gate still establishes order, but without either map lock held. Agent stream replay barriers never acquire a leaf gate while held.

Progress mutation checks the current connection after acquiring the leaf gate and progress mutex. Cleanup removes routing before taking the progress mutex. A write therefore finishes before cleanup or is rejected. No routing lock spans a leaf-gate wait or frame enqueue.

Progress items are generic connection-owned statuses, not projections of tool invocations. The producer chooses an update ID within a leaf and supplies the current authoritative sent turn. Items have no per-leaf, per-connection, or server-wide count caps. Payload validation remains unchanged: identifiers and titles are bounded, text rejects controls, and an item has at most five optional lines. Visualizer descriptors retain their wire shape and live runtime macro ownership checks.

Progress ingestion uses the existing positive report_progress.itr as a high-water mark for each connection owner, leaf, current sent turn, and update ID. After validation, a positive iteration at or below that key's accepted high-water mark is silently ignored. Other IDs, owners, leaves, and turns have independent history; there is no connection-wide lower-iteration rejection or callback FIFO requirement. Omitted, zero, negative, or otherwise unusable iterations keep compatibility arrival-order behavior and do not erase positive iteration history.

Newer identical replacements and clears of absent items advance this history without publishing a snapshot. Clear records retain only the owner, update ID, and iteration, never old summary payloads. They do not reserve an inactive ID against another owner. Ordering records have no count cap or eviction policy and last only through the current sent turn and owner lifetime. Disconnect, leaf deletion, and authoritative sent-turn changes clear the corresponding records, including transitions discovered during ingestion and gate-held rewind reconciliation. Records-only cleanup does not publish an unchanged snapshot.

Identical replacements and clears of absent items skip snapshot capture and publication after turn and ownership validation. Turn transitions still publish complete affected leaf snapshots, including a transition discovered by a stale report. A status published once stays in RAM without subscribers or refreshes; leaf stats, switching, and reconnect replay recover it. Producers clear their statuses when work ends. Disconnect or provider death clears all items owned by that connection, and a new authoritative sent turn clears the leaf's old items. Queued drafts do not advance this authority, and late old-turn reports cannot restore cleared statuses.

Who may claim a capability, and how does reload preserve routing?

Tools, macros, and plugins register in a daemon-global namespace for each capability kind. Project configuration can supply an automatic loading fallback, but does not create a project-local provider scope. An existing live owner takes precedence over that fallback. Once a project-triggered provider registers, its claims participate in the same global routing as any other provider. Registration does not by itself add a capability to every leaf's enabled set.

Use distinct registered names for distinct implementations that must coexist, including generated unique macro names for workflows. Distinct service definitions that must coexist also need distinct service names, because the process pool is keyed by service name. Reusing a capability name does not create a local override.

Configured capability claims come only from direct JSONL service definitions, never a peer's hello name; background service capability lists are discarded. Runtime announces and configured placeholders are first-live-owner-wins. When an owner disconnects or releases, runtime-only claims vanish; configured placeholders remain and become claimable again. Reload reconciles placeholders without replacing live owners or in-flight calls, so each admitted request retains its configuration snapshot. Results must be claimed exactly once by their owning connection; malformed results complete synthetically rather than stranding a call.

A model tool call retains the provider connection selected when its definition was offered. Dispatch checks that connection instance and the registry's current owner together, then reserves the trusted invocation before sending. A disconnected configured direct service can recover before reservation: the daemon verifies the same launched service name and definition, requests missing tool metadata even when the replacement omits announce, waits for metadata, and checks that the offered description and parameter schema still match under the run's admitted overrides. Recovery refreshes the private caller's binding; it cannot redirect a call to an unrelated provider or a different service definition. Each dispatch attempts recovery at most once. Validation and timeout selection merge the selected provider's metadata with the explicit tool overrides from the run's admitted config. Provider disconnect completes both pre-ack and result waits, including parallel calls and calls with disabled timers. A sent call or failed send is never automatically replayed because its execution status may be unknown.

Macro dispatch also retains the admitted provider connection. Disconnect cleanup eagerly aborts visible calls, while each waiter observes that connection's closure to cover calls admitted during the cleanup sweep. Results, timeouts, and disconnects share one terminal claim. Connection release and registry shutdown preserve pending macro, tool, and plugin calls for terminal completion when the provider closes. Plugin waiters also claim a disconnect result without relying on watchdog expiry.

Inbound peers and spawned services use the same fresh c_ connection-ID allocator. An ID identifies one connection lifetime and is never intentionally reused. Service names remain process-pool keys; PIDs are for diagnostics and process management. Disconnect removes routing and capability claims before cleaning up leaf state. Managed-service replacement waits for that generation's cleanup; unrelated incoming connections do not wait. Deferred sends retain the captured transport. Late capability frames, subscriptions, and progress reports check that their connection is still current.

Prompt and steer accept the requester after their leaf admission reservation and before recovery or mutation. Rewind checks after acquiring its leaf gate, before changing history. The short routing liveness check is the acceptance point. Rejected work neither starts an Agent nor mutates history. Once prompt or replay work is accepted, requester cleanup does not affect it: the run survives with zero connected clients and later subscribers receive its normal snapshot and durable history. Explicit abort remains the cancellation path. Accepted steers retain their existing detached processing and append-failure behavior. No routing lock spans Agent, storage, startup, or leaf-gate calls.

How are external services kept alive or reaped?

ProcessPool is keyed by service name: concurrent direct requests share one spawn flight and its published connection. Lazy GetOrSpawn is direct-only; background services are started with StartService and have no JSONL connection. Failed or immediately exited children are never published, and shutdown waits for admitted startup records rather than relying on output EOF. Direct-service IPC closure retires the exact managed child even if it is still alive. Replacement waits for reaping and connection cleanup, with a two-second retirement limit, so old cleanup cannot remove a new generation's claims. Recovery callers share a startup flight and can cancel their own wait without cancelling startup for other leaves. Failed flights have a 250-millisecond retry cooldown. A healthy matching replacement is reused; recovery never displaces a differently configured service instance.

Service executables do not resolve through PATH or the project working directory: relative paths are beside the physical daemon executable, ~ is the daemon user's home, and Ruby services use the bundled ez-agent-ruby launcher.

Spawned services inherit ordinary operation settings, including XDG, locale, certificate, path, proxy routing, and service-specific variables. The daemon filters every environment variable named by a user-global auth profile's api_key_env (project config cannot redirect that auth source), common provider API keys, token/secret/password/credential suffixes, AWS credentials, and the caller's AGENTCLI; it then supplies an AGENTCLI resolved beside the running daemon when available. Uppercase and lowercase HTTP, HTTPS, and all-proxy settings remain available after URL userinfo is removed, while NO_PROXY and no_proxy pass through unchanged. Malformed credential-bearing proxy values are dropped. This reduces accidental credential exposure. It is not a sandbox, and configured subprocesses still run with the daemon user's filesystem and process privileges.

What must remain true when touching lifecycle, routing, or progress?

  • The state-directory lock precedes socket binding and SQLite access; interrupting startup unlinks the socket and releases the lock.
  • Server.Stop is idempotent: leaf operations close their Agent snapshot while the server shuts down processes, listener, connections, and registry state. The leaf owner atomically closes Agent registration and captures that snapshot. A lazy generation that loses registration is closed before recovered work can launch; new construction after the boundary also produces a closed Agent. Every Agent is canceled before any owned subscription resolution is drained, so one slow renewal cannot defer cancellation of other leaves. Ordinary close and closed-generation removal also drain credential persistence. These waits do not join tools, plugins, or whole run loops. StopDaemonContext allows up to 80 seconds for this bounded renewal/save drain, still honoring caller cancellation. Its startup probe and readiness handshake keep their short deadlines. TUI disconnect does not stop the daemon or its accepted leaf work.
  • Progress belongs to the authoritative sent turn. The leaf owner publishes canonical turns before advancing and clearing progress. A visualizer macro must be live and owned by its reporting connection; disconnect removes its progress through the leaf owner. Operations that already hold the leaf gate can reconcile a storage-resolved sent turn with advanceProgressTurnLocked before capturing their own canonical snapshot; they must not recursively call AdvanceSentTurn while holding that gate.
  • Leaf deletion is a daemon-side decision: an in-progress prompt or prompt-like idle user steer reserves the leaf before admission, and deletion returns leaf_busy until that request has produced its acceptance or error. Clients do not preflight, retry, or participate in an additional handshake.
  • Timeout policy is provided by pkg/watchdog, not duplicated here.

Where detail lives

NeedAuthority
Service definitions and reload inputsservice/config
Roots, leaves, turns, and maintenanceservice/session
Per-leaf prompting and model executionservice/agent
Unix sockets and JSONL transportpkg/ipcsocket, pkg/ezagentapi
Frame contractspkg/protocol, JSONL API
Tools, plugins, and macrospkg/tools, cmd/ez-agent-builtin

For behavior-level examples, start with daemon_startup_test.go and process_pool_test.go.

Service waits and incident timing

leafGateRegistry pins and locks a new gate before publishing it, then validates its leaf outside the global registry mutex. Other leaves can look up and release gates while SQLite is blocked. Same-leaf waiters share the validation and retain one gate through capture and response enqueue. Failed validation retires the gate; a retiring gate remains registered until its last reference drains. No competing gate can overlap deletion or retirement.

The daemon creates one incident recorder before global configuration loading, state locking, socket binding, or database open. The executable calls RunDaemon(nil) to load configuration inside this timed path; fixtures and other Go callers may still pass an already resolved configuration. It carries that recorder into the ready server and closes it after storage and state-lock cleanup. Healthy breadcrumbs remain in memory and create no audit directory, file, or worker.

Fixed observation thresholds live in pkg/service/audit.go:

ObservationThresholdMeaning
Selected dispatch-lane wait, RPC, gate validation/wait, stats capture2 secondsRecord a timeout while work is still waiting; slow abort handling records cleanup_slow. Do not cancel it.
Each startup phase5 secondsRecord a slow config-load, state-lock, socket, DB-open, maintenance, or server-start phase before it returns.
Each shutdown phase5 secondsRecord cleanup_slow while pool, admission publication boundary, Agent, registry, transport, storage, or state-lock cleanup is still running.
Final audit or panic-boundary drain100 millisecondsBound the caller's wait; audit failure never gates service success.

The API's Handlers.OnRequestQueued hook records selected decoded request IDs before callback serialization. The dispatch timer remains active while that connection's callback lane is blocked, then ends before the handler's own start observation. Matching responses still bypass the lane for correlation; neither the hook nor the timer changes dispatch ordering or cancellation semantics.

Selected handlers record receipt, start, response-enqueue decisions, and safe unexpected boundaries for stats, prompt, abort, and rename requests. Only admitted machine IDs and numeric observations enter audit data, never names, errors, payloads, or panic values. Ordinary abort/rejection is a breadcrumb, not an incident. Selected panic boundaries record a fixed category and rethrow the original value without inspecting it. Abort evidence distinguishes the requested cancellation, process-local aborting state and snapshot publication, abort_received enqueue, and later prompt completion. Enqueue is not proof that a peer read an acknowledgement, and an accepted abort is not proof that a durable ABORT turn has committed.

Operation/storage results and response delivery have separate callpoints. Expected typed not-found, validation, busy, and cancellation outcomes remain noncritical and end with fail or cancel, not success. Fast unexpected storage/admission failures open an incident even when their public rejection is successfully enqueued. Known terminal transport causes use the shared ezagentapi.IsTerminalTransportError classifier and record cancellation rather than an unexpected incident. This includes the distinct closed JSONL sentinel. A failed acknowledgement does not roll back an admission or authorize a retry.

The internal leaf router returns its fanout enqueue result. An abort snapshot records completed/fail when any subscribed enqueue fails; the missed-snapshot connection is still closed. A closed peer alone is noncritical, so this outcome may remain only in the breadcrumb ring until another incident opens the file.

Pool observations use duration_ms for the change in DBStats.WaitDuration, attempt for the change in WaitCount, and pending for ending InUse. These are process-wide counters observed around an operation, not exclusive attribution of wait time to its request. The single SQLite connection remains intentional.

Stats and abort carry the handler context into storage where useful; selected responses use it for enqueue. The current transport does not convey a client's local RPC timeout as server cancellation. Leaf mutex waits also remain ordinary mutex waits. A local client timeout neither rolls back admitted work nor proves that its response will never arrive.

audit_test.go, audit_admission_test.go, leaf_sync_test.go, and daemon_startup_test.go cover cold recorders, timer-triggered incidents during unfinished phases, safe error/ID filtering, nonfatal sink failure, and a blocked real one-connection validation without global gate contention, correlated callback-lane waiting, fast failures, actual shutdown admission-mutex waits, and abort fanout failures. Thresholds are observation budgets, not new wire contracts or shutdown deadlines.

Final prompt admission revalidates the supplied parent under the Agent lifecycle lock immediately before durable append. Preliminary ensureAgent validation is not admission authority: an intervening completed run makes an older parent an expected turn_conflict rejection, not a storage incident. The typed agent.ErrPromptParentConflict survives wrapping for internal audit classification. prompt_parent_admission_test.go holds one connection after preliminary validation, completes a prompt from another connection, then verifies stale admission leaves history unchanged.

Connection-owned renewable waits

Tool, plugin and macro heartbeats require the exact pending kind, call ID and owner connection. Results and acknowledgements use the same owner boundary. Plugins and default macros retain five-second inactivity watchdogs without a default elapsed-time maximum; explicit metadata maxima and caller limits remain. On-demand metadata uses the Go API's shared typed RPC correlation and renewable watchdog. Startup readiness remains bounded separately.

Connection cleanup terminally retires all outstanding kinds, including acknowledged tool calls. A replacement has a fresh connection ID and serves new calls only. Existing pre-dispatch configured-provider startup/recovery remains; a dispatched call is never transferred or replayed. Local cancellation makes no rollback claim and adds no cancellation protocol. Abort/shutdown replies, tool stop/kill paths and LLM provider retry rules are unchanged.