UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines • 23.1 kB
import{t as toStringifiedError}from"./stringified-error-B2ELAgdP.mjs";import{o as writeRuntimeJson}from"./runtime-DIcLIHcp.mjs";import{c as sha256File}from"./directory-durability-o_aQCRBZ.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{n as formatDiskSpaceBytes,r as tryReadDiskSpace}from"./disk-space-D746MnLp.mjs";import{t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import{i as assertSqliteIntegrity}from"./sqlite-integrity-BzUEDiX5.mjs";import{n as readEngineAnchor}from"./open-1OjrnB9v.mjs";import{r as configureSqliteReadOnlyPragmas}from"./sqlite-wal-BDqYXlcm.mjs";import{r as readOpenClawAgentDatabaseRegistryRows}from"./openclaw-agent-db-registry.read-BLUjVOoj.mjs";import{m as list,r as extract}from"./esm-Ch36GTgp.mjs";import{i as readEngineAnchorIdentity}from"./physical-store-inspection-BHEZGfsf.mjs";import{a as normalizeArchiveRoot,c as resolvePortableArchivePathKey,i as normalizeArchivePath,n as findPortableArchiveEntryPathCollision,r as isArchivePathWithin,s as recordArchiveSymbolicLink,t as buildBackupArchivePath}from"./backup-archive-path-policy-CotYunH-.mjs";import{n as assertOpenClawAgentDatabaseOwner}from"./openclaw-agent-db-maintenance-BgAjdkRB.mjs";import{t as loadSqliteVecExtension}from"./sqlite-vec-D-Kq5nmv.mjs";import{c as verifyBackupManifestEntries,i as parseBackupManifest,l as verifyBackupSqliteCoverage,n as isRegularArchiveFile,o as readBackupManifestEntry,r as isRootBackupManifestEntry,s as resolvePostgresRestoreEntries}from"./backup-verify-manifest-B0AbwU0Y.mjs";import{c as resolveBackupArchivePath,t as BACKUP_MAX_DECOMPRESSION_RATIO}from"./backup-shared-CVcoDGTC.mjs";import{n as finishBackupScratch,t as createBackupScratchDirectory}from"./backup-scratch-C-DF8QD0.mjs";import{t as createBackupProgressLogger}from"./backup-progress-D6RlLyBn.mjs";import path from"node:path";import fs from"node:fs/promises";import os from"node:os"; //!src/commands/backup-recovery-config.ts function resolveBackupRecoveryConfig(e,t,n){const r=e.paths?.configPath??e.assets.find(e=>e.kind===`config`)?.sourcePath;if(!r)return{};const i=buildBackupArchivePath(e.archiveRoot,r);let a=e.paths?.configSourcePath??r;if(!e.paths?.configSourcePath){const t=n.find(({entryPath:e})=>e===i);if(t){const n=e.platform===`win32`?path.win32:path.posix;a=n.resolve(n.dirname(r),t.linkpath)}}const o=buildBackupArchivePath(e.archiveRoot,a);return{recoveryConfigContextPath:i,recoveryConfigPath:t.some(e=>e.normalized===o&&isRegularArchiveFile(e.type))?o:void 0}} //!src/commands/backup-verify-spool.ts const MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES=68719476736;const DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES=268435456;function resolveExtractionBytes(e,t=false){const n=t?`SQLite snapshot`:`Archive`;let r=0;for(const i of e){if(!t&&!isRegularArchiveFile(i.type))continue;if(!Number.isSafeInteger(i.size)||(i.size??-1)<0)throw new Error(t?`SQLite snapshot has an invalid archive size: ${i.normalized}`:`Archive regular file has an invalid size: ${i.normalized}`);if(t&&i.size===0)throw new Error(`SQLite snapshot is empty: ${i.normalized}`);r+=i.size??0;if(!Number.isSafeInteger(r))throw new Error(`${n} extraction size exceeds the supported integer range.`)}return r}async function assertSnapshotExtractionBudget(e){const t=e.postgres?`PostgreSQL artifacts`:`SQLite snapshots`;const n=resolveExtractionBytes(e.entries,!e.postgres);if(n>MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES)throw new Error(`${t} require ${formatDiskSpaceBytes(n)} of extraction space; the verification limit is ${formatDiskSpaceBytes(MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES)}.`);const r=n-e.spool.retainedBytes(e.entries);let i=tryReadDiskSpace(e.tempRoot);if(i&&r+DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES>i.availableBytes){await e.spool.discardExcept(e.entries);i=tryReadDiskSpace(e.tempRoot)}if(i&&r+DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES>i.availableBytes)throw new Error(`${t} require ${formatDiskSpaceBytes(r)} of extraction space, but only ${formatDiskSpaceBytes(i.availableBytes)} is available near ${e.tempRoot}; verification reserves ${formatDiskSpaceBytes(DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES)} for the host.`)}async function assertSqliteSnapshotFileShape(e,t,n){const r=Buffer.alloc(100);const i=await fs.open(e,`r`);try{const{bytesRead:e}=await i.read(r,0,r.byteLength,0);if(e!==r.byteLength||r.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`)throw new Error(`SQLite snapshot ${t} has an invalid database header.`)}finally{await i.close()}const a=r.readUInt16BE(16);const o=a===1?65536:a;if(!(o>=512&&o<=65536&&(o&o-1)===0)||n%o!==0)throw new Error(`SQLite snapshot ${t} has an invalid page layout.`);const s=r.readUInt32BE(24);const c=r.readUInt32BE(28);const l=r.readUInt32BE(92);if(c!==0&&s===l&&c!==n/o)throw new Error(`SQLite snapshot ${t} has an invalid page layout.`)}async function prepareDatabaseArtifacts(e,t,n){const{directory:r,missing:i}=await t.materialize(n);const a=new Map(i.map(e=>[e.raw,e]));if(i.length)await extract({file:e,gzip:true,maxDecompressionRatio:BACKUP_MAX_DECOMPRESSION_RATIO,cwd:r,strict:true,preserveOwner:false,filter:(e,t)=>{const n=a.get(e);if(!n)return false;if(t.size!==n.size)throw new Error(`Database artifact size changed during verification: ${e}`);return true}});t.recordExtracted(i,r);for(const e of n){const t=await fs.lstat(path.join(r,...e.normalized.split(`/`)));if(!t.isFile()||t.size!==e.size)throw new Error(`Extracted database artifact does not match archive: ${e.normalized}`)}return r}var BackupArchiveSpool=class{constructor(e){this.onProgress=e;this.disabled=false;this.nextFileId=0;this.capturedBytes=0;this.files=/* @__PURE__ */ new Map;this.materialized=/* @__PURE__ */ new Map;this.tempRoot=os.tmpdir()}async root(){const e=this.scratch??=createBackupScratchDirectory(this.tempRoot);try{return(await e).directory}catch(e){this.scratch=void 0;throw e}}async capture(e,t){const n=e.size;let r=/(?:\.sqlite|\.postgres\/(?:manifest\.json|\.pending))$/u.test(t);let i=r;let a=Buffer.alloc(0);let o;let s;const abandon=async()=>{this.disabled=true;this.files.delete(t);await s?.close().catch(()=>void 0);s=void 0;if(o)await fs.rm(o,{force:true}).catch(()=>void 0)};const write=async e=>{if(!r||this.disabled)return;try{if(!s){const e=tryReadDiskSpace(this.tempRoot)?.availableBytes;if(n>MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES||e!==void 0&&n+DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES>e){r=false;return}o=path.join(await this.root(),`candidate-${this.nextFileId++}`);s=await fs.open(o,`wx`,384);this.files.set(t,o)}await s.writeFile(e);this.capturedBytes+=e.length;this.onProgress?.({stage:`verify-spool`,phase:`progress`,bytes:this.capturedBytes})}catch{await abandon()}};try{for await(const t of e){let n=t;if(!i){const e=16-a.length;a=Buffer.concat([a,n.subarray(0,e)]);if(a.length<16)continue;r=a.toString(`latin1`)===`SQLite format 3\0`;i=true;if(r)n=Buffer.concat([a,n.subarray(e)])}await write(n);if(e.destroyed)break}if(n===0)await write(Buffer.alloc(0))}finally{try{await s?.close()}catch{await abandon()}}}async materialize(e){const t=path.join(await this.root(),`payload`);const n=[];for(const r of e){if(this.materialized.has(r.normalized))continue;const e=this.files.get(r.normalized);if(!e){n.push(r);continue}const i=path.join(t,...r.normalized.split(`/`));await fs.mkdir(path.dirname(i),{recursive:true,mode:448});await fs.rename(e,i);this.files.delete(r.normalized);this.materialized.set(r.normalized,i)}if(n.length)await fs.mkdir(t,{recursive:true,mode:448});return{directory:t,missing:n}}retainedBytes(e){return e.reduce((e,t)=>e+(this.files.has(t.normalized)||this.materialized.has(t.normalized)?t.size??0:0),0)}async discardExcept(e){const t=new Set(e.map(e=>e.normalized));for(const e of[this.files,this.materialized])for(const[n,r]of e)if(!t.has(n)){await fs.rm(r);e.delete(n)}}recordExtracted(e,t){for(const n of e)this.materialized.set(n.normalized,path.join(t,...n.normalized.split(`/`)))}async[Symbol.asyncDispose](){if(this.scratch){const e=await finishBackupScratch(await this.scratch);if(e)throw new Error(e)}}};async function listBackupArchiveEntries(e,t){const n=[];let r;let i;let a;const o=/* @__PURE__ */ new Map;let s;try{await list({noResume:true,file:e,gzip:true,maxDecompressionRatio:BACKUP_MAX_DECOMPRESSION_RATIO,onwarn:(e,t)=>{if(e===`TAR_BAD_ARCHIVE`||e===`TAR_ENTRY_INVALID`)r??=formatErrorMessage(t)},onReadEntry:e=>{if(i){e.resume();return}let r;try{r=normalizeArchivePath(e.path,`Archive entry`)}catch(t){i??=toStringifiedError(t);e.resume();return}n.push({raw:e.path,normalized:r,...e.linkpath?{linkpath:e.linkpath}:{},...Number.isSafeInteger(e.size)&&e.size>=0?{size:e.size}:{},...e.type?{type:e.type}:{}});let c;if(!a&&isRootBackupManifestEntry(r)){a=readBackupManifestEntry(e);c=a}else if(t&&isRegularArchiveFile(e.type))c=t(e,r).catch(e=>{s??=toStringifiedError(e)});if(c){o.set(e,c);c.finally(()=>{o.delete(e);e.resume()})}else e.resume()}})}catch(e){for(const e of o.keys())e.destroy();throw e}finally{await Promise.all(o.values())}if(s)throw s;return{entries:n,invalidReason:r,pathError:i,manifestContent:a}} //!src/commands/backup-verify.ts function formatResult(e){return[terminalText`Backup archive OK: ${e.archivePath}`,terminalText`Archive root: ${e.archiveRoot}`,terminalText`Created at: ${e.createdAt}`,terminalText`Runtime version: ${e.runtimeVersion}`,terminalText`Assets verified: ${e.assetCount}`,terminalText`Archive entries scanned: ${e.entryCount}`,terminalText`Symbolic links checked: ${e.symlinkCount}`,e.sqliteInventoryVerified?`SQLite database inventory verified.`:`SQLite database coverage unknown: this legacy archive has no database inventory.`,...(e.warnings??[]).map(e=>terminalText`${e}`)].join(` `)}function assertCanonicalStateAssetRoot(e){const t=e.assets.filter(e=>e.kind===`state`);const n=t[0];if(!n)return;if(t.length!==1)throw new Error(`Backup manifest must contain at most one state asset; found ${t.length}.`);if(normalizeArchivePath(n.archivePath,`Backup manifest state asset path`)!==buildBackupArchivePath(normalizeArchiveRoot(e.archiveRoot),n.sourcePath))throw new Error(`Backup manifest state asset archivePath does not match its sourcePath.`)}function listSqliteSnapshotEntries(e,t,n,r){const i=new Map(t.map(e=>[resolvePortableArchivePathKey(e.archivePath),e]));const a=[];const o=new Map(e.map(e=>[e.normalized,e]));for(const t of e){const e=resolvePortableArchivePathKey(t.normalized);for(const n of SQLITE_SIDECAR_SUFFIXES)if(e.endsWith(n)&&i.has(e.slice(0,-n.length)))throw new Error(`Backup contains a SQLite snapshot sidecar: ${t.normalized}`);const s=i.get(e);if(!s)continue;if(t.normalized!==s.archivePath)throw new Error(`Backup contains a SQLite path with incorrect letter casing: ${t.normalized}`);if(!isRegularArchiveFile(t.type))throw new Error(`SQLite snapshot must be a regular archive file: ${t.normalized}`);if(r.has(t.normalized))continue;const c=`${t.normalized}.postgres`;const l=n.has(t.normalized)?o.get(`${c}/database.sqlite`):t;if(!l||!isRegularArchiveFile(l.type))throw new Error(`PostgreSQL snapshot is missing its portable database: ${c}`);a.push({...l,...s})}return a}function readArchivedAgentDatabaseOwners(e,t,n){const r=readOpenClawAgentDatabaseRegistryRows(e,n);const i=t.platform===`win32`?path.win32:path.posix;return r.map(e=>({archivePath:buildBackupArchivePath(t.archiveRoot,i.isAbsolute(e.path)?e.path:i.join(n,e.path)),role:`agent`,agentId:e.agent_id}))}function assertExpectedSqliteRole(e,t,n){if(e.prepare(`SELECT type FROM sqlite_schema WHERE name = 'schema_meta'`).get()?.type!==`table`)throw new Error(`SQLite snapshot ${t} is missing the expected schema_meta table.`);const r=e.prepare(`SELECT role FROM schema_meta WHERE meta_key = 'primary'`).get();const i=typeof r?.role===`string`?r.role:`missing`;if(i!==n)throw new Error(`SQLite snapshot ${t} has role ${i}; expected ${n}.`)}async function verifyPostgresSnapshots(e,t,n,r){if(!n.length)return;const i=new Set(n.flatMap(({directoryPath:e,anchorPath:t})=>[t,...[`manifest.json`,`anchor.sqlite`,`database.sqlite`,`.pending`].map(t=>`${e}/${t}`)]));const a=t.filter(e=>i.has(e.normalized));await assertSnapshotExtractionBudget({entries:a,tempRoot:r.tempRoot,postgres:true,spool:r});const o=await prepareDatabaseArtifacts(e,r,a);const{readBackupEngineImage:s,verifyMatchedPostgresBackup:c}=await import(`./database-backup-uv1npbi6.mjs`);for(const{directoryPath:e,anchorPath:t,manifestSha256:r}of n){const n=path.join(o,e,`manifest.json`);if(r&&(await sha256File(n)).digest!==r)throw new Error(`PostgreSQL capsule does not match its capture inventory: ${e}`);const i=s(path.join(o,t),t);if(i.engine!==`postgres`)throw new Error(`PostgreSQL backup has an invalid outer anchor: ${t}`);await c(path.join(o,e),`user-backup`,i)}}async function verifyLocalCompanionAnchors(e,t,n,r){if(n.profile!==`local-companion`)return[];if(t.some(e=>e.normalized.split(`/`).some(e=>e.toLowerCase().endsWith(`.postgres`))))throw new Error(`Local-companion checkpoint contains an undeclared PostgreSQL export.`);const i=(n.postgresAnchors??[]).map(e=>({sourcePath:e.sourcePath,storeId:e.storeId,namespace:e.namespace,archivePath:buildBackupArchivePath(n.archiveRoot,e.sourcePath)}));const a=new Map(t.map(e=>[e.normalized,e]));const o=new Set(t.map(e=>resolvePortableArchivePathKey(e.normalized)));const s=i.map(e=>{const t=a.get(e.archivePath);if(!t||!isRegularArchiveFile(t.type)||SQLITE_SIDECAR_SUFFIXES.some(t=>o.has(resolvePortableArchivePathKey(`${e.archivePath}${t}`))))throw new Error(`Local-companion anchor is missing, invalid, or has sidecars: ${e.archivePath}`);return t});if(!s.length)return[];assertCanonicalStateAssetRoot(n);await assertSnapshotExtractionBudget({entries:s,tempRoot:r.tempRoot,spool:r});const c=await prepareDatabaseArtifacts(e,r,s);const l=[];for(const[e,t]of i.entries())try{var u=_usingCtx();const r=path.join(c,t.archivePath);await assertSqliteSnapshotFileShape(r,t.archivePath,s[e].size);const i=u.u(openNodeSqliteDatabase(r,{readOnly:true}));configureSqliteReadOnlyPragmas(i);assertSqliteIntegrity(i,t.archivePath);const a=readEngineAnchorIdentity(i,t.archivePath);if(a.engine!==`postgres`||a.storeId!==t.storeId||a.namespace!==t.namespace)throw new Error(`Local-companion PostgreSQL identity mismatch: ${t.archivePath}`);const o=n.sqliteSnapshots?.find(e=>e.sourcePath===t.sourcePath);if(o)l.push({...o,archivePath:t.archivePath})}catch(e){u.e=e}finally{u.d()}return l}async function verifySqliteSnapshots(e){const t=[];const n=e.manifest.paths?.stateDir??e.manifest.assets.find(e=>e.kind===`state`)?.sourcePath;if(!n)return t;const r=buildBackupArchivePath(e.manifest.archiveRoot,n);const i=resolvePortableArchivePathKey(r);for(const t of e.entries)if(isArchivePathWithin(resolvePortableArchivePathKey(t.normalized),i)&&!isArchivePathWithin(t.normalized,r))throw new Error(`Backup contains a case-mangled state asset path: ${t.normalized}`);const a=[{archivePath:path.posix.join(r,`state/openclaw.sqlite`),role:`global`},...(e.manifest.sqliteSnapshots??[]).filter(e=>e.role===`agent`).map(({sourcePath:t,role:n,agentId:r})=>({role:n,agentId:r,archivePath:buildBackupArchivePath(e.manifest.archiveRoot,t)}))];const o=listSqliteSnapshotEntries(e.entries,a,e.postgresAnchors,e.companionAnchors);if(o.length===0)return t;assertCanonicalStateAssetRoot(e.manifest);const s=e.spool.tempRoot;const c=[o];if(!o.some(e=>e.role===`global`))await e.spool.discardExcept(o);const l=[];for(const r of c){l.push(...r);await assertSnapshotExtractionBudget({entries:l,tempRoot:s,spool:e.spool});const i=await prepareDatabaseArtifacts(e.archivePath,e.spool,r);for(const o of r){const r=path.join(i,...o.normalized.split(`/`));let s;try{await assertSqliteSnapshotFileShape(r,o.normalized,o.size);s=openNodeSqliteDatabase(r,{allowExtension:true,readOnly:true});if(readEngineAnchor(s))throw new Error(`PostgreSQL anchor has no owned matched capsule. Re-run backup with this version on the source installation.`);configureSqliteReadOnlyPragmas(s);await loadSqliteVecExtension({db:s});e.onProgress?.({stage:`verify-sqlite-integrity`,phase:`start`,sourceBytes:o.size});assertSqliteIntegrity(s,o.normalized);e.onProgress?.({stage:`verify-sqlite-integrity`,phase:`done`,bytes:o.size});if(o.role===`agent`)assertOpenClawAgentDatabaseOwner(s,{agentId:o.agentId,pathname:o.normalized});else assertExpectedSqliteRole(s,o.normalized,o.role);t.push({...o});if(o.role===`global`){const t=readArchivedAgentDatabaseOwners(s,e.manifest,n);const r=new Map(a.map(e=>[resolvePortableArchivePathKey(e.archivePath),e]));for(const e of t){const t=resolvePortableArchivePathKey(e.archivePath);const n=r.get(t);if(n&&(n.role!==`agent`||e.role!==`agent`||n.agentId!==e.agentId||n.archivePath!==e.archivePath))throw new Error(`SQLite snapshot has conflicting registered owners: ${e.archivePath}`);r.set(t,e)}const i=listSqliteSnapshotEntries(e.entries,t,e.postgresAnchors,e.companionAnchors).filter(e=>!l.some(t=>t.raw===e.raw));if(i.length>0)c.push(i);await e.spool.discardExcept(c.flat())}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Backup SQLite snapshot failed verification: ${o.normalized}. ${t}`,{cause:e})}finally{s?.close()}}}return t}async function verifyResolvedBackupArchive(e,t,n){try{var r=_usingCtx();let i;try{i=await fs.stat(e)}catch(e){if(hasErrnoCode(e,`ENOENT`))throw new Error("Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.",{cause:e});throw new Error(`Archive could not be inspected. ${formatErrorMessage(e)} Check the path and file permissions, then try again.`,{cause:e})}if(!i.isFile())throw new Error("Archive must be a regular file. Choose a backup archive created by `openclaw backup create` and try again.");n?.({stage:`verify-archive-read`,phase:`start`,totalBytes:i.size});n?.({stage:`verify-spool`,phase:`start`});const a=r.a(new BackupArchiveSpool(n));const o=await listBackupArchiveEntries(e,(e,t)=>a.capture(e,t)).catch(e=>{throw new Error(`Archive could not be read or parsed. ${formatErrorMessage(e)} Check the file permissions and archive integrity, then try again.`)});n?.({stage:`verify-archive-read`,phase:`done`,bytes:i.size});n?.({stage:`verify-spool`,phase:`done`});if(o.invalidReason)throw new Error(`Archive is not a valid OpenClaw backup. ${o.invalidReason.replace(/[.!?]*$/u,`.`)} Choose another archive or create a new one with \`openclaw backup create\`.`);if(o.pathError)throw o.pathError;const s=o.entries;const c=s.filter(e=>e.type===`SymbolicLink`).map(e=>({entryPath:e.raw,linkpath:e.linkpath}));const l=/* @__PURE__ */ new Map;let u;for(const e of s){if(l.has(e.normalized))u??=e.normalized;l.set(e.normalized,e)}const d=new Set(l.keys());const f=s.filter(e=>isRootBackupManifestEntry(e.normalized));if(f.length!==1)throw new Error(`Expected exactly one backup manifest entry, found ${f.length}.`);if(u)throw new Error(`Archive contains duplicate entry path: ${u}`);const p=findPortableArchiveEntryPathCollision(s);if(p)throw new Error(`Archive contains a portable path collision: ${p.first} and ${p.second}`);if(!o.manifestContent)throw new Error(`Backup archive manifest entry could not be resolved.`);const m=await o.manifestContent;if(m instanceof Error)throw m;const h=parseBackupManifest(m);verifyBackupManifestEntries(h,d);const g=normalizeArchiveRoot(h.archiveRoot);const _=/* @__PURE__ */ new Map;for(const e of s)if(e.type===`Link`){const t=normalizeArchivePath(e.linkpath??``,`Archive hardlink target for ${e.raw}`);const n=isArchivePathWithin(t,g)?t:path.posix.join(g,t);let r=l.get(n)?.raw;if(!r&&!isArchivePathWithin(t,g)){const n=/* @__PURE__ */ new Set;for(let r=path.posix.dirname(e.normalized);isArchivePathWithin(r,g);r=path.posix.dirname(r)){const e=l.get(path.posix.join(r,t));if(e&&isRegularArchiveFile(e.type))n.add(e.raw);if(r===g)break}if(n.size>1)throw new Error(`Archive hardlink target is ambiguous: ${e.raw} -> ${t}`);r=n.values().next().value}if(!r)throw new Error(`Archive hardlink target is missing from archive entries: ${e.raw} -> ${n}`);_.set(e.raw,r)}const v=[];const y=[];const b=new Set(c.map(({entryPath:e})=>resolvePortableArchivePathKey(normalizeArchivePath(e,`Archive symbolic link path`))));for(const e of s)for(let t=path.posix.dirname(e.normalized);t!==`.`;t=path.posix.dirname(t))if(b.has(resolvePortableArchivePathKey(t)))throw new Error(`Archive entry is beneath a symbolic link: ${e.raw}`);const x=h.assets.find(e=>e.kind===`state`)??(h.paths?.stateDir?{sourcePath:h.paths.stateDir,archivePath:buildBackupArchivePath(h.archiveRoot,h.paths.stateDir)}:void 0);for(const e of c){const{external:t,...n}=recordArchiveSymbolicLink({...e,archiveRoot:h.archiveRoot,platform:h.platform,state:x,hasExternalLinkReport:h.externalSymbolicLinks!==void 0,assets:h.assets});v.push(n);if(t)y.push(n)}const S=new Map((h.externalSymbolicLinks??[]).map(({entryPath:e,linkpath:t})=>[e,t]));if(h.externalSymbolicLinks!==void 0&&(S.size!==y.length||y.some(({entryPath:e,linkpath:t})=>S.get(e)!==t)))throw new Error(`Backup manifest external symbolic links do not match archive entries.`);const{captures:C,warnings:w}=resolvePostgresRestoreEntries(s,h);await verifyPostgresSnapshots(e,s,C,a);const T=await verifyLocalCompanionAnchors(e,s,h,a);const E=await verifySqliteSnapshots({archivePath:e,entries:s,manifest:h,spool:a,onProgress:n,postgresAnchors:new Set(C.map(({anchorPath:e})=>e)),companionAnchors:new Set((h.postgresAnchors??[]).map(({sourcePath:e})=>buildBackupArchivePath(h.archiveRoot,e)))});verifyBackupSqliteCoverage(h,t,[...E,...T]);if(h.profile===`local-companion`)w.push(`Local-companion checkpoint contains no PostgreSQL rows and is not disaster recovery; restore keeps the same PostgreSQL stores and namespaces.`);return{result:{ok:true,archivePath:e,archiveRoot:h.archiveRoot,createdAt:h.createdAt,runtimeVersion:h.runtimeVersion,assetCount:h.assets.length,entryCount:s.length,symlinkCount:c.length,sqliteInventoryVerified:h.sqliteSnapshots!==void 0,...h.profile?{profile:h.profile}:{},...w.length?{warnings:w}:{},...y.length?{externalSymbolicLinks:y}:{}},...resolveBackupRecoveryConfig(h,s,v),manifest:h,hardlinkTargets:_,symbolicLinks:v,regularFileExtractionBytes:resolveExtractionBytes(s),databaseRestoreCandidates:C}}catch(e){r.e=e}finally{await r.d()}}async function prepareBackupArchive(e,t=[],n){const r=resolveBackupArchivePath(e,`<archive>`);return await verifyResolvedBackupArchive(r,t,n).catch(e=>{const t=e instanceof Error?e.message:formatErrorMessage(e);throw new Error(`Backup archive verification failed: ${r}. ${t}`)})}async function verifyBackupArchive(e,t=[],n){return(await prepareBackupArchive(e,t,n)).result}async function backupVerifyCommand(e,t){const n=createBackupProgressLogger(n=>t.json?e.error(n):e.log(n));let r;try{r=await verifyBackupArchive(t.archive,[],n)}finally{n.finish()}if(t.json)writeRuntimeJson(e,r);else e.log(formatResult(r));return r}export{prepareBackupArchive as n,verifyBackupArchive as r,backupVerifyCommand as t};