openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 35.3 kB
JavaScript
import{n as containsAsciiControlCharacter}from"./string-normalization-D_oBUpO3.mjs";import{f as syncDirectoryIfSupported,i as pinDirectory,l as syncDirectory,n as getPublishFileExclusiveFailureDetails,o as publishFileNoClobber,s as requireDirectorySync,t as ensureDurableDirectory}from"./directory-durability-o_aQCRBZ.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{i as ensureAbsoluteDirectory$1,o as isPathInside,r as canonicalPathFromExistingAncestor$1}from"./fs-safe-Bxzu1j4h.mjs";import"./paths-D_FOvGon.mjs";import{n as normalizeAgentId,t as isValidAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{o as readSqliteUserVersion}from"./sqlite-user-version-DaJ6mdUV.mjs";import{i as findGitRoot}from"./git-commit-Cb3n8ZQM.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{t as applyPrivateModeSync}from"./private-mode-Bw_N-P5J.mjs";import{c as createPrivateSqliteDirectory,l as createPrivateSqliteTempDirectory}from"./sqlite-snapshot-staging-DUZ7pEYA.mjs";import{t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import{i as assertSqliteIntegrity}from"./sqlite-integrity-BzUEDiX5.mjs";import{i as assertSupportedStateSchemaVersion}from"./openclaw-state-db-schema-version-DreEd78i.mjs";import{n as assertOpenClawStateDatabaseForMaintenance,r as assertOpenClawStateDatabaseOwner}from"./openclaw-state-db-maintenance-BGNaiVRT.mjs";import{i as createVerifiedSqliteSnapshot,o as publishVerifiedSqliteFile}from"./sqlite-snapshot-D4gm3rAo.mjs";import{t as readBackupEngine}from"./physical-store-Dt80uUi6.mjs";import{t as resolveSystemBin}from"./resolve-system-bin-BxjtTRjs.mjs";import{n as runExec}from"./exec-c5tqm8tb.mjs";import{i as assertSupportedAgentSchemaVersion}from"./openclaw-agent-db-schema-read-CQmdNEsa.mjs";import{n as sanitizeOpenClawStateLeaseRows,t as sanitizeOpenClawGlobalStateSnapshot}from"./openclaw-state-snapshot-sanitizer-C-SbyO9u.mjs";import{t as assertNotUpdateCapturePath}from"./update-capture-paths-C5GOuESg.mjs";import{t as embedSessionColdArchivesInSnapshot}from"./session-cold-storage-backup-5R4hIGmo.mjs";import{a as assertFreshRestoreTarget,c as hashSnapshotArtifact,d as SNAPSHOT_MANIFEST_FILENAME,f as SNAPSHOT_SQLITE_FILENAME,l as readSnapshotManifest,n as readSnapshotExportEnvelope,o as assertNoSqliteSidecarsSync,s as copySnapshotArtifact,u as writeSnapshotManifest}from"./export-envelope-Dwkiigow.mjs";import{r as verifyMatchedPostgresBackup}from"./database-backup.operations-C3IunZW3.mjs";import{n as capturePostgresBackup,s as preparePostgresRestore,u as runOfflineDatabaseBackup}from"./database-backup-yFN_P503.mjs";import{n as assertOpenClawAgentDatabaseOwner,t as assertOpenClawAgentDatabaseForMaintenance}from"./openclaw-agent-db-maintenance-BgAjdkRB.mjs";import{t as loadSqliteVecExtension}from"./sqlite-vec-D-Kq5nmv.mjs";import fs from"node:fs";import path from"node:path";import{randomUUID}from"node:crypto";import fs$1 from"node:fs/promises";import os from"node:os";import{isDeepStrictEqual}from"node:util";import{assertDirectoryIdentitySync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import{FsSafeError}from"@openclaw/fs-safe/errors";import{readOwnerAndDaclBatch}from"@openclaw/fs-safe/permissions";import assert from"node:assert/strict";
//!src/snapshot/openclaw-snapshot-copy.ts
function normalizeSnapshotIdentity(e){if(e.role===`global`)return e;if(e.role===`agent`){const t=normalizeAgentId(e.agentId);if(!isValidAgentId(e.agentId)||t!==e.agentId)throw new Error(`SQLite snapshot agent id must be canonical: ${e.agentId}`);return{role:`agent`,agentId:t}}const t=e.id.trim();if(!t||t!==e.id||t.length>256||containsAsciiControlCharacter(t))throw new Error(`SQLite snapshot generic database id is invalid.`);return{role:`generic`,id:t}}function buildSnapshotValidator(e){return(t,n)=>{if(e.role===`global`){const e=assertSupportedStateSchemaVersion(t,n);const r=assertOpenClawStateDatabaseOwner(t,{pathname:n});assert(e>0&&r.schema_version===e,`Invalid snapshot schema version.`)}else if(e.role===`agent`){const r=assertSupportedAgentSchemaVersion(t,n);const i=assertOpenClawAgentDatabaseOwner(t,{pathname:n,agentId:e.agentId});assert(r>0&&i.schemaVersion===r,`Invalid snapshot schema version.`)}}}async function createOpenClawSnapshotCopy(e){assertNotUpdateCapturePath(e.database.path,resolveStateDir());const t=normalizeSnapshotIdentity(e.database.identity);return{identity:t,...await createVerifiedSqliteSnapshot({sourcePath:e.database.path,targetPath:e.targetPath,requireNonEmptySource:t.role!==`generic`,transform:async n=>{if(t.role===`global`)sanitizeOpenClawGlobalStateSnapshot(n);else if(t.role===`agent`)sanitizeOpenClawStateLeaseRows(n);await embedSessionColdArchivesInSnapshot({database:n,sourceStorePath:e.database.path})},validate:t.role===`global`?(e,t)=>assertOpenClawStateDatabaseForMaintenance(e,{pathname:t}):t.role===`agent`?(e,n)=>assertOpenClawAgentDatabaseForMaintenance(e,{pathname:n,agentId:t.agentId}):void 0})}}
//!src/snapshot/local-repository-directory-policy.ts
const MACOS_REPLACEMENT_ACL_PERMISSIONS=/* @__PURE__ */ new Set([`add_file`,`add_subdirectory`,`chown`,`delete`,`delete_child`,`writesecurity`]);const WINDOWS_STAGING_REPLACEMENT_RIGHTS_MASK=302841920;const WINDOWS_TRUSTED_OWNER_SIDS=/* @__PURE__ */ new Set([`S-1-5-18`,`S-1-5-32-544`,`S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464`]);const WINDOWS_TRUSTED_ACCESS_SIDS=/* @__PURE__ */ new Set([...WINDOWS_TRUSTED_OWNER_SIDS,`S-1-3-0`]);const WINDOWS_FILE_RIGHTS=[[1,`RD`],[2,`WD`],[4,`AD`],[8,`REA`],[16,`WEA`],[32,`X`],[64,`DC`],[128,`RA`],[256,`WA`],[65536,`D`],[131072,`RC`],[262144,`WDAC`],[524288,`WO`],[1048576,`S`],[33554432,`MA`],[268435456,`GA`],[536870912,`GE`],[1073741824,`GW`],[2147483648,`GR`]];const WINDOWS_KNOWN_FILE_RIGHTS_MASK=WINDOWS_FILE_RIGHTS.reduce((e,[t])=>e|t,0);let macosTrustedAclPrincipalsPromise;function assertDirectory(e,t,n){if(e.isSymbolicLink()||!e.isDirectory())throw new Error(`${n} must be a real directory: ${t}`)}async function assertDirectoryIdentity(e,t){const n=await fs$1.lstat(e,{bigint:true});assertDirectory(n,e,`SQLite staging directory`);if(!sameFileIdentity(n,t))throw new Error(`SQLite staging directory changed during operation: ${e}`)}function assertDirectoryIdentitySync$1(e,t){const n=fs.lstatSync(e,{bigint:true});assertDirectory(n,e,`SQLite staging directory`);if(!sameFileIdentity(n,t))throw new Error(`SQLite staging directory changed during operation: ${e}`)}async function assertTrustedStagingRoot(e,t,n={}){const r=path.resolve(t);const i=await fs$1.realpath(r);const a=await fs$1.lstat(i,{bigint:true});assertDirectory(a,i,`Private SQLite staging root`);if(!sameFileIdentity(a,e))throw new Error(`Private SQLite staging root changed during operation: ${r}`);if(process.platform===`win32`){await assertTrustedWindowsStagingPath(i);return i}const o=typeof process.getuid===`function`?process.getuid():void 0;const s=(Number(a.mode)&18)!==0;if(o===void 0||Number(a.uid)!==o||s&&n.allowModeRepair!==true)throw new Error(`Private SQLite staging root must be owned by the current user and not writable by other users: ${r}`);if(process.platform===`darwin`)await assertTrustedMacosAcl(i,n.allowModeRepair!==true);await assertTrustedPosixStagingAncestors(i,a,o);return i}async function assertPrivateStagingDirectory(e,t){const n=await fs$1.lstat(t,{bigint:true});assertDirectory(n,t,`Private SQLite staging directory`);if(!sameFileIdentity(n,e))throw new Error(`Private SQLite staging directory changed during operation: ${t}`);if(process.platform===`win32`)return;const r=typeof process.getuid===`function`?process.getuid():void 0;if(r===void 0||Number(n.uid)!==r||(n.mode&63n)!==0n)throw new Error(`Private SQLite staging directory permissions are unsafe: ${t}`);if(process.platform===`darwin`)await assertTrustedMacosAcl(t,true)}async function assertTrustedPosixStagingAncestors(e,t,n){let r=t;let i=path.dirname(e);while(i!==e){const e=await fs$1.lstat(i);assertDirectory(e,i,`SQLite staging ancestor`);const t=(e.mode&18)!==0;const a=e.uid!==n&&e.uid!==0;const o=e.uid===n||e.uid===0;const s=(e.mode&512)!==0&&o&&Number(r.uid)===n;if(a||t&&!s)throw new Error(`SQLite staging ancestor must not allow another user to replace its child: ${i}`);if(process.platform===`darwin`)await assertTrustedMacosAcl(i,false);const c=path.dirname(i);if(c===i)return;r=e;i=c}}function parseMacosAclEntries(e,t){const n=e.split(/\r?\n/u);const r=n.shift();if(!r)throw new Error(`Unable to inspect macOS ACL for SQLite staging: ${t}`);const i=[];for(const e of n){if(!/^\s*\d+:\s/u.test(e))continue;const n=e.match(/^\s*\d+:\s+(.+?)\s+(?:inherited\s+)?(allow|deny)\s+([a-z_,]+)\s*$/u);if(!n)throw new Error(`Unable to parse macOS ACL for SQLite staging: ${t}`);const[,r,a,o]=n;if(!r||!o||a!==`allow`&&a!==`deny`)throw new Error(`Unable to parse macOS ACL for SQLite staging: ${t}`);i.push({principal:normalizeAclPrincipal(r),effect:a,permissions:new Set(o.split(`,`))})}if(/^[^\s]{10}\+/u.test(r)&&i.length===0)throw new Error(`Unable to parse macOS ACL for SQLite staging: ${t}`);return i}function normalizeAclPrincipal(e){return e.trim().toLowerCase()}async function resolveTrustedMacosAclPrincipals(){macosTrustedAclPrincipalsPromise??=(async()=>{const e=resolveSystemBin(`dsmemberutil`);if(!e)throw new Error(`Unable to resolve dsmemberutil for macOS ACL verification.`);const t=os.userInfo().username;const n=/* @__PURE__ */ new Set([t,`root`]);const r=/* @__PURE__ */ new Set;for(const t of n){const{stdout:n}=await runExec(e,[`getuuid`,`-U`,t],{timeoutMs:5e3,maxBuffer:65536});const i=n.trim();if(!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu.test(i))throw new Error(`Unable to resolve trusted macOS ACL principal for ${t}.`);r.add(normalizeAclPrincipal(i));r.add(normalizeAclPrincipal(t));r.add(normalizeAclPrincipal(`user:${t}`))}return r})();return await macosTrustedAclPrincipalsPromise}async function assertTrustedMacosAcl(e,t){const n=resolveSystemBin(`ls`);if(!n)throw new Error(`Unable to verify macOS ACL for SQLite staging: ${e}`);let r;try{const[t,i]=await Promise.all([runExec(n,[`-lden`,`--`,e],{timeoutMs:5e3,maxBuffer:1048576}),resolveTrustedMacosAclPrincipals()]);r=parseMacosAclEntries(t.stdout,e).filter(e=>!i.has(e.principal))}catch(t){throw new Error(`Unable to verify macOS ACL for SQLite staging: ${e}`,{cause:t})}if(r.find(e=>e.effect===`allow`&&(t||[...e.permissions].some(e=>MACOS_REPLACEMENT_ACL_PERMISSIONS.has(e)))))throw new Error(`macOS ACL permits untrusted SQLite staging access: ${e}`)}async function assertTrustedWindowsStagingPath(e){const t=[e];let n=path.dirname(e);while(n!==e){t.push(n);const e=path.dirname(n);if(e===n)break;n=e}let r;try{r=await readOwnerAndDaclBatch(t)}catch(t){throw new Error(`Unable to verify private Windows ACL for SQLite staging: ${e}`,{cause:t})}for(const[e,n]of t.entries()){const t=r[e];if(t.status!==`supported`||!t.isLocal||!t.daclPresent||!t.complete)throw new Error(`Unable to verify private Windows ACL for SQLite staging: ${n}`);assertTrustedWindowsAcl(n,e===0,t)}}function assertTrustedWindowsAcl(e,t,n){const r=t?`repository root`:`ancestor`;const i=n.currentUserSid.toUpperCase();const a=n.ownerSid.toUpperCase();if(a!==i&&!WINDOWS_TRUSTED_OWNER_SIDS.has(a))throw new Error(`Windows SQLite staging ${r} is owned by an untrusted principal: path=${e} principal=${a}. Choose a local directory owned only by the current user or a trusted OS principal.`);const o=n.aces.filter(e=>e.aceType===`allow`);if(o.length===0)throw new Error(`Unable to verify private Windows ACL for SQLite staging: ${e}`);let s=t?-1048577:WINDOWS_STAGING_REPLACEMENT_RIGHTS_MASK|~WINDOWS_KNOWN_FILE_RIGHTS_MASK;if(!t&&n.isVolumeRoot===true)s&=-65537;const c=o.find(e=>{const n=e.sid.toUpperCase();return n!==i&&!WINDOWS_TRUSTED_ACCESS_SIDS.has(n)&&(t||!e.flags.inheritOnly)&&(e.mask&s)!==0});if(c)throw new Error(`Windows ACL permits untrusted SQLite staging access on ${r}: path=${e} principal=${c.sid.toUpperCase()} rights=${formatWindowsSecurityRights(c)}. Remove the untrusted grant or choose a private local directory; do not use a shared or synced root.`)}function formatWindowsSecurityRights(e){const t=WINDOWS_FILE_RIGHTS.filter(([t])=>(e.mask&t)!==0).map(([,e])=>e);if((e.mask&~WINDOWS_KNOWN_FILE_RIGHTS_MASK)!==0)t.push(`UNKNOWN`);return`${[e.flags.objectInherit?`(OI)`:``,e.flags.containerInherit?`(CI)`:``,e.flags.noPropagateInherit?`(NP)`:``,e.flags.inheritOnly?`(IO)`:``].join(``)}(${t.join(`,`)})`}
//!src/snapshot/local-repository-private-directory.ts
function isPrivateDirectoryAlreadyExists(e){return process.platform===`win32`?e instanceof FsSafeError&&e.code===`already-exists`:e.code===`EEXIST`}async function createPrivateSnapshotDirectory(e){try{await createPrivateSqliteDirectory(e)}catch(t){if(isPrivateDirectoryAlreadyExists(t))throw new Error(`SQLite snapshot directory already exists: ${e}`,{cause:t});throw t}}
//!src/snapshot/local-repository.ts
const SNAPSHOT_DIRECTORY_MODE=448;const SNAPSHOT_FILE_MODE=384;const SNAPSHOT_PENDING_FILENAME=`.pending`;const SNAPSHOT_ARTIFACT_ENTRIES=/* @__PURE__ */ new Set([SNAPSHOT_MANIFEST_FILENAME,SNAPSHOT_PENDING_FILENAME,SNAPSHOT_SQLITE_FILENAME]);const RESTORE_STAGING_ENTRIES=/* @__PURE__ */ new Set([SNAPSHOT_SQLITE_FILENAME]);const VALIDATION_STAGING_ENTRIES=/* @__PURE__ */ new Set([SNAPSHOT_SQLITE_FILENAME,...SQLITE_SIDECAR_SUFFIXES.map(e=>`${SNAPSHOT_SQLITE_FILENAME}${e}`)]);function createLocalSqliteSnapshotProvider(e){return new LocalSqliteSnapshotProvider(e)}function createLocalSnapshotProvider({expectedPostgresSource:e,...t}){const n=createLocalSqliteSnapshotProvider(t);const r=path.resolve(t.repositoryPath);const locate=async e=>{const t=path.resolve(e.path);if(path.dirname(t)!==r)throw new Error(`Snapshot must be an immediate repository child.`);await assertTrustedStagingRoot(await fs$1.lstat(r,{bigint:true}),r);assertDirectory(await fs$1.lstat(t,{bigint:true}),t,`Snapshot`);return t};const i={async create(e){if(readBackupEngine(e.path).engine===`sqlite`)return n.create(e);const i=await ensurePrivateSnapshotRepositoryRoot(r);const a=path.join(i,`${(t.now?.()??/* @__PURE__ */ new Date).toISOString().replaceAll(/[:.]/g,`-`)}-${randomUUID()}`);const o=normalizeSnapshotIdentity(e.identity);if(t.allowedDatabaseRoles&&!t.allowedDatabaseRoles.includes(o.role))throw new Error(`Snapshot database role is not allowed.`);const s=await capturePostgresBackup({sourcePath:e.path,directory:a});return{ref:{path:a},manifest:s}},async verify(t){const r=await locate(t);if((await readSnapshotExportEnvelope(r)).engine===`sqlite`&&!e)return n.verify(t);return{ok:true,manifest:await verifyMatchedPostgresBackup(r,`user-backup`,e)}},async restoreFresh(t,i){const a=await locate(t);const o=await readSnapshotExportEnvelope(a);if(o.engine===`sqlite`&&!e)return n.restoreFresh(t,i);const s=path.join(await canonicalPathFromExistingAncestor$1(path.dirname(path.resolve(i))),path.basename(i));if(isPathInside(r,s))throw new Error(`Restore target must be outside its repository.`);await assertFreshRestoreTarget(s);const c=await ensureRestoreParentDirectory(path.dirname(s));return runOfflineDatabaseBackup(s,({config:t,assertCurrent:n})=>withPrivateSqliteStagingDirectory({rootReceipt:c,prefix:`.tmp-restore-`,allowedEntries:RESTORE_STAGING_ENTRIES,operation:async r=>{const i=path.join(r,SNAPSHOT_SQLITE_FILENAME);const c=await preparePostgresRestore({directory:a,anchorPath:i,config:t,profile:`user-backup`,expectedSource:e,assertCurrent:n});await publishVerifiedSqliteFile({sourcePath:i,sourceIdentity:await fs$1.lstat(i,{bigint:true}),targetPath:s,expectedContent:c,requireAtomicPublication:true,beforePublish:async()=>{n();await assertFreshRestoreTarget(s)},afterPublish:e=>e.assertTargetMatchesExpectedContent(n)});return{ok:true,manifest:o.manifest}}}))},async list(){const e=[];if(!await lstatIfExists(r))return[];for(const t of await fs$1.readdir(r,{withFileTypes:true})){if(!t.isDirectory()||t.name.startsWith(`.tmp-`))continue;const n={path:path.join(r,t.name)};if(await lstatIfExists(path.join(n.path,`.pending`)))continue;e.push({ref:n,manifest:(await i.verify(n)).manifest})}return e.toSorted((e,t)=>t.manifest.createdAt.localeCompare(e.manifest.createdAt))}};return i}var LocalSqliteSnapshotProvider=class{#e;#t;#n;#r;constructor(e){this.#e=e.allowedDatabaseRoles;this.#t=path.resolve(e.repositoryPath);this.#n=path.resolve(e.validationRootPath??path.dirname(this.#t));this.#r=e.now??(()=>/* @__PURE__ */ new Date)}async create(e){const t=await ensurePrivateDirectory(this.#t,`SQLite snapshot repository`);const n=t.exactIdentity;const r=await assertTrustedStagingRoot(n,this.#t);const i=path.resolve(e.path);const a=normalizeSnapshotIdentity(e.identity);const o=this.#r();if(!Number.isFinite(o.getTime()))throw new Error(`SQLite snapshot timestamp is invalid.`);const s=`${o.toISOString().replaceAll(/[:.]/g,`-`)}-${randomUUID()}`;const c=path.join(this.#t,s);const l=path.join(r,s);const u=path.join(r,`.tmp-${randomUUID()}`);const d=path.join(u,SNAPSHOT_SQLITE_FILENAME);await assertDirectoryIdentity(r,n);await createPrivateSqliteDirectory(u);let f;let p;let m;const h=/* @__PURE__ */ new Map;let g=false;try{await assertDirectoryIdentity(r,n);f=await fs$1.lstat(u,{bigint:true});applyPrivateModeSync(u,SNAPSHOT_DIRECTORY_MODE);await assertPrivateStagingDirectory(f,u);await assertDirectoryIdentity(r,n);const e=await createOpenClawSnapshotCopy({database:{path:i,identity:a},targetPath:d});applyPrivateModeSync(d,SNAPSHOT_FILE_MODE);const _=await hashSnapshotArtifact(u);const v={schemaVersion:1,snapshotId:s,createdAt:o.toISOString(),database:buildDatabaseManifest(a,i,e.userVersion),artifact:{path:SNAPSHOT_SQLITE_FILENAME,sha256:_.sha256,sizeBytes:_.sizeBytes}};await writeSnapshotManifest(u,v);applyPrivateModeSync(path.join(u,SNAPSHOT_MANIFEST_FILENAME),SNAPSHOT_FILE_MODE);await syncDirectoryIfSupported(u);await assertDirectoryIdentity(r,n);await createPrivateSnapshotDirectory(l);g=true;await assertDirectoryIdentity(r,n);p=await pinDirectory(l,{label:`SQLite snapshot directory`});m=p.receipt.exactIdentity;applyPrivateModeSync(l,SNAPSHOT_DIRECTORY_MODE);await assertPrivateStagingDirectory(m,l);await p.assertCurrent();const y=path.join(l,SNAPSHOT_PENDING_FILENAME);const b=await fs$1.open(y,`wx+`,SNAPSHOT_FILE_MODE);let x;try{x=await b.stat({bigint:true});h.set(SNAPSHOT_PENDING_FILENAME,x);await b.sync()}finally{await b.close()}await p.assertCurrent();requireDirectorySync(await p.sync(),`SQLite snapshot directory`);await assertDirectoryIdentity(r,n);requireDirectorySync(await syncDirectory(t),`SQLite snapshot repository`);await p.assertCurrent();await publishSnapshotEntryNoOverwrite(path.join(u,SNAPSHOT_SQLITE_FILENAME),path.join(l,SNAPSHOT_SQLITE_FILENAME),SNAPSHOT_SQLITE_FILENAME,h);await p.assertCurrent();await publishSnapshotEntryNoOverwrite(path.join(u,SNAPSHOT_MANIFEST_FILENAME),path.join(l,SNAPSHOT_MANIFEST_FILENAME),SNAPSHOT_MANIFEST_FILENAME,h);await p.assertCurrent();requireDirectorySync(await p.sync(),`SQLite snapshot directory`);await commitPendingSnapshot({allowedDatabaseRoles:void 0,repositoryIdentity:n,repositoryPath:r,snapshotPath:l,snapshotDirectory:p,validationRootPath:r,expected:{manifest:v,pendingIdentity:x}});h.delete(SNAPSHOT_PENDING_FILENAME);await p.close();p=void 0;return{ref:{path:c},manifest:v}}catch(e){await p?.close().catch(()=>void 0);if(g)m??=await fs$1.lstat(l,{bigint:true}).catch(()=>void 0);if(m){if(await removePublishedSnapshotDirectoryIfOwned(l,m,h))await syncDirectoryIfSupported(r)}throw e}finally{if(f?await removePrivateDirectoryIfOwned(u,f,SNAPSHOT_ARTIFACT_ENTRIES).catch(()=>false):await fs$1.rmdir(u).then(()=>true).catch(()=>false))await syncDirectoryIfSupported(r).catch(()=>void 0)}}async verify(e){const t=await this.#i(e);const n=await readVerifiedSnapshotManifest(t);assertAllowedDatabaseRole(n,this.#e);const r=await hashSnapshotArtifact(t);const i=path.join(t,SNAPSHOT_SQLITE_FILENAME);assertArtifactMatchesManifest(i,r,n);await verifySnapshotDatabaseFile(i,r.identity,n,this.#n);await assertSnapshotContents(t);return{ok:true,manifest:n}}async restoreFresh(e,t){const n=await this.#i(e);const r=await readVerifiedSnapshotManifest(n);assertAllowedDatabaseRole(r,this.#e);const i=path.resolve(t);await assertFreshRestoreTarget(i);const a=await fs$1.realpath(this.#t);const o=await canonicalPathFromExistingAncestor$1(path.dirname(i));const s=path.join(o,path.basename(i));if(isPathInside(a,s))throw new Error(`SQLite restore target must be outside snapshot repository ${this.#t}: ${i}`);const c=path.dirname(s);const l=await ensureRestoreParentDirectory(c);const u=await fs$1.realpath(c);const d=path.join(u,path.basename(i));if(!isPathInside(s,d)||!isPathInside(d,s))throw new Error(`SQLite restore target changed while creating its parent: ${i}`);if(isPathInside(a,d))throw new Error(`SQLite restore target must be outside snapshot repository ${this.#t}: ${i}`);const f=await fs$1.lstat(u,{bigint:true});if(!sameFileIdentity(l.exactIdentity,f))throw new Error(`SQLite restore parent changed after durable creation: ${u}`);await assertFreshRestoreTarget(d);return await withPrivateSqliteStagingDirectory({rootReceipt:l,prefix:`.tmp-restore-`,allowedEntries:RESTORE_STAGING_ENTRIES,operation:async(e,t)=>{const i=path.join(e,SNAPSHOT_SQLITE_FILENAME);const a=await copySnapshotArtifact(n,i);await assertDirectoryIdentity(e,t);assertArtifactMatchesManifest(i,a,r);await assertSnapshotContents(n);await verifySnapshotDatabaseFile(i,a.identity,r,u);await publishVerifiedSqliteFile({sourceIdentity:a.identity,sourcePath:i,targetPath:d,expectedContent:r.artifact,requireAtomicPublication:true,beforePublish:async()=>{await assertDirectoryIdentity(u,f);await assertFreshRestoreTarget(d)},afterPublish:e=>{e.assertTargetMatchesExpectedContent(()=>{assertDirectoryIdentitySync$1(u,f);assertNoSqliteSidecarsSync(d,`Restored SQLite database has unexpected sidecar`)})}});return{ok:true,manifest:r}}})}async list(){const e=await lstatIfExists(this.#t);if(!e)return[];assertDirectory(e,this.#t,`SQLite snapshot repository`);if(findGitRoot(this.#t,{maxDepth:1}))throw new Error(`Git backup repository is not a SQLite snapshot repository: ${this.#t}. Use \`openclaw backup git log --repository <path>\` instead.`);const t=await fs$1.readdir(this.#t,{withFileTypes:true});const n=[];for(const r of t){const t=path.join(this.#t,r.name);if(r.name.startsWith(`.tmp-`)){if(r.isSymbolicLink()||!r.isDirectory())throw new Error(`SQLite snapshot repository contains unsafe staging entry: ${t}`);continue}if(r.isSymbolicLink()||!r.isDirectory())throw new Error(`SQLite snapshot repository contains unexpected entry: ${t}`);const i=await classifySnapshotDirectory(t);if(i===`incomplete`)continue;const a=i===`complete-pending`?await recoverCompletePendingSnapshot({allowedDatabaseRoles:this.#e,repositoryIdentity:e,repositoryPath:this.#t,snapshotPath:t,validationRootPath:this.#n}):await readVerifiedSnapshotManifest(t);assertAllowedDatabaseRole(a,this.#e);n.push({ref:{path:t},manifest:a})}return n.toSorted((e,t)=>t.manifest.createdAt.localeCompare(e.manifest.createdAt)||t.manifest.snapshotId.localeCompare(e.manifest.snapshotId))}async#i(e){const t=path.resolve(e.path);if(path.dirname(t)!==this.#t)throw new Error(`SQLite snapshot must be an immediate child of repository ${this.#t}: ${t}`);const n=await lstatIfExists(this.#t);if(!n)throw new Error(`SQLite snapshot repository does not exist: ${this.#t}. Check the snapshot path or create a snapshot with \`openclaw backup sqlite create\`.`);assertDirectory(n,this.#t,`SQLite snapshot repository`);const r=await lstatIfExists(t);if(!r)throw new Error(`SQLite snapshot does not exist: ${t}. Run \`openclaw backup sqlite list --repository ${this.#t}\` to inspect available snapshots.`);assertDirectory(r,t,`SQLite snapshot`);if(await lstatIfExists(path.join(t,SNAPSHOT_PENDING_FILENAME))){if(await classifySnapshotDirectory(t)===`complete-pending`)await recoverCompletePendingSnapshot({allowedDatabaseRoles:this.#e,repositoryIdentity:n,repositoryPath:this.#t,snapshotPath:t,validationRootPath:this.#n})}return t}};async function readVerifiedSnapshotManifest(e){await assertSnapshotContents(e);return await readSnapshotManifest(e)}function assertArtifactMatchesManifest(e,t,n){if(t.sizeBytes!==n.artifact.sizeBytes)throw new Error(`Snapshot artifact size mismatch for ${e}: expected ${n.artifact.sizeBytes}, got ${t.sizeBytes}`);if(t.sha256!==n.artifact.sha256)throw new Error(`Snapshot artifact hash mismatch for ${e}: expected ${n.artifact.sha256}, got ${t.sha256}`)}function assertAllowedDatabaseRole(e,t){if(!t||t.includes(e.database.role))return;throw new Error(`SQLite snapshot database role ${e.database.role} is not allowed for this operation.`)}async function verifySnapshotDatabaseFile(e,t,n,r){const i=await fs$1.lstat(e,{bigint:true});if(i.isSymbolicLink()||!i.isFile()||i.nlink>1n||!sameFileIdentity(t,i))throw new Error(`Snapshot artifact changed before SQLite verification: ${e}`);const a=await lstatIfExists(r);if(!a)throw new Error(`SQLite validation root does not exist: ${r}. Create a private directory there or pass an existing directory with \`--scratch\`.`);assertDirectory(a,r,`SQLite validation root`);const o=await fs$1.realpath(r);await withPrivateSqliteStagingDirectory({rootReceipt:{path:o,realPath:o,identity:a,exactIdentity:a},prefix:`.tmp-verify-`,allowedEntries:VALIDATION_STAGING_ENTRIES,operation:async t=>{const r=path.join(t,SNAPSHOT_SQLITE_FILENAME);const i=await copySnapshotArtifact(path.dirname(e),r);assertArtifactMatchesManifest(r,i,n);const a=openNodeSqliteDatabase(r,{allowExtension:true,readOnly:true});try{a.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`);await loadSqliteVecExtension({db:a});assertSqliteIntegrity(a,e);buildSnapshotValidator(n.database)(a,e);const t=readSqliteUserVersion(a);if(t!==n.database.userVersion)throw new Error(`Snapshot database user_version mismatch for ${e}: expected ${n.database.userVersion}, got ${t}`)}finally{a.close()}const o=await hashSnapshotArtifact(t);if(!sameFileIdentity(i.identity,o.identity))throw new Error(`Snapshot validation copy changed: ${r}`);assertArtifactMatchesManifest(r,o,n)}});const s=await fs$1.lstat(e,{bigint:true});if(s.isSymbolicLink()||!s.isFile()||s.nlink>1n||!sameFileIdentity(t,s))throw new Error(`Snapshot artifact changed during SQLite verification: ${e}`);const c=await hashSnapshotArtifact(path.dirname(e));if(!sameFileIdentity(t,c.identity))throw new Error(`Snapshot artifact changed after SQLite verification: ${e}`);assertArtifactMatchesManifest(e,c,n)}function buildDatabaseManifest(e,t,n){const r=path.basename(t);if(e.role===`global`)return{role:`global`,basename:r,userVersion:n};if(e.role===`agent`)return{role:`agent`,agentId:e.agentId,basename:r,userVersion:n};return{role:`generic`,id:e.id,basename:r,userVersion:n}}async function ensurePrivateDirectory(e,t){let n;if(process.platform!==`win32`){n=await lstatIfExists(e);if(n){assertDirectory(n,e,t);const r=await assertTrustedStagingRoot(n,e,{allowModeRepair:true});assertDirectoryIdentitySync(e,{dev:n.dev,ino:n.ino,realPath:r});applyPrivateModeSync(e,SNAPSHOT_DIRECTORY_MODE)}}const r=await ensureDurableDirectory({directoryPath:e,label:t,expectedExistingIdentity:n,create:async e=>{if(process.platform===`win32`){const n=await ensureAbsoluteDirectory$1(path.dirname(e),{mode:SNAPSHOT_DIRECTORY_MODE,scopeLabel:t});if(!n.ok)throw n.error;try{await createPrivateSqliteDirectory(e);return}catch(e){if(!isPrivateDirectoryAlreadyExists(e))throw e}}const n=await ensureAbsoluteDirectory$1(e,{mode:SNAPSHOT_DIRECTORY_MODE,scopeLabel:t});if(!n.ok)throw n.error;applyPrivateModeSync(n.path,SNAPSHOT_DIRECTORY_MODE)}});requireDirectorySync(r.parentSync,t);return r}async function ensureRestoreParentDirectory(e){const t=await ensureDurableDirectory({directoryPath:e,label:`SQLite restore target`,create:async e=>{const t=await ensureAbsoluteDirectory$1(e,{mode:SNAPSHOT_DIRECTORY_MODE,scopeLabel:`SQLite restore target`});if(!t.ok)throw t.error}});requireDirectorySync(t.parentSync,`SQLite restore target`);return t}async function publishSnapshotEntryNoOverwrite(e,t,n,r){let i;try{i=await publishFileNoClobber(e,t,{strategy:`link-or-copy`,moveSource:true,durability:`fail-closed`})}catch(i){const a=getPublishFileExclusiveFailureDetails(i);if(a?.targetCreated&&a.cleanup!==`removed`){const[i,o]=await Promise.all([fs$1.lstat(e,{bigint:true}).catch(()=>void 0),fs$1.lstat(t,{bigint:true}).catch(()=>void 0)]);const s=a.exactTargetIdentity&&o&&sameFileIdentity(a.exactTargetIdentity,o);const c=i&&o&&sameFileIdentity(i,o);if(o&&(s||c))r.set(n,o)}throw i}const a=i.exactIdentity;r.set(n,a);const o=await fs$1.lstat(t,{bigint:true});if(!sameFileIdentity(a,o))throw new Error(`SQLite snapshot entry changed during publication: ${t}`);const s=await fs$1.lstat(t,{bigint:true});if(!sameFileIdentity(o,s))throw new Error(`SQLite snapshot entry changed after publication: ${t}`)}async function assertSnapshotContents(e,t=false){const n=/* @__PURE__ */ new Set([SNAPSHOT_MANIFEST_FILENAME,SNAPSHOT_SQLITE_FILENAME]);const r=await fs$1.readdir(e,{withFileTypes:true});for(const i of r){if(t&&i.name===SNAPSHOT_PENDING_FILENAME){readPendingSnapshotIdentity(path.join(e,i.name));continue}if(!n.delete(i.name))throw new Error(`SQLite snapshot contains unexpected entry: ${path.join(e,i.name)}`);if(i.isSymbolicLink()||!i.isFile())throw new Error(`SQLite snapshot entry must be a regular file: ${path.join(e,i.name)}`);if((await fs$1.lstat(path.join(e,i.name))).nlink>1)throw new Error(`SQLite snapshot entry must not be hardlinked: ${path.join(e,i.name)}`)}if(n.size>0)throw new Error(`SQLite snapshot is missing ${[...n].join(`, `)}: ${e}`)}async function classifySnapshotDirectory(e){const t=await fs$1.readdir(e,{withFileTypes:true});const n=/* @__PURE__ */ new Set([SNAPSHOT_MANIFEST_FILENAME,SNAPSHOT_PENDING_FILENAME,SNAPSHOT_SQLITE_FILENAME]);for(const r of t)if(!n.has(r.name)||r.isSymbolicLink()||!r.isFile())throw new Error(`SQLite snapshot contains unexpected incomplete entry: ${path.join(e,r.name)}`);const r=new Set(t.map(e=>e.name));if(r.size===0)return`incomplete`;if(!r.has(SNAPSHOT_PENDING_FILENAME))return`committed`;return r.has(`manifest.json`)&&r.has(`database.sqlite`)?`complete-pending`:`incomplete`}async function recoverCompletePendingSnapshot(e){const t=await assertTrustedStagingRoot(e.repositoryIdentity,e.repositoryPath);await assertDirectoryIdentity(t,e.repositoryIdentity);const n=await pinDirectory(e.snapshotPath,{label:`SQLite pending snapshot directory`});try{await assertPrivateStagingDirectory(n.receipt.exactIdentity,e.snapshotPath);return await commitPendingSnapshot({...e,repositoryPath:t,snapshotDirectory:n})}finally{await n.close().catch(()=>void 0)}}async function commitPendingSnapshot(e){const{snapshotPath:t,snapshotDirectory:n,expected:r}=e;const i=r?`SQLite snapshot directory`:`SQLite pending snapshot directory`;await n.assertCurrent();await assertSnapshotContents(t,true);const a=await readSnapshotManifest(t);if(r&&!isDeepStrictEqual(a,r.manifest))throw new Error(`SQLite snapshot manifest changed during publication: ${t}`);assertAllowedDatabaseRole(a,e.allowedDatabaseRoles);const o=await hashSnapshotArtifact(t);const s=path.join(t,SNAPSHOT_SQLITE_FILENAME);assertArtifactMatchesManifest(s,o,a);await verifySnapshotDatabaseFile(s,o.identity,a,e.validationRootPath);if(!r)requireDirectorySync(await n.sync(),i);const c=path.join(t,SNAPSHOT_PENDING_FILENAME);const l=readPendingSnapshotIdentity(c);if(l){if(r&&!sameFileIdentity(r.pendingIdentity,l))throw new Error(`SQLite snapshot pending marker changed: ${c}`);await n.assertCurrent();const e=readPendingSnapshotIdentity(c);if(e){if(!sameFileIdentity(l,e))throw new Error(`SQLite snapshot pending marker changed: ${c}`);try{fs.unlinkSync(c)}catch(e){if(e.code!==`ENOENT`)throw e}}}requireDirectorySync(await n.sync(),i);await n.assertCurrent();const u=await readSnapshotManifest(t);if(!isDeepStrictEqual(u,a))throw new Error(`SQLite snapshot manifest changed ${r?`after commit`:`during recovery`}: ${t}`);assertArtifactMatchesManifest(s,await hashSnapshotArtifact(t),u);await assertSnapshotContents(t);await n.assertCurrent();await assertDirectoryIdentity(e.repositoryPath,e.repositoryIdentity);return u}function readPendingSnapshotIdentity(e){const t=lstatIfExistsSync(e);if(t&&(t.isSymbolicLink()||!t.isFile()||t.nlink>1n))throw new Error(`SQLite snapshot pending marker is unsafe: ${e}`);return t}async function lstatIfExists(e){try{return await fs$1.lstat(e,{bigint:true})}catch(e){if(e.code===`ENOENT`)return;throw e}}function lstatIfExistsSync(e){try{return fs.lstatSync(e,{bigint:true})}catch(e){if(e.code===`ENOENT`)return;throw e}}async function removePrivateDirectoryIfOwned(e,t,n){const r=await lstatIfExists(e);if(!r)return false;if(r.isSymbolicLink()||!r.isDirectory()||!sameFileIdentity(r,t))throw new Error(`Private SQLite staging directory changed before cleanup: ${e}`);const i=await fs$1.readdir(e,{withFileTypes:true});const a=[];for(const t of i){const r=path.join(e,t.name);if(!n.has(t.name)||t.isSymbolicLink()||!t.isFile())throw new Error(`Private SQLite staging directory has unexpected entry: ${r}`);if((await fs$1.lstat(r)).nlink>1)throw new Error(`Private SQLite staging file must not be hardlinked: ${r}`);a.push(r)}await Promise.all(a.map(async e=>await fs$1.unlink(e)));await fs$1.rmdir(e);return true}async function withPrivateSqliteStagingDirectory(e){const t=await assertTrustedStagingRoot(e.rootReceipt.exactIdentity,e.rootReceipt.path);await assertDirectoryIdentity(t,e.rootReceipt.exactIdentity);const n=await createPrivateSqliteTempDirectory(t,e.prefix);const r=await fs$1.lstat(n,{bigint:true});let i;try{applyPrivateModeSync(n,SNAPSHOT_DIRECTORY_MODE);await assertPrivateStagingDirectory(r,n);await assertDirectoryIdentity(t,e.rootReceipt.exactIdentity);i={ok:true,value:await e.operation(n,r)}}catch(e){i={ok:false,error:e}}try{if(!await removePrivateDirectoryIfOwned(n,r,e.allowedEntries))throw new Error(`Private SQLite staging directory disappeared: ${n}`)}catch(e){if(!i.ok)throw new AggregateError([i.error,e],`SQLite staging operation and cleanup both failed: ${n}`,{cause:e});throw new Error(`Failed to clean private SQLite staging directory: ${n}`,{cause:e})}requireDirectorySync(await syncDirectory(e.rootReceipt),`Private SQLite staging root`);if(!i.ok)throw i.error;return i.value}async function ensurePrivateSnapshotRepositoryRoot(e){const t=await lstatIfExists(e);if(t)return await assertTrustedStagingRoot(t,e);const n=await ensurePrivateDirectory(e,`Git backup repository`);return await assertTrustedStagingRoot(n.exactIdentity,e)}async function removePublishedSnapshotDirectoryIfOwned(e,t,n){const r=await lstatIfExists(e);if(!r||r.isSymbolicLink()||!r.isDirectory()||!sameFileIdentity(r,t))return false;const i=await fs$1.readdir(e,{withFileTypes:true});for(const t of i){const r=n.get(t.name);if(!r||t.isSymbolicLink()||!t.isFile())continue;const i=path.join(e,t.name);const a=await fs$1.lstat(i,{bigint:true});if(sameFileIdentity(a,r))await fs$1.unlink(i)}if((await fs$1.readdir(e)).length>0)return false;await fs$1.rmdir(e);return true}export{createOpenClawSnapshotCopy as a,buildSnapshotValidator as i,createLocalSqliteSnapshotProvider as n,ensurePrivateSnapshotRepositoryRoot as r,createLocalSnapshotProvider as t};