openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 9.73 kB
JavaScript
import{o as writeRuntimeJson}from"./runtime-DIcLIHcp.mjs";import{l as isValidEnvSecretRefId}from"./ref-contract-CdpCUlb6.mjs";import"./types.secrets-UWdyCdE6.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as formatDiskSpaceBytes,r as tryReadDiskSpace}from"./disk-space-D746MnLp.mjs";import{s as readConfigFileSnapshot}from"./io.runtime-BvSeVFIY.mjs";import"./config-DkZ8y8Gv.mjs";import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{r as extract}from"./esm-Ch36GTgp.mjs";import{t as buildBackupArchivePath}from"./backup-archive-path-policy-CotYunH-.mjs";import{a as resolveLegacyConfigSnapshotForBackup}from"./automatic-config-repair-BDdrbCM_.mjs";import{c as resolveBackupArchivePath,i as canonicalizePathForContainment,s as resolveBackupAgentRoots,t as BACKUP_MAX_DECOMPRESSION_RATIO}from"./backup-shared-CVcoDGTC.mjs";import{r as prepareRestoredClientCredentials}from"./client-credential-restore-v5gh1bv1.mjs";import{n as prepareBackupArchive}from"./backup-verify-Lqpvf4CJ.mjs";import path from"node:path";import fs from"node:fs/promises";import{isPathInside}from"@openclaw/fs-safe/path";
//!src/commands/backup-restore.ts
const BACKUP_RESTORE_WARNINGS=[`Restoring an archive is time travel: every restored state surface rolls back to the archive timestamp.`,`Messaging-channel credentials with ratchet state, especially WhatsApp, may desynchronize after rollback and require relinking.`,`Approvals and delivery/dedupe state also roll back; review pending approvals before resuming the Gateway.`,"Plugin node_modules are not archived; after activation, run `openclaw plugins update <id>` or reinstall with `openclaw plugins install <spec> --force`.","Generated plugin-skills links are not archived; after activation, run `openclaw skills list` or start an agent session to rebuild them."];const BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES=268435456;async function assertTargetOutsideLiveState(e){const[t,n]=await Promise.all([canonicalizePathForContainment(e),canonicalizePathForContainment(resolveStateDir())]);if(isPathInside(n,t))throwExpectedCliError(`Backup restore target must be outside the live OpenClaw state directory: ${e}`);const r=await readConfigFileSnapshot({observe:false});const i=await resolveLegacyConfigSnapshotForBackup(r);if(!i)return;const a=await resolveBackupAgentRoots(i.config);for(const{sourcePath:n}of a)if(isPathInside(n,t))throwExpectedCliError(`Backup restore target must be outside the live OpenClaw agent directory: ${e}`)}async function prepareRestoreTarget(e){try{if(!(await fs.lstat(e)).isDirectory())throwExpectedCliError(`Backup restore target must be a directory: ${e}`);if((await fs.readdir(e)).length>0)throwExpectedCliError(`Backup restore target directory must be empty: ${e}`);return{created:false}}catch(e){if(e.code!==`ENOENT`)throw e}await fs.mkdir(e,{recursive:true,mode:448});return{created:true}}function assertRestoreCapacity(e,t){const n=tryReadDiskSpace(e);if(!n)return;const r=t+BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES;if(r<=n.availableBytes)return;const i=path.resolve(e)===path.resolve(n.checkedPath)?e:`${e} (volume checked at ${n.checkedPath})`;throwExpectedCliError(`Backup restore requires ${formatDiskSpaceBytes(r)} of free space at ${i} (${formatDiskSpaceBytes(t)} archive data plus ${formatDiskSpaceBytes(BACKUP_RESTORE_FREE_SPACE_RESERVE_BYTES)} reserve), but only ${formatDiskSpaceBytes(n.availableBytes)} is available. Choose a target on a volume with enough free space.`)}async function cleanupFailedRestore(e,t){if(t){await fs.rm(e,{recursive:true,force:true});return}for(const t of await fs.readdir(e))await fs.rm(path.join(e,t),{recursive:true,force:true})}async function extractBackupArchive(e,t,n,r){let i;await extract({file:e,gzip:true,maxDecompressionRatio:BACKUP_MAX_DECOMPRESSION_RATIO,cwd:t,strict:false,preserveOwner:false,filter:e=>!r.has(e),onReadEntry:e=>{const t=n.get(e.path);if(t!==void 0)e.linkpath=t},onwarn:(e,t,n)=>{i??=n instanceof Error?n:Object.assign(/* @__PURE__ */ new Error(`${e}: ${t}`),n)}});if(i)throw i}async function restorePostgresExports(e,t,n,r,i,a,o){if(t.length===0){a?.();return}if(!n)throw new Error(`PostgreSQL archive restore requires its captured configuration.`);const s=path.join(e,n);if(!isPathInside(await fs.realpath(e),await fs.realpath(s)))throw new Error(`PostgreSQL recovery configuration must be inside the restored archive.`);const{discardPostgresRestores:c,preparePostgresRestore:l,readBackupEngineImage:u,runOfflineDatabaseBackup:d}=await import(`./database-backup-uv1npbi6.mjs`);const{publishVerifiedSqliteFile:f}=await import(`./sqlite-snapshot-C6LLrZkv.mjs`);const p=[];for(const n of t){const t=path.join(e,n.anchorPath);const r=u(t,t);if(r.engine!==`postgres`)throw new Error(`PostgreSQL backup artifact has no matched anchor: ${n.anchorPath}`);p.push({...n,source:r})}await d(e,async({config:t,assertCurrent:n})=>{const r=await fs.mkdtemp(path.join(e,`.postgres-restore-`));const i=[];try{const o=path.join(r,`openclaw.json`);await fs.rename(s,o);for(const[a,o]of p.entries()){const s=path.join(e,o.anchorPath);const c=path.join(r,`${a}.sqlite`);const u=await l({directory:path.join(e,o.directoryPath),anchorPath:c,config:t,profile:`user-backup`,expectedSource:o.source,assertCurrent:n});i.push({sourcePath:c,targetPath:s,content:u})}for(const e of i){n();await fs.unlink(e.targetPath);await f({sourcePath:e.sourcePath,sourceIdentity:await fs.lstat(e.sourcePath,{bigint:true}),targetPath:e.targetPath,expectedContent:e.content,requireAtomicPublication:true,beforePublish:async()=>n(),afterPublish:e=>e.assertTargetMatchesExpectedContent(n)})}n();a?.();for(const{directoryPath:t}of p)for(const n of[`manifest.json`,`anchor.sqlite`,`database.sqlite`])await fs.unlink(path.join(e,t,n));n();await fs.rename(o,s);await fs.rm(r,{recursive:true,force:true})}catch(e){try{await c(t,i.map(({content:e})=>e.namespace))}catch(t){throw new AggregateError([e,t],`PostgreSQL restore failed and its scratch namespaces could not be cleaned: ${formatErrorMessage(t)}`,{cause:e})}throw e}},{configPath:path.join(e,r??n),configSourcePath:s,...o?{postgresConnectionEnv:o}:{},env:{...process.env,OPENCLAW_INCLUDE_ROOTS:path.join(e,i,`payload`)},mapIncludePath:t=>isPathInside(e,t)?t:path.join(e,buildBackupArchivePath(i,t))})}function formatRestoreResult(e){return[terminalText`Backup archive restored to staging: ${shortenHomePath(e.targetPath)}`,terminalText`Verified archive: ${shortenHomePath(e.archivePath)}`,terminalText`Archive root: ${e.archiveRoot}`,terminalText`Archive entries restored: ${e.entryCount}`,...e.postgresConnectionEnv?[terminalText`PostgreSQL stores imported through: $${e.postgresConnectionEnv}`,`The restored config keeps the archived PostgreSQL connection; point it at the same server before activation.`]:[],``,`Rollback warnings:`,...e.warnings.map(e=>terminalText`- ${e}`),``,"Activation is explicit: stop the Gateway, move the restored asset tree into place or point OPENCLAW_STATE_DIR at the restored state asset, then run `openclaw doctor`."].join(`
`)}async function backupRestoreCommand(e,t){const n=t.postgresConnectionEnv;if(n!==void 0){if(!isValidEnvSecretRefId(n))throwExpectedCliError(`--postgres-connection-env requires an environment variable name.`);if(!process.env[n]?.trim())throwExpectedCliError(`--postgres-connection-env: ${n} is not set; nothing was restored.`)}const r=resolveBackupArchivePath(t.target,`--target`);await assertTargetOutsideLiveState(r);const{result:i,hardlinkTargets:a,symbolicLinks:o,regularFileExtractionBytes:s,databaseRestoreCandidates:c,recoveryConfigPath:l,recoveryConfigContextPath:u,manifest:d}=await prepareBackupArchive(t.archive);if(t.sourceEngine===`sqlite`&&(c.length>0||(d.postgresAnchors?.length??0)>0))throw new Error(`This restore requires a SQLite-only archive; PostgreSQL namespaces were not imported.`);if(t.localCompanion&&d.profile!==`local-companion`)throwExpectedCliError(`--local-companion requires a local-companion checkpoint; no PostgreSQL data was imported.`);if(n!==void 0&&c.length===0)throwExpectedCliError(`--postgres-connection-env requires an archive with PostgreSQL stores; nothing was restored.`);assertRestoreCapacity(r,s);const f=await prepareRestoreTarget(r);try{await extractBackupArchive(i.archivePath,r,a,new Set(o.map(({entryPath:e})=>e)));const e=prepareRestoredClientCredentials({manifest:d,targetPath:r});for(const{entryPath:e}of o)await fs.mkdir(path.dirname(path.join(r,e)),{recursive:true});for(const{entryPath:e,linkpath:t}of o)await fs.symlink(t,path.join(r,e));await restorePostgresExports(r,c,l,u,i.archiveRoot,e,n)}catch(e){try{await cleanupFailedRestore(r,f.created)}catch(t){throw new AggregateError([e,t],`Backup restore failed and the incomplete target could not be cleaned: ${r}. Cleanup error: ${formatErrorMessage(t)}`,{cause:e})}throw new Error(`Backup restore failed; the incomplete target was cleaned: ${r}. ${formatErrorMessage(e)}`,{cause:e})}const p={...i,targetPath:r,...n===void 0?{}:{postgresConnectionEnv:n},warnings:[...d.profile===`local-companion`?[`Local files roll back to the checkpoint; PostgreSQL rows do not. This checkpoint is not disaster recovery.`,...BACKUP_RESTORE_WARNINGS.slice(1,2),...BACKUP_RESTORE_WARNINGS.slice(3)]:BACKUP_RESTORE_WARNINGS,...i.warnings??[],...(i.externalSymbolicLinks??[]).map(({entryPath:e,linkpath:t})=>`External link restored (target not copied through link): ${JSON.stringify(e)} -> ${JSON.stringify(t)}`)]};if(t.json)writeRuntimeJson(e,p);else e.log(formatRestoreResult(p));return p}export{backupRestoreCommand as t};