Local storage and recovery
Guard uses a private SQLite profile to keep the local state that supports policy decisions, approvals, runtime records, local discovery, cloud delivery, workspace assessment, and recovery. The store gives daemon, hook, resident, and client work one durable view of local authority while keeping damaged or incomplete state from becoming permission.
SQLite profile
The SQLite profile is the local view of Guard state for one guard_home. It combines durable decisions with bounded working state so later requests can use facts produced by earlier daemon, hook, client, and worker actions.
State domains
The profile keeps durable authority beside short-lived work state. These domains let enforcement and user-facing flows share local facts without treating every stored value as permission.
| State domain | System purpose |
|---|---|
| Policy and inventory | Keep local decisions, policy bundles, artifact views, and trust facts used by enforcement. |
| Approvals and receipts | Track review requests, one-use approvals, decision receipts, evidence, and activity history. |
| Cloud continuity | Keep sign-in shape, sync status, delivery cursors, failure records, and bounded event queues. |
| Local connector authority | Bind observed CLI or MCP identity to grants, command choices, provider choices, and capabilities. |
| Runtime and worker handoff | Resume daemon work, worker refresh, approval attention, sessions, and operation state. |
| Workspace assessment | Track admitted worktrees, queued runs, leases, findings, and fix proposals. |
| Bounded summaries and caches | Serve posture, inventory, analytics, and cloud status without scanning all detail rows. |
References: rust/…/guard_store_sync_state.rs• L17-32 rust/…/guard_store_cloud_status_rows.rs• L18-28 rust/…/guard_store_workspace_assessment_queue.rs• L1-11
Relational and document state
Guard uses schema-backed tables for records that need keys, joins, ordering, or safe state changes. It uses sync_state JSON documents for small local cursors, settings, summaries, and handoff rows. A document may be missing or hold the wrong JSON shape without making the whole profile unusable; authority rows and trust rows use stricter checks when a malformed value could change a decision.
The store keeps event history and cloud delivery queues separate from current state. This lets a later sync retry or inspect durable evidence without rebuilding current authority from an opaque cache.
References: rust/…/guard_store_db.rs• L9-31 rust/…/guard_store_sync_state.rs• L22-79 rust/…/guard_store_cloud_events.rs• L33-73
Consistent local views
A snapshot is a read of related rows at one database point. Guard uses snapshots when a caller must compare state that can change together, such as policy trust rows, Cloud Review consent, connector continuity, queue lanes, or several sync documents. This prevents a decision from combining a new row with an old companion row.
Writes use one store transaction when several records describe one change. The transaction either publishes the authority and its evidence together or leaves the previous state in place.
References: rust/…/guard_store_op.rs• L232-279 rust/…/guard_store_op_kind.rs• L5-10 rust/…/guard_store_sync_payload_snapshot.rs• L7-15
Durable authority and continuity
Local storage is not only a cache. Some rows can change what Guard permits, so the store binds them to identity, revision, integrity, or an external decision before they can affect enforcement.
Policy and cloud authority
Cloud policy state is kept with the keyrings, acceptance checkpoint, workspace binding, acknowledgement, and delivery status that explain whether a cached bundle is still usable. Guard publishes last-good bundle state and redaction bookkeeping as one local change, so a later sync does not see a bundle without the matching privacy or delivery context.
Cloud Review uses request, capability, OAuth binding, revocation, and receipt state together. A remote result is applied only when the current local rows still match what was checked. A receipt claims the result once, and an accepted allow creates its local one-use authority in the same transaction as the request resolution.
References: rust/…/guard_store_policy_trust_rows.rs• L82-109 rust/…/guard_store_policy_bundle_activated.rs• L24-59 rust/…/guard_store_exact_cloud_apply.rs• L269-295 rust/…/guard_store_exact_cloud_apply.rs• L381-467
Approval and receipt continuity
Approval rows connect a review request to its queue identity, evidence, scope, and any short-lived continuation. Reads expose a projected request for normal callers and a raw row for exact consistency checks, so a projection cannot hide a stored change.
Receipts preserve the final local decision, action envelope, approval link, evidence, and cloud event as one record set. Bounded pages and summaries let the daemon and cloud sync consume this history without loading all detail into one reply.
References: rust/…/guard_store_approval_reads.rs• L31-67 rust/…/guard_store_approval_raw_row.rs• L12-19 rust/…/guard_store_receipt_writes.rs• L109-200 rust/…/guard_store_event_log_pages.rs• L32-112
Connector identity and capabilities
Local CLI and MCP state starts as observation. An operator decision becomes authority only when the grant still matches the observed connector identity and revision. A changed identity makes the old grant stale, and a blocked, removed, or re-identified grant clears capabilities that belonged to it.
Discovery can suggest connectors and tools from local history, but discovery does not grant access. Provider and command choices are checked against the current catalog and authority namespace before they are stored.
References: rust/…/guard_store_local_cli_inventory.rs• L108-160 rust/…/guard_store_continuity_write.rs• L74-187 rust/…/guard_store_continuity_write.rs• L342-430 rust/…/guard_store_observed_mcp_discovery.rs• L265-335
Workspace assessment state
Workspace assessment state tracks which worktrees Guard watches and how far each assessment has progressed. A trigger advances a dirty generation and coalesces work into one queued run. A worker claims a fenced lease, and only the current lease holder can record the result.
If the worktree changes while a run is active, the run is marked superseded and a successor is queued. Findings and fix proposals remain linked to the run and snapshot that produced them, so later verification cannot silently settle a newer proposal against an older assessment.
References: rust/…/guard_store_workspace_assessment_admissions.rs• L67-155 rust/…/guard_store_workspace_assessment_queue.rs• L110-192 rust/…/guard_store_workspace_assessment_queue.rs• L373-448 rust/…/guard_store_workspace_fix_proposals.rs• L149-204
Schema lifecycle
Schema setup brings a new or old guard.db to a supported shape before normal use. It creates shared and domain tables, adds known columns and indexes, repairs selected rows, checks domain markers, and records completed versions in schema_migrations.
Migration coordination
Schema changes use an in-process lock and the schema-migration.lock file lock. A waiting process checks the schema again after the leader succeeds. If initialization fails, the next process can try again instead of accepting a partial result.
Domain stores also carry their own compatibility markers when their state has a separate contract. An unknown or mismatched marker fails closed. This prevents a newer meaning from being read as an older one.
References: src/…/store_connection_schema.py• L671-729 src/…/store_connection_schema.py• L1129-1178 rust/…/guard_store_command_pack_activation.rs• L78-128
Compatibility boundaries
Older profiles can lack a table or column that a read does not need. Such reads return an empty or null shape where that is safe. State that is needed to verify authority instead returns a refusal when its schema marker, stored type, or companion table is missing.
This distinction lets ordinary status and discovery survive an older profile while preventing an incomplete authority record from becoming active.
References: rust/…/guard_store_local_cli_inventory.rs• L216-243 rust/…/guard_store_command_pack_activation.rs• L80-128 rust/…/guard_store_command_pack_legacy_evidence.rs• L96-167
Access and durability
Guard opens the profile through rust/…/guard_store_op.rs. The operation reuses a warm connection when possible, applies SQLite settings, chooses a read, snapshot, or write boundary, and commits only after the method and store finalization succeed.
Connection and transaction boundaries
Normal reads do not take a write lock. Snapshots use one deferred transaction and then roll back any incidental store work. Writes use an immediate transaction, so related rows either become visible together or remain unchanged.
The operation reports whether a write committed separately from the method result. This matters when a durable write is followed by a reply or outbox error; a caller must not repeat a committed action as if it never happened.
References: rust/…/guard_store_op.rs• L77-91 rust/…/guard_store_op.rs• L121-145 rust/…/guard_store_op.rs• L232-298
SQLite tuning and contention
Guard uses SQLite WAL mode so readers can continue during short writes. It applies bounded busy waits, a bounded page cache, and memory mapping settings to reduce normal contention. SQLite errors remain distinct: busy and locking errors are not treated as corruption, while corruption and system I/O errors use recovery-aware codes.
The store also bounds native replies and reads large histories a page at a time. Cursor-based reads continue from stable sort keys, so new rows do not cause a caller to repeat or skip older rows.
References: rust/…/guard_store_op.rs• L184-210 rust/…/guard_store_op.rs• L301-309 rust/…/guard_store_db.rs• L41-64 rust/…/guard_store_event_log_pages.rs• L19-35
File access and sidecars
The profile is private to the Guard home. Access gates coordinate daemon, native resident, and recovery work across processes. File permissions, WAL and shared-memory sidecars, and file identity are handled as one storage unit so a repair cannot expose or quarantine only part of the active profile.
References: src/…/store_connection_schema.py• L396-517 src/…/store_connection_scope.py• L31-75 src/…/sqlite_quarantine_forensics.py• L1-151
Storage maintenance
Storage maintenance limits high-volume local detail without removing rows still needed for enforcement or cloud delivery. The daemon runs cleanup as best effort in bounded work, so delayed housekeeping does not block a security decision.
Detail retention and summaries
Receipt summaries and activity rollups provide totals and trends without scanning every detail row. Detail remains the source for rebuilds, so archived rows can reduce local size while retained totals still support status and analytics.
Cloud event queues use byte and count limits. An event that cannot fit a native response is dropped with a recorded reason, and the capacity state returns to recovered after upload reduces the pending backlog.
References: src/…/store_connection_schema.py• L1240-1277 rust/…/guard_store_cloud_events.rs• L168-205 rust/…/guard_store_cmd_api.rs• L280-438
Bounded caches
Posture diagnostics, runtime sections, inventory summaries, and AI-BOM sync facts are useful only while their time, workspace, or scope still matches. The store returns fresh entries and records the next sync or retry time; stale entries cause a new collection rather than an unsafe reuse.
References: rust/…/guard_store_fleet_posture_state.rs• L80-140 rust/…/guard_store_fleet_posture_diagnostics.rs• L38-84 rust/…/guard_store_fleet_posture_runtimes.rs• L39-100 rust/…/guard_store_aibom_state.rs• L77-159
Corruption containment
Guard treats a fatal SQLite error as a recovery signal only after it proves that the active store is unusable. Lock contention and unrelated SQL errors do not qualify. Disk I/O errors receive an extra write-path check because a temporary device or directory problem can resemble corruption.
The proof checks the database with quick_check and confirms that the file identity did not change. Recovery proceeds only when the same file is still fatally unusable.
Quarantine and replacement
After proof, Guard takes the exclusive storage gate and records a small owner-only forensic result. It moves guard.db and matching WAL and shared-memory sidecars into a timestamped quarantine group.
Guard restores the quarantined store when it opens cleanly. Otherwise it creates a new schema and attempts independent salvage for Cloud Review state and local CLI state. Each salvage path has its own allowlist and authority boundary, so failure in one path does not discard the other. The request that saw the database error still fails; a later request uses the restored or replacement store.
References: src/…/store_connection_schema.py• L257-374 src/…/sqlite_recovery.py• L27-279 src/…/sqlite_quarantine_forensics.py• L1-151 rust/…/guard_store_db.rs• L41-64
Recovery paths
Local recovery separates schema drift, transient contention, proven corruption, missing secret material, unverifiable authority, stale identity, and interrupted delivery. The failure class selects the path because replacement is safe only when the store cannot be used.
This flow shows how normal access moves through schema repair and corruption proof before Guard restores or rebuilds usable local state.
flowchart TD
A[Open local profile] --> B{Schema supported?}
B -->|No| C[Run coordinated schema repair]
B -->|Yes| D[Use WAL connection]
C --> D
D --> E{Storage result}
E -->|Success| F[Commit or return the view]
E -->|Busy or unrelated SQL| G[Return the error]
E -->|Fatal or persistent I/O| H[Prove the store is unusable]
H -->|Healthy, changed, or uncertain| G
H -->|Proven unusable| I[Quarantine database and sidecars]
I --> J{Quarantined store opens?}
J -->|Yes| K[Restore the store]
J -->|No| L[Create a new schema]
L --> M[Salvage protected domains independently]
K --> N[Later requests use usable state]
M --> N
Secret and authority recovery
SQLite stores references and state for local credentials, but secret values use a separate credential store. Reads accept secret material only when it matches the stored identity. A missing OAuth secret rebuilds metadata only through its validated fallback path.
Policy-integrity recovery does not create a second signing identity when native authority is already armed. Extension authority resumes an anchored transition when possible. If its chain is not verifiable, it archives the old rows and starts a fresh protected authority.
References: rust/…/guard_store_oauth_sign_in_stamp.rs• L45-92 rust/…/guard_store_cloud_workspace_id.rs• L21-39 rust/…/guard_store_command_pack_legacy_evidence.rs• L100-167 src/…/store_extension_control_authority.py• L49-153
Delivery and worker recovery
Cloud and worker flows resume from explicit rows rather than from in-memory assumptions. Sync transitions merge only the fields for the current step, worker requests use nonces, approval attention is taken and deleted in one change, and replay markers keep binding and authority history across retries.
This keeps a restart from repeating a completed handoff or treating a stale response as the answer for a newer request.
References: rust/…/guard_store_review_sync_transition.rs• L135-167 rust/…/guard_store_worker_host.rs• L109-125 rust/…/guard_store_worker_host.rs• L180-261 rust/…/guard_store_review_replay_marker.rs• L117-163
Recovery boundaries
Local database recovery and daemon recovery solve different failures. Database recovery restores or rebuilds local state after corruption proof. Daemon recovery reconnects or restarts a service after identity, authorization, and protection checks. The daemon path may read the store for its final health check, but it does not replace the SQLite recovery path.
References: src/…/store_connection_schema.py• L267-374 rust/…/guard_store_op.rs• L163-210
Change checklist
When these files or sections are changed, remember to consider these:
- A schema or column change must keep migration markers, current-schema checks, domain compatibility markers, and salvage allowlists aligned.
- A new
sync_statekey must define its JSON shape, ownership, missing-row behavior, unreadable-row behavior, and whether it is authority or cache state. - A snapshot change must keep all related rows in the same view and preserve the distinction between missing, malformed, scalar, and unreadable values.
- A policy or review-memory change must preserve atomic replacement of decisions with its checkpoint, acknowledgement, keyring, and delivery state.
- Approval reads must keep raw-row comparison, projected-row scope, native queue ownership, byte budgets, cursor identity, and unavailable-store behavior aligned.
- Local CLI changes must keep connector identity, authority revision, grant state, capabilities, catalog revisions, and continuity events in one transaction.
- Workspace assessment changes must keep dirty generations, queue coalescing, lease fencing, result snapshots, and proposal verification tied together.
- A new SQLite sidecar or journal mode must be included in permission repair, file-identity checks, access gating, and quarantine decisions.
- Connection and reply-budget changes must preserve bounded reads, stable cursors, success-only finalization, and the rule that a failed request does not imply an uncommitted write.
- Recovery changes must preserve repeated proof checks, the exclusive gate, independent salvage paths, and the rule that the request that saw the database error still returns that error.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Two processes initialize an old schema together | Migration can race with reads or another migration | In-process state and schema-migration.lock serialize initialization. |
| A domain marker is newer or has the wrong checksum | Stored authority cannot be trusted by this build | Domain compatibility checks fail closed. |
| A snapshot combines rows from different moments | A decision can use a new authority with an old binding or cursor | Related rows are read in one deferred transaction. |
| A local CLI identity changes | An old grant could apply to a different connector | The grant becomes stale and dependent capabilities are cleared. |
| A policy checkpoint or trust row is invalid | A stale or downgraded policy could become active | Activation checks the bundle and its trust rows before the write boundary. |
| A remote receipt is delivered twice | One cloud decision could resolve two local requests | The receipt claim is unique and committed before the resolution. |
| A workspace run lease expires or is fenced | A late worker could attach findings to newer content | Lease generation and expiry checks reject stale workers. |
| A lock or temporary I/O error resembles corruption | A usable database could be quarantined | Guard probes the store, checks the write path, and confirms file identity. |
| A fatal error is caught inside a store operation | Later nested work could write through a bad connection | The operation rolls back the active transaction and returns a typed store error. |
| A queued event or page exceeds the reply budget | Sync or status work can fail instead of making progress | Reads use byte budgets, stable cursors, and explicit oversized-row handling. |
| A quarantined database cannot open but one salvage domain is readable | Rebuild could silently remove recoverable Cloud Review or CLI state | Salvage paths run independently with narrow allowlists. |
| A worker response has an old nonce | A late worker could overwrite current status | Status reads require the current request nonce. |
Key files
| File | Why to read it |
|---|---|
| rust/…/guard_store_op.rs | Shows the profile entry point, transaction kinds, SQLite settings, commit result, and reply boundary. |
| rust/…/guard_store_op_kind.rs | Shows which operations are reads, snapshots, writes, or isolated reads. |
| rust/…/guard_store_db.rs | Shows row decoding and the distinction between busy, corrupt, I/O, integrity, and contract errors. |
| rust/…/guard_store_sync_state.rs | Shows the shared document-state contract and the module groups that own sync rows. |
| rust/…/guard_store_policy_trust_rows.rs | Shows the consistent policy bundle and trust view used before policy activation. |
| rust/…/guard_store_exact_cloud_apply.rs | Shows request re-checks, receipt replay protection, and local one-use authority application. |
| rust/…/guard_store_continuity_write.rs | Shows the atomic local connector authority and continuity write. |
| rust/…/guard_store_cloud_events.rs | Shows the local event log, cloud queue limits, upload state, and oversized-event handling. |
| rust/…/guard_store_workspace_assessment_queue.rs | Shows dirty generations, coalescing, leases, retries, and superseded runs. |
| rust/…/guard_store_workspace_assessment_reads.rs | Shows paged worktree and run views with stable cursors. |
| rust/…/guard_store_workspace_fix_proposals.rs | Shows proposal preparation, review-only diff exposure, and run-bound verification. |
| rust/…/guard_store_worker_host.rs | Shows durable handoff rows for approval attention, worker refresh, and self-check status. |
| rust/…/guard_store_review_replay_marker.rs | Shows binding-aware retry and replay state for interrupted Cloud Review delivery. |
| src/…/sqlite_recovery.py | Defines corruption proof, readable-store restore, independent salvage, and quarantine retention. |
docs/daemon-and-local-service-lifecycle.md | Provides the parent view of daemon startup, service operation, and shutdown around local storage. |