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 / daemon-and-local-service-lifecycle

Daemon and local service lifecycle

The Guard daemon is the local service that keeps protection, review, setup, evidence, and status in one trusted place. It owns one Guard home, serves authenticated loopback requests, isolates hook work, and reports service health only when its process and recovery boundaries are known.

Lifecycle model

The lifecycle joins ownership, startup work, request handling, worker supervision, health reporting, safe retirement, and update handoff. A client first reuses a proven daemon. If no safe generation exists, Guard starts one native daemon and binds that generation to the Guard home.

This diagram shows how a local client reaches a ready service and how the service leaves the home safely.

flowchart LR
    A[CLI, hook, or dashboard] --> B[Find or ensure daemon]
    B --> C{Proven current service?}
    C -- Yes --> D[Use authenticated loopback service]
    C -- No --> E[Claim Guard-home start ownership]
    E --> F[Launch native daemon]
    F --> G[Bind listener and publish signed state]
    G --> H[Start workers and prepare hook capacity]
    H --> I[Report ready]
    I --> J[Serve requests and record activity]
    J --> K[Retire, recover, or update]
    K --> L[Prove process and worker containment]
    L --> M{Contained?}
    M -- Yes --> N[Clear current state and release ownership]
    M -- No --> O[Keep ownership and quarantine the home]

The Guard home is the boundary for service identity and local state. A service is trusted only when its signed state, process identity, runtime identity, endpoint, and bounded health response agree. The native daemon loads the shared auth secret from that home and does not receive it in the launch input. Its launch handoff binds the pending receipt, nonce, process identity, owner, and port before a caller accepts the service.

References: rust/…/daemon_policy_authority.rs• L271-332 rust/…/daemon_manage_ensure.rs• L1015-1081 rust/…/daemon_edge_serve.rs• L1-12

Startup ownership

Startup reserves one daemon slot before it begins work that can read or change local state. The manager uses a start lock and launch records so concurrent callers wait for one handoff instead of creating two services for one Guard home.

The manager first reuses a live current daemon. It can also adopt a live daemon that lost its state when the endpoint, health response, Guard home, and runtime identity match. Otherwise it retires stale generations, resolves abandoned launch records, removes only proven Guard processes, and launches the native daemon.

A launch that misses its wait is not always dead. Guard keeps a progressing child under its signed launch record and returns a retryable start result. A launch that cannot prove progress is retired. A process that Guard cannot prove belongs to this home is left alone and its port is skipped.

References: rust/…/daemon_manage_ensure.rs• L119-155 rust/…/daemon_manage_ensure.rs• L229-328 rust/…/daemon_manage_ensure.rs• L759-1081

Native service registration

The native daemon is the resident loopback service. It binds a loopback listener, publishes signed discovery state, and sends a handshake to the request edge. The handshake carries the service identity needed for auth, store access, dashboard assets, session checks, and activity reporting.

The edge may answer safe native reads and writes itself. Requests outside that set are relayed to the Guard library or resident runtime without changing their bytes. A relayed call returns its shaped status and body when the owning service answers. An unavailable service is relayed again, while a raised or uncertain call closes the connection instead of replaying work that may have committed.

The public route policy separates daemon-token routes, dashboard-session routes, hosted API routes, extension-control routes, and local-CLI routes. Path segmentation is shared by auth and dispatch, so a route cannot be authorized under one path shape and handled under another.

References: rust/…/daemon_edge_composed.rs• L63-184 rust/…/daemon_edge_route_calls.rs• L13-47 rust/…/daemon_edge_route_calls.rs• L210-237 rust/…/daemon_route_paths.rs• L246-320

Resident service composition

Resident services keep long-lived work outside the short request path. The daemon composes harness status, capabilities, policy status, Cloud status, extension controls, local-CLI actions, update status, and supply-chain views from the service that owns each concern.

This split gives callers one local service boundary without making the edge the authority for every state change. Composed replies report the current auth surface and daemon compatibility, while malformed or unavailable resident replies are treated as unavailable rather than as valid service state.

References: rust/…/daemon_edge_composed.rs• L82-184 rust/…/daemon_edge_composed.rs• L186-247 rust/…/daemon_edge_route_calls.rs• L50-79

Context assistance service

Context assistance is a resident service reached through the daemon's local API. The edge frames each request, binds the reply to its schema, request identity, and digest, checks the reply shape, and maps service refusals to stable HTTP results.

Read-only status, installation, job, usage, and Codex switch views can pass through without a settings gate. Actions that expand workspace access or change the engine version pass the approval gate first. Codex input is checked before that gate, and a failed best-effort short-replies request does not undo a saved context-assistance setting.

References: rust/…/daemon_edge_context_assistance.rs• L1-10 rust/…/daemon_edge_context_assistance.rs• L74-148 rust/…/daemon_edge_context_assistance.rs• L264-331 rust/…/daemon_edge_codex_config.rs• L49-84 rust/…/daemon_edge_settings_short_replies.rs• L16-32

Request service

The loopback service connects hooks, the dashboard, local clients, and review flows. The edge limits active connections and rejects overload instead of allowing a burst of peers to consume all service capacity. A stalled response writer is closed after a bounded wait, while idle connections are not treated as stalled writes.

Native routes answer only when the request shape and caller are unambiguous. The edge checks auth before reading guarded bodies, rejects unsupported transfer forms, and relays requests it cannot safely classify. A store write that may have committed is not repeated by the relay path.

Local request pages merge the saved store queue with the native business queue only after the store page ends. A bad cursor returns a refresh instruction. Detail reads remove private queue hints and may add advisory extension or connector setup information only after a current resident check.

Hook requests use a shared deadline for admission, policy preparation, review, and response work. A request that cannot obtain capacity or finish safely receives the fixed fail-safe envelope for its harness rather than an ambiguous empty result.

References: rust/…/daemon_edge.rs• L34-48 rust/…/daemon_edge_requests.rs• L24-140 rust/…/daemon_edge_requests.rs• L220-265 rust/…/daemon_edge_route_calls.rs• L210-237 rust/…/daemon_edge_hook_review.rs• L99-172

Service preparation

Startup prepares the work that makes the first hook reliable without making the hook wait for every cold-start task. The daemon reconciles managed runtime artifacts beside worker-host startup, waits for a bounded readiness window, and records when slow reconciliation continues after the service reports ready.

It warms the native hook worker and may prewarm the resident runtime. The prewarm produces no decision, receipt, or approval. The native runtime also primes a verified private copy of its executable when the Guard home is suitable, so a cold host can overlap first-run work with worker startup.

References: rust/…/daemon_edge_serve.rs• L268-362 rust/…/daemon_edge_workers.rs• L219-329 rust/…/daemon_edge_resident_prewarm.rs• L1-41 rust/…/daemon_edge_runtime_copy.rs• L46-88

Background services

Background services handle work that should not delay a hook response. They cover the runtime heartbeat, Cloud and bundle work, storage maintenance, inventory upkeep, extension refresh, cleanup, plugin reporting, idle shutdown, and the worker host.

Each scheduled pass has a normal interval and a failure backoff. The worker host runs signal-driven work as one supervised child. A short-lived host restarts with increasing waits. A stable host restarts quickly after a later exit. The daemon closes the host's input when it stops, so the child follows the daemon lifecycle.

Idle shutdown applies only when there are no active connections and no durable work such as a pending review or eligible Cloud event. Startup reconciliation is allowed to finish before the idle clock can stop the daemon.

References: rust/…/daemon_edge_workers.rs• L1-17 rust/…/daemon_edge_workers.rs• L40-103 rust/…/daemon_edge_workers.rs• L343-385 rust/…/daemon_edge_worker_ticks.rs• L157-263

Worker isolation

Hook review uses boundaries outside ordinary request work. The boundaries limit the effect of untrusted hook input, evaluator faults, timeouts, and child-process failure. The daemon exposes worker capacity only after the native policy path proves readiness.

Hook admission

Hook admission settles the event deadline, client identity, request size, and every directory named by the request before policy work starts. Directory trust evaluates the action workdir, payload workspace, query workspace, Guard home, and user home as one admission result. A missing action directory fails at once because the command cannot run there; an untrusted directory is refused as a policy condition.

The scheduler gives decision events priority over content-security work and shares capacity by harness and client. It keeps the policy preparation barrier inside the admitted slot, then releases the slot before the final response is written. Out-of-band payloads are accepted only when their metadata matches a Guard-written reference and their size stays within the bounded reservation.

References: rust/…/daemon_edge_hook_admission.rs• L63-95 rust/…/daemon_edge_hook_admission.rs• L231-312 rust/…/daemon_edge_hook_admission.rs• L315-337 rust/…/daemon_edge_hook_review.rs• L327-475

Native policy readiness

The readiness route prepares a workspace's native policy before a timed hook begins. It returns a clear not-ready result when the resident policy is not acknowledged, and it returns a typed input error when the Guard home or workspace is invalid.

An unmanaged harness receives an observation-only readiness result. A managed harness must have a prepared workspace before protected hook review proceeds. This keeps a cold or unavailable policy publisher from being mistaken for an allowed action.

References: rust/…/daemon_edge_hook_readiness.rs• L9-89 rust/…/daemon_edge_hook_review.rs• L428-445 rust/…/daemon_edge_hook_policy_tests.rs• L5-49

Hook decisions

The daemon reviews a hook when the resident direct lane did not answer it. It first applies admission and native preparation, then handles harness lifecycle events, Cursor's exact contained-test sink, and the normal policy review. A native refusal is mapped to a fixed harness envelope so each host receives a known safe response.

The Cursor sink path admits only a real beforeShellExecution event that names the exact contained sink command. A route probe, receipt-only call, malformed launcher, or command the probe did not write stays on the normal review path. This keeps the shortcut tied to a trusted launch shape and a known workspace.

Claude lifecycle events can update permission and turn state without a new policy review. A Claude approval question is settled only when its session and signed authority state match. Other supported harnesses can pass their own permission prompt through when Guard is not the authority for that event.

References: rust/…/daemon_edge_hook_review.rs• L291-485 rust/…/daemon_edge_hook_cursor_sink.rs• L20-115 rust/…/daemon_edge_hook_envelopes.rs• L64-87 rust/…/daemon_edge_hook_lifecycle_tests.rs• L11-50

Evidence and policy writes

Decision work and evidence work have different timing goals. The daemon can finish a hook response before durable evidence is written, but it validates the record identity and preserves the required ordering when it dispatches evidence.

Policy decisions and clears run through the approval gate and the policy-integrity generation boundary. Once the gate has run, a failed write closes the connection instead of sending the body to another path that could run the gate twice. The edge holds the generation lock while it starts and finishes the store mutation. Settings writes use the same principle and keep the exported settings contract separate from secrets and receipt evidence.

References: rust/…/daemon_edge_policy_write.rs• L32-87 rust/…/daemon_edge_policy_write.rs• L90-156 rust/…/daemon_edge_policy_write.rs• L251-269 rust/…/daemon_edge_settings_write.rs• L42-124

Hook failure policy

Hook availability separates security enforcement from lifecycle observation. When native policy or the worker is unavailable, high-impact pre-action events use the harness fail-safe contract. Lifecycle events that do not own the security decision can continue or pass through according to the harness contract.

This distinction keeps service failure visible without turning every daemon outage into an unrelated host failure. A capacity refusal names retry guidance and a repair command. An unmanaged app remains recording-only and does not cause Guard to launch or rebuild that app's protection.

References: rust/…/daemon_edge_hook_envelopes.rs• L38-87 rust/…/daemon_edge_hook_review.rs• L314-325 rust/…/daemon_edge_hook_lifecycle.rs• L76-93

Runtime registration and liveness

Liveness has two parts: the service must answer a bounded health check, and its current runtime session must continue to report activity. This lets clients separate a live service from stale discovery state and lets the dashboard separate daemon health from policy, evidence, and Cloud health.

Health interfaces

Public health is a small compatibility signal for launchers and hooks. Authenticated detailed health adds the process, runtime, Guard-home, storage, worker, request, and evidence facts needed by the operator surface.

The native edge has a bounded connection limit and a public overload response. It also retries transient accept errors for a short bounded run. These limits protect health and recovery requests from ordinary hook bursts.

The policy authority accepts a daemon only when signed discovery state, the auth-token identity, compatibility, process liveness, loopback health, and Guard-home identity agree. It uses only 127.0.0.1 and never sends the daemon token to a redirected or non-loopback endpoint.

References: rust/…/daemon_edge_serve.rs• L39-48 rust/…/daemon_edge_serve.rs• L289-317 rust/…/daemon_policy_authority.rs• L275-332 rust/…/daemon_policy_authority.rs• L529-604

Heartbeat behavior

The heartbeat records the active session, endpoint, start time, and latest activity in the Guard store. Request handling touches activity, and the edge reports activity for requests it answers before the normal daemon handler. A store wait is bounded so health work does not hold a request slot forever.

The heartbeat belongs to the current session. Shutdown clears or replaces state only when the identity still matches, so a late write from an older generation cannot make a stopped daemon look live.

References: rust/…/daemon_edge_reads.rs• L188-212 rust/…/daemon_edge_reads.rs• L340-441 rust/…/daemon_edge_worker_ticks.rs• L157-170

Lifecycle diagnostics

Diagnostics explain startup, readiness, reconciliation, failure, recovery, retirement, and stop without blocking the security path. The lifecycle journal is storage-independent and records small private JSON events. It keeps normal lifecycle history separate from the shorter recovery ring.

The journal detects earlier daemon runs that published state but never recorded a terminal event. It reports missing or invalid entries as a read condition rather than treating an incomplete timeline as trusted service state. The journal and diagnostic log have bounded size and private access rules.

References: rust/…/daemon_edge_lifecycle.rs• L1-7 rust/…/daemon_edge_lifecycle.rs• L32-64 rust/…/daemon_edge_lifecycle.rs• L122-137 rust/…/daemon_edge_lifecycle.rs• L348-443

Diagnostics and recovery

Recovery first proves whether a current authenticated generation still serves the Guard home. It does not treat an auth error, an endpoint error, or a stale file as proof that the process is dead.

Recovery classification

The manager checks authenticated state, process liveness, process identity, command identity, endpoint health, and runtime compatibility before it starts a replacement. A live busy daemon can therefore remain in service while a dead or stale generation is retired.

If no current generation can be proven, one scheduled recovery or ensure operation owns the next attempt. A pending launch record and progress marker prevent many failing hooks from launching competing daemons. Recovery returns stable timeout or runtime outcomes instead of hiding an unresolved start.

References: rust/…/daemon_manage_ensure.rs• L157-186 rust/…/daemon_manage_ensure.rs• L476-599 rust/…/daemon_manage_ensure.rs• L621-722 rust/…/daemon_policy_authority.rs• L762-778

Process retirement

Retirement targets an exact daemon generation. Guard checks the start marker, owner, command identity, and platform process identity immediately before each signal. If any check is missing or changes, Guard leaves the process running and keeps enough state to explain why.

After a signal, Guard waits for death and may use a stronger stop only for the same proven process. It then re-reads the process table. A process that Guard cannot prove is its own is never signalled; it is journaled as a leftover and its port is excluded from the next launch.

References: rust/…/daemon_manage_retire.rs• L97-188 rust/…/daemon_manage_retire.rs• L367-484 rust/…/daemon_manage_leftovers.rs• L78-180

Locator repair

Repair removes stale locator and untrusted discovery state without deleting the Guard store or pending review data. It keeps a live daemon when its identity is trusted. It retires a live process before clearing state when the identity is invalid, and it reports an unresolved identity instead of claiming repair success.

The daemon can request this repair from its own route, but it does not retire itself or its parent through that request. A successful repair returns the exact state records it cleared; an unsafe or unwritable state remains an explicit failure.

References: rust/…/daemon_manage.rs• L275-365 rust/…/daemon_edge_writes.rs• L345-415

Quarantine state

Quarantine protects the Guard home when shutdown is incomplete. If a worker host, hook tree, request path, or other owned child cannot be contained within its bound, Guard keeps ownership and refuses to start a replacement beside an unknown process.

Once containment is proven, the service can clear current discovery state, release ownership, and allow a later start. Persistence, integrity state, evidence retention, and local data repair belong to Local storage and recovery.

References: rust/…/daemon_manage_retire.rs• L453-532 rust/…/daemon_manage_orphans.rs• L16-41

Update handoff

An update must not restart a daemon from code that the update may replace. The handoff uses a detached launch and a fresh runtime identity. It accepts success only after the new process publishes compatible state, answers health checks, and proves the launch binding.

The manager prefers a live compatible daemon and does not let an older caller replace a newer or Desktop-owned service. When it must launch, it separates the child from launcher cleanup, records a signed pending receipt, and verifies the nonce, process, port, owner, and runtime before clearing that receipt.

The update route checks whether the install can update before scheduling work. A Desktop handoff records a request only for a Desktop-managed install with a release newer than the running Core. If a fresh status check loses an offered release, the daemon accepts the offered version only after a strict version comparison; Desktop performs the final feed and signature checks.

The dashboard reconnect path uses a short-lived authorization bound to the Guard home and installation identity. Route tables keep reconnect preparation and verification in the authenticated local service surface rather than treating any process on a loopback port as the successor.

References: rust/…/daemon_manage_ensure.rs• L568-587 rust/…/daemon_manage_ensure.rs• L759-1081 rust/…/daemon_edge_update.rs• L95-149 rust/…/daemon_edge_update.rs• L152-210 rust/…/daemon_edge_writes.rs• L170-207 rust/…/daemon_route_paths.rs• L161-168

Persistence and recovery boundaries

The daemon lifecycle depends on local records for identity, runtime activity, lifecycle evidence, logs, policy authority, and command activity. The storage rules for these records belong to Local storage and recovery. Read that page when a lifecycle problem may involve migration, integrity state, rollback, evidence retention, or local data recovery.

Change checklist

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

  • Keep the launch schema, signed daemon state, handshake fields, route auth rules, health checks, and process identity checks aligned. One changed identity field can make a live service look stale.
  • Keep the start lock, pending launch receipt, progress marker, adoption rule, stale-state cleanup, and handoff verification aligned across native launches and update launches.
  • Keep exact-generation retirement tied to start marker, owner, command identity, process creation identity, port handling, leftover classification, and post-signal reads.
  • Keep native-edge routing aligned with the daemon's body parsing, caller checks, refusal records, session routes, replay behavior, and store-commit outcomes.
  • Keep composed route ownership aligned with resident request schemas, request digests, compatibility versions, dashboard session access, and relay behavior.
  • Keep context-assistance actions aligned with resident state schemas, workspace data roles, approval gates, Codex input checks, and short-replies follow-up behavior.
  • Keep hook admission, directory trust, payload references, Cursor sink recognition, scheduler lanes, deadline budgets, fail-safe envelopes, lifecycle pass-through, and evidence timing aligned.
  • Keep worker-host readiness, artifact reconciliation, resident prewarm, runtime-copy priming, idle holds, restart backoff, heartbeat, and shutdown ownership aligned.
  • Keep lifecycle journal event classes, predecessor detection, recovery-ring bounds, private file rules, and diagnostic log labels aligned.
  • Keep policy authority checks aligned with signed discovery state, auth-token identity, compatibility, health tables, loopback-only transport, and Guard-home binding.
  • Keep update success tied to a fresh process identity, signed handoff binding, compatible runtime, current locator, and dashboard reconnect proof.
  • Keep settings export and import schemas aligned with the privacy contract. Settings must not silently include secrets or receipt evidence.
  • Keep persistence, integrity, evidence, and rollback changes aligned with Local storage and recovery.

Important failure modes

TriggerConsequenceGuard
Two launchers target one Guard homeTwo generations may serve the same local stateCross-process start lock and signed pending launch ownership serialize startup
A launch misses its wait while its child is still progressingA valid slow start may be killed or a later caller may start beside itProgress markers keep the launch retryable; only a non-progressing launch is retired
A live process loses its daemon stateA replacement may collide with the live listenerAdopt only after health, Guard-home identity, and runtime identity match
Process identity or command identity is unreadableGuard may signal the wrong processLeave the process alone and classify it as an unproven leftover
A leftover process holds every candidate portRecovery cannot start a replacement safelyJournal the process, skip its port, and report the held-port condition
The edge reaches active connection capacityHook or health requests may wait without a clear resultReturn a bounded 503 overload response and keep the accept loop moving
A response peer stops readingA service slot can remain occupied indefinitelyApply the stalled-write timeout only while a write is blocked
A resident reply has the wrong schema, request id, digest, or shapeThe edge may accept data from another operationBind every reply to the request and refuse malformed payloads
A dashboard session reaches a route outside its session classA valid browser session may receive 401 or bypass the intended caller checkDerive auth and dispatch from the same route segments and route tables
Native policy readiness is missingA protected action could run without a trusted policyReturn a typed not-ready result and use the harness fail-safe envelope
A hook spends its budget before review completesThe host receives a late or ambiguous decisionShare one deadline across admission, preparation, review, and response work
A payload reference is not Guard-written or exceeds its reservationThe daemon may read untrusted or oversized local dataRequire valid reference metadata and reserve a bounded maximum before reading
A store write fails after a gate or commit may have runRetrying through the daemon can apply a gate or mutation twiceClose the connection or preserve the commit-uncertain result instead of replaying blindly
A worker host exits repeatedlyBackground work may consume service capacity or never become readySupervise the host with bounded restart backoff and a readiness wait
Shutdown cannot prove child containmentA replacement may run beside an unknown childKeep ownership and quarantine the Guard home until containment is proven
Lifecycle files are missing or invalidDiagnostics may present a false service historyBound reads and report journal condition instead of treating incomplete data as state
An update publishes state without a matching pending receiptAn unrelated process may be accepted as the new daemonBind nonce, pid, port, owner, runtime identity, and process markers before handoff
A dashboard reconnect sees a process on the expected portThe browser may attach to the wrong installation or Guard homeRequire the short-lived reconnect proof and current service identity

Key files

FileWhy to read it
rust/…/daemon_edge_serve.rsDefines the native daemon process, launch input, listener binding, signed state publication, startup phases, and service handoff.
rust/…/daemon_edge.rsDefines connection limits, overload handling, and the native edge connection loop.
rust/…/daemon_edge_composed.rsShows how the daemon composes resident and library reads into local service replies and capabilities.
rust/…/daemon_edge_context_assistance.rsDefines the context-assistance service boundary, reply checks, refusal mapping, and approval-gated actions.
rust/…/daemon_edge_reads.rsDefines the daemon handshake, activity reporting, bounded store calls, and native-versus-relayed request boundary.
rust/…/daemon_route_paths.rsDefines shared path segmentation and caller classes for daemon tokens, dashboard sessions, hosted APIs, extension controls, and local surfaces.
rust/…/daemon_edge_hook_review.rsDefines hook auth, admission, deadlines, policy preparation, review, and fail-safe responses.
rust/…/daemon_edge_hook_admission.rsDefines event budgets, directory trust inputs, client fairness keys, and payload-reference limits.
rust/…/daemon_edge_hook_cursor_sink.rsDefines the narrow trusted route for Cursor contained-test sink calls.
rust/…/daemon_edge_hook_envelopes.rsDefines stable harness responses when worker or policy review cannot complete.
rust/…/daemon_edge_requests.rsDefines queue pagination, native business queue merging, request detail behavior, and resume reads.
rust/…/daemon_edge_workers.rsDefines background schedules, worker-host supervision, startup reconciliation, and idle shutdown.
rust/…/daemon_edge_lifecycle.rsDefines storage-independent lifecycle evidence, predecessor detection, validation, and bounded reads.
rust/…/daemon_manage_ensure.rsDefines reuse, adoption, stale-generation handling, native launch, progress, and handoff verification.
rust/…/daemon_manage_retire.rsDefines exact-generation retirement, containment checks, pending-launch resolution, and completion checks.
rust/…/daemon_manage_leftovers.rsDefines bounded process inventory reads and the safe handling of unproven processes.
rust/…/daemon_policy_authority.rsDefines signed daemon identity, health checks, process binding, and loopback-only authority calls.
rust/…/daemon_edge_policy_write.rsDefines approval-gated policy mutations and integrity-generation coordination.
rust/…/daemon_edge_recommend.rsDefines advisory request-detail recovery and resident-bound extension recommendations.
rust/…/daemon_edge_update.rsDefines update status checks, scheduling, Desktop handoff, and safe release selection.
rust/…/daemon_edge_writes.rsDefines native write ownership, body handling, repair entry points, reconnect preparation, and relay boundaries.
Local storage and recoveryExplains the persistence, integrity, evidence, migration, and rollback rules behind the lifecycle boundary.