openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 22.9 kB
JavaScript
import{r as collectErrorGraphCandidates}from"./error-coercion-DlKnt6w-.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{c as sha256File}from"./directory-durability-o_aQCRBZ.mjs";import{d as shortenHomeInString,f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.mjs";import{n as ignoreMissingPath,t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{v as resolveGatewayLockDir}from"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{n as runtimeProcessEntrypoints}from"./runtime-process-entrypoints-Dnd1WskT.mjs";import{a as resolveRuntimeWorkerUrl,n as resolveRuntimeWorkerArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{a as tableExists}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{a as resolveOpenClawRegisteredAgentDatabasePath,c as resolveQuarantineStorePath,s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{g as withExistingOpenClawStateDatabaseReadOnly}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{r as selectDatabaseEngine,t as listDatabaseEngineStores}from"./registry-ByN-O5dB.mjs";import{a as resolveSqliteDatabaseFilePaths,r as isAppleDoubleMetadataFile,t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import{t as getOrCreateWeakOwnerMap}from"./weak-owner-map-B5mTikxj.mjs";import{n as readEngineAnchor}from"./open-1OjrnB9v.mjs";import{r as assertOpenClawStateDatabaseOwner}from"./openclaw-state-db-maintenance-BGNaiVRT.mjs";import{i as createVerifiedSqliteSnapshot}from"./sqlite-snapshot-D4gm3rAo.mjs";import{t as resolveClientCredentialStorePath}from"./client-credential-paths-D__QHGyH.mjs";import{n as CONFIG_AUDIT_SCOPE}from"./io.audit-DXCsuLiP.mjs";import{p as resolvePluginMetadataSnapshot}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{r as readOpenClawAgentDatabaseRegistryRows}from"./openclaw-agent-db-registry.read-BLUjVOoj.mjs";import{i as inspectOpenClawRegisteredAgentDatabases}from"./openclaw-agent-db-registry-listing-Bnnfy4SV.mjs";import{i as engineStringPosition}from"./scalar-D316fGYE.mjs";import{n as SYSTEM_AGENT_AUDIT_SCOPE}from"./audit-DM5LFpao.mjs";import{n as resolveAgentPortRoots}from"./agent-port-B0iL4NPS.mjs";import{n as readBackupEngineImage}from"./physical-store-inspection-BHEZGfsf.mjs";import{n as sanitizeOpenClawStateLeaseRows,t as sanitizeOpenClawGlobalStateSnapshot}from"./openclaw-state-snapshot-sanitizer-C-SbyO9u.mjs";import{n as isTransientSqliteBackupPath}from"./backup-volatile-filter-C7OiuXr0.mjs";import{t as assertNotUpdateCapturePath}from"./update-capture-paths-C5GOuESg.mjs";import{r as sealBackupResourceInventory,t as createBackupResourcePlan}from"./backup-resource-inventory-VtmOfu9w.mjs";import{t as embedSessionColdArchivesInSnapshot}from"./session-cold-storage-backup-5R4hIGmo.mjs";import{o as resolveDaemonRuntimePinStorePath}from"./runtime-pin-store-BeqKlM5M.mjs";import{n as capturePostgresBackup}from"./database-backup-yFN_P503.mjs";import{t as listDefaultAgentDatabasePaths}from"./agent-database-path-discovery-BuUeLS_W.mjs";import{n as assertOpenClawAgentDatabaseOwner}from"./openclaw-agent-db-maintenance-BgAjdkRB.mjs";import{i as planBackupSqliteSources,n as captureBackupSqliteSourceGroup,t as assertBackupSqliteSourceGroup}from"./backup-sqlite-source-groups-BENi3PrL.mjs";import{a as readLegacyAuditSourcePrefixSnapshotForBackup,d as serializePreparedAuditRecords,g as detectLegacyAuditLogs,i as readLegacyAuditRecoverySourceForBackup,m as legacyAuditMoveCandidates,r as findPreviousLegacyAuditRawCheckpoint,u as prepareLegacyAuditRecords,v as legacyAuditSourceGenerationKey}from"./state-migrations.audit-recovery-DjiJDuGs.mjs";import{n as inspectLegacyMigrationLinkedMove}from"./state-migrations.no-replace-move-r8fD1wpn.mjs";import{i as collectStateDatabasePaths}from"./update-candidate-state-CF8SlkPu.mjs";import path from"node:path";import{createHash}from"node:crypto";import fs from"node:fs/promises";import{isMainThread}from"node:worker_threads";import childProcess from"node:child_process";import{sameFileIdentity}from"@openclaw/fs-safe/advanced";import{isPathInside}from"@openclaw/fs-safe/path";import{walkDirectory}from"@openclaw/fs-safe/walk";
//!src/infra/sqlite-header-probe.ts
const SQLITE_HEADER_PROBE_BATCH_SIZE=4096;const SQLITE_HEADER_PROBE_TIMEOUT_MS=1e4;const log=createSubsystemLogger(`backup`);function probeSqliteHeaderBatch(e,t,n){const r=childProcess.spawnSync(process.execPath,e,{input:JSON.stringify(t),encoding:`utf8`,maxBuffer:67108864,timeout:SQLITE_HEADER_PROBE_TIMEOUT_MS});if(r.error){if(hasErrnoCode(r.error,`ETIMEDOUT`)&&t.length>1){const r=Math.ceil(t.length/2);probeSqliteHeaderBatch(e,t.slice(0,r),n);probeSqliteHeaderBatch(e,t.slice(r),n);return}throw r.error}if(r.status===3){const e=asOptionalRecord(JSON.parse(r.stderr));throw Object.assign(/* @__PURE__ */ new Error(`Header probe could not read a source`),{code:e?.code,errno:e?.errno,path:e?.path})}if(r.status!==0)throw new Error(`Header probe exited with status ${r.status}: ${r.stderr.trim()}`);const i=JSON.parse(r.stdout);if(!Array.isArray(i)||i.length!==t.length||!i.every(e=>typeof e===`boolean`))throw new Error(`Header probe returned an incomplete result`);if(r.stderr.trim()){const e=`SQLite header probe recovered after retrying source reads: ${r.stderr.trim()}`;log.warn(e,{consoleMessage:shortenHomeInString(e)})}for(let e=0;e<t.length;e++)n.set(t[e],i[e])}function probeSqliteDatabaseHeaders(e){const t=[...new Set(e)];if(t.length===0)return/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new Map;try{const e=resolveRuntimeWorkerArgv(resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.sqliteHeaderProbe));for(let r=0;r<t.length;r+=SQLITE_HEADER_PROBE_BATCH_SIZE)probeSqliteHeaderBatch(e,t.slice(r,r+SQLITE_HEADER_PROBE_BATCH_SIZE),n);return n}catch(e){const n=asOptionalRecord(e);const r=typeof n?.path===`string`?` Backup source ${shortenHomePath(n.path)} could not be read (${typeof n.code===`string`?n.code:`unknown error`}). Check read permissions or close the program using it, then retry the backup or update.`:` Check that the backup worker can run and the source files are readable, then retry the backup.`;const i=hasErrnoCode(e,`ETIMEDOUT`);throw Object.assign(new Error(i?`SQLite header probe timed out after ${SQLITE_HEADER_PROBE_TIMEOUT_MS} ms while checking ${t.length} backup paths. For a blocked update, preserve a verified backup and follow the manual package-manager hop: https://docs.openclaw.ai/install/updating/update-methods#alternative-manual-npm-pnpm-or-bun`:`Could not determine whether backup files are SQLite databases.${r}`,{cause:e}),{code:i?`backup-sqlite-probe-timeout`:`backup-sqlite-probe-failed`})}}
//!src/infra/state-migrations.audit-backup.ts
var LegacyAuditBackupStateChangedError=class extends Error{constructor(e=`Legacy audit state changed while backup was capturing it`){super(e);this.name=`LegacyAuditBackupStateChangedError`}};const LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE=`migration.legacy-audit-raw`;function createLegacyAuditDatabaseWitness(e){const t=executeSqliteQuerySync(e,getNodeSqliteKysely(e).selectFrom(`diagnostic_events`).select([`scope`,`event_key`,`payload_json`,`created_at`,`sequence`]).where(t=>t.or([t.and([t(`scope`,`in`,[CONFIG_AUDIT_SCOPE,SYSTEM_AGENT_AUDIT_SCOPE]),t(engineStringPosition(e,t.ref(`event_key`),t.val(`legacy:`)),`=`,1)]),t(`scope`,`=`,LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE)])).orderBy(`scope`).orderBy(`event_key`).orderBy(`sequence`)).rows;return createHash(`sha256`).update(JSON.stringify(t)).digest(`hex`)}function legacyAuditBackupCapturesMatch(e,t){return e.filesystemWitness===t.filesystemWitness&&e.databaseWitness===t.databaseWitness}function rewriteLegacyAuditBackupCheckpoints(e,t){if(e.prepare(`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`).get(`diagnostic_events`)?.ok!==1)return;const n=LEGACY_AUDIT_RAW_CHECKPOINT_SCOPE;e.prepare(`DELETE FROM diagnostic_events WHERE scope = ?`).run(n);const r=e.prepare(`INSERT INTO diagnostic_events (
scope, event_key, payload_json, created_at, sequence
) VALUES (?, ?, ?, ?, ?)`);let i=1;for(const e of t){if(!e.checkpoint)continue;r.run(n,e.checkpoint.key,JSON.stringify(e.checkpoint.value),0,i);i+=1}}async function createLegacyAuditBackupSnapshotsOnce(e){const t=detectLegacyAuditLogs({stateDir:e.stateDir,doctorOnlyStateMigrations:true});if(t.sources.length===0)return{snapshots:[],filesystemWitness:createHash(`sha256`).digest(`hex`)};const n=await root(e.stateDir,{hardlinks:`reject`,maxBytes:Number.MAX_SAFE_INTEGER,mkdir:false,mode:384,symlinks:`reject`});const r=[];const i=createHash(`sha256`);for(const[a,o]of t.sources.entries()){const t=path.relative(path.resolve(e.stateDir),o.sourcePath);let s;for(const e of await legacyAuditMoveCandidates(n,o))if((e.retained===t||e.removed===t)&&await inspectLegacyMigrationLinkedMove(n,e.retained,e.removed)){s=e;break}if(s&&s.retained!==t)continue;const c=o.storage===`raw-archive`?await readLegacyAuditRecoverySourceForBackup(n,t,s?.removed):await readLegacyAuditSourcePrefixSnapshotForBackup(n,t,s?.removed);const l=legacyAuditSourceGenerationKey(t);const u=o.storage===`raw-archive`?findPreviousLegacyAuditRawCheckpoint(e.stateDir,t):void 0;const d=prepareLegacyAuditRecords(o,c.raw,l,u?.recordOrdinalBase??0);if(!d.ok)throw new Error(`Legacy ${o.label} append archive cannot be sanitized for backup: ${d.warnings.join(`; `)}`);const f=path.join(e.tempDir,`legacy-audit-raw-${a}.jsonl`);await fs.writeFile(f,d.sanitizedJsonl,{mode:384});let p;if(u){if(u.recordCount>d.records.length)throw new Error(`Legacy ${o.label} append archive is shorter than its durable checkpoint`);const e=Buffer.from(serializePreparedAuditRecords(d.records.slice(0,u.recordCount)),`utf8`);const t={...u,dev:`0`,ino:`0`,mtimeMs:0,size:e.length,contentHash:createHash(`sha256`).update(e).digest(`hex`)};p={key:t.generationKey,value:t}}const m={sourcePath:f,archiveSourcePath:o.sourcePath,...p?{checkpoint:p}:{},skippedSourcePaths:/* @__PURE__ */ new Set([path.resolve(o.sourcePath),...s?[path.resolve(e.stateDir,s.removed)]:[],path.resolve(`${o.sourcePath}.doctor-scrub-progress`),path.resolve(`${o.sourcePath}.doctor-scrub-restore`),path.resolve(`${o.sourcePath}.doctor-scrub-staging`)])};const h=JSON.stringify([m.archiveSourcePath,c.dev,c.ino,c.mtimeMs,c.size,m.checkpoint]);for(const e of[h,d.sanitizedJsonl])i.update(String(Buffer.byteLength(e))).update(`:`).update(e);r.push(m)}return{snapshots:r,filesystemWitness:i.digest(`hex`)}}async function createLegacyAuditBackupCapture(e){let t;for(let n=0;;n+=1)try{t=await createLegacyAuditBackupSnapshotsOnce(e);break}catch(e){if(n===2)throw e;await new Promise(e=>{setTimeout(e,25)})}const n=withExistingOpenClawStateDatabaseReadOnly(({db:e})=>createLegacyAuditDatabaseWitness(e),{env:{...process.env,OPENCLAW_STATE_DIR:e.stateDir}})??createHash(`sha256`).digest(`hex`);return{...t,databaseWitness:n}}
//!src/infra/backup-sqlite-snapshot.ts
function findLegacyAuditBackupStateChange(e){return collectErrorGraphCandidates(e,e=>e instanceof Error?[e.cause]:[]).find(e=>e instanceof LegacyAuditBackupStateChangedError)}const sqliteHeaderAnswers=/* @__PURE__ */ new WeakMap;function stripSqliteSidecarSuffix(e){const t=SQLITE_SIDECAR_SUFFIXES.find(t=>e.endsWith(t));return t?e.slice(0,-t.length):e}function classifyBackupSqliteSource(e,t){const n=path.resolve(e);if(!(isPathInside(t.stateDir,n)||t.agentRoots.some(({sourcePath:e})=>isPathInside(e,n)))||t.isPackageContent(n))return;const r=isTransientSqliteBackupPath(n);const i=stripSqliteSidecarSuffix(n);const a=i.endsWith(`.sqlite`);if(!t.isIncludedByOwner(n))return a?`excluded`:void 0;if(!r&&!a){const e=getOrCreateWeakOwnerMap(sqliteHeaderAnswers,t);if(!e.has(i))for(const[t,n]of probeSqliteDatabaseHeaders([i]))e.set(t,n);if(!e.get(i))return}if(r)return`excluded`;if(!t.isIncluded(n))return a?`excluded`:void 0;if(isAppleDoubleMetadataFile(n))return`excluded`;const o=t.resolveSqliteSource(i);if(o&&o.role===`unresolvable-link`)return n===i?`opaque-skip`:`opaque`;return o?`sqlite`:`opaque`}async function discoverBackupSqliteSources(e){const t=/* @__PURE__ */ new Set;const n=/* @__PURE__ */ new Set;const r=/* @__PURE__ */ new Set;const i=[];const a=resolveGatewayLockDir(e.inventory.stateDir);const isRetainedPath=t=>!isPathInside(a,t)&&!e.inventory.isVolatile(t);const isSelectedPath=t=>!e.resourceRoots||e.resourceRoots.some(e=>isPathInside(e,t)||isPathInside(t,e));for(const t of[e.inventory.stateDir,...e.inventory.agentRoots.map(({sourcePath:e})=>e)]){const n=path.resolve(t);if(r.has(n))continue;r.add(n);const{entries:a,failedDirs:o}=await walkDirectory(n,{symlinks:`include`,include:t=>(t.kind===`file`||t.kind===`symlink`)&&isSelectedPath(t.path)&&isRetainedPath(t.path)&&e.inventory.isIncludedByOwner(t.path),descend:t=>{if(r.has(t.path)||!isSelectedPath(t.path)||!isRetainedPath(t.path)||!e.inventory.isTraversable(t.path)||e.inventory.isPackageContent(t.path))return false;r.add(t.path);return true}});const s=o.find(({error:e})=>!hasErrnoCode(e,`ENOENT`));if(s)throw s.error;for(const e of a)i.push(e)}const o=getOrCreateWeakOwnerMap(sqliteHeaderAnswers,e.inventory);const s=[...i.map(e=>e.path),...r].map(stripSqliteSidecarSuffix).filter(e=>!e.endsWith(`.sqlite`));for(const[e,t]of probeSqliteDatabaseHeaders(s))o.set(e,t);for(const r of i){if(classifyBackupSqliteSource(r.path,e.inventory)!==`sqlite`)continue;n.add(r.path);if(!SQLITE_SIDECAR_SUFFIXES.some(e=>r.name.endsWith(e)))t.add(r.path)}for(const r of e.inventory.coreDatabaseSourcePaths)if(e.inventory.isIncluded(r)){t.add(r);n.add(r)}return{snapshotPaths:[...t].toSorted((e,t)=>e.localeCompare(t)),discoveredSourcePaths:n}}async function discoverBackupDatabasePaths(e){if(isMainThread&&selectDatabaseEngine({id:`state`,postgres:true},e.config)===`postgres`){const{preparePostgresBackupDiscovery:t}=await import(`./backup-database-discovery-4ur3KcRn.mjs`);return(await t(e)).paths}const t=[...(await collectStateDatabasePaths(e)).values()].flatMap(e=>e.spellings);t.push(...await resolveAgentPortRoots({...e,env:e.env??process.env},e.agentRegistry));const n=resolvePluginMetadataSnapshot(e);const r=new Set(listDatabaseEngineStores().filter(e=>e.postgres).map(e=>e.id));const i=n.plugins.flatMap(e=>(e.backupResources??[]).filter(t=>r.has(t.databaseFamily??e.id)).map(t=>Object.assign({},t,{pluginId:e.id})));const a=await createBackupResourcePlan({stateDir:e.stateDir,configPaths:[],oauthDirs:[],workspaceDirs:[],excludedWorkspaceDirs:[],agentRoots:[],pluginResources:i,pluginRoots:n.plugins.map(e=>e.rootDir)});const o=sealBackupResourceInventory(a,[]);t.push(...(await discoverBackupSqliteSources({inventory:o,resourceRoots:a.pluginResourceRoots})).snapshotPaths);const s=[];for(const e of new Set(t))if((await fs.stat(e).catch(ignoreMissingPath))?.isFile())s.push(await fs.realpath(e));return[...new Set(s)].toSorted()}async function createBackupSqliteSnapshotPlan(e){const t=/* @__PURE__ */ new Map;const n=[];const r=[];const i=[];let a;let o=[];function captureAgentRegistry(e,t){o=readOpenClawAgentDatabaseRegistryRows(e,t).map(e=>({role:`agent`,agentId:normalizeAgentId(e.agent_id),sourcePath:resolveOpenClawRegisteredAgentDatabasePath(t,e.path)}))}async function captureSource(a,s,c){if(!s)throw new Error(`SQLite ownership changed after discovery: ${a}`);if(c&&!sameFileIdentity(c.identity,await fs.stat(a,{bigint:true})))throw new Error(`Canonical SQLite path changed after discovery: ${a}`);const l=s.sourcePath;assertNotUpdateCapturePath(a,e.resources.stateDir);assertNotUpdateCapturePath(l,e.resources.stateDir);const u=path.join(e.tempDir,`openclaw-state-db-${n.length}.sqlite`);const d={"source-acquisition":`sqlite-source-acquisition`,"source-integrity":`sqlite-source-integrity`,"online-copy":`sqlite-online-copy`,vacuum:`sqlite-vacuum`,hash:`sqlite-hash`,"published-integrity":`sqlite-published-integrity`};let f=`online-copy`;let p;try{const capture=()=>createVerifiedSqliteSnapshot({sourcePath:l,targetPath:u,...e.onProgress?{onStage:(t,n,r)=>{if(n===`start`)f=t;e.onProgress?.({stage:d[t],phase:n,...n===`start`?{sourceBytes:r}:{bytes:r}})},onProgress:({totalPages:t,remainingPages:n})=>{if(t>0)e.onProgress?.({stage:d[f],phase:`progress`,pages:t-n,totalPages:t})}}:{},...e.preserveSourceArtifacts?{sourceAcquisition:{mode:`isolated-process`,stagingRoot:e.tempDir,preserveSourceArtifacts:true},preserveRowIds:true}:{},requireNonEmptySource:Boolean(c),validate:c?(e,t)=>{p??=readEngineAnchor(e)!==void 0;if(p)return;if(c.role===`global`)assertOpenClawStateDatabaseOwner(e,{pathname:t});else if(c.role===`agent`)assertOpenClawAgentDatabaseOwner(e,{agentId:c.agentId,pathname:t})}:void 0,transform:async t=>{p??=readEngineAnchor(t)!==void 0;if(p)return;if(e.localCompanion&&c?.role===`client`)return;if(c?.role===`global`){captureAgentRegistry(t,c.archiveSourcePath);if(e.legacyAuditDatabaseWitness!==void 0&&createLegacyAuditDatabaseWitness(t)!==e.legacyAuditDatabaseWitness)throw new LegacyAuditBackupStateChangedError(`Legacy audit database rows changed during SQLite backup`);sanitizeOpenClawGlobalStateSnapshot(t);rewriteLegacyAuditBackupCheckpoints(t,e.legacyAuditSnapshots)}else if(c?.role===`agent`)sanitizeOpenClawStateLeaseRows(t);else if(c?.role===`client`&&tableExists(t,`native_exec_socket_credentials`))executeSqliteQuerySync(t,getNodeSqliteKysely(t).updateTable(`native_exec_socket_credentials`).set({socket_token:null}));await embedSessionColdArchivesInSnapshot({database:t,sourceStorePath:c?.archiveSourcePath??l})}});const n=t.get(s);await captureBackupSqliteSourceGroup(s,()=>n?fs.copyFile(n,u,fs.constants.COPYFILE_EXCL):capture());t.set(s,u)}catch(e){const t=findLegacyAuditBackupStateChange(e);if(t)throw t;throw new Error(`SQLite database cannot be compacted safely for backup: ${a}. ${formatErrorMessage(e)}. The source must pass full integrity checks, online SQLite backup, and offline compaction with its required SQLite capabilities; a direct file copy was refused because it can retain deleted data. For a plugin-owned database, restore the required SQLite capabilities or use the plugin's own backup procedure before retrying.`,{cause:e})}const m=readBackupEngineImage(u,l);if(m.engine===`postgres`&&e.localCompanion){i.push({sourcePath:a,storeId:m.storeId,namespace:m.namespace});if(c?.role===`global`)o=(await inspectOpenClawRegisteredAgentDatabases({env:{...process.env,OPENCLAW_STATE_DIR:e.resources.stateDir},includeIncompatibleSchemaVersions:true})).map(({agentId:e,path:t})=>({role:`agent`,agentId:e,sourcePath:t}))}else if(m.engine===`postgres`){const e=path.join(`${u}.postgres`,path.basename(`${a}.postgres`));await fs.mkdir(path.dirname(e),{mode:448});await capturePostgresBackup({sourcePath:l,directory:e});if(c?.role===`global`)try{var h=_usingCtx();captureAgentRegistry(h.u(openNodeSqliteDatabase(path.join(e,`database.sqlite`),{readOnly:true})),c.archiveSourcePath)}catch(e){h.e=e}finally{h.d()}for(const t of[`anchor.sqlite`,`database.sqlite`,`manifest.json`])n.push({sourcePath:path.join(e,t),archiveSourcePath:`${a}.postgres/${t}`,skippedSourcePaths:/* @__PURE__ */ new Set});const t=`${u}.anchor`;await fs.copyFile(path.join(e,`anchor.sqlite`),t,fs.constants.COPYFILE_EXCL);n.push({sourcePath:t,archiveSourcePath:a,skippedSourcePaths:new Set(resolveSqliteDatabaseFilePaths(l))});r.push({sourcePath:a,manifestSha256:(await sha256File(path.join(e,`manifest.json`))).digest});return}n.push({sourcePath:u,archiveSourcePath:a,skippedSourcePaths:new Set([a,l].flatMap(e=>resolveSqliteDatabaseFilePaths(e).map(e=>path.resolve(e))))})}const s=resolveOpenClawStateSqlitePath({...process.env,OPENCLAW_STATE_DIR:e.resources.stateDir});const c=await fs.lstat(s,{bigint:true}).catch(ignoreMissingPath);let l;let u;if(c){l=c.isSymbolicLink()?await fs.stat(s,{bigint:true}):c;if(!l.isFile())throw new Error(`Canonical global SQLite path must be a regular file or symlink to one: ${s}`);const t={role:`global`,archiveSourcePath:s,sourcePath:await fs.realpath(s),identity:l};const n=sealBackupResourceInventory(e.resources,[{role:`global`,sourcePath:s,identity:l}]);const{snapshotPaths:r}=await discoverBackupSqliteSources({inventory:n});const{groups:i}=await planBackupSqliteSources(n,r.filter(e=>n.resolveSqliteSource(e)?.role===`global`));u=i.get(t.sourcePath);await captureSource(s,u,t);a=t.sourcePath}else for(const e of resolveSqliteDatabaseFilePaths(s).slice(1))if(await fs.lstat(e).catch(ignoreMissingPath))throw new Error(`Canonical global SQLite database is missing but a sidecar remains: ${e}`);const d=[{role:`global`,sourcePath:s,identity:l}];const f=await listDefaultAgentDatabasePaths(e.resources.stateDir);const p=[];const m=[{role:`client`,sourcePath:resolveClientCredentialStorePath({OPENCLAW_STATE_DIR:e.resources.stateDir})},{role:`services`,sourcePath:resolveDaemonRuntimePinStorePath({OPENCLAW_STATE_DIR:e.resources.stateDir})},{role:`quarantine`,sourcePath:resolveQuarantineStorePath({...process.env,OPENCLAW_STATE_DIR:e.resources.stateDir})},...o,...e.resources.agentRoots.map(({agentId:e,databasePath:t})=>({role:`agent`,agentId:e,sourcePath:t})),...f.toSorted((e,t)=>e.path.localeCompare(t.path)).map(({agentId:e,path:t})=>({role:`agent`,agentId:normalizeAgentId(e),sourcePath:t,discoveredPath:t}))];for(const{discoveredPath:e,...t}of m){const n=await fs.stat(t.sourcePath,{bigint:true}).catch(ignoreMissingPath);if(n&&!n.isFile())throw new Error(`Core SQLite path must resolve to a regular file: ${t.sourcePath}`);if(e&&!n)continue;if(e){p.push(e);t.sourcePath=await fs.realpath(t.sourcePath)}d.push(Object.freeze({...t,identity:n}))}const h=sealBackupResourceInventory({...e.resources,protectedPaths:[...e.resources.protectedPaths,...p]},d);const g=await discoverBackupSqliteSources({inventory:h});const{sources:_,groups:v}=await planBackupSqliteSources(h,g.snapshotPaths);for(const e of _)if(e.archiveSourcePath!==s)await captureSource(e.archiveSourcePath,e.canonicalSource?.role===`global`?u:v.get(e.path),e.canonicalSource);if(u)await assertBackupSqliteSourceGroup(u);for(const e of d)if(e.identity&&!sameFileIdentity(e.identity,await fs.stat(e.sourcePath,{bigint:true})))throw new Error(`Canonical SQLite path changed after discovery: ${e.sourcePath}`);return{inventory:h,snapshots:n,postgresSnapshots:r,postgresAnchors:i,discoveredSourcePaths:g.discoveredSourcePaths,sharedDatabaseSourcePath:a}}export{LegacyAuditBackupStateChangedError as a,stripSqliteSidecarSuffix as i,createBackupSqliteSnapshotPlan as n,createLegacyAuditBackupCapture as o,discoverBackupDatabasePaths as r,legacyAuditBackupCapturesMatch as s,classifyBackupSqliteSource as t};