Introducing a new way to review your PRs.

Read the announcement

hashgraph-online / hol-guard

Open-source antivirus and firewall for AI agents: block risky tools, secret access, prompt injection, malicious packages, MCP servers, plugins, and skills at runtime.

View on GitHub

44 documents · Updated Nov 23, 2026

docs / native-runtime-residency-and-recovery

Native runtime residency and recovery

The Rust native runtime supports fresh one-shot decisions and a managed resident service for repeated local work. It provides one authenticated boundary for requests, keeps process ownership and persisted state bounded, and recovers only when the runtime identity and policy remain trusted. See Native runtime authority, Native command evaluation and classification, Native command source programs, and Native command catalog and pack lifecycle for related authority and command flows.

Execution modes

The runtime offers two process shapes for different request patterns. One-shot execution gives a caller a fresh process for one bounded exchange. Managed-resident execution keeps a verified service available for repeated requests while its owner or active clients still use it.

One-shot execution

One-shot execution reads one bounded request and returns one bounded result. It suits calls that need fresh process state or do not use the resident service. A failed native authority call does not silently switch to a second semantic evaluator. Guard returns the defined fail-safe outcome instead.

References: rust/…/main.rs• L688-743

Managed-resident execution

Managed-resident execution starts only when a request needs it. A starter creates one generation under a startup lock. A supervisor owns the serving child, supplies its authentication and liveness input, and records how it ends. The serving child loads the generation policy before it accepts work, then owns the endpoint while its owner or a client of the same runtime remains live.

Each client holds a lease while it uses the service. The lease lets the service outlive the process that started it, but it does not let a client from another runtime keep an old generation alive. When the owner and same-runtime clients are gone, the liveness path closes and the service exits without waiting for its full idle limit.

The supervisor remains part of the managed run until it reaps the serving child and writes its exit evidence and restart-budget update. A requested shutdown is recorded as a clean lifecycle event rather than as a crash. This makes “stopped” mean that the child and its recovery state are both settled.

Resident work uses separate capacity for ordinary evaluation, control requests, and context jobs. Context jobs include response delivery in their limit, so slow readers cannot grow that lane. Its small worker set is reused while busy and retires after a short idle period. Closing the lane finishes work already admitted and refuses new context work with a bounded busy result.

This diagram shows the ownership, dispatch, and shutdown relationship between the caller, supervisor, resident, and client leases.

flowchart LR
    Caller[Owning caller] -->|starts under lock| Supervisor[Supervisor]
    Supervisor -->|liveness signal| Resident[Resident service]
    Client[Authenticated client] -->|lease and requests| Resident
    Caller -->|identity and liveness| Supervisor
    Resident -->|ordinary, control, or context work| Lanes[Bounded resident lanes]
    Resident -->|idle, shutdown, or lost liveness| Exit[Serving child exits]
    Exit -->|exit evidence and budget update| Supervisor
    Supervisor -->|quiescent run| Stopped[Managed run stopped]

References: rust/…/managed_resident.rs• L96-155 rust/…/managed_resident.rs• L222-307 rust/…/managed_resident.rs• L310-450 rust/…/managed_resident_lease.rs• L145-220 rust/…/managed_resident_exit.rs• L93-223 rust/…/resident_context_dispatch.rs• L13-21 rust/…/resident_context_dispatch.rs• L146-224

Mode selection

Native mode controls which system owns the decision. off keeps Python authoritative. shadow compares native evidence while Python remains authoritative. auto and force require native results for supported native-authority hook paths.

When the native runtime is unavailable in an authoritative mode, the result is not allow. Supported hook paths return their defined pause, block, or withheld-output result. Unsupported events can remain on their existing path because they are outside the native fast path.

References: src/…/native_runtime.py• L35-47 src/…/hook_worker.py• L120-178 src/…/hook_worker.py• L275-315

Client protocol

The resident client protocol turns a local request into an authenticated, request-bound exchange. The client uses the private Guard state area and a verified runtime identity to find the service, prove trust, send bounded data, and validate the matching result.

Endpoint authentication

The client first finds a current generation and checks its recorded process identity. It connects to the endpoint and performs mutual proof with the service secret before sending hook material. On Unix, it also checks the kernel-reported peer identity when the platform provides it.

After authentication, each message carries a protocol marker, request identity, digest, and bounded length. The response must match the request identity and digest. These checks stop stale, forged, partial, or cross-generation data from becoming a decision.

The client keeps one absolute deadline from request capture through connection, authentication, evaluation, and response. Once it has fully sent a request, a response-side disconnect is not replayed because the service may already have applied the request.

References: rust/…/resident_client.rs• L89-188 rust/…/resident_client.rs• L191-323 rust/…/resident_client.rs• L349-455 rust/…/managed_resident_client_request.rs• L33-57

Resident operations

The resident protocol is the typed request boundary for the service. It accepts named operations, edge envelopes, and direct hook requests. The closed operation set maps each named operation to a versioned request shape instead of exposing an untyped command channel. It also covers the runtime's authority, approval, policy, command, package, workspace, connector, and lifecycle request families through the same boundary.

The capability report is derived from the running binary. It identifies the protocol, rule, build, target, and packaged command-program data. It also reports the resident operations and one-shot helper features that this build can serve. Transport, execution, and helper features that need a specific platform are reported only on that platform. This keeps clients from routing work to an operation that the binary cannot honor.

Requests are checked before evaluation. The runtime uses strict JSON parsing, rejects unknown fields where the request contract requires it, and applies bounded response encoding. A disabled or unsupported operation returns a finite unavailable or safe error result rather than an implied success. Error responses expose only approved lifecycle, approval, and command-control codes. Other invalid input is reduced to a generic invalid-request result. Hook evaluation also uses the policy snapshot for the resident generation, so a missing or stale snapshot cannot enter the evaluator.

The protocol keeps the command-review surface inside the resident boundary. Dispatch connects each named operation to its native authority path and checks the Guard home or store path when that operation uses scoped state. These scope checks bind a request to the resident's policy store before the operation can read or write per-home state. Command operations use the runtime's packaged capability and catalog identity when those contracts require it, while unsupported platform operations remain unavailable instead of being advertised as usable.

References: rust/…/resident_protocol.rs• L45-194 rust/…/resident_protocol.rs• L197-400 rust/…/resident_protocol.rs• L439-474 rust/…/resident_op_features.rs• L1-31 rust/…/resident_op_features.rs• L184-233 rust/…/resident_op_features.rs• L235-359 rust/…/resident_ops.rs• L22-98 rust/…/resident_ops.rs• L99-186 rust/…/resident_ops_scope.rs• L1-144

Resident inspection boundary

Resident command reviews answer environment and Git questions from facts captured with the request and from the resident's own safety checks. This keeps the shared command model independent from Python-side inspection and gives the native authority path one source for trusted Git and environment evidence.

The inspection boundary fails closed when a platform cannot provide a safe check. On Unix, supported package and executable evidence can use protected path handling. Outside Unix, checks that need that evidence remain unrecognized rather than becoming an allow result.

References: rust/…/resident_inspection_host.rs• L1-15 rust/…/resident_inspection_host.rs• L17-52 rust/…/resident_inspection_host.rs• L55-143 rust/…/resident_inspection_host.rs• L145-173

Admission and retry

Admission limits local work during bursts or slow client behavior. Authentication and evaluation use separate bounded capacity. Control work such as health and shutdown retains a separate path so an overloaded service can still be inspected or stopped. Context assistance has its own small resident-local lane, which also bounds response delivery and does not consume control capacity.

The transport authenticates a connection and reads its frame header before it sends work to evaluation. This keeps a slow payload from holding an authentication worker. A complete buffered request may continue on the evaluation path, while a fragmented request that cannot enter that path receives bounded overload instead of occupying the authentication path.

Long Codex continuation retries use a small side capacity, so they cannot consume the evaluation workers needed by ordinary requests. Context workers reuse an existing worker for sequential jobs and retire when idle. The client retries only when evidence shows that the recorded service was absent, stale, or tearing down before it accepted the request. Authentication rejection, frame failure, response mismatch, integrity failure, and deadline failure do not grant restart permission. A request that was fully flushed is never replayed after response-side teardown.

Evaluation is isolated from a panic in the resident worker. The transport turns that panic into a bounded native failure response instead of allowing it to unwind through the serving process.

References: rust/…/resident_transport.rs• L55-130 rust/…/resident_transport.rs• L210-307 rust/…/resident_transport.rs• L310-420 rust/…/resident_transport.rs• L476-649 rust/…/resident_context_dispatch.rs• L52-126 rust/…/resident_context_dispatch.rs• L146-224 rust/…/managed_resident_client_request.rs• L151-334 rust/…/resident_client.rs• L404-455

Persisted runtime state

The resident persists only the state needed to find, identify, authenticate, and recover a service. State is private to Guard and scoped by the runtime executable digest. Policy freshness uses a separate durable generation and policy digest.

Generation records

A generation record identifies the serving process, owner process, runtime digest, transport, endpoint, creation time, generation number, and service secret. A MAC protects the record, but the MAC alone is not enough. Clients also require valid field values, a digest-matched scope, and a transport-appropriate endpoint. This prevents a correctly signed but unsafe record from becoming a trusted discovery result.

Discovery prefers the current executable digest and checks only a bounded set of fallback scopes. It retains a small amount of recent state so cleanup and recovery can explain a failed run. Publication prunes superseded records while retaining live and recent generations. Retirement is identity-bound, which stops an old process from deleting a newer generation record.

References: rust/…/resident_state.rs• L49-85 rust/…/resident_state.rs• L243-287 rust/…/resident_state.rs• L347-482 rust/…/resident_state_discovery.rs• L12-182 rust/…/resident_state_manifest_tests.rs• L39-135

Policy snapshots

The resident evaluates against a policy snapshot tied to its generation. The snapshot carries a durable generation and policy digest. The evaluator rejects stale data, a reused generation with a changed digest, or a snapshot that does not match the current rule contract.

References: rust/…/managed_resident.rs• L239-267 rust/…/resident_ops.rs• L62-91

Runtime supersession

Runtime supersession prevents an old resident from serving after its executable changes. The runtime compares the loaded executable with the current executable and checks the process start identity so a recycled process ID cannot pass as the original process. On Unix it also checks file identity when reusing a recent digest verification, so an in-place rewrite or replacement is hashed again. A changed or unreadable executable is treated as superseded.

References: rust/…/resident_state_supersession.rs• L8-107 rust/…/resident_runtime_verification.rs• L11-62 rust/…/resident_runtime_verification.rs• L65-173 rust/…/resident_process_identity.rs• L203-287

Client leases

A client lease is the shared-use signal for one runtime generation. Its heartbeat keeps the resident alive. Cleanup removes a lease only when the record is stale and its identity still proves that the same client created it.

The liveness check fails closed when it cannot inspect the lease area or when bounded inspection cannot cover the records. A recent malformed lease is treated as live. Update retirement drains only leases for the selected runtime, which keeps a newer runtime from being pinned by an older one.

References: rust/…/managed_resident_lease.rs• L20-40 rust/…/managed_resident_lease.rs• L145-335 rust/…/managed_resident_lease_record.rs• L29-80 rust/…/managed_resident_lease_record.rs• L121-227

Startup ownership and restart budget

Startup ownership prevents two processes from creating overlapping residents. A home-wide startup lock records the owner identity and runtime digest. A stale lock is removed only after age and identity checks show that its owner is no longer valid. The serving process then holds a separate owner lock for its full lifetime.

Restart attempts are durable, so a crash loop cannot reset its count by creating another client process. The runtime allows three attempts in a sixty-second window. It then applies persisted backoff from two seconds up to thirty seconds. Budget and requested-stop records use private temporary-file replacement and fail closed when their ownership or file shape is not trusted. A clean supervised run returns its own charge. An authenticated managed stop clears the budget only after containment succeeds.

References: rust/…/resident_startup_lock.rs• L25-187 rust/…/managed_resident_owner_lock.rs• L147-329 rust/…/resident_restart_budget.rs• L9-27 rust/…/resident_restart_budget.rs• L301-437 rust/…/resident_private_file.rs• L19-72 rust/…/resident_private_file.rs• L161-224

Platform process handling

The transport and process boundary differ by platform, but the trust goal is the same. Only a caller that can use the protected state and prove knowledge of the current service secret can use a resident.

POSIX process handling

Linux and macOS use a private Unix socket. The runtime protects the state area and socket path from unsafe path substitution. The resident watches both its owner identity and its liveness input. The supervisor keeps the serving child in the managed process unit so startup containment can address the full unit.

The client checks the peer process identity where the platform exposes it. The recorded process start marker also guards against process-ID reuse. An idle resident retires when no owner or same-runtime client keeps it live.

References: rust/…/managed_resident.rs• L92-150 rust/…/managed_resident.rs• L321-377 rust/…/resident_client.rs• L244-323 rust/…/resident_peer_identity.rs• L4-50 rust/…/managed_resident_containment.rs• L55-124

Windows process handling

Windows uses authenticated IPv4 loopback rather than a Unix socket. The client requires a loopback endpoint and checks the expected runtime identity before message authentication. Managed child creation preserves the handles that carry liveness and authentication to the child.

State paths use protected access rules for the current user and system account. Process identity includes the executable path and a start marker. When needed, the runtime also checks the executable digest so a recycled process cannot inherit trust from a dead resident.

References: rust/…/managed_resident_windows.rs• L12-150 rust/…/managed_resident_transport.rs• L122-192 rust/…/resident_state_files.rs• L134-181 rust/…/resident_state_windows.rs• L14-73 rust/…/resident_runtime_verification.rs• L11-45

Recovery behavior

Recovery separates an unavailable service from an unsafe service. The client first tries a valid current generation. If none can answer, one owner starts a new generation under the durable restart budget and waits only within the caller's deadline.

Startup and restart

When a resident request cannot connect, the runtime follows this sequence:

  1. Discover and validate current state, with the current runtime digest preferred.
  2. Check process identity and try each valid live generation within the deadline.
  3. Acquire the startup lock or wait briefly for its current owner.
  4. Remove a stale lock only after its owner fails identity checks.
  5. Consume one restart-budget attempt.
  6. Start a new managed generation with a new secret.
  7. Use the service only after it returns an authenticated response.

If another process owns startup, the caller does not start a second service. Failed startup is contained only through verified process identity. Cleanup checks all known processes in the generation and retires state only when the recorded identity and token still match.

References: rust/…/managed_resident_client_request.rs• L214-334 rust/…/resident_startup_lock.rs• L62-187 rust/…/managed_resident_containment.rs• L306-475 rust/…/managed_resident_exit.rs• L93-223

Runtime handoff

An update can leave an older runtime resident in the shared home. A newer client may request authenticated shutdown when that resident has no live client for its runtime or rejects the current policy snapshot or request shape. The client then waits for exact process and state containment. A runtime whose executable identity no longer verifies cannot be treated as a safe handoff target.

If handoff cannot prove containment, the old service remains in place and the caller fails closed. The containment check matches the old generation, process ID, and start marker, so a replacement resident is not stopped by a late cleanup action.

References: rust/…/managed_resident_handoff.rs• L13-117 rust/…/managed_resident_client_request.rs• L59-149 rust/…/resident_runtime_verification.rs• L25-62

Managed shutdown

Managed shutdown is a contained lifecycle operation, not a process hint. The client serializes shutdown with startup and sends an authenticated request. Success requires the serving listener to stop, owner locks to be free, the generation state to be accounted for, published Unix endpoints to be gone, and supervisors to be quiescent.

The serving process marks shutdown ready only after it releases its lifetime lock. It then allows the final response to leave the process. This prevents an acknowledgement from arriving before the service has completed its teardown.

References: rust/…/managed_resident.rs• L153-201 rust/…/managed_resident.rs• L76-87 rust/…/managed_resident_exit.rs• L93-153

Critical failure

A panic, abort, containment failure, invalid response, or repeated transport failure must not stop the Python daemon. The native child is isolated so the daemon can retain control and diagnostic functions while native authority is unavailable. Resident evaluation catches worker panics and returns a bounded native failure instead of exposing an unwind through the service. A panic in a context job also releases its admission slot and leaves the worker available for later work.

For authoritative native hook paths, failure maps to the hook stage. PreToolUse pauses or denies unless the exact emergency-safe profile is current and authenticated. PostToolUse withholds output or blocks it until an authoritative review completes. No transport, parser, policy, timeout, overload, or evaluator failure becomes allow.

Recovery may restart a verified Rust generation, but it must re-check package identity, executable digest, protocol, target, rule digest, and policy snapshot before service resumes. The Python daemon does not revive a second semantic evaluator after native authority has taken over.

References: docs/…/0009-native-and-daemon-critical-failure.md• L7-31 docs/…/rust-native-fail-safe-matrix.v1.json• L4-44 src/…/hook_worker.py• L219-252 rust/…/resident_transport.rs• L265-307 rust/…/resident_transport.rs• L368-389 rust/…/resident_context_dispatch.rs• L108-144 rust/…/resident_protocol.rs• L443-459

Health states

Health is aggregate state for local diagnosis, not a record of hook content. The resident health operation reports serving state, protocol and build identity, target, uptime, lane shape, queue depth, and bounded counters. It does not report request paths, commands, credentials, or other work content. The wider runtime health layer distinguishes startup, healthy, degraded, recovering, overloaded, circuit-open, and quarantined conditions. It also tracks bounded counts for starts, restarts, resident failures, one-shot failures, overloads, and consecutive failures.

Integrity failures are stronger than ordinary availability failures. A package, manifest, rule, or build mismatch quarantines that runtime identity in process-local health state. Ordinary failures can recover after cooldown and a successful resident response. Optional diagnostics add bounded phase evidence without request payloads.

References: src/…/native_runtime_resilience.py• L29-59 src/…/native_runtime_resilience.py• L216-264 src/…/native_runtime.py• L404-482 rust/…/resident_diagnostics.rs• L192-218 rust/…/resident_health_op_tests.rs• L16-65 rust/…/resident_health_op_tests.rs• L119-170

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep one-shot and resident mode selection aligned with native authority rules and the fail-safe outcome matrix.
  • Keep operation names, request types, capability features, platform gates, actual dispatch, and Guard-home/store-path scope bindings aligned. Do not advertise a feature that the binary cannot serve.
  • Keep frame markers, request IDs, digests, size limits, authentication proof, and one absolute deadline aligned across client and server.
  • Keep generation state, state MAC inputs, endpoint checks, process identity, executable supersession, and identity-bound retirement aligned.
  • Keep owner locks, startup locks, client leases, supervisor holds, liveness handles, shutdown acknowledgement, and endpoint cleanup aligned.
  • Keep durable restart attempts, healthy-run charge release, backoff, failure evidence, and process-local health circuits bounded together.
  • Keep POSIX peer checks and Windows loopback, handle, ACL, and executable checks aligned with any transport or state-path change.
  • Keep policy snapshot generation and digest checks aligned between snapshot writers and the resident evaluator.
  • Keep resident command inspection inputs, Git safety checks, and platform-specific fail-closed behavior aligned with command-model authority.
  • Keep authentication and evaluation queue limits, control-path capacity, continuation side limits, and overload responses aligned so slow clients cannot starve control or review work.
  • Keep context-lane admission, worker reuse, idle retirement, close-and-drain behavior, and busy responses aligned with the operations routed to that lane.
  • Keep resident health fields limited to identity, figures, lane state, and bounded counters. Do not add request-derived text to diagnostics.
  • Keep state publication, manifest field validation, retained-generation pruning, dead-socket pruning, and platform ownership checks aligned.
  • Keep runtime-digest verification cache keys tied to process start identity and file identity, especially when executable replacement can occur.

Important failure modes

TriggerConsequenceGuard
State MAC, digest, endpoint, process marker, or schema is invalidThe client cannot trust the recorded serviceReject the record and start only a digest-matched generation under the startup lock
A manifest has a valid MAC but an invalid field or endpointA signed record could point discovery at unsafe state or transportValidate the field shape and endpoint scope in addition to the MAC
An operation or request contains an unknown shape or unsupported featureA caller could mistake invalid work or an unavailable platform path for a decisionUse the closed operation contract, strict parsing, capability gating, and finite safe error responses
An operation names a different Guard home or store path than the resident snapshotThe request could read or write state outside the resident's bound scopeCheck operation scope before dispatch and reject mismatched paths
A request is fully sent and the response connection closesReplaying it could apply work twiceTreat response-side teardown as non-retryable
Resident admission is full or a client sends a fragmented payload too slowlyThe hook may miss its native result deadlineUse bounded admission and return overload without holding an authentication worker indefinitely
A resident evaluation panicsThe serving process could lose a request or unwind across its boundaryCatch the panic and return a non-retryable bounded native failure
Two context responses remain blocked or the context lane is closedMore context work could hold workers or strand admitted jobsCount response delivery in the lane limit, finish admitted jobs, and refuse later work with a bounded busy result
Three restarts occur in one minuteA crash loop can consume hook resourcesPersist the count and apply bounded backoff
The loaded executable changes or disappearsAn old resident could serve after an updateMark the runtime superseded and require a verified generation
A verified executable path is replaced after a cached checkA stale digest could authorize the wrong imageRecheck file identity and hash the replacement before reuse
Startup or owner lock belongs to a live processTwo residents could race or overlapKeep the lock and wait or return a bounded in-progress result
Shutdown acknowledgement arrives before supervisors and locks quiesceA new process can race with an old oneRequire authenticated acknowledgement plus full containment
Rust fails after native authority cutoverA review is incompleteKeep the daemon alive and pause, block, deny, or withhold rather than allow
Policy generation or rule digest is staleA decision may use old policyReject the snapshot and require a current authenticated snapshot
A resident command review needs unavailable platform evidenceAn unsafe command could be treated as trustedKeep the inspection unrecognized and fail closed
The client uses an unsupported platform operationThe caller may treat unavailable work as a decisionAdvertise only supported features and return a finite unavailable result

Key files

FileWhy to read it
rust/…/managed_resident.rsShows resident startup, liveness, supervision, managed shutdown, and owner handoff entry points.
rust/…/resident_protocol.rsDefines resident request families, capabilities, platform features, strict protocol handling, and safe error responses.
rust/…/resident_op_features.rsDefines the operation and one-shot helper capability registry that the protocol reports to clients.
rust/…/resident_ops.rsConnects validated resident requests to native authority operations and scoped policy state.
rust/…/resident_ops_scope.rsShows which resident operations bind to a Guard home or explicit store path before dispatch.
rust/…/resident_transport.rsShows authenticated admission, separate control and evaluation paths, bounded worker capacity, overload handling, continuation limits, and panic containment.
rust/…/resident_context_dispatch.rsShows the bounded context lane, worker reuse, idle retirement, close-and-drain behavior, and panic-safe delivery.
rust/…/resident_inspection_host.rsShows how resident command reviews use request facts and native safety checks for environment and Git inspection.
rust/…/resident_client.rsShows endpoint checks, authentication, framing, process identity, and retry evidence.
rust/…/managed_resident_client_request.rsShows discovery, startup ownership, admission, restart, and failure classification.
rust/…/managed_resident_exit.rsShows supervisor exit evidence and the quiescence boundary used by stop.
rust/…/managed_resident_lease.rsShows client lease liveness and identity-bound cleanup.
rust/…/resident_state.rsShows generation identity, protected state, publication, and retention.
rust/…/resident_state_manifest_tests.rsShows that signed state still needs valid schema, identity, transport, endpoint, and digest fields.
rust/…/resident_state_prune.rsShows fail-closed cleanup for stale resident directories and bounded prune reports.
rust/…/resident_state_prune_sockets.rsShows how old Unix sockets are identified as dead before removal.
rust/…/resident_restart_budget.rsShows durable restart attempts, backoff, healthy-run release, and budget clearing.
rust/…/resident_private_file.rsShows private atomic persistence for restart and stop records.
rust/…/resident_runtime_verification.rsShows process-start and executable identity checks with bounded digest reuse.
rust/…/resident_health_op_tests.rsShows the resident health contract and its content-free diagnostic boundary.
rust/…/managed_resident_windows.rsShows Windows child creation and liveness-handle transfer.
src/…/native_runtime.pyShows runtime selection, compatibility checks, and native authority result handling.
src/…/native_runtime_resilience.pyShows health, overload, circuit, and recovery state outside the Rust child.
docs/…/0009-native-and-daemon-critical-failure.mdStates the daemon isolation and critical-failure contract.
docs/…/rust-native-fail-safe-matrix.v1.jsonMaps runtime failures to safe hook outcomes.