Skip to content

Commit e69a973

Browse files
authored
feat(backup): add whole-archive restore into a fresh staging directory (#122750)
* feat(backup): add whole-archive restore into a fresh staging directory Verify-first extraction with fresh-target and live-state-dir guards, cleanup on failure, and explicit rollback warnings (ratchet-bearing channel credentials, approvals, delivery state). Activation stays an explicit operator step. * fix(cli): sync backup catalog description with registered command
1 parent ab6d465 commit e69a973

10 files changed

Lines changed: 582 additions & 98 deletions

File tree

‎docs/cli/backup.md‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ openclaw backup create --verify
2121
openclaw backup create --no-include-workspace
2222
openclaw backup create --only-config
2323
openclaw backup verify ./2026-03-09T08-00-00.000+08-00-openclaw-backup.tar.gz
24+
openclaw backup restore ./2026-03-09T08-00-00.000+08-00-openclaw-backup.tar.gz --target ./restored-openclaw
2425
openclaw backup sqlite create --global --repository ~/Backups/openclaw-sqlite
2526
openclaw backup sqlite create --agent main --repository ~/Backups/openclaw-sqlite
2627
openclaw backup sqlite list --repository ~/Backups/openclaw-sqlite
@@ -36,11 +37,9 @@ openclaw backup enable --repository ~/Backups/openclaw-git --every 24h --push
3637
openclaw backup disable
3738
```
3839

39-
Archive `create` and `verify`, plus SQLite `create`, `list`, `verify`, and
40+
Archive `create`, `verify`, and `restore`, plus SQLite `create`, `list`, `verify`, and
4041
`restore`, accept `--json` for one machine-readable result on stdout.
4142

42-
OpenClaw does not currently provide an `openclaw backup restore` command. Follow [Restore a full archive](/install/backups#restore-a-full-archive) for the manual, manifest-driven copy-back flow.
43-
4443
## Notes
4544

4645
- The archive embeds a `manifest.json` with the resolved source paths and archive layout.
@@ -49,6 +48,38 @@ OpenClaw does not currently provide an `openclaw backup restore` command. Follow
4948
- `openclaw backup verify <archive>` checks that the archive contains exactly one root manifest, rejects traversal-style archive paths and SQLite sidecars, confirms every manifest-declared payload exists, validates every SQLite snapshot's file shape, and runs full integrity and role checks on canonical OpenClaw databases. Dedicated plugin schemas remain opaque because they may require owner-defined SQLite capabilities. `openclaw backup create --verify` runs that validation immediately after writing the archive.
5049
- `openclaw backup create --only-config` backs up just the active JSON config file.
5150

51+
## Restore a full archive
52+
53+
Restore a complete archive into a fresh staging directory without touching the
54+
live state directory:
55+
56+
```bash
57+
openclaw backup restore <archive.tar.gz> --target <fresh-directory>
58+
```
59+
60+
The target must not exist or must be an empty directory. Restore verifies the
61+
archive and its SQLite databases before creating or writing the target, refuses
62+
a non-empty target, and removes an incomplete extraction if anything fails. It
63+
never restores in place and has no `--force` mode. The extracted layout retains
64+
the archive root, manifest, and `payload/` paths exactly as recorded in the
65+
archive.
66+
67+
<Warning>
68+
Restoring an archive is time travel. Messaging-channel credentials with
69+
ratchet state, especially WhatsApp, may desynchronize after rollback and need
70+
relinking. Approvals and delivery/dedupe state also roll back, so review
71+
pending approvals before resuming the Gateway. Plugin `node_modules` trees
72+
are not archived; after activation, run `openclaw plugins update <id>` or
73+
reinstall with `openclaw plugins install <spec> --force`.
74+
</Warning>
75+
76+
Activation is a separate offline operator step. Stop the Gateway, move the
77+
restored state asset into place or point `OPENCLAW_STATE_DIR` at that asset,
78+
then run `openclaw doctor` before restarting. Use `manifest.json` as the source
79+
of truth for the state, config, credentials, and workspace asset paths. See
80+
[Restore a full archive](/install/backups#restore-a-full-archive) for the full
81+
disaster-recovery sequence.
82+
5283
## SQLite snapshots
5384

5485
Use `openclaw backup sqlite` when you need a portable artifact for one OpenClaw-owned SQLite database instead of a broad state archive.

‎docs/install/backups.md‎

Lines changed: 30 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ tool before an update, reset, uninstall, or machine move, and a reasonable
5858
daily routine for small installs. For large workspaces or frequent backups,
5959
prefer snapshots or continuous replication below.
6060

61+
On ephemeral container hosts, keep the archive outside the container and use
62+
`openclaw backup restore` as the disaster-recovery primitive for rebuilding a
63+
fresh persistent state tree. Restore stages files only; activation remains an
64+
explicit offline deployment step.
65+
6166
## Per-database snapshots
6267

6368
```bash
@@ -233,32 +238,29 @@ verify` checks archive structure and payload layout, but it does not
233238
authenticate the archive or make untrusted content safe.
234239

235240
Before a full restore, review [What gets backed
236-
up](/cli/backup#what-gets-backed-up). Archives intentionally omit volatile
237-
files, plugin dependency trees, and installer-managed runtime roots such as
238-
state-local `tmp/`. Recreate those artifacts after restore.
239-
240-
Verify before extracting, then stage the archive in a private temporary
241-
directory:
241+
up](/cli/backup#what-gets-backed-up). Then verify and extract into a fresh
242+
staging directory with one command:
242243

243244
```bash
244-
set -euo pipefail
245-
246245
ARCHIVE=./2026-03-09T08-00-00.000+08-00-openclaw-backup.tar.gz
247-
248-
openclaw backup verify "$ARCHIVE"
249-
250-
restore_dir="$(mktemp -d -t openclaw-restore.XXXXXX)"
251-
trap 'rm -rf "$restore_dir"' EXIT
252-
253-
tar -xzf "$ARCHIVE" -C "$restore_dir"
254-
manifest_path="$(find "$restore_dir" -mindepth 2 -maxdepth 2 -name manifest.json -print -quit)"
255-
test -n "$manifest_path"
256-
cat "$manifest_path"
246+
openclaw backup restore "$ARCHIVE" --target ./restored-openclaw
257247
```
258248

259-
Treat the staging directory as sensitive. It can contain credentials, auth
260-
profiles, sessions, and workspace data. The `trap` removes it when the shell
261-
exits.
249+
The target must not exist or must be empty. OpenClaw verifies archive structure,
250+
the manifest, hardlinks, and SQLite databases before it writes the target. A
251+
non-empty target is refused, and a failed extraction cleans its incomplete
252+
output. The command never touches the live state directory and has no force or
253+
in-place mode. Treat the restored directory as sensitive: it can contain
254+
credentials, auth profiles, sessions, and workspace data.
255+
256+
<Warning>
257+
Restoring an archive is time travel. Messaging-channel credentials with
258+
ratchet state, especially WhatsApp, may desynchronize after rollback and need
259+
relinking. Approvals and delivery/dedupe state also roll back, so review
260+
pending approvals before resuming the Gateway. Plugin `node_modules` trees
261+
are not archived; after activation, run `openclaw plugins update <id>` or
262+
reinstall with `openclaw plugins install <spec> --force`.
263+
</Warning>
262264

263265
The manifest records `archiveRoot`, the original paths under `paths`, and an
264266
`assets[]` list. Each asset includes its `kind`, original `sourcePath`, and
@@ -274,48 +276,13 @@ The archive layout is:
274276
<archive-root>/payload/relative/<relative-source-path>/...
275277
```
276278

277-
Before copying files back, stop the Gateway and any node hosts that use them.
278-
Make a fresh backup of the current state or move the current directories
279-
aside. Restore the smallest set of assets needed.
280-
281-
For example, this restores the state asset to the current user's default
282-
state directory. The target stays absent until `cp -a` creates it, preserving
283-
the staged directory's mode and metadata:
284-
285-
```bash
286-
set -euo pipefail
287-
288-
state_archive_path="$(
289-
node -e 'const fs = require("node:fs"); const manifest = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); process.stdout.write(manifest.assets.find((asset) => asset.kind === "state")?.archivePath ?? "");' "$manifest_path"
290-
)"
291-
test -n "$state_archive_path"
292-
293-
state_source="$restore_dir/$state_archive_path"
294-
state_target="$HOME/.openclaw"
295-
state_backup="$HOME/.openclaw.pre-restore.$(date +%s)"
296-
297-
test -d "$state_source"
298-
openclaw gateway stop
299-
300-
if [ -e "$state_target" ] || [ -L "$state_target" ]; then
301-
mv "$state_target" "$state_backup"
302-
fi
303-
test ! -e "$state_target"
304-
test ! -L "$state_target"
305-
cp -a "$state_source" "$state_target"
306-
307-
openclaw doctor
308-
openclaw gateway start
309-
openclaw health
310-
openclaw status
311-
```
312-
313-
For a same-machine restore, the manifest `sourcePath` values are usually the
314-
intended targets. On a new machine or under a different home directory,
315-
choose the new targets first, then copy only the matching asset payloads.
316-
Typical full-restore targets are the state directory, active config file,
317-
credentials directory, and workspace directories. See
318-
[Updating](/install/updating#rollback) for the rollback workflow.
279+
To activate, stop the Gateway and any node hosts that use the restored files.
280+
Make a fresh backup of current state or move it aside. Then move the extracted
281+
state asset into place, or point `OPENCLAW_STATE_DIR` at that asset, and run
282+
`openclaw doctor` before restarting the Gateway. On a new machine or under a
283+
different home directory, use the manifest to map config, credentials, and
284+
workspace assets to their new paths. See [Updating](/install/updating#rollback)
285+
for the rollback workflow.
319286

320287
### Restore a database
321288

‎src/cli/program/core-command-descriptors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ const coreCliCommandCatalog = defineCommandDescriptorCatalog([
4545
},
4646
{
4747
name: "backup",
48-
description: "Create and verify backup archives and SQLite snapshots",
48+
description: "Create, verify, and restore backup archives and SQLite snapshots",
4949
hasSubcommands: true,
5050
},
5151
{

‎src/cli/program/register.backup.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { registerBackupCommand } from "./register.backup.js";
55

66
const mocks = vi.hoisted(() => ({
77
backupCreateCommand: vi.fn(),
8+
backupRestoreCommand: vi.fn(),
89
backupSqliteCreateCommand: vi.fn(),
910
backupSqliteListCommand: vi.fn(),
1011
backupSqliteRestoreCommand: vi.fn(),
@@ -18,6 +19,7 @@ const mocks = vi.hoisted(() => ({
1819
}));
1920

2021
const backupCreateCommand = mocks.backupCreateCommand;
22+
const backupRestoreCommand = mocks.backupRestoreCommand;
2123
const backupSqliteCreateCommand = mocks.backupSqliteCreateCommand;
2224
const backupSqliteListCommand = mocks.backupSqliteListCommand;
2325
const backupSqliteRestoreCommand = mocks.backupSqliteRestoreCommand;
@@ -29,6 +31,10 @@ vi.mock("../../commands/backup.js", () => ({
2931
backupCreateCommand: mocks.backupCreateCommand,
3032
}));
3133

34+
vi.mock("../../commands/backup-restore.js", () => ({
35+
backupRestoreCommand: mocks.backupRestoreCommand,
36+
}));
37+
3238
vi.mock("../../commands/backup-verify.js", () => ({
3339
backupVerifyCommand: mocks.backupVerifyCommand,
3440
}));
@@ -54,6 +60,7 @@ describe("registerBackupCommand", () => {
5460
beforeEach(() => {
5561
vi.clearAllMocks();
5662
backupCreateCommand.mockResolvedValue(undefined);
63+
backupRestoreCommand.mockResolvedValue(undefined);
5764
backupSqliteCreateCommand.mockResolvedValue(undefined);
5865
backupSqliteListCommand.mockResolvedValue(undefined);
5966
backupSqliteRestoreCommand.mockResolvedValue(undefined);
@@ -113,6 +120,24 @@ describe("registerBackupCommand", () => {
113120
expect(options.json).toBe(true);
114121
});
115122

123+
it("runs whole-archive restore with forwarded options", async () => {
124+
await runCli([
125+
"backup",
126+
"restore",
127+
"/tmp/openclaw-backup.tar.gz",
128+
"--target",
129+
"/tmp/restored-openclaw",
130+
"--json",
131+
]);
132+
133+
const options = expectForwardedOptions(backupRestoreCommand);
134+
expect(options).toEqual({
135+
archive: "/tmp/openclaw-backup.tar.gz",
136+
target: "/tmp/restored-openclaw",
137+
json: true,
138+
});
139+
});
140+
116141
it("registers the SQLite snapshot command group", () => {
117142
const program = new Command();
118143

‎src/cli/program/register.backup.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
backupGitRestoreCommand,
1010
backupGitVerifyCommand,
1111
} from "../../commands/backup-git.js";
12+
import { backupRestoreCommand } from "../../commands/backup-restore.js";
1213
import { backupDisableCommand, backupEnableCommand } from "../../commands/backup-schedule.js";
1314
import {
1415
backupSqliteCreateCommand,
@@ -27,7 +28,7 @@ import { formatHelpExamples } from "../help-format.js";
2728
export function registerBackupCommand(program: Command) {
2829
const backup = program
2930
.command("backup")
30-
.description("Create and verify backup archives and SQLite snapshots")
31+
.description("Create, verify, and restore backup archives and SQLite snapshots")
3132
.addHelpText(
3233
"after",
3334
() =>
@@ -107,6 +108,35 @@ export function registerBackupCommand(program: Command) {
107108
});
108109
});
109110

111+
backup
112+
.command("restore <archive>")
113+
.description("Restore a verified backup archive to a fresh staging directory")
114+
.requiredOption("--target <dir>", "Fresh target directory; non-empty directories are refused")
115+
.option("--json", "Output JSON", false)
116+
.addHelpText(
117+
"after",
118+
() =>
119+
`\n${theme.heading("Examples:")}\n${formatHelpExamples([
120+
[
121+
"openclaw backup restore ~/Backups/latest.tar.gz --target ./restored-openclaw",
122+
"Verify, then extract the whole archive into a fresh staging directory.",
123+
],
124+
[
125+
"openclaw backup restore ~/Backups/latest.tar.gz --target ./restored-openclaw --json",
126+
"Emit machine-readable restore details and rollback warnings.",
127+
],
128+
])}`,
129+
)
130+
.action(async (archive, opts) => {
131+
await runCommandWithRuntime(defaultRuntime, async () => {
132+
await backupRestoreCommand(defaultRuntime, {
133+
archive: archive as string,
134+
target: opts.target as string,
135+
json: Boolean(opts.json),
136+
});
137+
});
138+
});
139+
110140
registerBackupSqliteCommands(backup);
111141
registerBackupGitCommands(backup);
112142
registerBackupScheduleCommands(backup);

0 commit comments

Comments
 (0)