Database layout
The task registry uses the global control-plane database. Runtime trajectory events live with their sessions in the per-agent database or a configured shared session SQLite store.
Meeting transcript tables
Meeting captures use threeSTRICT tables in the shared
state/openclaw.sqlite database, separate from per-agent conversation transcripts.
The transcript store (src/transcripts/store.ts) owns their reads and writes;
src/transcripts/sqlite-schema.ts ensures the tables on first use. Markdown and
JSON files under the transcripts directory are explicit exports, not runtime
storage. See Transcripts CLI.
meeting_transcript_sessions
One row per capture identity. The primary key is (session_id, started_at);
selector is unique. Indexes support start-time, session-ID, slug, and export-key
lookups.
Reopening an occupancy-driven capture clears
stopped_at without changing the
primary key, so the same meeting retains its utterances.
meeting_transcript_utterances
Append-ordered speech records. The primary key is
(session_id, session_started_at, sequence); the session pair references
meeting_transcript_sessions(session_id, started_at) with ON DELETE CASCADE.
meeting_transcript_summaries
One current summary per capture. The primary key is
(session_id, session_started_at) and references the session primary key with
ON DELETE CASCADE. At least one of summary_json or markdown must be non-null.
These are existing feature-local tables. Occupancy episodes and model-backed
notes do not change their schema or database version.
Update run ledger
update_runs stores one durable record per update in the shared
state/openclaw.sqlite database. src/infra/update-run-ledger.ts owns writes
from the admitting Gateway, orchestrator CLI, and restarted Gateway. The table
is additive at shared schema version 15: the canonical schema declares it and
first use ensures it inside the same write transaction. Existing tables and the
schema version stay unchanged; older readers ignore the new table.
run_id is the UUID primary key. Rows retain creation/update timestamps,
trigger, phase, status, reason, origin, target, before/after versions, steps,
verification facts, repair attempts, confirmation/finish timestamps, and known
downtime. Each JSON column has a 16 KiB hard limit with deterministic truncation
and redaction. The ledger stores bounded diagnostic summaries, not raw logs or
credentials. There is no automatic history deletion.
The CLI and Gateway share WAL-backed transactions, including while the Gateway
is stopped. The first terminal outcome wins; subsequent verification can enrich
its observed facts without rewriting success, failure, skip, or rollback status.
The restart sentinel carries stats.runId and remains the continuation owner;
consuming it does not delete the run row. Chat, CLI, and status reports read that
row. See Run history and reports.
Versioning contract
Each database records its schema in two places:PRAGMA user_versionis the SQLite schema version.- The primary
schema_metarow recordsrole,agent_id,schema_version, andapp_version.app_versionis the OpenClaw build that last wrote the schema metadata.
user_version is newer than the running build and reports a newer schema version error. The Gateway checks all registered databases before startup. openclaw update also refuses a package or source target whose declared schema support is older than an on-disk database. Target packages published before schema metadata was added cannot be preflighted.
When Gateway startup encounters a newer database schema, it exits with status 78 so the generated systemd service does not restart it repeatedly. On macOS, it also parks its managed LaunchAgent to stop KeepAlive retries. This applies to failures during CLI bootstrap as well as server startup and does not depend on the database-backed crash counter. Start the Gateway with a build that supports the existing schemas. The older install cannot repair them with doctor --fix; run Doctor from the compatible install if further migration is required, then restart through the service or deployment owner.
Changes may stay at the same schema version only when downgraded readers remain safe. New tables qualify because older builds ignore them. An explicitly compatible column on an existing table qualifies only when its declaration is exactly one bare nullable SQLite STRICT datatype: ANY, BLOB, INT, INTEGER, REAL, or TEXT. The declaration cannot have a default, NOT NULL, a primary or unique key, a check, a reference, a collation, a generated expression, or another suffix. Constrained existing-table additions require a schema-version bump or a companion table instead.
Matching numeric versions are necessary but not sufficient. A release can add a lazy or startup-repairable table, column, index, or trigger without advancing user_version, so two databases at the same version can still have different shapes. OpenClaw validates the canonical table definitions, constraints, indexes, triggers, virtual tables, and table options owned by the running release.
Agent schema 19 records collected input consumption in the nullable
session_pending_inputs.consumed_event_id TEXT column. Doctor and the feature’s
first-use ensure add it when needed; the schema version stays 19. The supported
beta upgrade runs Doctor from the upcoming release. Intermediate builds that
already validate the optional pending-input table may reject the added column
despite sharing version 19. Consumed source receipts remain until their session
window is deleted, so rewriting a transcript cannot make an old input runnable again.
The placement-move table uses this same-version rule for its nullable bare
abandon_source INTEGER column. The feature lazily ensures the column on first
move use. NULL means ordinary reconcile-first movement; 1 records the
operator’s explicit offline-device abandonment decision so restart recovery
cannot accidentally resume remote reconciliation. Older readers ignore the
column and can reopen the same database safely.
Conversation associations use the same rule for the nullable bare
route_context_json TEXT column. The database-open repair ensures the column
for updated binaries. Older readers ignore it and can reopen and update the
same database safely; their association update invalidates context captured by
a newer writer so it cannot be replayed after re-upgrade.
Transcript context eligibility uses a bare nullable
session_transcript_active_events.context_eligible INTEGER column without
changing agent schema 18. Database open installs the column and a non-unique
partial index of unclassified rows. 1 includes an entry in bounded context
acquisition, 0 excludes display-only activity, and NULL means the projection
still needs reconciliation. Bootstrap control markers remain eligible; history
counts, positions, and cursors do not change. Raw transcript JSON stays canonical.
Older same-version writers can append or rebuild without supplying eligibility.
The existing transcript reconciler detects their NULL rows even when its
sequence watermark is current, then rebuilds from raw events before publishing
readiness. Readers return a retryable projection-unavailable result while this
work is pending; they do not parse every payload or guess eligibility. Initial
index creation scans projection metadata once, and startup awaits reconciliation
with off-thread parsing and bounded write chunks. Total rebuild cost remains
proportional to history. Rewrites invalidate or rebuild the projection in their
own transaction, and transcript deletion removes its eligibility rows. Downgrade
leaves the additive column and index intact; re-upgrade reconciles unknown rows.
User profiles use the same rule for the nullable bare user_profiles.role TEXT
column in state schema 9. Operator-role assignment lazily ensures the column on
first use. Older readers ignore the column and can reopen the same database
safely.
Web Push subscription ownership uses the same rule for nullable bare
web_push_subscriptions.device_id TEXT, user_profile_id TEXT, and
preferences_json TEXT columns. Web Push lazily ensures all three columns on
first use. Existing rows remain unbound and test-only until the browser
reconnects; older readers ignore the columns and continue reading or updating
the endpoint and key fields safely.
Approval-notification cleanup uses the same-version additive
web_push_approval_deliveries table. It records the approval/subscription
identifiers plus the request-time device/profile binding for notifications that
may have reached a browser. A terminal or restarted Gateway sends only when the
current subscription still has that binding. The table is lazily created on
first use, rows cascade away with their approval or subscription, and older
readers ignore it safely.
Installing OpenClaw manually through npm bypasses the updater guard. Database open checks still refuse an incompatible build.
Structured Goal controls use a lazy
per-agent session_goal_operations table without changing the schema version.
Goal start/resume commits the Goal transition, input turn, run lifecycle, and
operation receipt in one transaction. Management operations commit the Goal
transition and receipt together. Older readers ignore the added table.
Receipts survive Goal clear and session reset/deletion until their 24-hour
validity expires; later Goal writes prune expired rows. They retain the
original result and a keyed request fingerprint, not a second raw request.
There is no backfill or configuration switch. Downgrading preserves the table
but disables the new structured controls; upgrading can read retained receipts.
Profile-owned skill library
Personal and team skills use four first-use tables in the shared state database without changing its schema version:skill_library_entries, skill_library_revisions, skill_library_events, and skill_library_uploads. Ordinary workspace skills and unused-library discovery do not create these tables. Ownership, sharing, the current revision pointer, portable file manifests, and publication events are canonical SQLite data. Session selections remain in the existing per-agent session store; inherited cron selections remain in the existing private job record.
Complete skill bundles are product artifacts under <state-dir>/skill-library/<skill-id>/revisions/<revision-hash>/. Publication writes and verifies an immutable bundle before committing its current pointer and event in one synchronous database transaction. Concurrent edits require the expected revision. A crash before that commit can leave an unreferenced complete bundle, but not a pointer to partially written content. Sharing and transfer change metadata without moving revision files.
Removing a skill excludes it from future selections; existing sessions retain their selected revisions. Published history and complete orphan revisions are retained conservatively. Expired upload records are pruned when another upload begins; clearly abandoned staging directories are cleaned during later publication. Back up both the state databases and the skill-library directory, not just the current revision pointers.
Older same-schema readers ignore the new tables but cannot provide managed-library selection or authoring. Keep the tables and bundle directory intact when changing builds; do not lower schema markers or delete revisions to disable the feature. The accepted storage and ownership decision is recorded in the profile-owned skills design issue.
Personal GitHub connections and publication
Personal GitHub connection state uses the existingsecret_store_entries identity scope, with the canonical authenticated profile as scope_id and the fixed private name github-connection. It is not a generic identity-secret API or a profile preference. One bounded record owns selection, pending device authorization, and refresh recovery. Personal managed CLI credentials use a separate credentials/github/personal/<opaque-profile-id> directory, outside older system/agent cleanup roots.
Personal publication uses the lazy, same-version github_personal_publication_requests table. It records the requesting profile, selected connection generation and account, immutable target/workspace snapshot, idempotency, and outcome; it contains no tokens. Reading status does not create the table. Existing system and agent requests remain in their original table and retain their existing lifecycle.
Older builds ignore both the personal request table and identity-scoped credential rows instead of executing a personal request as System. Re-upgrade still enforces original authorization expiry. Unfinished personal publication requires fresh confirmation by the same authenticated owner after a Gateway restart; remote-result reconciliation reuses the original request markers.
Disconnect removes usable local credentials and retains a secret-free disconnected selection to fence stale work. Profile merges preserve target state, including an explicit disconnection; a source connection transfers only when the target has no state, with new selection authority. Credentials stranded by a profile merge performed on an older build require reconnect, not runtime adoption through aliases.
Personal publication receipts remain for the logical session’s lifetime. Archive/reset preserves receipts and invalidates incompatible unfinished work. Permanent session deletion fences execution and removes its personal receipts. There is no timed idempotency expiry, and deleting local state does not undo an already-created GitHub commit or pull request.
See the accepted personal GitHub ownership and publication design and the operator-facing GitHub connections guide.
Personal model accounts
Personal model accounts use the existingsecret_store_entries identity scope, keyed by the canonical Gateway profile. A versioned model-accounts record owns provider selections, while each model-account:<profile-id> record owns one inline OAuth or token credential and its usage state. Each record retains the existing 64 KiB secret-store limit; connecting more accounts or merging profiles does not combine credentials under one size limit. This adds no table, column, index, or schema version. Generic secret-list/read methods and profile preferences do not expose these records.
The credential and its selected link commit in one synchronous transaction after the Gateway revalidates the initiating authorization. Runtime loads only an explicitly selected credential and routes refresh and usage updates to that same owner. Shared and agent-local auth saves exclude the reserved personal-profile namespace, including runtime snapshots and CLI mirrors.
Unlink records an explicit disconnected selection and retains credentials used by existing session pins. A verified identity merge transfers only the live source’s records, preserving the target’s selections and disconnections while retaining old credential IDs for pinned sessions. Credentials stranded on an alias by an older build are not adopted at runtime. A compatible downgrade leaves private records outside the older shared-account pool; re-upgrade can use retained records, while accounts stranded by older identity merges need reconnecting.
See Per-person model accounts for connection, cancellation, session billing, and unlink behavior.
Apple companion delivery journals
Companion Watch chat has separate app-local storage. It does not change the Gateway control-plane or per-agent database schema, andopenclaw doctor
does not migrate it. Open the updated iPhone and Watch apps to use the new
delivery protocol. See Watch voice and chat
for delivery statuses and recovery.
The iPhone’s existing client-state.sqlite owns watch_message_journal.
The named GRDB migration client-state-watch-message-journal-v9 adds that table
and a nullable watch_route_generation TEXT column to
gateway_routing_identity. The generation changes after Forget and re-pairing;
a late callback or queued command from the old pairing cannot become new work.
Admission, accepted run identity and terminal receipt state share one journal
owner, separate from the general chat outbox.
The journal’s nullable command_fingerprint BLOB stores SHA-256 of each
admitted command’s canonical bytes. Dismiss preserves this hash, so reusing an
ID with changed content or submission time cannot return the original result
after its command text is cleared. The hash expires with the row or is removed
by Forget; legacy imports have no command fingerprint.
The migration is registered by shared Apple client storage, so the Mac client
also sees the additive schema; it does not process companion Watch delivery.
The additive client-state-watch-message-legacy-receipts-v1 migration creates
watch_message_legacy_imports. It stores SHA-256 hashes of exact legacy command
IDs and imported content, never the text or Gateway ID. A nullable content hash
records the older app’s ID-only recent-message suppression policy; it is not
proof of a matching body or successful execution.
Old Watch UserDefaults are decoded and reconciled in one SQLite transaction
whenever the phone prepares its journal. Imported rows and their hash receipts
commit together before cleanup checks that both source blobs are unchanged.
This also recovers messages written by an older app after downgrade. Unprovable
queued text becomes Needs review, never an automatic send. Conflicting IDs
or unseen messages associated with a previously forgotten Gateway preserve the
source and surface a recovery error instead of discarding or retargeting text.
Imported text remains until explicit discard or Gateway Forget. Its hash-only
receipt has no timed expiry and survives both actions, so an identical old
snapshot cannot resurrect deleted text. This storage grows per legacy ID and is
removed only by a full onboarding reset, which clears the old UserDefaults
before deleting client state. New commands and their reply replay instead have
an immutable 48-hour deadline. Dismiss hides a completed card without changing
its receipt, acknowledgment state or deadline; active deliveries cannot be
discarded or dismissed.
Expired copies are pruned when delivery state is next used, including opening
the phone’s delivery list. An idle or suspended app does not promise immediate
wall-clock erasure.
The Watch owns its outbound commands and received results in its own SQLite
journal. A 90-second speech timeout does not remove this delivery state or
cancel the remote run. Both apps commit before issuing their application-level
admission or terminal receipt. A permanent rejection is explicitly not an
admission and creates no phone journal row. If dispatch became ambiguous before an accepted run was recorded,
recovery reports uncertainty rather than automatically executing the message
again. The phone retains its current WAL policy: this is app-termination
recovery, not a claim of power-loss durability.
Forget removes phone journal rows in the existing irreversible removal
transaction, including rows imported without a routing parent. The phone first
accounts for retained legacy source and refuses removal if that cannot be done
safely. The additive
schema leaves the old reader’s explicit routing updates intact, and a deletion
trigger keeps its Forget path effective after downgrade. An older app cannot
offer the new receipt protocol. Do not remove migration markers or reset
client-state.sqlite to downgrade: that file also contains other user-owned
client state.
The accepted design records
the schema, migration, ownership, retention and validation boundaries.
Preparing for another database backend
SQLite remains the supported runtime store. Preparation for PostgreSQL should improve the existing store owners and their tests before adding a driver or configuration option. The initial target is remote persistence for one Gateway; multiple active Gateways would require a separate ownership and coordination design. A shared database alone does not make process-local writer queues, session lifecycles, or host-owned leases safe across Gateway instances.Keep operations at the owning store
Callers should request domain operations, such as claiming a cron run or appending a transcript report, from the store that owns the invariant. That owner selects and decodes rows, validates current authority, commits changes, and publishes the result. Avoid exposing a generic SQL callback to application code or adding an asynchronous wrapper around an existing asynchronous facade. The plugin KV API already has asynchronous methods over its SQLite owner. Use Kysely for ordinary queries and mutations. The currentgetNodeSqliteKysely facade compiles queries; executeSqliteQuerySync runs them
on the supplied node:sqlite connection. Calling Kysely’s asynchronous
execute method on that facade is an error. Query compilation with another
dialect can identify syntax coupling, but does not prove driver behavior,
isolation, or database compatibility.
Acquire a connection once for an operation and pass that exact connection
through its transactional helpers. SQLite write callbacks remain synchronous:
finish asynchronous planning first, then reread authoritative rows after write
admission. Publish live session changes and other dependent effects only after
the durable write succeeds. A future network-backed owner must preserve that
ordering while awaiting its driver.
Preserve the data and concurrency contracts
An adapter must make these contracts explicit and verify them against a real database:
Kysely’s TypeScript types do not convert driver results; the driver determines
runtime values. See Kysely data types.
PostgreSQL transactions must use one acquired client, and its default Read
Committed isolation can give successive statements different snapshots. An
adapter therefore needs operation-specific isolation and retry decisions, not
a mechanical replacement of
BEGIN IMMEDIATE. See
node-postgres transactions
and PostgreSQL isolation.
Do not automatically convert canonical JSON text to jsonb: PostgreSQL’s
jsonb representation changes whitespace, object-key order, and duplicate-key
handling. A searchable jsonb projection would need an explicit design and
migration decision. See PostgreSQL JSON types.
Keep engine-specific capabilities owned
SQLite FTS5/BM25, vector tables, JSON table-valued queries, attached shadow databases, WAL maintenance, integrity checks, and backup operations remain SQLite capabilities. Keep their implementation behind the memory or database lifecycle owner. A future backend must supply equivalent product behavior or an explicit capability boundary; a second SQL dialect alone cannot replace these features. Schema, retention, migration, and multi-host changes still use the review checkpoint below.Review checkpoint for material changes
Before implementing a material SQLite or persistent-store change, open or link a maintainer discussion and record acceptance of the design. A schema-version bump is always material, but a change can be material even when the numeric version stays the same. Treat a change as material when it introduces or materially changes any of these:- a table, dedicated database, durable projection, cache, index, or other persisted representation
- which data is canonical, derived, reconstructible, retained, deleted, exported, or visible after restart
- user-visible persistence semantics, including a second interpretation of existing durable data
- migration, backfill, repair, downgrade, rollback, retention, compaction, or corruption recovery
- transaction boundaries, writer ownership, concurrency, locking, publication fencing, or reader consistency
- read, write, disk, startup, or maintenance cost enough to affect the store’s operating model
Preflight a target release
Before activating or rolling back a release, run that target release’s CLI against one explicit copied state database:exact: the copied database matches the target release’s runtime schema. Feature-local tables that are intentionally absent until first use do not require repair.startup-repairable: the numeric version matches and a runtime-owned additive difference remains; startup needs a write to converge the shape.migration-required: the database is older than the target release.incompatible: the database is newer, or its same-version shape has blocking drift such as an unexpected column.indeterminate: the file, integrity metadata, or ownership metadata could not be verified.
schema: "openclaw.state-schema-preflight.v1".
Use a SQLite online backup or another WAL-aware snapshot produced while the source is safely coordinated. The resulting preflight input must be one consolidated file with no sibling -wal, -shm, or -journal; sidecars make the result indeterminate. Do not copy only the main .sqlite file from an active WAL database. Preflight the exact runtime that will be activated; a package version or numeric schema version alone does not prove same-version shape compatibility.
Agent schema history
Version 3 was an unshipped development step folded into version 4.
Creator namespace migration
Agent schema 19 and shared-state schema 14 add a source discriminator to human creator actors in the existing session and cron JSON records. No table, sidecar, or separate identity ledger is added. The session node remains the immutable creator owner; mutable owner assignments and explicit sharing grants are unchanged. Historical human creators stamped directly byoperator or run creation become profile; channel creation becomes channel. Origin-losing cron, inherited spawn or Talk, legacy createdBy, and missing-source history remain unknown. The migration preserves IDs, attribution, creation times, content, and existing sandbox restrictions. A UUID, profile lookup, participant, current route, or required sandbox never supplies missing creator authority. Recovery from incomplete physical projections also produces unknown human attribution.
Before upgrading, stop the Gateway and all other writers, then create and verify a WAL-aware backup. Run openclaw doctor --fix with the new build. The agent migration retains the stopped-writer maintenance gate and runs after the schema-18 participant migration, without rebuilding already migrated participant rows. Canonical data and both schema markers commit in the owning database transaction. Shared-state and agent databases are separate transactions; if one fails, keep writers stopped and rerun Doctor before starting the Gateway.
Older builds refuse the new versions. For rollback, stop all writers and restore the verified pre-upgrade backups with their matching older build. Do not decrement either schema marker: an older writer cannot maintain the creator-source contract. Unknown historical provenance is irrecoverable from the stored ID alone. Administrators retain sharing management access; assigning responsibility does not restore an implicit creator grant.
Required sandbox resources keep their existing keys for proven profile creators. Channel and unknown creators instead use canonical-session isolation, with no new persisted principal field. Their old ambiguous resources are left untouched by migration, not automatically adopted or copied; operators must recover needed files explicitly before ordinary retention or cleanup. See sandbox scope and recovery.
Participant identity migration
Agent schema 18 rebuildssession_participants with the unique key (session_key, identity_namespace, actor_id). The raw actor ID remains separate from its namespace. This replaces the old (session_key, actor_type, actor_id) key; it is not a same-version additive change. Both schema markers advance together. No companion table or per-input ledger is added.
Before upgrading existing data, take a verified, WAL-aware backup and stop the Gateway and other agent-database writers. Run openclaw doctor --fix with the new build. The migration uses the existing maintenance lease to reject active writers and fence new claims. Ordinary runtime opens refuse the old participant schema rather than migrating it behind active readers. Earlier structural and media migrations run in their historical order before participant convergence. Explicit Doctor repair exits nonzero if an existing configured, default-layout, or registered database still fails runtime schema readiness, including when a live writer or an unknown table dependency blocks this migration. Readiness uses the same target discovery as migration without registering, pruning, or creating stores. Archive migration warnings remain advisory when required database schemas are ready.
Membership and recorded contribution aggregates survive. Historical profile timestamps are unknown because earlier source promotion could contaminate them even when a contribution count was present. Supported agent and channel-only observation times remain; an unresolved historical channel domain stays unresolved. Migration does not invent missing channel rows or inspect transcripts to reconstruct identities. New observations do not turn an unknown first input time into a claimed first-ever time.
The rebuild, data copy, version markers, and foreign-key validation commit atomically. Unknown table shapes or database-local dependents are refused. A failed migration rolls back rather than leaving a partial replacement table. Older builds refuse schema 18; do not decrement either version marker or restore the old unique key. Downgrade recovery requires the verified pre-migration backup.
Normal admission remains bounded at 32 identities. Same-store alias repair sums aggregates; retryable cross-store copies retain the larger recorded aggregate. Repairs preserve already-retained histories above the admission bound. Reset retains logical-session participation, while deletion removes it with the session node.
State schema history
State schema 15
Schema 15 removestarget_agent_id and target_session_id from current_conversation_bindings. The target index uses the complete target_session_key and remains non-unique: several conversations may point at the same destination. This lets plugin-owned targets persist without inventing an OpenClaw agent owner. Channel/account isolation, plugin approvals, binding identifiers, target keys, JSON metadata, expiry, and detach behavior are unchanged.
Startup and openclaw doctor --fix run the migration in the existing exclusive write transaction. They remove only the two projections and replace the target index, preserving all other row values. A dependent trigger, index, or failed schema check rolls the transaction back; migration does not discard an unknown dependency to force the upgrade. Column removal rewrites the binding table, so upgrade cost scales with its size.
Stop older writers and create a verified, WAL-aware backup before upgrading. Builds supporting shared-state schema 14 or earlier refuse the migrated database. To return to an older build, restore that pre-upgrade backup into a separate state directory; do not lower the version markers or reconstruct an agent projection. See downgrade limitations for the general recovery contract.
State schema 13
Schema 13 makescron_jobs.job_json, cron_jobs.state_json, and subagent_runs.payload_json the canonical records. Physical columns remain only where production queries, ordering, or runtime-only updates require them. Cron jobs shrink from 75 columns to 15, and subagent runs shrink from 59 columns to six. Migration preserves failure-destination fields explicitly configured as undefined by encoding them as JSON null; it also normalizes legacy run-status aliases into state_json before removing the redundant projections.
The shared-state auth_profile_stores and auth_profile_state singletons move into config_machine_state under authProfiles.store and authProfiles.state; per-agent auth tables remain unchanged. Because these rows contain credentials, secret-redacted Git backups omit the authProfiles. machine-state prefix.
State schema 11
Schema 11 removes theskill_lifecycle and skill_workshop_proposal_origin_runs tables. Archived-skill lifecycle state is discarded during the upgrade: previously archived Workshop skills return to the active collection, where weekly collection review judges them by content. The origin-run rows were a never-read projection; canonical proposal provenance stays in skill_workshop_proposals.record_json. Recorded skill usage and collection-review state are preserved.
State schema 9
Schema 9 stores anagent_databases.path value relative to the state directory when the registered agent database is inside that directory. During migration, a foreign default-layout row is re-anchored to the in-root counterpart when that file exists. It is deleted only when the same agent already holds its in-root registration, because dual default-layout registrations cannot produce a valid combined session list. Otherwise, the absolute row is preserved, so genuine external registrations are never deleted. This keeps a copied state directory self-contained without dropping supported external database paths.
Integrity checks
The Gateway startup preflight reads schema headers only.
openclaw database preflight performs the release-local shape comparison for an explicit copied file. The background verifier also scans already-open databases about once daily.
Memory search and maintenance managers borrow the verified per-agent connection. Acquisition does not reopen or rescan a healthy shared handle. Native and transformed plugin modules share the same process-owned connection lifecycle, query cache, and commit observers. Nested synchronous writes use SQLite savepoints on that connection. A manager retains that exact connection against cache eviction until its work drains, then releases its borrow without closing the database. Explicit quarantine and disposal still revoke it. Full memory rebuilds use separate temporary shadow databases and publish their derived tables in one synchronous transaction. Read-only memory status keeps its separate diagnostic connection and does not create or migrate a missing database.
The shared cache targets 64 handles, but live borrows, synchronous transactions, and incognito state are not evicted. After owners release them, the next new connection trims idle handles back to that target.
Quarantine decisions live only in a dedicated openclaw-quarantine.sqlite store, so they survive damage to the databases being quarantined. Verification results are logged.
Background verification errors retain the original name and message and append bounded Node code and SQLite errcode values from up to eight cause-chain nodes. These diagnostics do not change the verdict: I/O failures remain inconclusive, while proven corruption is reconfirmed by the database owner before quarantine. A generic disk I/O error (errcode=10) does not establish disk exhaustion.
Agent database maintenance fences other writers with a 60-second lease in the shared state database. A dedicated worker renews that lease during synchronous integrity scans and migration phases. Maintenance still checks the exact persisted owner before mutations and commit, and stops if the heartbeat fails or ownership expires or changes. Finishing or cancelling maintenance stops renewal before releasing the lease; process death leaves at most the remaining lease duration.
The heartbeat proves ownership, not migration progress. A live but stuck maintenance process can keep its lease; stop that process before retrying Doctor.
Troubleshooting
SQLite read-only worker failures append code and numeric SQLite errcode diagnostics when the underlying error supplies valid values, including through a bounded cause chain. Report the full code suffix when investigating a failure. A generic disk I/O error or SQLITE_IOERR alone does not prove the disk is full.
Why you cannot go back after updating to 2026.7.2
Every release throughv2026.7.1 used agent schema 1 and state schema 1. The 2026.7.2 release train (starting with v2026.7.2-beta.1) migrates your databases forward on first start. That migration is one-way: the data is rewritten into the newer schema, and installing an older OpenClaw afterwards does not undo it. The older build refuses to start with a newer schema version error that names the build that owns the database.
Downgrading the binary never downgrades the data. If you must run a release older than 2026.7.2 after updating, you have three options:
- Restore a backup taken before the update. Create and verify backups before major updates.
- Run the older build against a separate state directory (
OPENCLAW_STATE_DIR). It starts fresh; your migrated data stays untouched for when you return to the newer build. - Follow the manual downgrade procedure below. It is unsupported and risks data loss without a verified backup.
openclaw update refuses to install a release that cannot open your current databases, so the updater will not put you in this situation. Installing an older version manually through npm bypasses that guard; the databases still refuse the old binary, but only after it is installed.
The Gateway refuses to start with a newer schema version error
A newer OpenClaw build wrote your databases, and the running build is older. The error names the refusing install — release version, commit, and install root — plus the schema it supports and the schema it found. Act on the install root, not the version. One release version string spans manymain commits, schema levels, and same-version schema shapes, so two installs can both call themselves 2026.7.2 and still disagree about a database. A prerelease version may not exist on the latest npm tag at all: check npm view openclaw dist-tags before reinstalling, because the tag carrying the schema you need may be beta, and reinstalling from latest can move you further away.
When a Gateway runs from a linked source checkout, its status and schema-refusal diagnostics report the commit captured when dist/ was built, not the checkout’s current Git HEAD. If that build identity is unknown, rebuild the checkout (pnpm build) before concluding the version is wrong.
Open the database with a build that supports its schema, or point the older build at a separate OPENCLAW_STATE_DIR. Do not edit the database to silence the error.
Config reads also save health fingerprints to this database. If that write fails,
Config health-state write failed reports the first failure for that database
in the current process. Repeated identical failures are suppressed while writes
continue to be attempted. A different error, or a failure after a successful
health-state write, is reported again. Suppressing duplicates does not resolve
the underlying database error.
A database is quarantined after integrity verification failed
The background verifier proved the file is corrupt, and every open now fails fast instead of rescanning. Restore the database from a backup or repair it, then runopenclaw doctor --fix to clear the quarantine record. Doctor reports an explicit error if the quarantine record itself cannot be cleared; rerun it until it reports clean.
Downgrades are unsupported
Manual schema downgrades are for agents and operators who accept the risk. Create and verify a backup before editing any database. Stop the Gateway and every process that can open the database. The general procedure is:- Read the target release’s schema and migrations.
- In one transaction, restore the target release’s exact table, column, index, and trigger definitions; remove newer objects and recreate objects retired by subsequent upgrades.
- Set
PRAGMA user_versionandschema_meta.schema_versionto the target version. - Run the target release’s full database verification before starting the Gateway.
Example: state schema 13 to 12
Schema 13 removed 60 cron-job projection columns, 53 subagent-run projection columns, and five unused indexes. A schema 12 build still expects the exact original column definitions, ordering, and indexes. Adding the removed required columns with defaults produces a different schema that older builds reject, so rebuild both tables instead. Reproject every v12 cron field from canonicaljob_json and state_json; abort before rebuilding when either record is malformed.
Disable foreign-key enforcement before starting the transaction. The cron-runtime authority table references cron_jobs with ON DELETE CASCADE, so dropping the original table while enforcement is active would silently delete its authority rows. Re-enable enforcement after the rebuild commits, and verify that PRAGMA foreign_key_check; returns no rows before starting the older build.
Run equivalent SQL against the global state database after inspecting the exact schema that wrote it:
false, numeric thread IDs, and runtime state. Canonical JSON bytes remain unchanged. Subagent-run state remains in payload_json; its retired projections are not runtime scheduling inputs. A botched downgrade means restore from the verified backup.
Example: state schema 12 to 11
Schema 12 folded durable state snapshots intoconfig_machine_state and retired rebuildable caches plus the write-only cron store epoch table. A schema 11 build still expects the thirteen former tables, so a manual downgrade must recreate their exact schemas and indexes before lowering the version.
Run equivalent SQL against the global state database after inspecting the exact schema that wrote it:
config_machine_state under voicewake.triggers, voicewake.routing, onboarding.recommendations.<workspaceKey>, update.checkState, sidebar.sectionOrder, nodeHost.config, and webPush.vapidKeys; manually repopulate their former tables if the older build must retain those settings. Node-host identity and Web Push signing keys are sensitive: avoid copying their values into shell history or logs. Skill-curator, promotions-feed, remote-catalog, and TUI last-session caches can be rebuilt. A botched downgrade means restore from the verified backup.
Example: state schema 11 to 10
Schema 11 removed the retired skill lifecycle table and the never-read proposal origin-run projection. A schema 10 build still requires both canonical tables, so a manual downgrade must recreate their exact empty schemas and lifecycle indexes before lowering the version. Run equivalent SQL against the global state database after inspecting the exact schema that wrote it:record_json. A botched downgrade means restore from the verified backup.
Example: state schema 10 to 9
Schema 10 removed six dead shared-state tables. A schema 9 build still requires those canonical tables and indexes, so a manual downgrade must recreate their exact empty schemas before lowering the version. Run equivalent SQL against the global state database after inspecting the exact schema that wrote it:Example: state schema 9 to 8
Schema 8 expects everyagent_databases.path value to be absolute. Before lowering user_version, inspect each registry row on the same platform that wrote it. Leave absolute external paths unchanged; replace every relative path with its platform-native absolute form by resolving it against the state directory that owns state/openclaw.sqlite. Then set both PRAGMA user_version and schema_meta.schema_version to 8 in the same transaction.
Do not lower the version while relative registry rows remain. A schema 8 build interprets them relative to its process working directory rather than the copied state directory.