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 / command-activity-persistence-and-api

Command activity persistence and API

Command activity persistence turns a guarded command decision into a private local evidence record. It preserves the record across the hook lifecycle, keeps daily summaries for fast views, and exposes bounded data to authenticated clients. An optional local-only invocation preview supports display without changing the aggregate or cloud boundary. The parent page, Command activity and evidence, describes the wider evidence flow. The dashboard view is described in Dashboard evidence and activity analytics. Local database recovery is covered in Local storage and recovery.

Evidence record

Activity schema

The activity schema describes what Guard knows about a command without storing the command payload in the structured activity row. An activity has an opaque identity, a UTC time, a harness, a hook phase, an execution status, a proof level, and bounded decision facts. It also carries prompt and approval-reuse state, parse confidence, latency bands, and an optional receipt link. Schema versions let storage and clients reject incompatible facts.

Each activity can have ordered match records and local correlation handles. A match identifies a built-in rule result and its effects. A correlation handle links related hook events without retaining the native request or session identifier. Related MCP evidence is produced by the native evidence owner from bounded artifact and argument data, then accepted only when the response is bound to the request.

An optional invocation preview is stored as a separate local-only display record. The preview is bounded to 4,096 characters, cannot be changed after creation, and is removed with its parent activity.

Commands with embedded scripts can carry a hash-addressed evidence index. The index records each script body’s hash, size, source span, and execution or file-write role without duplicating the body in the activity evidence.

Package evidence uses a bounded manifest read with file identity checks and a content digest. This keeps a package decision tied to the manifest that was actually read.

RecordPurpose
ActivityOne logical command evaluation and its bounded facts
Invocation previewOne bounded local-only display value for an activity
MatchOne rule result linked to the activity
Match effectA typed effect claimed by a match
CorrelationA local handle for request or session association

References: src/…/command_activity_contract.py• L18-23 src/…/command_activity_contract.py• L90-136 src/…/command_activity_contract.py• L171-229 src/…/embedded_script_evidence.py• L19-39 src/…/package_evidence_common.py• L23-67 src/…/store_command_activity.py• L17-50 src/…/store_command_activity_display_schema.py• L12-42

Lifecycle states

The lifecycle uses one activity row for the pre-hook decision and any later execution proof. A pre-hook record starts as attempted, then becomes prevented or allowed_unconfirmed. Only allowed_unconfirmed can become confirmed_success or confirmed_failure when an exact request correlation proves that the post hook belongs to the same command.

An unmatched post hook becomes unpaired_post. This state records that a post event arrived without claiming a decision, match, prompt, receipt, parse result, or request identity. Decision and match facts stay fixed after the pre-hook write. Identical replays are safe, while conflicting or out-of-order changes are rejected. A managed Cursor observer is trusted only when its runtime, approval binding, event, and native proof all agree, so an observed post event cannot confirm the wrong command.

The lifecycle relationship is shown below.

flowchart LR
    A[Pre-hook evaluation] --> B[attempted]
    B --> C[prevented]
    B --> D[allowed_unconfirmed]
    D -->|exact request proof| E[confirmed_success]
    D -->|exact request proof| F[confirmed_failure]
    P[Post hook without exact request proof] --> G[unpaired_post]

References: src/…/command_activity_contract.py• L236-279 src/…/command_activity_contract.py• L282-355 src/…/command_activity_lifecycle.py• L116-175 src/…/command_activity_cursor.py• L18-47

Privacy and local storage

Privacy boundary

Command activity is a local security-evidence domain. The default policy is local_only, so activity creation does not send data to a network service. An explicit aggregate_only mode can permit transfer of one rare-cell-suppressed daily count.

The privacy boundary uses field and value allowlists. It excludes command payloads from structured evidence, arguments, paths, workspace and environment data, free-form reason text, secrets, raw harness identifiers, installation identifiers, and weak identifiers. An optional invocation preview is a separate bounded local-only display value. Native request and session identifiers become HMAC-SHA-256 handles made with an independent per-installation key. Raw values remain short-lived, and handles stay on the device.

Cloud data is narrower than local data. It contains a calendar day, one bounded dimension and value, a count above the privacy threshold, and the aggregate schema version. It does not contain a per-command row, exact time, invocation preview, receipt, correlation handle, or local identity.

References: src/…/command_activity_privacy.py• L30-40 src/…/command_activity_privacy.py• L49-118 src/…/command_activity_privacy.py• L121-186 src/…/command_activity_privacy.py• L189-235 src/…/store_command_activity_display_schema.py• L12-42

Transactional storage

The activity client validates and serializes an activity with its optional invocation preview and related evidence. The native resident owns the SQL write, rollups, and replay arbitration, so one store operation decides whether the record is new or an exact replay. Parent-child rules prevent orphan facts. Deletion follows the storage contract so related local state is removed or marked together.

Lifecycle updates are also atomic. A valid transition changes only mutable lifecycle and persistence fields, then moves the affected rollup cells. Persistence failure does not decide whether Guard allows or stops a command. The store records bounded drop and error counts instead.

References: src/…/store_command_activity.py• L1-6 src/…/store_command_activity.py• L29-70 src/…/store_command_activity.py• L82-106 src/…/store_command_activity_schema.py• L117-194 src/…/store_command_activity_display_schema.py• L16-42 src/…/store_command_activity_lifecycle.py• L127-175

Hook evidence handoff

Hook evidence is handed off after the hook response so persistence cannot change an enforcement result. A bounded ordered dispatch keeps receipt, activity, and related evidence in submission order, while a full queue drops best-effort work rather than holding the hook open.

The resident owns the evidence queue, journal, and store for each Guard home. The Python client sends typed requests and accepts a result only when its request identity and digest match. An unavailable or invalid resident response raises an explicit writer error instead of claiming that evidence was queued. Store-fatal signals return to the client for local recovery and remain pending until recovery is acknowledged.

Direct-answer hooks and native MCP relay calls use the same evidence handoff as daemon-answered hooks. The drain validates each bounded record before it recreates the receipt, activity, review, or approval surface that the normal proxy path would create. Package calls also rebuild the decision artifact from the relay’s workspace and search path, and reject a record when the rebuilt artifact does not match the resident’s artifact identity.

References: src/…/hook_evidence_dispatch.py• L14-28 src/…/hook_evidence_dispatch.py• L60-145 src/…/native_hook_evidence_writer.py• L3-29 src/…/native_hook_evidence_writer.py• L117-191 src/…/native_hook_evidence_writer.py• L324-363 src/…/hook_direct_evidence_drain.py• L73-142 src/…/mcp_relay_evidence_drain.py• L99-207 src/…/mcp_relay_package_evidence_drain.py• L120-267

Rollups and maintenance

Daily rollups

Daily rollups provide counts without scanning every retained activity row. Each activity contributes once to its UTC day and to bounded cells for harness, extension, rule, disposition, execution status, prompt status, proof level, and latency bands. Lifecycle changes move only the cells that can change.

Reconciliation can rebuild counts from retained detail before compaction. This gives maintenance a way to detect and repair aggregate drift while the source rows still exist.

References: src/…/store_command_activity_rollups.py• L16-27 src/…/store_command_activity_rollups.py• L40-78 src/…/store_command_activity_rollups.py• L165-270

Retention and maintenance

Maintenance runs in bounded crash-safe batches. It first completes pending rollup work, then removes detail past the configured retention period, and finally removes aggregate data outside the fixed 13-month window. Rollup membership remains after detail deletion so an activity is not counted again. Correlations, invocation previews, and shadow data tied to deleted detail leave with it.

Maintenance state stores progress such as the last completed day, backfill position, compaction start time, and counts from the last run. A later run can continue from that state instead of repeating one large job.

References: src/…/store_command_activity_maintenance.py• L21-49 src/…/store_command_activity_maintenance.py• L51-115 src/…/store_command_activity_maintenance.py• L134-177 src/…/store_command_activity_maintenance.py• L205-247 src/…/store_command_activity_maintenance_schema.py• L18-95

Persistence health

Persistence health separates cumulative evidence loss from an active outage. The store keeps drop and error totals with a bounded last error, plus active error classes for command writes, shadow work, and maintenance. A successful operation clears only the class that it repairs.

Clients receive healthy or degraded state. Diagnostics add table counts, proof coverage, allowlisted identifiers, bounded error classes, and schema versions. They do not return command content or correlation data.

References: src/…/store_command_activity_health_schema.py• L11-30 src/…/store_command_activity_lifecycle.py• L55-63 src/…/store_command_activity_lifecycle.py• L177-256 src/…/command_activity_privacy.py• L22-52 src/…/command_activity_privacy.py• L124-190

Client API

Activity and analytics endpoints

The authenticated local daemon exposes activity pages and analytics as separate read contracts. GET /v1/command-activity returns items with their matches, an optional bounded invocation preview, and an opaque next_cursor. It supports bounded filters for harness, status, proof, prompt state, approval reuse, extension, rule, and an inclusive UTC date range. The default page is 50 items, and the maximum is 100.

GET /v1/command-activity/analytics returns the date window, selected scope, daily trends, top values for supported dimensions, feedback counts, and persistence health. Its default window is 90 days, with a 397-day maximum. A scope can select one harness, extension, or rule. Dimension breakdowns remain global, so clients must use the returned scope when they explain a trend.

EndpointResultClient use
GET /v1/command-activityActivity pages with matches and optional display previewsTable and detail views
GET /v1/command-activity/analyticsTrends and dimension countsSummary cards and charts
GET /v1/command-extensionsExtension and rule descriptionsFilter choices and rule context

The API version is guard.command-activity-api.v1. The dashboard calls these endpoints through its activity API client and normalizes the response before it reaches the workspace.

References: src/…/command_activity_api_contract.py• L20-25 src/…/command_activity_api_contract.py• L33-112 src/…/store_command_activity_api.py• L30-104 src/…/store_command_activity_api.py• L215-344 src/…/server.py• L2131-2148 dashboard/…/command-activity-api.ts• L150-185

Cursor and event contracts

Activity pages use a descending (occurred_at, activity_id) position. The server reads one extra row to detect another page. It signs the cursor with the daemon token and binds it to the API version and every list filter. A cursor cannot move between queries or authentication tokens. This list cursor is separate from the proof used to trust a Cursor post observer.

The event stream uses a separate integer sequence. GET /v1/command-activity/events accepts a query cursor or Last-Event-ID and returns server-sent events for changed activity IDs. The invalidation log keeps 10,000 entries. A cursor outside that range produces a reset event so the client can discard its position and reload.

The dashboard treats an invalidation as a refresh signal rather than a complete activity record. It advances the event cursor, then refetches the page and analytics.

References: src/…/command_activity_api.py• L34-55 src/…/command_activity_api.py• L91-133 src/…/store_command_activity_api.py• L166-212 src/…/store_command_activity_api_schema.py• L12-13 src/…/command_activity_api.py• L294-351 src/…/command_activity_cursor.py• L18-47 dashboard/…/command-activity-api.ts• L263-319 dashboard/…/use-command-activity.ts• L138-160

Feedback and privacy operations

POST /v1/command-activity/feedback attaches one bounded label to an activity. Repeating the same label is unchanged, while a new label replaces the old one. Each change creates an invalidation so clients can refresh the item and analytics.

GET /v1/command-activity/diagnostics returns allowlisted storage and health data. DELETE /v1/command-activity clears activity detail and derived state in one transaction. It requires the exact confirmation string and the high-risk approval gate. The response reports counts by data type rather than deleted records. The deletion also resets health, maintenance progress, and invalidation sequence state.

The dashboard rejects unexpected or forbidden fields and bounds response and event-frame sizes. The daemon remains responsible for authentication and server-side validation.

References: src/…/store_command_activity_api_schema.py• L12-109 src/…/store_command_activity_api.py• L106-164 src/…/store_command_activity_privacy.py• L53-122 src/…/command_activity_privacy.py• L73-121 src/…/server.py• L2332-2367 src/…/server.py• L2460-2465 dashboard/…/command-activity-normalizers.ts• L86-100 dashboard/…/command-activity-api.ts• L94-147

Change checklist

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

  • When an activity or match fact changes, update the runtime contract, local schema, write projection, API payload, and dashboard normalizer together.
  • When an invocation preview changes, keep its local-only schema, length and content validation, immutable behavior, parent deletion, and API response aligned.
  • When a lifecycle status changes, review the allowed transition graph and the rollup cells that represent the mutable status.
  • When hook evidence fields or receipt validation changes, keep the resident request shape, ordered dispatch, queue limits, recovery path, and store handoff aligned.
  • When native MCP evidence inputs or outputs change, keep the bounded DTO, feature gate, request digest, typed result validation, and omission behavior aligned.
  • When package evidence changes, keep the manifest integrity checks, search path binding, artifact identity check, and receipt projection aligned.
  • When a list filter or response field changes, update cursor binding, server validation, client types, and URL filter state as one contract.
  • When invalidation retention changes, review reset behavior and the dashboard reload path for stale cursors.
  • When retention or rollup rules change, preserve rollup completion before detail deletion and recheck the compaction boundary.
  • When privacy policy changes, review both the local field allowlist and the separate flat cloud aggregate allowlist.
  • When feedback or deletion changes, keep invalidation records aligned with the state that clients must refresh.
  • When the API or display schema changes, keep migration versions, expected table shapes, trigger sets, and schema validation counts aligned.

Important failure modes

TriggerConsequenceGuard
A post hook has no exact strong request correlationIt cannot become confirmed execution evidenceStore it as unpaired_post with no pre-hook facts
A replay changes an immutable decision or match factOne activity could describe more than one evaluationReject the replay as conflicting
A supplied invocation preview is empty, contains a null byte, or exceeds 4,096 charactersThe activity write is rejected rather than storing unsafe display dataValidate the preview before the transaction and enforce the local schema limit
The ordered dispatch queue reaches its boundBest-effort hook evidence is droppedWait only briefly for a slot and keep the enforcement response independent of persistence
The resident writer is unavailable or returns an unbound resultThe caller cannot know that evidence was acceptedRaise a typed unavailable error and report degraded health rather than returning success
A native MCP evidence request is too large, unsupported, or malformedRuntime or firewall evidence is omitted or rejected rather than guessedSend only the bounded DTO, require the feature and protocol, and validate the bound typed response
A package relay record rebuilds to a different artifactEvidence could be attached to the wrong package requestReject the record when its rebuilt artifact identity differs
A list cursor is used with changed filters or an old API versionThe page may skip or repeat recordsBind and sign the cursor against the query and schema
An event cursor falls outside the retained invalidation rangeThe client may miss changesEmit command_activity_reset and require a reload
Maintenance deletes detail before its rollup is claimedLong-term counts can under-report activityComplete rollup work before detail deletion
Activity persistence or maintenance failsEvidence health becomes incomplete while enforcement continuesCount bounded errors and expose degraded health
A client submits command content or an unexpected nested fieldPrivate data could cross the evidence or API boundaryEnforce closed field and value allowlists on both sides

Key files

FileWhy to read it
src/…/command_activity_contract.pyDefines activity facts, match facts, proof levels, and lifecycle rules.
src/…/store_command_activity.pyShows the validated handoff for one activity, its optional display preview, and related evidence.
src/…/store_command_activity_schema.pyDefines core local tables, relationships, indexes, and deletion rules.
src/…/store_command_activity_display_schema.pyDefines the local-only invocation preview and its migration and parent-safety rules.
src/…/command_activity_privacy.pyDefines local-only behavior, correlation protection, and cloud aggregate limits.
src/…/hook_evidence_dispatch.pyShows the ordered, bounded handoff from finished hooks to resident evidence work.
src/…/native_hook_evidence_writer.pyDefines the resident writer client, bound responses, health signals, and store recovery handoff.
src/…/hook_direct_evidence_drain.pyShows how direct resident answers reach the same evidence path as daemon answers.
src/…/mcp_relay_evidence_drain.pyShows how relayed MCP tool decisions recreate receipts and related review state.
src/…/mcp_relay_package_evidence_drain.pyShows package-call identity checks and package approval evidence.
src/…/store_command_activity_rollups.pyExplains daily totals, dimensions, lifecycle deltas, backfill, and reconciliation.
src/…/store_command_activity_maintenance.pyShows bounded maintenance, retention, compaction, and aggregate expiry.
src/…/store_command_activity_api_schema.pyDefines feedback storage and the bounded invalidation stream that clients use for refresh.
src/…/store_command_activity_api.pyOwns list, analytics, feedback, invalidation, and health query behavior.
src/…/command_activity_api.pyDefines route validation, signed cursors, and the event stream contract.
src/…/command_activity_cursor.pyDefines the trust checks for managed Cursor post-observer evidence.
src/…/embedded_script_evidence.pyDefines the bounded evidence index for embedded shell scripts.
src/…/package_evidence_common.pyDefines integrity checks for package manifests used by package evidence.
src/…/native_mcp_runtime_evidence.pyDefines the bound native source for MCP command text and runtime evidence.
src/…/native_mcp_tool_evidence.pyDefines the bound native source for MCP firewall and risk evidence.
dashboard/…/command-activity-api.tsShows how clients call, size-bound, and normalize the local API.
dashboard/…/command-activity-types.tsGives client-facing response shapes and allowed values.