openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,049 lines (1,048 loc) • 49.9 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { c as resolveOpenClawAgentSqlitePath, i as isPersistentOpenClawAgentDatabasePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { w as readSqliteDatabaseIntegrityVerification, z as revokeSqliteDatabaseAdmissions } from "./sqlite-database-admission-DQIqro3d.mjs";
import { l as quoteSqliteIdentifier, t as extractSqliteTableSchema } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { t as OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema-BDRJZxWF.mjs";
import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { i as executeSqliteQuerySync, s as getNodeSqliteKysely, u as prepareSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs";
import { d as invalidateSqliteSchemaFacts, f as isSqliteSchemaAdmissionCold, o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema, y as readSqliteTextEncoding } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { a as setSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { r as readExistingAgentSchemaMeta } from "./openclaw-agent-db-metadata-C3YvwHLh.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { n as configureSqlitePreSchemaPragmas } from "./sqlite-wal-DGPrWPl6.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { a as resolveSqliteDatabaseFilePaths } from "./sqlite-files-rWisKj_V.mjs";
import { l as runSqliteIntegrityOperationSync, r as assertSqliteIntegrity, u as sqliteIntegrityCheckSteps } from "./sqlite-integrity-CCmEgO_m.mjs";
import { t as assertSqliteSchemaContains } from "./sqlite-schema-contract-D3pR9vZs.mjs";
import { f as resolveSchemaMigrationIntegrityTables } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import { b as repairCanonicalSqliteIndexes, h as resolveSchemaMigrationIntegrityCheck, l as runOpenClawStateWriteTransaction, x as verifyAndRepairCanonicalSqliteIndexSteps } from "./openclaw-state-db-ARhwdPJg.mjs";
import { r as migrateSqliteSchemaToStrictInTransaction } from "./sqlite-strict-BeSerG73.mjs";
import { o as registerOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { d as AGENT_INDEX_RETIREMENT_SQL, i as withoutTrajectoryPayloadColumns, m as AGENT_COLD_ARCHIVE_CHUNKS_SQL, n as migrateAgentTrajectoryStorageInTransaction, o as AGENT_MEMORY_REVISION_SQL } from "./openclaw-agent-trajectory-storage-migration-BbWlWZSu.mjs";
import { n as agentDatabaseMaintenanceAuthority, r as assertAgentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-maintenance-authority-C4Yhyki9.mjs";
import { a as hasAgentDatabaseApplicationSchema, i as assertSupportedAgentSchemaVersion, r as assertExistingAgentSchemaOwner } from "./openclaw-agent-db-schema-read-U5-_81Kg.mjs";
import { n as migrateAgentWriteLayoutInTransaction } from "./openclaw-agent-write-layout-migration-BPVNzU5a.mjs";
import { d as prepareAgentDeletionPathFence, h as assertAgentDeletionRecoveryAllowsMutation, n as assertAgentDeletionPathFence } from "./agent-deletion-journal-DgNbVVSp.mjs";
import { g as renewAgentDatabaseMaintenanceAuthorityIfPresent, l as invalidateOpenClawAgentDatabaseIntegrityBeforeMutation, r as assertAgentDatabaseMaintenanceAuthorityIfPresent } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { n as migrateMemoryIndexSourcesIdentity, u as migrateMemoryIndexStorage, v as ensureMemoryRecallMetadataSchema, x as ensureMemoryChunkProvenance } from "./memory-schema-B3FrMV9P.mjs";
import { s as interruptHistoricalPendingInputs } from "./openclaw-agent-db-schema-compatibility-DMUbFiMM.mjs";
import { C as withoutSessionEntrySnapshotsSchema, S as sessionEntrySnapshotsSchemaSql, _ as getOpenClawAgentMigrationSchema, b as withLegacyAgentStorageSchema, g as canonicalSessionValidationSchemaSql, x as DEPLOYED_FTS_ROWS_SCHEMA } from "./openclaw-agent-progress-card-schema-CDOtPrpA.mjs";
import { C as adoptCanonicalSessionValidationSchema, w as assertCanonicalSessionValidationSchema, y as setOpenClawAgentDatabaseValidation } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import { a as parseSqliteSessionEntryRecord } from "./session-entry-json-BctywCJg.mjs";
import { A as seedCanonicalSessionValidationPending, C as migrateSessionTranscriptActiveProjection, D as persistAgentSchemaMetadata, O as ensureLegacySessionEntryValidityTriggers, S as migrateSessionCreatorNamespaces, T as readSqliteTableColumns, _ as assertSupportedAgentMigrationSchemas, a as assertOpenClawAgentSchemaContains, b as ensureSessionEntryValidityProjection, c as finishAgentSchemaMigration, d as migrateRetiredAgentStateLeaseSchema, f as migratedSessionColumn, h as migrateSessionParticipantsSchema, i as assertOpenClawAgentCurrentRuntimeSchema, j as ensureOpenClawAgentBoardSchemaInTransaction, k as migrateCanonicalSessionWriterValidation, l as hasPendingCurrentVersionAgentDatabaseMigration, m as repairAndAssertOpenClawAgentV16Validity, n as migrateAgentJsonPredicatesInTransaction, o as ensureSessionKeyContractSchemaInTransaction, p as repairAndAssertOpenClawAgentV14SchemaForMigration, r as assertAgentSchemaVersion, s as ensureSessionReactionsSchemaInTransaction, t as migrateOutboxEnqueueSequenceInTransaction, u as hasPendingMemoryChunkMetadataMigration, v as backfillSessionConversations, w as migrateSessionTranscriptGenerations, x as migrateConversationDeliveryTargetColumn, y as ensureSessionAdditiveColumns } from "./openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs";
import { t as registerOpenClawAgentDatabase } from "./openclaw-agent-db-registry-DobcJNwx.mjs";
import { t as resolveZstdCodec } from "./zstd-codec-DyrkXXaa.mjs";
import { o as encodeUsageCostRollup, t as USAGE_COST_ROLLUP_SCOPE } from "./session-cost-usage-rollup-codec--B5D1pln.mjs";
import { i as splitSessionEntrySnapshots } from "./session-entry-snapshots-BIxBwjSA.mjs";
import { i as prepareTranscriptPayload } from "./transcript-payload-Cb_Kmk8c.mjs";
import { t as MAX_COMPRESSED_EVENT_BYTES } from "./transcript-payload-read-Dd5D3FtH.mjs";
import { chmodSync, existsSync, mkdirSync, statSync } from "node:fs";
import path from "node:path";
//#region src/state/openclaw-agent-db-permissions.ts
const OPENCLAW_AGENT_DB_DIR_MODE = 448;
const OPENCLAW_AGENT_DB_FILE_MODE = 384;
function ensureMode(e, t) {
if (process.platform === "win32" || (statSync(e).mode & 4095) !== t) chmodSync(e, t);
}
function ensureOpenClawAgentDatabasePermissions(e, t) {
const n = path.dirname(e);
const r = resolveOpenClawAgentSqlitePath({
agentId: t.agentId,
env: t.env
});
const i = path.resolve(e) === path.resolve(r);
const a = existsSync(n);
mkdirSync(n, {
recursive: true,
mode: OPENCLAW_AGENT_DB_DIR_MODE
});
if (i || !a) ensureMode(n, OPENCLAW_AGENT_DB_DIR_MODE);
for (const t of resolveSqliteDatabaseFilePaths(e)) try {
ensureMode(t, OPENCLAW_AGENT_DB_FILE_MODE);
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
}
//#endregion
//#region src/infra/session-cost-usage-cache-migration.ts
const PREVIOUS_SCOPE = "session-cost-usage-rollup-v2";
/** Migration-only reader for the version-6 complete-JSON representation. */
function decodePreviousRollup(e) {
const t = safeParseJsonRecord(e ?? "");
if (!t || t.version !== 6 || typeof t.pricingFingerprint !== "string" || !isRecord(t.checkpoint) || t.checkpoint.kind !== "jsonl" && t.checkpoint.kind !== "sqlite" || typeof t.scannedAt !== "number" || typeof t.parsedRecords !== "number" || typeof t.countedRecords !== "number" || !isRecord(t.rollup) || !isRecord(t.rollup.buckets) || !isRecord(t.rollup.untimestamped)) return;
return t;
}
/** Caller owns the migration transaction; retain at most one complete report body at a time. */
function migrateSessionCostUsageRollupStorage(e, t) {
const n = getNodeSqliteKysely(e);
let r;
for (;;) {
t?.();
let i = n.selectFrom("cache_entries").select([
"key",
"value_json",
"updated_at"
]).where("scope", "=", PREVIOUS_SCOPE).orderBy("key", "asc").limit(1);
if (r !== void 0) i = i.where("key", ">", r);
const a = executeSqliteQuerySync(e, i).rows[0];
if (!a) break;
r = a.key;
const o = decodePreviousRollup(a.value_json);
if (o) {
const t = encodeUsageCostRollup(o);
executeSqliteQuerySync(e, n.insertInto("cache_entries").values({
scope: USAGE_COST_ROLLUP_SCOPE,
key: a.key,
value_json: t.valueJson,
blob: t.blob,
updated_at: a.updated_at,
expires_at: null
}).onConflict((e) => e.columns(["scope", "key"]).doNothing()));
}
executeSqliteQuerySync(e, n.deleteFrom("cache_entries").where("scope", "=", PREVIOUS_SCOPE).where("key", "=", a.key));
}
}
//#endregion
//#region src/state/openclaw-agent-db-session-provenance.ts
function backfillTranscriptMutationWatermarks(e) {
if (!tableExists(e, "transcript_events")) return;
e.exec(`
UPDATE sessions
SET
transcript_updated_at = COALESCE(
transcript_updated_at,
(SELECT MAX(transcript_events.created_at)
FROM transcript_events
WHERE transcript_events.session_id = sessions.session_id)
),
transcript_observed_at = COALESCE(transcript_observed_at, updated_at)
WHERE EXISTS (
SELECT 1 FROM transcript_events
WHERE transcript_events.session_id = sessions.session_id
);
`);
}
//#endregion
//#region src/state/openclaw-agent-db-legacy-schema.ts
function migrateOpenClawAgentSchema(e) {
if (readSqliteUserVersion(e) >= 38) return;
const t = readSqliteTableColumns(e, "sessions");
if (!t) return;
for (const [n, r] of Object.entries({
transcript_updated_at: "INTEGER DEFAULT NULL",
transcript_observed_at: "INTEGER DEFAULT NULL",
session_entry_provenance: "INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1))",
acp_owned: "INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1))",
plugin_owner_id: "TEXT",
hook_external_content_source: "TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook'))"
})) if (!t.has(n)) e.exec(`ALTER TABLE sessions ADD COLUMN ${n} ${r};`);
backfillTranscriptMutationWatermarks(e);
}
//#endregion
//#region src/state/openclaw-agent-db-schema-admission.ts
/** Publish completed canonical schema admission from the still-open maintenance handle. */
function admitOpenClawAgentDatabaseSchema(e, t) {
if (e.location() && readSqliteDatabaseIntegrityVerification(e) && (isSqliteSchemaAdmissionCold(e) || getAdmittedSqliteSchemaFacts(e))) {
admitSqliteSchema(e);
assertCanonicalSessionValidationSchema(e);
registerOpenClawAgentDatabaseIdentity(e);
setOpenClawAgentDatabaseValidation({
db: e,
...t
});
return e;
}
}
//#endregion
//#region src/state/openclaw-agent-db-session-nodes-migration.ts
const SESSION_NODE_SCHEMA_VERSION = 14;
function jsonText(e) {
return `CASE
WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') = 'text'
THEN NULLIF(trim(CAST(json_extract(entry_json, '${e}') AS TEXT)), '')
ELSE NULL
END`;
}
function jsonNumber(e) {
return `CASE
WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') IN ('integer', 'real')
THEN CAST(json_extract(entry_json, '${e}') AS INTEGER)
ELSE NULL
END`;
}
function createSessionNodes(e) {
e.exec(`
CREATE TABLE IF NOT EXISTS session_nodes (
session_key TEXT NOT NULL PRIMARY KEY,
current_session_id TEXT NOT NULL,
entry_json TEXT NOT NULL,
updated_at INTEGER NOT NULL,
status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
created_at INTEGER,
created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
created_actor_id TEXT,
parent_session_key TEXT,
spawned_by TEXT,
fork_source_session_key TEXT,
fork_source_session_id TEXT,
fork_source_entry_id TEXT,
label TEXT,
display_name TEXT,
category TEXT,
icon TEXT,
pinned_at INTEGER,
archived_at INTEGER,
last_read_at INTEGER,
last_interaction_at INTEGER,
last_activity_at INTEGER
) STRICT;
`);
}
/** Live entries take precedence over routes, then retained generations. */
function backfillSessionNodes(e) {
const t = readSqliteTableColumns(e, "session_entries");
const n = readSqliteTableColumns(e, "session_routes");
if (t) {
const n = migratedSessionColumn(t, "status", "NULL");
e.exec(`INSERT OR REPLACE INTO session_nodes (
session_key, current_session_id, entry_json, updated_at, status,
created_at, created_via, created_actor_type, created_actor_id,
parent_session_key, spawned_by, fork_source_session_key,
fork_source_session_id, fork_source_entry_id, label, display_name,
category, icon, pinned_at, archived_at, last_read_at,
last_interaction_at, last_activity_at
) SELECT
session_key,
session_id,
entry_json,
updated_at,
${n},
${jsonNumber("$.createdAt")},
CASE
WHEN json_valid(entry_json)
AND json_extract(entry_json, '$.createdVia') IN
('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')
THEN json_extract(entry_json, '$.createdVia')
ELSE NULL
END,
CASE
WHEN json_valid(entry_json)
AND json_extract(entry_json, '$.createdActor.type') IN ('human', 'agent', 'system')
THEN json_extract(entry_json, '$.createdActor.type')
WHEN ${jsonText("$.createdBy.id")} IS NOT NULL THEN 'human'
ELSE NULL
END,
COALESCE(${jsonText("$.createdActor.id")}, ${jsonText("$.createdBy.id")}),
COALESCE(${jsonText("$.parentSessionKey")}, ${jsonText("$.spawnedBy")}),
${jsonText("$.spawnedBy")},
${jsonText("$.forkSource.sessionKey")},
${jsonText("$.forkSource.sessionId")},
${jsonText("$.forkSource.entryId")},
${jsonText("$.label")},
${jsonText("$.displayName")},
${jsonText("$.category")},
NULL,
${jsonNumber("$.pinnedAt")},
${jsonNumber("$.archivedAt")},
${jsonNumber("$.lastReadAt")},
${jsonNumber("$.lastInteractionAt")},
${jsonNumber("$.lastActivityAt")}
FROM session_entries;`);
}
if (n) e.exec(`INSERT OR IGNORE INTO session_nodes
(session_key, current_session_id, entry_json, updated_at)
SELECT session_key, session_id, '{}', updated_at FROM session_routes;`);
e.exec(`INSERT OR IGNORE INTO session_nodes
(session_key, current_session_id, entry_json, updated_at)
SELECT session_key, session_id, '{}', updated_at FROM sessions;`);
}
/** Project the legacy window owner with the migration's entry/route precedence. */
function createLegacySessionWindowSelect(e) {
const t = readSqliteTableColumns(e, "sessions");
if (!t) return;
const n = readSqliteTableColumns(e, "session_entries");
const r = readSqliteTableColumns(e, "session_routes");
const ownerValue = (e, t) => `(SELECT candidate.${t}
FROM ${e} AS candidate
INNER JOIN session_windows AS owner_window ON owner_window.session_id = candidate.session_id
WHERE candidate.session_id = session_windows.session_id
ORDER BY CASE WHEN candidate.session_key = owner_window.session_key THEN 0 ELSE 1 END,
candidate.updated_at DESC,
candidate.session_key ASC
LIMIT 1)`;
const i = n ? ownerValue("session_entries", "session_key") : "NULL";
const a = r ? ownerValue("session_routes", "session_key") : "NULL";
const o = n ? ownerValue("session_entries", "entry_json") : "NULL";
return {
columns: `session_id, session_key, previous_session_id, reason, session_scope,
created_at, updated_at, transcript_updated_at, transcript_observed_at,
session_entry_provenance, acp_owned, plugin_owner_id,
hook_external_content_source, started_at, ended_at, status, chat_type,
channel, account_id, primary_conversation_id, model_provider, model,
agent_harness_id, parent_session_key, spawned_by, display_name`,
sql: `SELECT
session_id,
COALESCE(${i}, ${a}, session_key),
CASE
WHEN json_valid(${o})
THEN NULLIF(trim(CAST(json_extract(${o}, '$.previousSessionId') AS TEXT)), '')
ELSE NULL
END,
NULL,
${migratedSessionColumn(t, "session_scope", "'conversation'")},
created_at,
updated_at,
${migratedSessionColumn(t, "transcript_updated_at", "NULL")},
${migratedSessionColumn(t, "transcript_observed_at", "NULL")},
${migratedSessionColumn(t, "session_entry_provenance", "0")},
${migratedSessionColumn(t, "acp_owned", "0")},
${migratedSessionColumn(t, "plugin_owner_id", "NULL")},
${migratedSessionColumn(t, "hook_external_content_source", "NULL")},
${migratedSessionColumn(t, "started_at", "NULL")},
${migratedSessionColumn(t, "ended_at", "NULL")},
${migratedSessionColumn(t, "status", "NULL")},
${migratedSessionColumn(t, "chat_type", "NULL")},
${migratedSessionColumn(t, "channel", "NULL")},
${migratedSessionColumn(t, "account_id", "NULL")},
${migratedSessionColumn(t, "primary_conversation_id", "NULL")},
${migratedSessionColumn(t, "model_provider", "NULL")},
${migratedSessionColumn(t, "model", "NULL")},
${migratedSessionColumn(t, "agent_harness_id", "NULL")},
${migratedSessionColumn(t, "parent_session_key", "NULL")},
${migratedSessionColumn(t, "spawned_by", "NULL")},
${migratedSessionColumn(t, "display_name", "NULL")}
FROM session_windows`
};
}
function migrateSessionWindows(e) {
const t = createLegacySessionWindowSelect(e);
if (!t) return;
e.exec("ALTER TABLE sessions RENAME TO session_windows;");
e.exec(`
DROP TABLE IF EXISTS session_windows_new;
CREATE TABLE session_windows_new (
session_id TEXT NOT NULL PRIMARY KEY,
session_key TEXT NOT NULL,
previous_session_id TEXT,
reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
transcript_updated_at INTEGER DEFAULT NULL,
transcript_observed_at INTEGER DEFAULT NULL,
session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
plugin_owner_id TEXT,
hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
started_at INTEGER,
ended_at INTEGER,
status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
channel TEXT,
account_id TEXT,
primary_conversation_id TEXT,
model_provider TEXT,
model TEXT,
agent_harness_id TEXT,
parent_session_key TEXT,
spawned_by TEXT,
display_name TEXT,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
) STRICT;
INSERT INTO session_windows_new (${t.columns})
${t.sql};
DROP TABLE session_windows;
ALTER TABLE session_windows_new RENAME TO session_windows;
`);
}
function renameTranscriptRewriteWatermarks(e) {
if (readSqliteTableColumns(e, "session_transcript_generations") && !readSqliteTableColumns(e, "transcript_rewrite_watermarks")) e.exec("ALTER TABLE session_transcript_generations RENAME TO transcript_rewrite_watermarks;");
}
function rebuildBoardTabs(e) {
if (!readSqliteTableColumns(e, "board_tabs")) return;
if (readSqliteTableColumns(e, "board_widgets")) e.exec(`
DELETE FROM board_widgets
WHERE NOT EXISTS (
SELECT 1 FROM session_nodes WHERE session_nodes.session_key = board_widgets.session_key
);
`);
e.exec(`
DROP TABLE IF EXISTS board_tabs_new;
CREATE TABLE board_tabs_new (
session_key TEXT NOT NULL,
tab_id TEXT NOT NULL,
title TEXT NOT NULL,
position INTEGER NOT NULL CHECK (position >= 0),
chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
revision INTEGER NOT NULL CHECK (revision >= 0),
PRIMARY KEY (session_key, tab_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
INSERT INTO board_tabs_new (
session_key, tab_id, title, position, chat_dock, created_by, revision
)
SELECT b.session_key, b.tab_id, b.title, b.position, b.chat_dock, b.created_by, b.revision
FROM board_tabs AS b
INNER JOIN session_nodes AS n ON n.session_key = b.session_key;
DROP TABLE board_tabs;
ALTER TABLE board_tabs_new RENAME TO board_tabs;
`);
}
function rebuildHeartbeatOutcomes(e) {
const t = readSqliteTableColumns(e, "heartbeat_outcomes");
if (!t) return;
e.exec(`
DROP TABLE IF EXISTS heartbeat_outcomes_new;
CREATE TABLE heartbeat_outcomes_new (
session_key TEXT NOT NULL PRIMARY KEY,
run_session_key TEXT NOT NULL,
outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
summary TEXT NOT NULL,
response_reason TEXT,
priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
next_check TEXT,
task_names_json TEXT,
wake_source TEXT,
wake_reason TEXT,
occurred_at INTEGER NOT NULL,
context_run_id TEXT,
context_claimed_at INTEGER,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
INSERT INTO heartbeat_outcomes_new (
session_key, run_session_key, outcome, summary, response_reason, priority,
next_check, task_names_json, wake_source, wake_reason, occurred_at,
context_run_id, context_claimed_at, updated_at
)
SELECT
h.session_key,
h.run_session_key,
h.outcome,
h.summary,
${migratedSessionColumn(t, "response_reason", "NULL")},
${migratedSessionColumn(t, "priority", "NULL")},
${migratedSessionColumn(t, "next_check", "NULL")},
${migratedSessionColumn(t, "task_names_json", "NULL")},
${migratedSessionColumn(t, "wake_source", "NULL")},
${migratedSessionColumn(t, "wake_reason", "NULL")},
h.occurred_at,
${migratedSessionColumn(t, "context_run_id", "NULL")},
${migratedSessionColumn(t, "context_claimed_at", "NULL")},
h.updated_at
FROM heartbeat_outcomes AS h
INNER JOIN session_nodes AS n ON n.session_key = h.session_key;
DROP TABLE heartbeat_outcomes;
ALTER TABLE heartbeat_outcomes_new RENAME TO heartbeat_outcomes;
`);
}
function rebuildSessionMembers(e) {
if (!readSqliteTableColumns(e, "session_members")) return;
e.exec(`
DROP TABLE IF EXISTS session_members_new;
CREATE TABLE session_members_new (
session_key TEXT NOT NULL,
identity_id TEXT NOT NULL,
added_by TEXT NOT NULL,
added_at INTEGER NOT NULL,
PRIMARY KEY (session_key, identity_id),
FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;
INSERT INTO session_members_new (session_key, identity_id, added_by, added_at)
SELECT m.session_key, m.identity_id, m.added_by, m.added_at
FROM session_members AS m
INNER JOIN session_nodes AS n ON n.session_key = m.session_key;
DROP TABLE session_members;
ALTER TABLE session_members_new RENAME TO session_members;
`);
}
function rebuildTranscriptIndexState(e) {
const t = readSqliteTableColumns(e, "session_transcript_index_state");
if (!t) return;
e.exec(`
DROP TABLE IF EXISTS session_transcript_index_state_new;
CREATE TABLE session_transcript_index_state_new (
session_id TEXT NOT NULL PRIMARY KEY,
indexed_seq INTEGER NOT NULL,
leaf_event_id TEXT,
needs_rebuild INTEGER NOT NULL DEFAULT 0,
active_event_count INTEGER NOT NULL DEFAULT 0,
active_message_count INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;
INSERT INTO session_transcript_index_state_new (
session_id, indexed_seq, leaf_event_id, needs_rebuild,
active_event_count, active_message_count, updated_at
)
SELECT
i.session_id,
i.indexed_seq,
${migratedSessionColumn(t, "leaf_event_id", "NULL")},
${migratedSessionColumn(t, "needs_rebuild", "0")},
${migratedSessionColumn(t, "active_event_count", "0")},
${migratedSessionColumn(t, "active_message_count", "0")},
i.updated_at
FROM session_transcript_index_state AS i
INNER JOIN session_windows AS w ON w.session_id = i.session_id;
DROP TABLE session_transcript_index_state;
ALTER TABLE session_transcript_index_state_new RENAME TO session_transcript_index_state;
`);
}
/** Replace split entry/route roots with logical nodes and generation windows. */
function migrateSessionNodesAndWindows(e, t) {
if (t >= SESSION_NODE_SCHEMA_VERSION || !readSqliteTableColumns(e, "sessions")) return;
createSessionNodes(e);
backfillSessionNodes(e);
migrateSessionWindows(e);
renameTranscriptRewriteWatermarks(e);
rebuildBoardTabs(e);
rebuildHeartbeatOutcomes(e);
rebuildSessionMembers(e);
rebuildTranscriptIndexState(e);
e.exec(`
DROP TABLE IF EXISTS session_routes;
DROP TABLE IF EXISTS session_entries;
`);
}
//#endregion
//#region src/state/openclaw-agent-session-snapshots-migration.ts
/** The existing schema owner holds maintenance authority and the outer write transaction. */
function migrateSessionEntrySnapshotsInTransaction(e) {
e.exec("ALTER TABLE session_nodes ADD COLUMN snapshot_revision INTEGER NOT NULL DEFAULT 0");
e.exec(sessionEntrySnapshotsSchemaSql(OPENCLAW_AGENT_SCHEMA_SQL));
const t = getNodeSqliteKysely(e);
const n = t.selectFrom("session_nodes").select([
"session_key",
"current_session_id",
"updated_at",
"entry_json"
]).orderBy("session_key").limit(64);
const r = prepareSqliteQuerySync(e, (e) => n.where("session_key", ">", e((e) => e)));
const i = prepareSqliteQuerySync(e, (e) => t.insertInto("session_entry_snapshots").values({
session_key: e((e) => e.sessionKey),
field: e((e) => e.field),
value_json: e((e) => e.valueJson)
}));
const a = prepareSqliteQuerySync(e, (e) => t.updateTable("session_nodes").set({ entry_json: e((e) => e.entryJson) }).where("session_key", "=", e((e) => e.sessionKey)));
const o = prepareSqliteQuerySync(e, (e) => t.updateTable("session_nodes").set({ entry_valid: 1 }).where("session_key", "=", e((e) => e)));
let s;
while (true) {
const { rows: t } = s === void 0 ? executeSqliteQuerySync(e, n) : r(s);
if (t.length === 0) return;
renewAgentDatabaseMaintenanceAuthorityIfPresent();
for (const e of t) {
if (typeof e.session_key !== "string" || typeof e.current_session_id !== "string" || typeof e.updated_at !== "number" || typeof e.entry_json !== "string") throw new Error("Unreadable session row during snapshot migration");
s = e.session_key;
const t = parseSqliteSessionEntryRecord({
current_session_id: e.current_session_id,
updated_at: e.updated_at,
entry_json: e.entry_json
});
if (!t) continue;
const { entryJson: n, snapshots: r } = splitSessionEntrySnapshots(t);
if (r.length === 0) continue;
for (const t of r) i({
sessionKey: e.session_key,
...t
});
a({
entryJson: n,
sessionKey: e.session_key
});
o(e.session_key);
}
}
}
//#endregion
//#region src/state/openclaw-agent-transcript-fts-schema.ts
const RETIRED_FTS_ROWS = "session_transcript_fts_rows_legacy22";
/** Preserve the FTS content; replace only its old, possibly incomplete ownership projection. */
function migrateDeployedTranscriptFtsRowsInTransaction(e, t) {
if (!e.isTransaction || e.prepare("PRAGMA foreign_keys").get()?.foreign_keys !== 0) throw new Error("Transcript FTS migration requires an admitted transaction with foreign keys off");
assertSqliteSchemaContains(e, "deployed transcript FTS ownership", DEPLOYED_FTS_ROWS_SCHEMA);
const n = e.prepare("PRAGMA table_xinfo(session_transcript_fts_rows)").all();
if (n.length !== 2 || n.some((e) => e.name !== "session_id" && e.name !== "fts_rowid")) throw new Error("Transcript FTS migration cannot discard unknown row-map columns");
const r = e.prepare(`SELECT name FROM sqlite_schema
WHERE (tbl_name = 'session_transcript_fts_rows' AND sql IS NOT NULL
AND type IN ('index', 'trigger') AND name != 'idx_agent_transcript_fts_rows_session')
OR (type IN ('view', 'trigger') AND sql LIKE '%session_transcript_fts_rows%')`).all();
const i = e.prepare(`SELECT schema.name FROM sqlite_schema AS schema
JOIN pragma_foreign_key_list(schema.name) AS fk
WHERE schema.type = 'table' AND fk."table" = 'session_transcript_fts_rows'`).all();
if (r.length || i.length) throw new Error("Transcript FTS migration cannot discard unknown row-map dependencies");
if (e.prepare("SELECT 1 FROM sqlite_schema WHERE name = ?").get(RETIRED_FTS_ROWS)) throw new Error("Transcript FTS migration table already exists");
e.exec(`ALTER TABLE session_transcript_fts_rows RENAME TO ${RETIRED_FTS_ROWS}`);
e.exec(extractSqliteTableSchema(t, "session_transcript_fts_rows", {
endMarker: "INSERT OR IGNORE INTO memory_index_state",
includeEndMarker: false
}));
e.exec(`INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
SELECT rowid, session_id, message_id FROM session_transcript_fts`);
e.exec(`UPDATE session_transcript_index_state AS state SET needs_rebuild = 1
WHERE needs_rebuild = 0 AND (
fts_row_count IS NULL
OR fts_row_count != (SELECT count(*) FROM ${RETIRED_FTS_ROWS} AS old WHERE old.session_id = state.session_id)
OR EXISTS (
SELECT 1 FROM ${RETIRED_FTS_ROWS} AS old
WHERE old.session_id = state.session_id AND NOT EXISTS (
SELECT 1 FROM session_transcript_fts_rows AS current
WHERE current.id = old.fts_rowid AND current.session_id = old.session_id))
OR EXISTS (
SELECT 1 FROM session_transcript_fts_rows AS current
WHERE current.session_id = state.session_id AND NOT EXISTS (
SELECT 1 FROM ${RETIRED_FTS_ROWS} AS old
WHERE old.fts_rowid = current.id AND old.session_id = current.session_id))
);
DROP TABLE ${RETIRED_FTS_ROWS};
ALTER TABLE session_transcript_index_state DROP COLUMN fts_row_count;`);
}
//#endregion
//#region src/state/openclaw-agent-transcript-payload-migration.ts
const MIGRATION_TABLE = "transcript_events_payload_migration";
const KNOWN_CHILDREN = /* @__PURE__ */ new Set(["transcript_event_identities", "session_transcript_active_events"]);
function assertTranscriptRebuildInputs(e) {
assertSqliteSchemaContains(e, "transcript payload migration", extractSqliteTableSchema(withLegacyAgentStorageSchema(OPENCLAW_AGENT_SCHEMA_SQL), "transcript_events"));
const t = e.prepare("PRAGMA table_xinfo(transcript_events)").all();
const n = /* @__PURE__ */ new Set([
"session_id",
"seq",
"event_json",
"created_at"
]);
if (t.length !== n.size || t.some((e) => typeof e.name !== "string" || !n.has(e.name))) throw new Error("Transcript payload migration cannot discard unknown columns");
if (e.prepare(`SELECT name FROM sqlite_schema
WHERE (type IN ('trigger', 'index') AND tbl_name = 'transcript_events' AND sql IS NOT NULL)
OR (type IN ('view', 'trigger') AND sql LIKE '%transcript_events%')`).all().length > 0) throw new Error("Transcript payload migration cannot rebuild unknown indexes, views, or triggers");
if (e.prepare("SELECT 1 FROM sqlite_schema WHERE name = ?").get(MIGRATION_TABLE)) throw new Error("Transcript payload migration table already exists");
for (const t of e.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all()) {
if (typeof t.name !== "string") throw new Error("Invalid table name during transcript payload migration");
if (KNOWN_CHILDREN.has(t.name)) continue;
if (e.prepare(`PRAGMA foreign_key_list(${quoteSqliteIdentifier(t.name)})`).all().some((e) => e.table === "transcript_events")) throw new Error("Transcript payload migration cannot rebuild an unknown foreign-key target");
}
}
/** Convert original bytes under the admitted agent migration; never hydrate oversized identity rows. */
function migrateTranscriptPayloadStorageInTransaction(e) {
if (!e.isTransaction || e.prepare("PRAGMA foreign_keys").get()?.foreign_keys !== 0) throw new Error("Transcript payload migration requires an admitted transaction with foreign keys off");
assertTranscriptRebuildInputs(e);
const t = readSqliteTextEncoding(e) === "UTF-8";
const n = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true
});
const r = resolveZstdCodec();
e.exec(extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL, "transcript_events").replace("IF NOT EXISTS transcript_events", MIGRATION_TABLE));
const i = e.prepare(`
INSERT INTO ${MIGRATION_TABLE}
(rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
SELECT rowid, session_id, seq, event_json, created_at, NULL,
CASE WHEN ? THEN octet_length(event_json) ELSE NULL END, ?
FROM transcript_events WHERE rowid = ?`);
const a = e.prepare(`
INSERT INTO ${MIGRATION_TABLE}
(rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
SELECT rowid, session_id, seq, NULL, created_at, ?, ?, ?
FROM transcript_events WHERE rowid = ?`);
i.setReadBigInts(true);
a.setReadBigInts(true);
const o = e.prepare("SELECT CAST(event_json AS BLOB) AS bytes FROM transcript_events WHERE rowid = ?");
const s = e.prepare("SELECT rowid AS storage_rowid, octet_length(event_json) AS bytes FROM transcript_events ORDER BY rowid");
s.setReadBigInts(true);
let c = performance.now();
for (const l of s.iterate()) {
if (performance.now() - c >= 1e3) {
renewAgentDatabaseMaintenanceAuthorityIfPresent();
c = performance.now();
}
if (typeof l.storage_rowid !== "bigint" || typeof l.bytes !== "bigint") throw new Error("Invalid transcript storage identity during migration");
let s = null;
let u = false;
if (t && l.bytes <= BigInt(4194304)) {
const t = o.get(l.storage_rowid)?.bytes;
if (!(t instanceof Uint8Array)) throw new Error("Transcript payload disappeared during migration");
let i;
try {
i = n.decode(t);
} catch {}
if (i !== void 0) {
const n = prepareTranscriptPayload(e, i, void 0, "UTF-8");
s = n.navigation_json;
if (n.event_zstd !== null) {
if (n.event_utf8_bytes === null || !r.decompress(n.event_zstd, n.event_utf8_bytes).equals(t)) throw new Error("Transcript compression did not preserve canonical bytes");
const e = a.run(n.event_zstd, n.event_utf8_bytes, s, l.storage_rowid);
if (Number(e.changes) !== 1) throw new Error("Transcript payload disappeared before migration publication");
u = true;
}
}
}
if (!u && Number(i.run(t ? 1 : 0, s, l.storage_rowid).changes) !== 1) throw new Error("Transcript identity payload disappeared before migration publication");
}
renewAgentDatabaseMaintenanceAuthorityIfPresent();
e.exec(`DROP TABLE transcript_events;
ALTER TABLE ${MIGRATION_TABLE} RENAME TO transcript_events;`);
}
//#endregion
//#region src/state/openclaw-agent-db-schema.ts
const agentDbLog = createSubsystemLogger("state/agent-db");
function migrateMemoryChunkMetadataSchema(e) {
ensureMemoryRecallMetadataSchema(e);
ensureMemoryChunkProvenance(e);
}
function* agentDatabaseIntegrityBeforeMutationSteps(e, t, n, r, i, a = false, o = false, s, c) {
if (a && o) {
if (r) r.integrityGateOutcome = "cached";
return false;
}
setSqliteBusyTimeout(e, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
const l = getAdmittedSqliteSchemaFacts(e)?.userVersion ?? readSqliteUserVersion(e);
const u = l === 0 && hasAgentDatabaseApplicationSchema(e);
const d = l === 0 && u || l > 0 && l < 38;
if (d) agentDbLog.info("agent database schema migration pending; verifying integrity first", {
fromVersion: l,
path: n,
toVersion: 38
});
const f = l === 38 && hasPendingCurrentVersionAgentDatabaseMigration(e);
const p = resolveSchemaMigrationIntegrityCheck({
kind: "agent",
foundVersion: l,
supportedVersion: 38
}, s);
const m = performance.now();
if (r?.integrityGateReason === "stale-lease-full" && r.because) agentDbLog.info(`agent database integrityGateReason=stale-lease-full because=${r.because}`, {
agentId: t,
path: n,
...r
});
if (l === 38 && !f) {
const o = a || i !== void 0 && !d && !f;
const validateSchema = (r) => assertOpenClawAgentCurrentRuntimeSchema(e, {
agentId: t,
pathname: n
}, r);
const l = yield* verifyAndRepairCanonicalSqliteIndexSteps(e, n, OPENCLAW_AGENT_SCHEMA_SQL, {
allowMissingColumns: true,
validateAfterRepair: validateSchema,
validateUnchanged: validateSchema,
diagnostics: r,
reuseIntegrity: o,
integrity: s ? {
...p,
tables: c ?? p.tables
} : void 0
});
if (l.length > 0) agentDbLog.warn(`Rebuilt canonical agent SQLite indexes for ${t} (${n}): ${l.join(", ")}`, {
agentId: t,
path: n,
indexes: l,
elapsedMs: Math.floor(performance.now() - m)
});
} else if (l === 0 && !u && e.prepare("PRAGMA page_count").get()?.page_count === 0) assertSqliteIntegrity(e, n, s ? p : void 0);
else yield* sqliteIntegrityCheckSteps(e, n, r, p);
return f;
}
function migrateAgentStorageInTransaction(e, t, n, r) {
renewAgentDatabaseMaintenanceAuthorityIfPresent();
if (n === 22) migrateDeployedTranscriptFtsRowsInTransaction(e, t);
else if (e.prepare("SELECT 1 FROM sqlite_schema WHERE name = ?").get("session_transcript_fts_rows")) throw new Error("Transcript FTS row map already exists before the schema-23 storage migration.");
renewAgentDatabaseMaintenanceAuthorityIfPresent();
migrateTranscriptPayloadStorageInTransaction(e);
renewAgentDatabaseMaintenanceAuthorityIfPresent();
migrateMemoryIndexStorage(e, {
renewAuthority: renewAgentDatabaseMaintenanceAuthorityIfPresent,
onWarning: (e) => r.push(e)
});
renewAgentDatabaseMaintenanceAuthorityIfPresent();
migrateSessionCostUsageRollupStorage(e, renewAgentDatabaseMaintenanceAuthorityIfPresent);
renewAgentDatabaseMaintenanceAuthorityIfPresent();
e.exec(t);
if (n !== 22) e.exec(`
INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
SELECT rowid, session_id, message_id FROM session_transcript_fts;
`);
}
function ensureAgentSchema(e, t, n, r = 38, i = (e) => e(), a, o = false, s) {
const c = [];
const l = getOpenClawAgentMigrationSchema(r);
e.exec("PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = OFF;");
let u = false;
try {
const mutate = () => {
invalidateSqliteSchemaFacts(e);
const i = readExistingAgentSchemaMeta(e);
assertExistingAgentSchemaOwner(i, t, n);
const a = assertSupportedAgentSchemaVersion(e, n);
const d = resolveSchemaMigrationIntegrityCheck({
kind: "agent",
foundVersion: a,
supportedVersion: r
}, s);
const f = a === 0 && !hasAgentDatabaseApplicationSchema(e);
const p = a < r && (a > 0 || i !== null);
const m = r >= 18 && p;
if (m && i?.schemaVersion !== a) throw new Error(`Agent schema markers disagree for ${n}; repair ownership metadata before migration.`);
if (a > r) throw new Error(`OpenClaw agent database ${n} uses schema version ${a}; expected at most ${r} for this migration.`);
if (!f && a < r) assertSupportedAgentMigrationSchemas(e, n, a);
const assertMigration = () => {
if (!p) return;
if (m) assertAgentDatabaseMaintenanceAuthority();
getOpenClawDatabaseMaintenanceScope()?.assertAgentSchemaMigration({
agentId: t,
path: n,
foundVersion: a,
supportedVersion: r
});
};
assertMigration();
if (a < r) interruptHistoricalPendingInputs(e, a);
if (f && r === 38) {
e.exec(l);
e.exec(`PRAGMA user_version = ${r};`);
persistAgentSchemaMetadata(e, t, r);
u = true;
return;
}
const crossesVersion = (e) => !f && a < e && r >= e;
const h = crossesVersion(25);
const g = crossesVersion(23);
const _ = crossesVersion(24);
const v = crossesVersion(30);
const y = v ? withoutTrajectoryPayloadColumns(l) : l;
const b = _ ? withoutSessionEntrySnapshotsSchema(y) : y;
const x = g ? withLegacyAgentStorageSchema(b, a) : b;
const finishStorageMigration = () => {
if (g) migrateAgentStorageInTransaction(e, b, a, c);
if (_) migrateSessionEntrySnapshotsInTransaction(e);
if (h) migrateCanonicalSessionWriterValidation(e);
if (crossesVersion(26)) migrateAgentJsonPredicatesInTransaction(e);
if (a < 27 && r >= 27) {
const r = migrateOutboxEnqueueSequenceInTransaction(e);
if (r !== null) agentDbLog.info("agent outbox enqueue sequence rebuilt", {
agentId: t,
pathname: n,
elapsedMs: r
});
}
if (crossesVersion(28)) migrateAgentWriteLayoutInTransaction(e);
if (crossesVersion(29)) e.exec(AGENT_INDEX_RETIREMENT_SQL);
if (v) migrateAgentTrajectoryStorageInTransaction(e);
if (crossesVersion(31)) e.exec(AGENT_MEMORY_REVISION_SQL);
if (crossesVersion(37)) e.exec(AGENT_COLD_ARCHIVE_CHUNKS_SQL);
if (a < 25) repairCanonicalSqliteIndexes(e, n, l, {
verifyPhysicalIntegrity: false,
integrity: d
});
finishAgentSchemaMigration(e, t, n, r, l, m, assertMigration, p ? resolveSchemaMigrationIntegrityTables({
kind: "agent",
foundVersion: a,
supportedVersion: r
}) : void 0);
};
if (a >= 25 && a < r) {
assertAgentSchemaVersion(e, {
agentId: t,
pathname: n,
version: a
}, getOpenClawAgentMigrationSchema(a));
if (!o) ensureSessionAdditiveColumns(e);
finishStorageMigration();
return;
}
if (a < r && a >= 21 - 1 && a < 25 && r >= 21) {
if (a >= 21) {
migrateRetiredAgentStateLeaseSchema(e, n, r);
ensureSessionAdditiveColumns(e);
ensureSessionEntryValidityProjection(e);
ensureLegacySessionEntryValidityTriggers(e);
ensureSessionKeyContractSchemaInTransaction(e);
if (hasPendingMemoryChunkMetadataMigration(e)) migrateMemoryChunkMetadataSchema(e);
}
const i = getOpenClawAgentMigrationSchema(a);
repairCanonicalSqliteIndexes(e, n, i, {
verifyPhysicalIntegrity: false,
integrity: d
});
assertAgentSchemaVersion(e, {
agentId: t,
pathname: n,
version: a
}, i);
if (a < 21) {
e.exec(canonicalSessionValidationSchemaSql(x));
if (!h) seedCanonicalSessionValidationPending(e);
}
finishStorageMigration();
return;
}
if (a === 17) {
ensureSessionAdditiveColumns(e);
ensureLegacySessionEntryValidityTriggers(e);
assertSqliteIntegrity(e, n, d);
migrateMemoryChunkMetadataSchema(e);
assertOpenClawAgentSchemaContains(e, n, getOpenClawAgentMigrationSchema(a), "legacy", true);
}
migrateRetiredAgentStateLeaseSchema(e, n, r);
if (a === r) {
ensureSessionAdditiveColumns(e);
ensureSessionEntryValidityProjection(e);
ensureSessionKeyContractSchemaInTransaction(e);
ensureSessionReactionsSchemaInTransaction(e);
if (hasPendingMemoryChunkMetadataMigration(e)) {
migrateMemoryChunkMetadataSchema(e);
e.exec(l);
}
repairCanonicalSqliteIndexes(e, n, l, {
verifyPhysicalIntegrity: false,
integrity: s ? d : void 0
});
if (a === 16) repairAndAssertOpenClawAgentV16Validity(e, n, l);
persistAgentSchemaMetadata(e, t, r);
assertAgentSchemaVersion(e, {
agentId: t,
pathname: n,
version: r
}, l);
assertAgentDatabaseMaintenanceAuthorityIfPresent();
return;
} else if (a === 14) repairAndAssertOpenClawAgentV14SchemaForMigration(e, {
agentId: t,
pathname: n
});
renewAgentDatabaseMaintenanceAuthorityIfPresent();
migrateMemoryIndexSourcesIdentity(e);
migrateOpenClawAgentSchema(e);
migrateConversationDeliveryTargetColumn(e);
if (a < 11) backfillSessionConversations(e);
migrateSessionNodesAndWindows(e, a);
renewAgentDatabaseMaintenanceAuthorityIfPresent();
ensureSessionAdditiveColumns(e);
if (r >= 18 && a < 18) migrateSessionParticipantsSchema(e, n);
if (r >= 19) migrateSessionCreatorNamespaces(e, a);
ensureSessionEntryValidityProjection(e);
renewAgentDatabaseMaintenanceAuthorityIfPresent();
e.exec(x);
if (a !== 17) migrateMemoryChunkMetadataSchema(e);
if (a < r) ensureOpenClawAgentBoardSchemaInTransaction(e);
migrateSessionTranscriptGenerations(e, a);
migrateSessionTranscriptActiveProjection(e, a);
if (a < 11) migrateSqliteSchemaToStrictInTransaction(e, x, {
databaseLabel: n,
integrityCheck: s
});
if (a < 21 && r >= 21 && !h) seedCanonicalSessionValidationPending(e);
finishStorageMigration();
};
runSqliteImmediateTransactionSync(e, mutate, {
databaseLabel: n,
operationLabel: "agent.schema.ensure",
withCommit: i
});
} finally {
if (e.isOpen) e.exec("PRAGMA foreign_keys = ON;");
}
if (u && (isSqliteSchemaAdmissionCold(e) || getAdmittedSqliteSchemaFacts(e))) {
admitSqliteSchema(e);
adoptCanonicalSessionValidationSchema(e);
}
for (const e of c) {
const n = `Agent ${t}: ${e}`;
agentDbLog.warn(n);
a?.(n);
}
}
/** Initialize agent schema/ownership metadata on an independently managed connection. */
function ensureOpenClawAgentDatabaseSchema(e, t) {
runSqliteIntegrityOperationSync(ensureOpenClawAgentDatabaseSchemaSteps(e, t));
}
/** Share one schema sequence between synchronous callers and leased maintenance. */
function* ensureOpenClawAgentDatabaseSchemaSteps(e, t) {
const n = normalizeAgentId(t.agentId);
const r = {
...t,
agentId: n
};
const i = e.location() ?? resolveOpenClawAgentSqlitePath(r);
if (!t.versionMigrationOnly) revokeSqliteDatabaseAdmissions(e);
assertExistingAgentSchemaOwner(readExistingAgentSchemaMeta(e), n, i);
const a = assertSupportedAgentSchemaVersion(e, i);
if (a < 38) assertSupportedAgentMigrationSchemas(e, i, a);
const o = r.register === true && isPersistentOpenClawAgentDatabasePath(i, r.env) ? prepareAgentDeletionPathFence({
agentId: n,
path: i
}, { env: r.env }, "maintenance") : void 0;
const withRegistrationFence = (e) => {
if (!o) return e();
return runOpenClawStateWriteTransaction((r) => {
const a = agentDatabaseMaintenanceAuthority.getStore()?.authority.holdWriteFence?.(r.db);
assertAgentDeletionRecoveryAllowsMutation(r, i);
assertAgentDeletionPathFence(r, o);
const s = e();
const c = a?.renew();
if (c) {
const e = `Agent ${n}: ${c}`;
agentDbLog.warn(e);
t.onMigrationWarning?.(e);
}
return s;
}, {
env: r.env,
initializationAgentPaths: [i]
});
};
withRegistrationFence(() => void 0);
if (e.location() && !t.versionMigrationOnly) invalidateOpenClawAgentDatabaseIntegrityBeforeMutation(i);
ensureOpenClawAgentDatabasePermissions(i, r);
setSqliteBusyTimeout(e, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS);
assertSupportedAgentSchemaVersion(e, i);
assertExistingAgentSchemaOwner(readExistingAgentSchemaMeta(e), n, i);
const withIntegrityMutation = (t) => o ? runSqliteImmediateTransactionSync(e, t, {
databaseLabel: i,
operationLabel: "agent.schema.integrity",
withCommit: withRegistrationFence
}) : t();
if (!t.versionMigrationOnly && readSqliteUserVersion(e) !== 17) {
const r = agentDatabaseIntegrityBeforeMutationSteps(e, n, i, void 0, void 0, false, false, t.integrityCheck);
try {
let e = withIntegrityMutation(() => r.next());
while (!e.done) {
let t;
try {
yield e.value;
} catch (e) {
t = { error: e };
}
e = withIntegrityMutation(() => t ? r.throw(t.error) : r.next());
}
} finally {
r.return(false);
}
}
configureSqlitePreSchemaPragmas(e, { busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS });
ensureAgentSchema(e, n, i, 38, withRegistrationFence, t.onMigrationWarning, t.versionMigrationOnly, t.integrityCheck);
if (t.versionMigrationOnly) return;
ensureOpenClawAgentDatabasePermissions(i, r);
const s = admitOpenClawAgentDatabaseSchema(e, {
agentId: n,
path: i
});
if (r.register === true) registerOpenClawAgentDatabase({
agentId: n,
path: i,
env: t.env,
admittedDb: s
});
}
//#endregion
export { admitOpenClawAgentDatabaseSchema as a, ensureOpenClawAgentDatabaseSchemaSteps as i, ensureAgentSchema as n, ensureOpenClawAgentDatabasePermissions as o, ensureOpenClawAgentDatabaseSchema as r, agentDatabaseIntegrityBeforeMutationSteps as t };