UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,277 lines • 57.3 kB
import { S as parseDateStringTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { t as safeParseJson } from "./json-coercion-CaJLaav-.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { _t as parseSqliteTableDefinition, pt as STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS, rt as OPENCLAW_STATE_SCHEMA_SQL } from "./sqlite-database-admission-DQIqro3d.mjs";
import { f as splitSqlList, l as quoteSqliteIdentifier, t as extractSqliteTableSchema } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { n as OPENCLAW_STATE_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as OpenClawStateOwnershipError } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { a as executeSqliteQueryTakeFirstSync, c as iterateSqliteQuerySync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { D as requireNativeDatabaseFile, v as readSqliteSchemaObjects } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists, c as SqliteSchemaMismatchError, n as ensureColumn, o as tableHasColumn, t as classifySqliteTableReadError } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { a as LAZY_ADDITIVE_STATE_INDEXES, i as FIRST_USE_STATE_TABLES, n as DOCTOR_OWNED_STATE_TABLES, o as LAZY_ADDITIVE_STATE_TABLES, r as FIRST_USE_STATE_INDEXES, s as MEETING_TRANSCRIPT_START_TIME_SCHEMA_VERSION, t as CLIENT_CREDENTIAL_CUTOVER_SCHEMA_VERSION } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { i as getStateSchemaVersionAdmission, r as getStateRuntimeSchemaAdmission, s as publishStateSchemaVersionAdmission, t as adoptPeerPublishedStateSchemaVersion } from "./openclaw-state-db-admission-Bw1Mtc4x.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { t as LEGACY_SKILL_WORKSHOP_COLLECTION_REVIEWS_INDEX } from "./openclaw-state-db-schema-migration-required-D2P85VUd.mjs";
import { S as jsonValid, h as jsonPathValue } from "./json-values-DVAB74RK.mjs";
import { l as stateCronIdentityMigration } from "./openclaw-state-db-cron-identity-migration-XoyKZWfG.mjs";
import { i as assertSqliteTableIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs";
import { c as runUpdateSqliteMigration } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs";
import { t as createSqliteTableContractReader } from "./sqlite-schema-catalog-BK5o5Jvf.mjs";
import { a as withLegacyTemplateStateCompatibility, c as CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS, d as needsPublicationDraftMigration, f as statePublicationDraftMigration, i as stateTemplateNamesMigration, l as CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS, o as withLegacyTemplateStateSchema, s as CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS, u as ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS } from "./openclaw-state-db-schema-v36-template-names-D8yHNQrP.mjs";
import { b as withLegacyLocalWorkspaceCas, f as readStateSchemaPublicationBlocker, g as withLegacyLocalWorkspaceManifests, h as stateLocalWorkspaceManifestMigration, p as resolveStateSchemaVersionToPublish, y as stateLocalWorkspaceCasMigration } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { i as assertSupportedStateSchemaVersion, o as readStateSchemaContentVersion } from "./openclaw-state-db-schema-version-uNbDFl6T.mjs";
import { a as getCanonicalSqliteNamedIndexContracts, i as collectSqliteSchemaIssues, n as assertSqliteSchemaTablesPresent, o as getCanonicalSqliteNamedIndexNames, t as assertSqliteSchemaContains } from "./sqlite-schema-contract-D3pR9vZs.mjs";
import { n as readWorkerPreparation } from "./preparation-identity.schema-g-tn5wja.mjs";
import { i as CLIENT_CREDENTIAL_SOURCE_TABLES } from "./client-credential-schema-DsmkD6RV.mjs";
import { r as withSqliteWritableSchema, t as hasDanglingSkillWorkshopCollectionReviewIndex } from "./openclaw-state-db-doctor-schema-C5bP-XwE.mjs";
import { n as prepareSqliteAuditRecord, t as createSqliteAuditRecordKernel } from "./sqlite-audit-record.kernel-DDF1lZnZ.mjs";
import { s as repairLegacySubagentRetainedResults } from "./openclaw-state-db-legacy-backfills-4EIWKKJD.mjs";
import { n as migratePortableIdentityColumnsV22, t as STATE_CURSOR_TABLES_V22 } from "./openclaw-state-db-schema-v22-columns-4T-BGc1o.mjs";
import { t as migrateSqliteTableWithoutRowid } from "./sqlite-table-layout-migration-CjG-AGzz.mjs";
import { n as assertOpenClawStateWriteAllowed } from "./openclaw-state-ownership-Wv4JBQVJ.mjs";
import { t as UpdateSchemaRefusalError } from "./openclaw-update-schema-refusal-DQDN1MLl.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import { createHash } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
//#region src/state/openclaw-state-db-image-snapshot-migration.ts
function historicalImageQuery(e) {
	return getNodeSqliteKysely(e).selectFrom("worker_environments").select(["environment_id", "profile_snapshot_json"]).where((t) => t(jsonValid(e, t.ref("profile_snapshot_json")), "=", 1)).where((t) => t(jsonPathValue(e, t.ref("profile_snapshot_json"), t.val("$.project.kind")), "=", "image"));
}
function hasHistoricalImageReserveSnapshots(e) {
	return tableExists(e, "worker_environments") && executeSqliteQueryTakeFirstSync(e, historicalImageQuery(e).limit(1)) !== void 0;
}
/** Doctor owns this data cutover even when an earlier import already published schema 22. */
function migrateHistoricalImageReserveSnapshots(e) {
	if (!tableExists(e, "worker_environments")) return [];
	const t = executeSqliteQuerySync(e, historicalImageQuery(e)).rows;
	for (const n of t) {
		if (typeof n.profile_snapshot_json !== "string" || typeof n.environment_id !== "string") throw new Error("Historical image reserve row is invalid");
		const t = JSON.parse(n.profile_snapshot_json);
		const r = isRecord(t) ? t.project : void 0;
		if (!isRecord(t) || !isRecord(r) || r.kind !== "image" || typeof r.key !== "string" || !/^[a-f0-9]{64}$/u.test(r.key) || !isRecord(r.preparation) || t.runtimePreparation !== void 0 || t.historicalProfileSnapshotJson !== void 0) throw new Error("Historical image reserve snapshot has conflicting or invalid preparation");
		t.runtimePreparation = {
			...r.preparation,
			source: "empty"
		};
		delete t.project;
		readWorkerPreparation(t);
		t.historicalProfileSnapshotJson = n.profile_snapshot_json;
		executeSqliteQuerySync(e, getNodeSqliteKysely(e).updateTable("worker_environments").set({ profile_snapshot_json: JSON.stringify(t) }).where("environment_id", "=", n.environment_id));
	}
	return t.length > 0 ? ["Migrated historical image reserves with original snapshot evidence retained"] : [];
}
//#endregion
//#region src/state/openclaw-state-db-cron-delivery-migration.ts
/** Absence of old delivery evidence cannot prove that a completion was never sent. */
function migrateCronDeliveryAttemptState(e, t) {
	return t < 20 && tableExists(e, "cron_run_receipts") ? ensureColumn(e, "cron_run_receipts", "delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started'))") : false;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v21-columns.ts
const statePredicateColumnMigration = {
	version: 21,
	tables: [
		"meeting_transcript_sessions",
		"meeting_transcript_summaries",
		"delivery_queue_entries"
	],
	columns: [
		...[
			"source_account_id",
			"source_guild_id",
			"source_channel_id",
			"source_meeting_url",
			"source_thread_ts",
			"source_file_id",
			"metadata_agent_id"
		].map((e) => `meeting_transcript_sessions.${e}`),
		"meeting_transcript_summaries.overview",
		"delivery_queue_entries.retention_id_prefix",
		"delivery_queue_entries.retention_max_age_ms",
		"delivery_queue_entries.retention_max_entries"
	],
	migrate: migratePredicateColumnsV21,
	applied: "Derived meeting transcript selectors and bounded delivery retention columns (v21)"
};
/** Complete the derived projection before any writer or column-only reader runs. */
function migratePredicateColumnsV21(e, t) {
	const n = t === 21 && statePredicateColumnMigration.columns.some((t) => {
		const n = t.indexOf(".");
		const r = t.slice(0, n);
		return tableExists(e, r) && !tableHasColumn(e, r, t.slice(n + 1));
	});
	if (t >= 21 && !n) return false;
	let r = false;
	const text = (e, t) => `CASE WHEN json_valid(${e}) THEN CASE WHEN json_type(${e}, '${t}') = 'text' THEN json_extract(${e}, '${t}') END END`;
	if (tableExists(e, "meeting_transcript_sessions")) {
		const t = [
			"accountId",
			"guildId",
			"channelId",
			"meetingUrl",
			"threadTs",
			"fileId"
		];
		const n = [
			"source_account_id",
			"source_guild_id",
			"source_channel_id",
			"source_meeting_url",
			"source_thread_ts",
			"source_file_id"
		];
		for (const t of [...n, "metadata_agent_id"]) r = ensureColumn(e, "meeting_transcript_sessions", `${t} TEXT`) || r;
		e.exec(`UPDATE meeting_transcript_sessions SET
      ${n.map((e, n) => `${e} = ${text("source_json", `$.${t[n]}`)}`).join(",")},
      metadata_agent_id = ${text("metadata_json", "$.agentId")}`);
	}
	if (tableExists(e, "meeting_transcript_summaries")) {
		r = ensureColumn(e, "meeting_transcript_summaries", "overview TEXT") || r;
		e.exec(`UPDATE meeting_transcript_summaries SET overview = ${text("summary_json", "$.overview")}`);
	}
	if (tableExists(e, "delivery_queue_entries")) {
		r = ensureColumn(e, "delivery_queue_entries", "retention_id_prefix TEXT") || r;
		r = ensureColumn(e, "delivery_queue_entries", "retention_max_age_ms INTEGER") || r;
		r = ensureColumn(e, "delivery_queue_entries", "retention_max_entries INTEGER") || r;
		e.exec(`UPDATE delivery_queue_entries SET
      (retention_id_prefix, retention_max_age_ms, retention_max_entries) = (
        SELECT id_prefix, max_age_ms, max_entries FROM (
          SELECT json_extract(entry_json, '$.completionRetention.idPrefix') id_prefix,
            json_extract(entry_json, '$.completionRetention.maxAgeMs') max_age_ms,
            json_extract(entry_json, '$.completionRetention.maxEntries') max_entries
          WHERE json_valid(entry_json)
            AND json_type(entry_json, '$.completionRetention') = 'object'
        ) WHERE typeof(id_prefix) = 'text' AND id_prefix <> ''
          AND substr(id, 1, length(id_prefix)) = id_prefix
          AND typeof(max_age_ms) = 'integer' AND max_age_ms BETWEEN 1 AND 9007199254740991
          AND typeof(max_entries) = 'integer' AND max_entries BETWEEN 1 AND 9007199254740991
      )`);
	}
	return r;
}
//#endregion
//#region src/state/openclaw-state-db-historical-imports.ts
const table = "worker_session_placements";
const archivalColumn = "repository_preparation TEXT";
/** Only the recognized historical contract may surrender its incomplete-preparation exception. */
function migrateHistoricalRepositoryPreparation(e) {
	if (!tableHasColumn(e, table, "repository_preparation")) return false;
	const t = extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, table).replace("  remote_workspace_dir TEXT,", "  " + archivalColumn + ",\n  remote_workspace_dir TEXT,");
	const n = createSqliteTableContractReader(e)(table);
	const r = parseSqliteTableDefinition(t, table);
	if (n?.strict === 1 && n.withoutRowid === 0 && isDeepStrictEqual(n.definition, r)) return false;
	const i = t.replace(archivalColumn + ",", archivalColumn + " CHECK (repository_preparation IN ('pending', 'ready', 'failed')),").replace("  CHECK (\n    (state IN", "  CHECK (repository_preparation IS NULL OR (repository_preparation = 'ready' AND workspace_base_manifest_ref IS NOT NULL) OR (repository_preparation = 'failed' AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed')) OR (repository_preparation = 'pending' AND workspace_base_manifest_ref IS NULL AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),\n  CHECK (\n    (state IN").replaceAll("AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir", "AND (workspace_base_manifest_ref IS NOT NULL OR repository_preparation IS 'pending' OR repository_preparation IS 'failed') AND remote_workspace_dir");
	if (!n || n.strict !== 1 || n.withoutRowid !== 0 || !isDeepStrictEqual(n.definition, parseSqliteTableDefinition(i, table))) throw new Error("Unrecognized historical worker placement schema; preserve the store for explicit recovery.");
	if (e.prepare("SELECT 1 FROM worker_session_placements WHERE repository_preparation IN ('pending', 'failed') AND turn_claim_owner = 'worker' LIMIT 1").get()) throw new Error("Historical repository preparation retains a worker turn claim; reconcile its owned cleanup before migrating.");
	const a = readSqliteSchemaObjects(e).filter((e) => e.tbl_name === table && (e.type === "index" || e.type === "trigger") && e.sql !== null);
	const o = n.columns.map((e) => e.name);
	const s = o.map((e) => {
		if (e === "state") return "CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'failed' ELSE state END";
		if (e === "recovery_error") return "CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'Historical repository preparation ' || repository_preparation || ' (previous placement ' || state || '); owned cleanup required before recovery.' || CASE WHEN recovery_error IS NULL THEN '' ELSE ' ' || recovery_error END ELSE recovery_error END";
		return quoteSqliteIdentifier(e);
	});
	e.exec(t.replace("CREATE TABLE IF NOT EXISTS " + table, "CREATE TABLE worker_session_placements_historical_migration") + " INSERT INTO worker_session_placements_historical_migration (rowid, " + o.map(quoteSqliteIdentifier).join(", ") + ") SELECT rowid, " + s.join(", ") + " FROM worker_session_placements; DROP TABLE worker_session_placements; ALTER TABLE worker_session_placements_historical_migration RENAME TO worker_session_placements;");
	for (const t of a) {
		if (typeof t.sql !== "string") throw new Error("Historical worker placement schema object is invalid");
		e.exec(t.sql);
	}
	return true;
}
/** Both bounded version publication and full Doctor repair retain the same historical owners. */
function migrateHistoricalStateImports(e, t, n = "version") {
	if (n === "version" && t > 22) return [];
	const r = [];
	const i = t === 21 && migrateHistoricalRepositoryPreparation(e);
	if (i) r.push("Preserved historical worker placement evidence and fenced incomplete repository preparation");
	if ((t === 21 || i) && migratePredicateColumnsV21(e, 21)) r.push(statePredicateColumnMigration.applied);
	if (n === "doctor" || t <= 22) r.push(...migrateHistoricalImageReserveSnapshots(e));
	return r;
}
//#endregion
//#region src/state/openclaw-state-db-index-ordering-migrations.ts
const stateIndexOrderingMigrations = [{
	version: 32,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Aligned PostgreSQL non-null index ordering (v32)"
}, {
	version: 33,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Aligned PostgreSQL partial-index ordering (v33)"
}];
//#endregion
//#region src/state/openclaw-state-db-meeting-chronology-migration.ts
/** The caller owns the schema transaction; legacy local dates freeze its timezone once. */
function migrateMeetingTranscriptStartTime(e, t) {
	if (t >= 23 || !tableExists(e, "meeting_transcript_sessions")) return false;
	let n = ensureColumn(e, "meeting_transcript_sessions", "started_at_ms INTEGER");
	const r = iterateSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("meeting_transcript_sessions").select(["session_id", "started_at"]));
	const i = e.prepare("UPDATE meeting_transcript_sessions SET started_at_ms = ? WHERE session_id = ? AND started_at = ?");
	for (const e of r) {
		i.run(parseDateStringTimestampMs(e.started_at) ?? null, e.session_id, e.started_at);
		n = true;
	}
	return n;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v13-widerow.ts
const FAILURE_DESTINATION_COLUMNS = [
	["failure_delivery_mode", "mode"],
	["failure_delivery_channel", "channel"],
	["failure_delivery_to", "to"],
	["failure_delivery_account_id", "accountId"]
];
function reprojectLegacyCronJson(e) {
	const t = FAILURE_DESTINATION_COLUMNS.map(([t]) => tableHasColumn(e, "cron_jobs", t) ? quoteSqliteIdentifier(t) : `NULL AS ${quoteSqliteIdentifier(t)}`);
	const n = tableHasColumn(e, "cron_jobs", "last_run_status") ? "last_run_status" : "NULL AS last_run_status";
	const r = e.prepare(`SELECT store_key, job_id, enabled, job_json, state_json, ${n}, ${t.join(", ")}
         FROM cron_jobs`).all();
	const i = e.prepare("UPDATE cron_jobs SET job_json = ?, state_json = ? WHERE store_key = ? AND job_id = ?");
	for (const e of r) {
		if (typeof e.store_key !== "string" || typeof e.job_id !== "string" || typeof e.job_json !== "string" || typeof e.state_json !== "string") throw new Error("OpenClaw v12 cron job row is not canonical");
		const t = asNullableRecord(safeParseJson(e.job_json));
		const n = asNullableRecord(safeParseJson(e.state_json));
		if (!t || !n) continue;
		let r = false;
		const a = asNullableRecord(t.delivery);
		const o = asNullableRecord(a?.failureDestination);
		if ((!Object.hasOwn(t, "delivery") || a !== null) && (!a || !Object.hasOwn(a, "failureDestination") || o !== null)) {
			const n = a ?? {};
			const i = o ?? {};
			for (const [t, n] of FAILURE_DESTINATION_COLUMNS) {
				const a = e[t];
				if (typeof a !== "string" || Object.hasOwn(i, n)) continue;
				i[n] = a === "" ? null : a;
				r = true;
			}
			if (r) {
				n.failureDestination = i;
				t.delivery = n;
			}
		}
		if (typeof t.enabled !== "boolean") {
			t.enabled = e.enabled !== 0;
			r = true;
		}
		const s = Object.hasOwn(n, "lastStatus");
		if (!Object.hasOwn(n, "lastRunStatus") && (s || typeof e.last_run_status === "string")) {
			n.lastRunStatus = s ? n.lastStatus : e.last_run_status;
			r = true;
		}
		if (r) i.run(JSON.stringify(t), JSON.stringify(n), e.store_key, e.job_id);
	}
}
function rebuildJsonCanonicalTable(e, t) {
	const n = `${t}_migration_v13`;
	if (tableExists(e, n)) throw new Error(`OpenClaw v13 migration table already exists: ${n}`);
	const r = extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, t, { errorMessage: `Canonical ${t} schema block is missing` }).replace(`CREATE TABLE IF NOT EXISTS ${t} (`, `CREATE TABLE ${n} (`);
	e.exec(r);
	const i = e.prepare(`PRAGMA table_xinfo(${n})`).all().flatMap((e) => e.hidden === 0 && typeof e.name === "string" ? [e.name] : []);
	const a = i.map((n) => {
		return CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS.some((e) => e.tableName === t && e.columnName === n) && !tableHasColumn(e, t, n) ? "NULL" : quoteSqliteIdentifier(n);
	});
	e.exec(`INSERT INTO ${n} (${i.map(quoteSqliteIdentifier).join(", ")}) SELECT ${a.join(", ")} FROM ${t};`);
	e.exec(`DROP TABLE ${t};`);
	e.exec(`ALTER TABLE ${n} RENAME TO ${t};`);
}
/** Fold obsolete physical projections into canonical JSON before removing their columns. */
function migrateJsonCanonicalWideRowsV13(e, t) {
	if (t >= 13) return false;
	let n = false;
	if (tableExists(e, "cron_jobs") && tableHasColumn(e, "cron_jobs", "schedule_kind")) {
		reprojectLegacyCronJson(e);
		rebuildJsonCanonicalTable(e, "cron_jobs");
		n = true;
	}
	const r = tableExists(e, "workspace_setup_state");
	const i = tableExists(e, "workspace_attestations");
	if (r && !tableHasColumn(e, "workspace_setup_state", "attested_at_ms")) {
		e.exec("ALTER TABLE workspace_setup_state ADD COLUMN attested_at_ms INTEGER;");
		e.exec("ALTER TABLE workspace_setup_state ADD COLUMN attestation_updated_at_ms INTEGER;");
		rebuildJsonCanonicalTable(e, "workspace_setup_state");
		n = true;
	}
	if (i) {
		e.exec(`
      UPDATE workspace_setup_state
         SET attested_at_ms = (
               SELECT attested_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             ),
             attestation_updated_at_ms = (
               SELECT updated_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             )
       WHERE workspace_key IN (SELECT workspace_key FROM workspace_attestations);
    `);
		const t = tableExists(e, "workspace_path_aliases") ? `(SELECT alias.workspace_path FROM workspace_path_aliases alias
           WHERE alias.workspace_key = a.workspace_key LIMIT 1)` : "NULL";
		e.exec(`
      INSERT INTO workspace_setup_state (
        workspace_key, workspace_path, attested_at_ms, attestation_updated_at_ms
      )
      SELECT a.workspace_key,
             ${t},
             a.attested_at_ms,
             a.updated_at_ms
        FROM workspace_attestations a
       WHERE a.workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `);
		e.exec("DROP TABLE workspace_attestations;");
		n = true;
	}
	if ((r || i) && tableExists(e, "workspace_generated_bootstrap_hashes")) {
		rebuildJsonCanonicalTable(e, "workspace_generated_bootstrap_hashes");
		e.exec(`
      DELETE FROM workspace_generated_bootstrap_hashes
       WHERE workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `);
	}
	for (const [t, r, i] of [[
		"auth_profile_stores",
		"store_json",
		"authProfiles.store"
	], [
		"auth_profile_state",
		"state_json",
		"authProfiles.state"
	]]) {
		if (!tableExists(e, t)) continue;
		e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
       SELECT ?, ${r}, updated_at FROM ${t} WHERE store_key = 'shared'
       ON CONFLICT(state_key) DO NOTHING`).run(i);
		e.exec(`DROP TABLE ${t};`);
		n = true;
	}
	if (tableExists(e, "installed_plugin_index")) {
		const t = e.prepare("SELECT * FROM installed_plugin_index WHERE index_key = 'installed-plugin-index'").get();
		if (t) {
			const n = asNullableRecord(safeParseJson(String(t.install_records_json)));
			const r = safeParseJson(String(t.plugins_json));
			const i = safeParseJson(String(t.diagnostics_json));
			if (!n || !Array.isArray(r) || !Array.isArray(i)) {
				const n = "plugins.installedIndex.quarantine";
				const r = `Preserved invalid legacy installed_plugin_index row in diagnostic_events (${n}). Run openclaw doctor --fix or openclaw plugins registry --refresh to repair the plugin index; inspect the preserved row if install records need recovery.`;
				createSqliteAuditRecordKernel(e, {
					scope: n,
					maxEntries: Number.MAX_SAFE_INTEGER
				}).register(prepareSqliteAuditRecord(n, {
					key: createHash("sha256").update(JSON.stringify(t)).digest("hex"),
					value: {
						level: "warn",
						message: r,
						raw: t
					},
					createdAt: Date.now()
				}));
				deferSqlitePostCommitPublication(e, () => createSubsystemLogger("state/db").warn(r));
			}
			const a = {
				version: Number(t.version),
				...typeof t.warning === "string" && t.warning ? { warning: t.warning } : {},
				hostContractVersion: t.host_contract_version,
				compatRegistryVersion: t.compat_registry_version,
				migrationVersion: Number(t.migration_version),
				policyHash: t.policy_hash,
				generatedAtMs: Number(t.generated_at_ms),
				...typeof t.workspace_dir === "string" ? { workspaceDir: t.workspace_dir } : {},
				...typeof t.refresh_reason === "string" && t.refresh_reason ? { refreshReason: t.refresh_reason } : {},
				installRecords: n,
				plugins: r,
				diagnostics: i
			};
			e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
         VALUES (?, ?, ?) ON CONFLICT(state_key) DO NOTHING`).run("plugins.installedIndex", JSON.stringify({
				revision: Number(t.updated_at_ms),
				index: a
			}), Number(t.updated_at_ms));
		}
		e.exec("DROP TABLE installed_plugin_index;");
		n = true;
	}
	if (tableExists(e, "subagent_runs") && tableHasColumn(e, "subagent_runs", "task")) {
		repairLegacySubagentRetainedResults(e);
		rebuildJsonCanonicalTable(e, "subagent_runs");
		n = true;
	}
	return n;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v24-indexes.ts
const TASK_RUN_INDEX_RETIREMENT_V24_SQL = `
    DROP INDEX IF EXISTS idx_task_runs_run_id;
    DROP INDEX IF EXISTS idx_task_runs_status;
    DROP INDEX IF EXISTS idx_task_runs_runtime_status;
    DROP INDEX IF EXISTS idx_task_runs_cleanup_after;
    DROP INDEX IF EXISTS idx_task_runs_last_event_at;
    DROP INDEX IF EXISTS idx_task_runs_owner_key;
    DROP INDEX IF EXISTS idx_task_runs_parent_flow_id;
    DROP INDEX IF EXISTS idx_task_runs_child_session_key;
    DROP INDEX IF EXISTS idx_task_runs_requester_session_key;
    DROP INDEX IF EXISTS idx_task_runs_runtime_source_ended;
    DROP INDEX IF EXISTS idx_task_runs_runtime_ended;
`;
/** Canonical DDL installs the replacement indexes in the same migration transaction. */
function migrateTaskRunIndexesV24(e, t) {
	if (t >= 24) return false;
	e.exec(TASK_RUN_INDEX_RETIREMENT_V24_SQL);
	return true;
}
//#endregion
//#region src/state/openclaw-state-db-schema-v26-layout.ts
/** Historical admission compares the physical layout installed before v26. */
function withLegacyStateHeadLayout(e) {
	return e.replace(/(CREATE TABLE IF NOT EXISTS session_state_heads \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u, "$1;");
}
function migrateSessionStateHeadLayoutV26(e, t) {
	return t < 26 && migrateSqliteTableWithoutRowid(e, "session_state_heads");
}
//#endregion
//#region src/state/openclaw-state-db-schema-v27-indexes.ts
/** Exact historical indexes used by source admission and the PostgreSQL generator. */
function withLegacyStateWriteIndexes(e) {
	return `${e.replace(/ON state_leases\(owner\);/u, "ON state_leases(owner, updated_at DESC);")}
CREATE INDEX IF NOT EXISTS idx_skill_usage_key
  ON skill_usage(skill_key, skill_file);
CREATE INDEX IF NOT EXISTS idx_acp_replay_events_session_seq
  ON acp_replay_events(session_id, seq);
`;
}
const STATE_WRITE_INDEX_RETIREMENT_V27_SQL = `
  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;
  DROP INDEX IF EXISTS idx_skill_usage_key;
  DROP INDEX IF EXISTS idx_state_leases_owner;
`;
function migrateStateWriteIndexesV27(e, t) {
	if (t >= 27) return false;
	e.exec(STATE_WRITE_INDEX_RETIREMENT_V27_SQL);
	return true;
}
//#endregion
//#region src/state/openclaw-state-schema-runtime.ts
const runtimeSchemaCache = /* @__PURE__ */ new Map();
/** Project canonical SQL to the tables the shared runtime may create during this open. */
function getOpenClawStateRuntimeSchema(e) {
	const { includeVersionLazyAdditiveTables: t, includeAgentDeletionJournal: n = true } = e;
	const r = `${t}:${n}`;
	const i = runtimeSchemaCache.get(r);
	if (i !== void 0) return i;
	let a = OPENCLAW_STATE_SCHEMA_SQL;
	const o = [...t ? FIRST_USE_STATE_TABLES : LAZY_ADDITIVE_STATE_TABLES, ...n ? [] : DOCTOR_OWNED_STATE_TABLES];
	const s = t ? FIRST_USE_STATE_INDEXES : LAZY_ADDITIVE_STATE_INDEXES;
	for (const e of o) a = a.replace(extractSqliteTableSchema(a, e, { errorMessage: `lazy additive state schema block is missing for ${e}` }), "");
	for (const e of s) {
		const t = a.indexOf(`CREATE INDEX IF NOT EXISTS ${e}`);
		const n = a.indexOf(`CREATE UNIQUE INDEX IF NOT EXISTS ${e}`);
		const r = t >= 0 ? t : n;
		const i = r >= 0 ? a.indexOf(";", r) : -1;
		if (r < 0 || i < 0) throw new Error(`lazy additive state schema index is missing for ${e}`);
		a = `${a.slice(0, r)}${a.slice(i + 1)}`;
	}
	runtimeSchemaCache.set(r, a);
	return a;
}
//#endregion
//#region src/state/openclaw-state-schema-compatibility.ts
const STATE_V6_ADDITIVE_TABLES = [
	...LAZY_ADDITIVE_STATE_TABLES,
	"worker_session_tool_operations",
	"worker_turn_tool_authorities"
];
const STATE_V5_ADDITIVE_TABLES = [
	"agent_database_leases",
	"agent_deletion_journal",
	"claw_cron_refs",
	"claw_installs",
	"claw_mcp_server_refs",
	"claw_package_refs",
	"claw_workspace_files",
	"config_machine_state",
	"cron_job_scratch",
	"meeting_transcript_sessions",
	"meeting_transcript_summaries",
	"meeting_transcript_utterances",
	"outbound_media_provenance",
	"worker_environment_credentials",
	"worker_transcript_commit_heads",
	"worker_transcript_commits",
	...STATE_V6_ADDITIVE_TABLES
];
const CLAW_LAZY_ADDITIVE_STATE_COLUMNS = CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`);
const CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS = CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`);
const CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_SET = new Set(CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS);
const CLAW_STARTUP_ADDITIVE_STATE_COLUMN_SET = /* @__PURE__ */ new Set([...CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName: e, tableName: t }) => `${t}.${e}`), ...Object.values(ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS).flat().map(([e, t]) => `${e}.${t.split(" ", 1)[0]}`)]);
const CLAW_STARTUP_ADDITIVE_STATE_TABLES = ["worker_session_tool_operations", "worker_turn_tool_authorities"];
const CLAW_STARTUP_ADDITIVE_STATE_TABLE_SET = new Set(CLAW_STARTUP_ADDITIVE_STATE_TABLES);
const CLAW_READONLY_OPTIONAL_STATE_INDEXES = [
	"idx_meeting_transcript_utterances_id",
	"idx_operator_approvals_source_run_resolved",
	"idx_worker_session_placements_environment"
];
let openClawStateCanonicalNamedIndexSet;
function getOpenClawStateCanonicalNamedIndexSet() {
	openClawStateCanonicalNamedIndexSet ??= new Set(getCanonicalSqliteNamedIndexNames(OPENCLAW_STATE_SCHEMA_SQL));
	return openClawStateCanonicalNamedIndexSet;
}
const RETAINED_STATE_TABLES = ["fleet_cells"];
const STATE_PERSISTENT_SCHEMA_COMPATIBILITY = {
	excludedTables: RETAINED_STATE_TABLES,
	allowCompatibleAdditiveColumns: true,
	allowedMissingTables: DOCTOR_OWNED_STATE_TABLES,
	allowedMissingColumns: CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS,
	allowedColumnDefinitions: {
		"diagnostic_events.sequence": ["sequence INTEGER NOT NULL DEFAULT 0"],
		"template_package_refs.package_integrity": ["package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'"],
		"template_package_refs.updated_at_ms": ["updated_at_ms INTEGER NOT NULL DEFAULT 0"],
		"cron_jobs.enabled": ["enabled INTEGER NOT NULL DEFAULT 1"],
		"cron_jobs.name": ["name TEXT NOT NULL DEFAULT ''"],
		"cron_jobs.payload_kind": ["payload_kind TEXT NOT NULL DEFAULT 'message'"],
		"current_conversation_bindings.conversation_kind": ["conversation_kind TEXT NOT NULL DEFAULT 'channel'"],
		"operator_approvals.resolution_ref": ["resolution_ref TEXT"],
		"worker_environments.desktop_json": ["desktop_json TEXT"],
		"worker_environments.bootstrap_install_kind": ["bootstrap_install_kind TEXT"],
		"worker_environments.shared_host": ["shared_host INTEGER CHECK (shared_host IN (0, 1))"],
		"worker_environments.node_setup_id": ["node_setup_id TEXT"],
		"worker_environments.node_device_id": ["node_device_id TEXT"],
		"worker_session_placements.terminal_reason": ["terminal_reason TEXT"],
		"worker_session_placements.terminal_at_ms": ["terminal_at_ms INTEGER"]
	}
};
const STATE_RUNTIME_SCHEMA_COMPATIBILITY = {
	...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
	excludedTables: [...RETAINED_STATE_TABLES, ...LAZY_ADDITIVE_STATE_TABLES],
	excludedIndexes: LAZY_ADDITIVE_STATE_INDEXES
};
/** Both cold admission and bounded upgrade selection require these present-table columns. */
function findMissingLazyStateStartupColumn(e) {
	for (const { tableName: t, columnName: n } of CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS) {
		if (!STATE_RUNTIME_SCHEMA_COMPATIBILITY.excludedTables?.includes(t)) continue;
		const r = e(t);
		if (r && !r.columns.some((e) => e.name === n)) return {
			tableName: t,
			columnName: n
		};
	}
}
const OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY = {
	...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
	allowedMissingTables: [
		...LAZY_ADDITIVE_STATE_TABLES,
		...CLAW_STARTUP_ADDITIVE_STATE_TABLES,
		...DOCTOR_OWNED_STATE_TABLES
	],
	allowedMissingIndexes: CLAW_READONLY_OPTIONAL_STATE_INDEXES,
	allowedMissingColumns: CLAW_LAZY_ADDITIVE_STATE_COLUMNS
};
/** Identify schema differences that the writable shared-state cold open repairs. */
function isOpenClawStateStartupRepairableSchemaIssue(e) {
	if (e.code === "missing-table") return CLAW_STARTUP_ADDITIVE_STATE_TABLE_SET.has(e.objectName);
	if (e.code === "missing-column") return CLAW_STARTUP_ADDITIVE_STATE_COLUMN_SET.has(e.objectName);
	return e.code === "missing-or-drifted-index" && getOpenClawStateCanonicalNamedIndexSet().has(e.objectName);
}
/** Identify compatible schema differences repaired only by their feature owner. */
function isOpenClawStateFirstUseSchemaIssue(e) {
	return e.code === "missing-column" && CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_SET.has(e.objectName);
}
//#endregion
//#region src/state/schema-migration-backup-tables.ts
/** Destination versions, declared only with proof through the complete migration runner. */
const SCHEMA_MIGRATION_BACKUP_TABLES = {
	agent: {
		[30]: [
			"trajectory_runtime_events",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		27: [
			"context_engine_turn_outbox",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		28: [
			"transcript_event_identities",
			"session_windows",
			"memory_entry_origins",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		29: [
			"session_nodes",
			"session_reactions",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		31: ["memory_index_sources", "memory_index_chunks"],
		32: [],
		33: [],
		34: [],
		35: [],
		36: [],
		37: ["session_transcript_cold_archive_chunks"],
		38: []
	},
	state: {
		[29]: [
			...CLIENT_CREDENTIAL_SOURCE_TABLES,
			"sqlite_stat1",
			"sqlite_stat4"
		],
		[23]: ["meeting_transcript_sessions", "worker_environments"],
		26: [
			"session_state_heads",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		27: [
			"acp_replay_events",
			"skill_usage",
			"state_leases",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		28: [
			"github_publication_requests",
			"github_personal_publication_requests",
			"github_repository_publication_requests"
		],
		30: [],
		31: [
			"local_workspace_projections",
			"local_workspace_manifest_nodes",
			"sqlite_stat1",
			"sqlite_stat4"
		],
		32: [],
		33: [],
		34: ["config_machine_state"],
		35: [
			"local_workspace_projections",
			"local_workspace_manifest_nodes",
			"local_workspace_tree_packs",
			"local_workspace_source_path_sets"
		],
		36: [
			"claw_installs",
			"template_installs",
			"claw_workspace_files",
			"template_workspace_files",
			"claw_package_refs",
			"template_package_refs",
			"claw_cron_refs",
			"template_cron_refs",
			"claw_mcp_server_refs",
			"template_mcp_server_refs",
			"agent_provenance",
			"sqlite_stat1",
			"sqlite_stat4"
		]
	}
};
//#endregion
//#region src/state/schema-migration-integrity-tables.ts
const indexStatistics = ["sqlite_stat1", "sqlite_stat4"];
const SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES = {
	agent: [
		"auth_profile_store",
		"auth_profile_state",
		"session_nodes",
		"session_entry_snapshots",
		"session_windows",
		"session_key_contract",
		"session_canonical_validation_pending",
		"memory_index_chunks",
		"memory_index_chunk_recall_metadata",
		"memory_index_chunk_provenance",
		"memory_index_sources",
		"memory_index_paths_fts",
		"memory_index_state",
		...indexStatistics
	],
	state: [
		...CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ tableName: e }) => e),
		...Object.values(ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS).flatMap((e) => e.map(([e]) => e)),
		"audit_events",
		"audit_identity_keys",
		"operator_approvals",
		"session_watch_cursors",
		"subagent_runs",
		"worker_session_placements",
		"meeting_transcript_sessions",
		"meeting_transcript_summaries",
		"delivery_queue_entries",
		"worker_turn_tool_authorities",
		"worker_session_tool_operations",
		"migration_runs",
		"sqlite_sequence",
		...indexStatistics
	]
};
const migrationTables = {
	agent: {
		...SCHEMA_MIGRATION_BACKUP_TABLES.agent,
		10: ["session_transcript_active_events", "session_transcript_index_state"],
		11: [
			"sessions",
			"conversations",
			"session_conversations"
		],
		13: ["transcript_rewrite_watermarks"],
		14: [
			"sessions",
			"session_entries",
			"session_routes",
			"session_nodes",
			"session_windows",
			"session_transcript_generations",
			"transcript_rewrite_watermarks",
			"board_tabs",
			"board_widgets",
			"heartbeat_outcomes",
			"session_members",
			"session_transcript_index_state"
		],
		17: ["state_leases"],
		18: ["session_participants"],
		19: ["session_nodes"],
		21: ["session_key_contract", "session_canonical_validation_pending"],
		22: ["session_transcript_fts_rows"],
		23: [
			"transcript_events",
			"session_transcript_fts",
			"session_transcript_fts_rows",
			"session_transcript_index_state",
			"memory_index_sources",
			"memory_index_chunks",
			"memory_index_chunks_fts",
			"memory_index_chunk_recall_metadata",
			"memory_embedding_cache",
			"memory_index_meta",
			"memory_index_state",
			"cache_entries"
		],
		24: ["session_nodes", "session_entry_snapshots"],
		25: [
			"session_pending_inputs",
			"session_nodes",
			"session_windows",
			"session_key_contract",
			"session_canonical_validation_pending"
		],
		26: [
			"session_nodes",
			"context_engine_turn_outbox",
			"transcript_events"
		]
	},
	state: {
		...SCHEMA_MIGRATION_BACKUP_TABLES.state,
		2: [
			"audit_events",
			"audit_identity_keys",
			"sqlite_sequence"
		],
		4: ["session_watch_cursors"],
		7: ["commitments"],
		8: ["worker_session_placements"],
		9: ["agent_databases"],
		10: [
			"agent_model_catalogs",
			"android_notification_recent_packages",
			"command_log_entries",
			"diagnostic_stability_bundles",
			"media_blobs",
			"model_capability_cache"
		],
		11: ["skill_lifecycle", "skill_workshop_proposal_origin_runs"],
		12: [
			"config_machine_state",
			"skill_curator_state",
			"update_check_state",
			"clawhub_promotions_feed_state",
			"model_catalog_remote",
			"voicewake_triggers",
			"voicewake_routing_routes",
			"voicewake_routing_config",
			"onboarding_recommendations",
			"cron_store_epochs",
			"tui_last_sessions",
			"sidebar_sections",
			"node_host_config",
			"web_push_vapid_keys"
		],
		13: [
			"cron_jobs",
			"subagent_runs",
			"workspace_setup_state",
			"workspace_attestations",
			"workspace_generated_bootstrap_hashes",
			"auth_profile_stores",
			"auth_profile_state",
			"installed_plugin_index",
			"config_machine_state",
			"diagnostic_events"
		],
		14: ["cron_jobs"],
		15: ["current_conversation_bindings"],
		17: ["worker_environments"],
		18: ["github_publication_session_lifecycles", "github_repository_publication_requests"],
		20: ["cron_run_receipts"],
		21: [
			"meeting_transcript_sessions",
			"meeting_transcript_summaries",
			"delivery_queue_entries",
			...indexStatistics
		],
		22: [
			"worker_session_placements",
			"meeting_transcript_sessions",
			"meeting_transcript_summaries",
			"delivery_queue_entries",
			"acp_sessions",
			"operator_approvals",
			"cron_run_receipts",
			"execution_decision_facts",
			"skill_workshop_changes",
			...indexStatistics
		],
		24: ["task_runs", ...indexStatistics],
		25: []
	}
};
/** Cumulative mutation scope; STRICT and index-repair owners check their actual rebuilds. */
function resolveSchemaMigrationIntegrityTables(e) {
	const t = /* @__PURE__ */ new Set(["schema_meta"]);
	if (e.foundVersion === e.supportedVersion) for (const n of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES[e.kind]) t.add(n);
	for (let n = e.foundVersion + 1; n <= e.supportedVersion; n++) for (const r of migrationTables[e.kind][n] ?? []) t.add(r);
	if (e.kind === "agent") {
		for (const { tableName: e } of STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS) t.add(e);
		if (e.foundVersion < 20) {
			t.add("board_widgets");
			t.add("memory_index_sources");
			t.add("memory_index_paths_fts");
		}
		if (e.foundVersion < 25) for (const e of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.agent) t.add(e);
	} else {
		t.add("config_machine_state");
		if (e.foundVersion < 20) for (const e of SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.state) t.add(e);
	}
	return [...t].toSorted();
}
//#endregion
//#region src/state/openclaw-state-db-maintenance.ts
function assertMigratedStateTableIntegrity(e, t, n, r = false) {
	const i = resolveSchemaMigrationIntegrityTables({
		kind: "state",
		foundVersion: n,
		supportedVersion: 36
	});
	const a = r ? /* @__PURE__ */ new Set([...i, ...SCHEMA_MIGRATION_HISTORICAL_REPAIR_TABLES.state]) : i;
	for (const n of a) if (tableExists(e, n)) assertSqliteTableIntegrity(e, t, n);
}
/**
* Make the known malformed index parseable, then let SQLite drop and reclaim it
* in the caller's transaction. A failed repair rolls both catalog edits back.
*/
function repairDanglingSkillWorkshopCollectionReviewIndex(e) {
	if (!hasDanglingSkillWorkshopCollectionReviewIndex(e)) return false;
	return withSqliteWritableSchema(e, () => {
		e.prepare("UPDATE sqlite_schema SET sql = ? WHERE type = 'index' AND name = ?").run(`CREATE INDEX ${LEGACY_SKILL_WORKSHOP_COLLECTION_REVIEWS_INDEX} ON skill_workshop_collection_reviews(create_time DESC, review_id DESC)`, LEGACY_SKILL_WORKSHOP_COLLECTION_REVIEWS_INDEX);
		const t = e.prepare("PRAGMA schema_version").get();
		const n = typeof t.schema_version === "number" ? t.schema_version : 0;
		e.exec(`PRAGMA schema_version = ${n + 1}; PRAGMA writable_schema = OFF;`);
		e.exec(`DROP INDEX ${LEGACY_SKILL_WORKSHOP_COLLECTION_REVIEWS_INDEX};`);
		return true;
	});
}
/** Admit Doctor repair, then return the ownership-rechecked catalog repair operation. */
function prepareStateDatabaseSchemaRepair(e, t, n) {
	const r = hasDanglingSkillWorkshopCollectionReviewIndex(e);
	const assertWriteAllowed = () => assertOpenClawStateWriteAllowed({
		database: e,
		databasePath: t,
		env: n,
		inspectOwnership: true
	});
	const admit = () => {
		assertSupportedStateSchemaVersion(e, t);
		if (r) assertWriteAllowed();
	};
	if (r) withSqliteWritableSchema(e, admit);
	else admit();
	return () => {
		if (r) withSqliteWritableSchema(e, assertWriteAllowed);
		else assertWriteAllowed();
		return repairDanglingSkillWorkshopCollectionReviewIndex(e) ? ["Removed dangling legacy Skill Workshop review index"] : [];
	};
}
const STATE_MIGRATION_VERSIONS = [
	5,
	6,
	7,
	8,
	9,
	10,
	11,
	12,
	13,
	14,
	15,
	16,
	17,
	18,
	19,
	20,
	21,
	22,
	23,
	24,
	25,
	26,
	27,
	28
];
/** Require canonical shared-state ownership without requiring the latest schema. */
function assertOpenClawStateDatabaseOwner(e, t) {
	const n = getStateSchemaVersionAdmission(e);
	if (n && getStateRuntimeSchemaAdmission(e)) return { schema_version: n.userVersion };
	const r = tableExists(e, "schema_meta");
	let i;
	try {
		i = r ? e.prepare("SELECT role, schema_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1").get() : void 0;
	} catch (t) {
		throw classifySqliteTableReadError(e, "schema_meta", [
			"meta_key",
			"role",
			"schema_version"
		], t);
	}
	if (i?.role !== "global") {
		const e = typeof i?.role === "string" ? i.role : "missing";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} has schema role ${e}; expected global. Run openclaw doctor --fix to inspect and repair its ownership.`);
	}
	return i;
}
/** Require the canonical shared-state owner and schema before offline file maintenance. */
function assertOpenClawStateDatabaseForMaintenance(e, t, n) {
	const { pathname: r, schemaVersions: i } = t;
	if (isPostgresSqlConnection(e)) requireNativeDatabaseFile("postgres", "repair");
	const a = assertSupportedStateSchemaVersion(e, r, i);
	if ((i?.contentVersion ?? readStateSchemaContentVersion(e)) !== 36) throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} uses schema version ${a}; run openclaw doctor --fix before compacting it.`);
	const o = assertOpenClawStateDatabaseOwner(e, t);
	if (o?.schema_version !== a && !adoptPeerPublishedStateSchemaVersion(e, o)) {
		const e = typeof o?.schema_version === "number" ? o.schema_version : "invalid";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${r} metadata schema version ${e} does not match ${a}; run openclaw doctor --fix before compacting it.`);
	}
	assertSqliteSchemaContains(e, r, OPENCLAW_STATE_SCHEMA_SQL, OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY, n);
}
function assertOpenClawStateDatabaseVersionForMigration(e, t) {
	const n = readSqliteUserVersion(e);
	if (readStateSchemaContentVersion(e) !== t.version) throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} uses schema version ${n}; expected ${t.version} before migrating it.`);
	const r = assertOpenClawStateDatabaseOwner(e, t);
	if (r?.schema_version !== n) {
		const e = typeof r?.schema_version === "number" ? r.schema_version : "invalid";
		throw new SqliteSchemaMismatchError(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${n}; repair the ownership metadata before migrating it.`);
	}
	assertSqliteSchemaTablesPresent(e, t.pathname, withLegacyTemplateStateSchema(OPENCLAW_STATE_SCHEMA_SQL), { allowedMissingTables: [...t.version === 5 ? STATE_V5_ADDITIVE_TABLES : t.version < 13 ? STATE_V6_ADDITIVE_TABLES : LAZY_ADDITIVE_STATE_TABLES, ...DOCTOR_OWNED_STATE_TABLES] });
}
/** Keep historical migration gates beside their version-specific ownership assertions. */
const openClawStateMigrationAssertions = new Map(STATE_MIGRATION_VERSIONS.map((e) => [e, (t, n) => assertOpenClawStateDatabaseVersionForMigration(t, {
	...n,
	version: e
})]));
function markCurrentStateSchemaVersion(e, t = {}) {
	if (!tableExists(e, "audit_events")) return;
	const n = resolveStateSchemaVersionToPublish(e);
	if (readSqliteUserVersion(e) !== n) e.exec(`PRAGMA user_version = ${n};`);
	publishStateSchemaVersionAdmission(e, {
		userVersion: n,
		contentVersion: 36
	});
	if (tableExists(e, "schema_meta") && [
		"meta_key",
		"schema_version",
		"updated_at"
	].every((t) => tableHasColumn(e, "schema_meta", t))) {
		const r = Date.now();
		if (t.createMetadataIfMissing) {
			e.prepare(`INSERT INTO schema_meta (
           meta_key, role, schema_version, agent_id, app_version, created_at, updated_at
         ) VALUES ('primary', 'global', ?, NULL, NULL, ?, ?)
         ON CONFLICT(meta_key) DO UPDATE SET
           schema_version = excluded.schema_version,
           updated_at = excluded.updated_at
         WHERE schema_meta.schema_version IS NOT excluded.schema_version`).run(n, r, r);
			return;
		}
		e.prepare("UPDATE schema_meta SET schema_version = ?, updated_at = ? WHERE meta_key = 'primary' AND schema_version IS NOT ?").run(n, r, n);
	}
}
/** Historical jobs lost the creator's origin; preserve attribution without guessing authority. */
function migrateCronCreatorNamespaces(e, t) {
	if (t >= 14 || !tableExists(e, "cron_jobs")) return false;
	e.exec(`
    UPDATE cron_jobs
       SET job_json = json_set(job_json, '$.createdActor.source', 'unknown')
     WHERE json_valid(job_json)
       AND json_extract(job_json, '$.createdActor.type') = 'human';
  `);
	return true;
}
/** Keep opaque plugin targets independent of agent identity without rewriting binding records. */
function migrateConversationBindingTargets(e, t) {
	if (t >= 15) return false;
	const n = ["target_agent_id", "target_session_id"].filter((t) => tableHasColumn(e, "current_conversation_bindings", t));
	if (n.length === 0) return false;
	e.exec("DROP INDEX IF EXISTS idx_current_conversation_bindings_target;");
	for (const t of n) e.exec(`ALTER TABLE current_conversation_bindings DROP COLUMN ${t};`);
	return true;
}
/** Add preparation and activation facts without rebuilding the referenced environment table. */
function migratePreparedWorkerOwnership(e, t) {
	if (t >= 17 || !tableExists(e, "worker_environments")) return false;
	const n = OPENCLAW_STATE_SCHEMA_SQL.indexOf("CREATE TABLE IF NOT EXISTS worker_environments (");
	const r = OPENCLAW_STATE_SCHEMA_SQL.indexOf("\n) STRICT;", n);
	if (n < 0 || r < n) throw new Error("OpenClaw worker environment schema marker is missing.");
	const i = splitSqlList(OPENCLAW_STATE_SCHEMA_SQL.slice(n + 48, r)).map((e) => e.trim()).filter((e) => e.startsWith("last_activated_at_ms ") || e.startsWith("preparation_"));
	let a = false;
	for (const t of i) a = ensureColumn(e, "worker_environments", t) || a;
	return a;
}
/** Historical publication rows retain unknown requesters; first use still owns absent tables. */
function migrateGitHubPublicationRequesterAuthority(e, t) {
	if (t >= 18) return false;
	let n = false;
	for (const t of ["github_publication_session_lifecycles", "github_repository_publication_requests"]) n = ensureColumn(e, t, "requester_authority_json TEXT") || n;
	return n;
}
const statePortableIdentityMigration = {
	version: 22,
	tables: ["acp_sessions", ...STATE_CURSOR_TABLES_V22],
	columns: [
		"acp_sessions.resume_agent_session_id",
		"acp_sessions.resume_acpx_session_id",
		...STATE_CURSOR_TABLES_V22.map((e) => `${e}.cursor_id`)
	],
	migrate: migratePortableIdentityColumnsV22,
	applied: "Promoted portable ACP resume keys and cursor identities (v22)"
};
const stateMeetingChronologyMigration = {
	version: 23,
	tables: ["meeting_transcript_sessions"],
	columns: ["meeting_transcript_sessions.started_at_ms"],
	migrate: migrateMeetingTranscriptStartTime,
	applied: "Persisted normalized meeting transcript start times"
};
const stateTaskIndexMigration = {
	version: 24,
	tables: ["task_runs"],
	columns: [],
	migrate: migrateTaskRunIndexesV24,
	applied: "Replaced retained task indexes with ordered cron history indexes (v24)"
};
const stateSubagentOperatorRecoveryMigration = {
	version: 25,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Required original operator authority for subagent recovery (v25)"
};
const stateHeadLayoutMigration = {
	version: 26,
	tables: ["session_state_heads"],
	columns: [],
	migrate: migrateSessionStateHeadLayoutV26,
	applied: "Stored session state heads in their composite primary-key tree (v26)"
};
const stateWriteIndexMigration = {
	version: 27,
	tables: [
		"acp_replay_events",
		"skill_usage",
		"state_leases"
	],
	columns: [],
	migrate: migrateStateWriteIndexesV27,
	applied: "Removed redundant replay and skill indexes and narrowed the lease-owner index (v27)"
};
const stateClientCredentialMigration = {
	version: 29,
	tables: CLIENT_CREDENTIAL_SOURCE_TABLES,
	columns: [],
	migrate: () => false,
	applied: "Moved client credentials and native socket material to the local owner (v29)"
};
const stateAutomationPolicyMigration = {
	version: 30,
	tables: [],
	columns: [],
	migrate: () => false,
	applied: "Fenced ordinary automation timing and delivery policies from older schedulers (v30)"
};
/** Version-gated column and row migrations, oldest first; each runs inside the caller's schema transaction. */
const versionedStateMigrations = [
	statePortableIdentityMigration,
	stateMeetingChronologyMigration,
	{
		migrate: migrateJsonCanonicalWideRowsV13,
		applied: "Consolidated shared state tables (v13)"
	},
	{
		migrate: migrateCronCreatorNamespaces,
		applied: "Qualified historical cron creator attribution as unknown (v14)"
	},
	{
		migrate: migrateConversationBindingTargets,
		applied: "Removed redundant conversation binding target projections (v15)"
	},
	{
		migrate: migratePreparedWorkerOwnership,
		applied: "Recorded prepared worker ownership and one-use lifecycle (v17)"
	},
	{
		migrate: migrateGitHubPublicationRequesterAuthority,
		applied: "Added original requester authority to GitHub publication receipts (v18)"
	},
	{
		migrate: migrateCronDeliveryAttemptState,
		applied: "Recorded cron completion delivery attempt uncertainty (v20)"
	},
	stateTaskIndexMigration,
	stateHeadLayoutMigration,
	stateWriteIndexMigration,
	statePublicationDraftMigration,
	stateLocalWorkspaceManifestMigration,
	stateCronIdentityMigration,
	stateLocalWorkspaceCasMigration,
	stateTemplateNamesMigration
];
/** Recent version migrations own only their tables; Doctor owns unrelated historical repair. */
function migrateBoundedStateSchema(e, t, n) {
	const r = [
		statePredicateColumnMigration,
		statePortableIdentityMigration,
		stateMeetingChronologyMigration,
		stateTaskIndexMigration,
		stateSubagentOperatorRecoveryMigration,
		stateHeadLayoutMigration,
		stateWriteIndexMigration,
		statePublicationDraftMigration,
		stateClientCredentialMigration,
		stateAutomationPolicyMigration,
		stateLocalWorkspaceManifestMigration,
		...stateIndexOrderingMigrations,
		stateCronIdentityMigration,
		stateLocalWorkspaceCasMigration,
		stateTemplateNamesMigration
	].filter(({ version: e }) => e > t);
	if (t >= 36 || r.length !== 36 - t) return;
	const i = new Set(r.flatMap((e) => e.tables));
	const a = getCanonicalSqliteNamedIndexContracts(OPENCLAW_STATE_SCHEMA_SQL).filter((e) => i.has(e.tableName));
	const o = t < 36 ? withLegacyTemplateStateSchema(OPENCLAW_STATE_SCHEMA_SQL) : OPENCLAW_STATE_SCHEMA_SQL;
	const s = t < 35 ? withLegacyLocalWorkspaceCas(o) : o;
	const c = t < 31 ? withLegacyLocalWorkspaceManifests(s) : s;
	const l = t < 27 ? withLegacyStateWriteIndexes(c) : c;
	const u = t < 26 ? withLegacyStateHeadLayout(l) : l;
	if (!n.versionMigrationOnly && (tableExists(e, "cron_run_logs") || !r.includes(statePublicationDraftMigration) && needsPublicationDraftMigration(e) || findMissingLazyStateStartupColumn(createSqliteTableContractReader(e)) !== void 0 || collectSqliteSchemaIssues(e, u, {
		...withLegacyTemplateStateCompatibility(STATE_RUNTIME_SCHEMA_COMPATIBILITY),
		allowedMissingColumns: [...STATE_RUNTIME_SCHEMA_COMPATIBILITY.allowedMissingColumns ?? [], ...r.flatMap((e) => e.columns)].map(withLegacyTemplateStateSchema),
		allowedMissingIndexes: [
			...STATE_RUNTIME_SCHEMA_COMPATIBILITY.allowedMissingIndexes ?? [],
			...a.map((e) => e.name),
			"idx_acp_replay_events_session_seq",
			"idx_skill_usage_key"
		],
		excludedIndexes: [
			...STATE_RUNTIME_SCHEMA_COMPATIBILITY.excludedIndexes ?? [],
			"idx_acp_sessions_resume_agent",
			"idx_acp_sessions_resume_acpx"
		]
	}).length > 0)) return;
	const d = migrateHistoricalStateImports(e, t);
	for (const i of r) {
		i.migrate(e, t, n);
		d.push(i.applied);
	}
	for (const t of a) if (tableExists(e, t.tableName)) {
		const n = t.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
		e.exec(`${n} IF NOT EXISTS ${t.name} ${t.definition};`);
	}
	return d;
}
function runStateSchemaMigrationTransaction(e, t, n, r, i) {
	return runUpdateSqliteMigration(e, t, () => {
		const a = Number(e.prepare("PRAGMA foreign_keys").get()?.foreign_keys) === 1;
		if (a) e.exec("PRAGMA foreign_keys = OFF;");
		try {
			return runSqliteImmediateTransactionSync(e, () => {
				i?.();
				const r = readSqliteUserVersion(e);
				const a = r < 36 ? readStateSchemaPublicationBlocker(e) : void 0;
				if (!a) return n();
				try {
					if (!tableExists(e, "config_machine_state")) throw new Error("Shared state schema publication requires config_machine_state.");
					return n();
				} catch (e) {
					if (e instanceof OpenClawStateOwnershipError) throw e;
					throw new UpdateSchemaRefusalError([{
						kind: "state",
						path: t,
						foundVersion: r,
						supportedVersion: 36
					}], a.updaterVersion, {
						targetVersion: VERSION,
						cause: e
					});
				}
			}, r);
		} finally {
			if (a && e.isOpen) e.exec("PRAGMA foreign_keys = ON;");
		}
	});
}
function writeCurrentStateSchemaMetadata(e, t) {
	const n = getNodeSqliteKysely(e);
	const r = resolveStateSchemaVersionToPublish(e);
	if (readSqliteUserVersion(e) !== r) e.exec(`PRAGMA user_version = ${r};`);
	publishStateSchemaVersionAdmission(e, {
		userVersion: r,
		contentVersion: 36
	});
	executeSqliteQuerySync(e, n.insertInto("schema_meta").values({
		meta_key: "primary",
		role: "global",
		schema_version: r,
		agent_id: null,
		app_version: VERSION,
		created_at: t,
		updated_at: t
	}).onConflict((e) => e.column("meta_key").doUpdateSet({
		role: "global",
		schema_version: r,
		agent_id: null,
		app_version: VERSION,
		updated_at: t
	}).where((e) => e.or([
		e("schema_meta.schema_version", "!=", r),
		e("schema_meta.app_version", "is not", VERSION),
		e("schema_meta.role", "!=", "global")
	]))));
}
function executeCanonicalStateSchema(e, t) {
	e.exec(getOpenClawStateRuntimeSchema({
		...t,
		includeAgentDeletionJournal: t.includeAgentDeletionJournal ?? tableExists(e, "agent_deletion_journal")
	}));
}
//#endregion
export { migrateHistoricalStateImports as C, withLegacyStateHeadLayout as S, hasHistoricalImageReserveSnapshots as T, findMissingLazyStateStartupColumn as _, markCurrentStateSchemaVersion as a, getOpenClawStateRuntimeSchema as b, prepareStateDatabaseSchemaRepair as c, writeCurrentStateSchemaMetadata as d, resolveSchemaMigrationIntegrityTables as f, STATE_RUNTIME_SCHEMA_COMPATIBILITY as g, RETAINED_STATE_TABLES as h, executeCanonicalStateSchema as i, runStateSchemaMigrationTransaction as l, OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY as m, assertOpenClawStateDatabaseForMaintenance as n, migrateBoundedStateSchema as o, SCHEMA_MIGRATION_BACKUP_TABLES as p, assertOpenClawStateDatabaseOwner as r, openClawStateMigrationAssertions as s, assertMigratedStateTableIntegrity as t, versionedStateMigrations as u, isOpenClawStateFirstUseSchemaIssue as v, migratePredicateColumnsV21 as w, withLegacyStateWriteIndexes as x, isOpenClawStateStartupRepairableSchemaIssue as y };