Skip to content

Commit 87ae401

Browse files
committed
fix(backup): report archive problems instead of raw errno text
1 parent b097aaa commit 87ae401

8 files changed

Lines changed: 187 additions & 31 deletions

‎src/cli/config-cli-input.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import {
1212
type SecretRefSource,
1313
} from "../config/types.secrets.js";
1414
import { SecretProviderSchema } from "../config/zod-schema.core.js";
15-
import { hasErrnoCode } from "../infra/errors.js";
1615
import {
1716
formatExecSecretRefIdValidationMessage,
1817
isValidFileSecretRefId,
@@ -515,14 +514,7 @@ async function readConfigPatchInput(opts: ConfigPatchOptions): Promise<unknown>
515514
if (stdin) {
516515
raw = await readStdinText();
517516
} else {
518-
try {
519-
raw = readConfigMutationFileSync(file as string, "--file");
520-
} catch (err) {
521-
if (hasErrnoCode(err, "ENOENT")) {
522-
throw new Error(`--file not found: ${file}`, { cause: err });
523-
}
524-
throw err;
525-
}
517+
raw = readConfigMutationFileSync(file as string, "--file");
526518
}
527519
try {
528520
return JSON5.parse(raw);

‎src/cli/config-cli.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2771,6 +2771,22 @@ describe("config cli", () => {
27712771
expect(mockWriteConfigFile).not.toHaveBeenCalled();
27722772
});
27732773

2774+
it("rejects a directory passed as --file", async () => {
2775+
const pathname = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-config-patch-directory-"));
2776+
try {
2777+
await expect(runConfigCommand(["config", "patch", "--file", pathname])).rejects.toThrow(
2778+
ExitError,
2779+
);
2780+
} finally {
2781+
fs.rmSync(pathname, { recursive: true, force: true });
2782+
}
2783+
2784+
expectErrorIncludes(
2785+
`--file must be a regular file: ${pathname}. Choose a JSON5 input file and try again.`,
2786+
);
2787+
expect(mockWriteConfigFile).not.toHaveBeenCalled();
2788+
});
2789+
27742790
it("rejects --file patches above the config mutation limit", async () => {
27752791
const pathname = path.join(
27762792
os.tmpdir(),

‎src/cli/config-set-input.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,17 @@ describe("config set input parsing", () => {
123123
).toThrow("--batch-file not found: /nonexistent/path/batch.json5");
124124
});
125125

126+
it("rejects a directory passed as --batch-file", () => {
127+
const batchPath = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-config-set-directory-"));
128+
try {
129+
expect(() => parseBatchSource({ batchFile: batchPath })).toThrow(
130+
`--batch-file must be a regular file: ${batchPath}. Choose a JSON5 input file and try again.`,
131+
);
132+
} finally {
133+
fs.rmSync(batchPath, { recursive: true, force: true });
134+
}
135+
});
136+
126137
it("rejects malformed --batch-file payloads", () => {
127138
withBatchFile("openclaw-config-set-input-invalid-", "{}", (batchPath) => {
128139
expect(() =>

‎src/cli/config-set-input.ts‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,23 @@ export function readConfigMutationFileSync(
5252
): string {
5353
// These explicit CLI file flags have historically followed user-provided
5454
// symlinks. Pin the opened descriptor, then bound the read without changing that contract.
55-
const fd = fs.openSync(filePath, "r");
55+
let fd: number;
5656
try {
57+
fd = fs.openSync(filePath, "r");
58+
} catch (error) {
59+
if (hasErrnoCode(error, "ENOENT")) {
60+
throw new Error(`${sourceLabel} not found: ${filePath}. Check the path and try again.`, {
61+
cause: error,
62+
});
63+
}
64+
throw error;
65+
}
66+
try {
67+
if (!fs.fstatSync(fd).isFile()) {
68+
throw new Error(
69+
`${sourceLabel} must be a regular file: ${filePath}. Choose a JSON5 input file and try again.`,
70+
);
71+
}
5772
try {
5873
return readFileDescriptorBoundedSync(fd, CONFIG_MUTATION_FILE_MAX_BYTES).toString("utf8");
5974
} catch (error) {
@@ -163,14 +178,6 @@ export function parseBatchSource(opts: ConfigSetOptions): ConfigSetBatchEntry[]
163178
if (!pathname) {
164179
throw new Error("--batch-file must not be empty.");
165180
}
166-
let raw: string;
167-
try {
168-
raw = readConfigMutationFileSync(pathname, "--batch-file");
169-
} catch (err) {
170-
if (hasErrnoCode(err, "ENOENT")) {
171-
throw new Error(`--batch-file not found: ${pathname}`, { cause: err });
172-
}
173-
throw err;
174-
}
181+
const raw = readConfigMutationFileSync(pathname, "--batch-file");
175182
return parseBatchEntries(raw, "--batch-file");
176183
}

‎src/commands/backup-sqlite.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,15 @@ describe("SQLite backup commands", () => {
151151
expect(listed.snapshots).toHaveLength(1);
152152
expect(listed.snapshots[0]?.manifest.snapshotId).toBe(created.manifest.snapshotId);
153153

154+
const missingScratchPath = path.join(tempDir, "missing-scratch");
155+
await expect(
156+
backupSqliteVerifyCommand(runtime, created.snapshotPath, {
157+
scratch: missingScratchPath,
158+
}),
159+
).rejects.toThrow(
160+
`SQLite validation root does not exist: ${missingScratchPath}. Create a private directory there or pass an existing directory with \`--scratch\`.`,
161+
);
162+
154163
const verified = await backupSqliteVerifyCommand(runtime, created.snapshotPath, {
155164
scratch: scratchPath,
156165
json: true,
@@ -183,6 +192,31 @@ describe("SQLite backup commands", () => {
183192
}
184193
});
185194

195+
it("reports missing snapshot paths for verify and restore", async () => {
196+
const tempDir = tempDirs.make("openclaw-backup-sqlite-missing-");
197+
const repositoryPath = path.join(tempDir, "snapshots");
198+
const snapshotPath = path.join(repositoryPath, "missing-snapshot");
199+
const restorePath = path.join(tempDir, "restored.sqlite");
200+
const runtime = createRuntimeCapture();
201+
const missingRepositoryMessage = `SQLite snapshot repository does not exist: ${repositoryPath}. Check the snapshot path or create a snapshot with \`openclaw backup sqlite create\`.`;
202+
203+
await expect(backupSqliteVerifyCommand(runtime, snapshotPath, {})).rejects.toThrow(
204+
missingRepositoryMessage,
205+
);
206+
await expect(
207+
backupSqliteRestoreCommand(runtime, snapshotPath, { target: restorePath }),
208+
).rejects.toThrow(missingRepositoryMessage);
209+
210+
await fs.mkdir(repositoryPath, { mode: 0o700 });
211+
const missingSnapshotMessage = `SQLite snapshot does not exist: ${snapshotPath}. Run \`openclaw backup sqlite list --repository ${repositoryPath}\` to inspect available snapshots.`;
212+
await expect(backupSqliteVerifyCommand(runtime, snapshotPath, {})).rejects.toThrow(
213+
missingSnapshotMessage,
214+
);
215+
await expect(
216+
backupSqliteRestoreCommand(runtime, snapshotPath, { target: restorePath }),
217+
).rejects.toThrow(missingSnapshotMessage);
218+
});
219+
186220
it("creates a snapshot for a normalized per-agent database", async () => {
187221
const tempDir = tempDirs.make("openclaw-backup-sqlite-");
188222
const stateDir = path.join(tempDir, "state");

‎src/commands/backup-verify.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { gzipSync } from "node:zlib";
77
import * as tar from "tar";
88
import { afterEach, describe, expect, it, vi } from "vitest";
99
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
10+
import { runCommandWithRuntime } from "../cli/cli-utils.js";
1011
import { requireNodeSqlite } from "../infra/node-sqlite.js";
1112
import { buildBackupArchivePath, buildBackupArchiveRoot } from "./backup-shared.js";
1213
import { backupVerifyCommand, testApi } from "./backup-verify.js";
@@ -243,6 +244,44 @@ describe("backupVerifyCommand", () => {
243244
}
244245
});
245246

247+
it.each([
248+
{
249+
name: "missing archive",
250+
prepare: async (tempDir: string) => path.join(tempDir, "missing.tar.gz"),
251+
detail:
252+
"Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.",
253+
},
254+
{
255+
name: "directory",
256+
prepare: async (tempDir: string) => tempDir,
257+
detail:
258+
"Archive must be a regular file. Choose a backup archive created by `openclaw backup create` and try again.",
259+
},
260+
{
261+
name: "non-tar garbage",
262+
prepare: async (tempDir: string) => {
263+
const archivePath = path.join(tempDir, "garbage.tar.gz");
264+
await fs.writeFile(archivePath, "garbage", "utf8");
265+
return archivePath;
266+
},
267+
detail:
268+
"Archive is not a valid OpenClaw backup. Unrecognized archive format. Choose another archive or create a new one with `openclaw backup create`.",
269+
},
270+
])("reports an actionable failure for $name", async ({ prepare, detail }) => {
271+
const tempDir = tempDirs.make("openclaw-backup-verify-input-");
272+
const archivePath = await prepare(tempDir);
273+
const runtime = createBackupVerifyRuntime();
274+
275+
await runCommandWithRuntime(runtime, async () => {
276+
await backupVerifyCommand(runtime, { archive: archivePath });
277+
});
278+
279+
expect(runtime.error).toHaveBeenCalledWith(
280+
`Backup archive verification failed: ${archivePath}. ${detail}`,
281+
);
282+
expect(runtime.exit).toHaveBeenCalledWith(1);
283+
});
284+
246285
it("verifies SQLite integrity and the canonical shared-state role", async () => {
247286
const stateAssetArchivePath = `${TEST_ARCHIVE_ROOT}/payload/posix/tmp/.openclaw`;
248287
const sqliteArchivePath = `${stateAssetArchivePath}/state/openclaw.sqlite`;
@@ -933,7 +972,7 @@ describe("backupVerifyCommand", () => {
933972
async (archivePath) => {
934973
const runtime = createBackupVerifyRuntime();
935974
await expect(backupVerifyCommand(runtime, { archive: archivePath })).rejects.toThrow(
936-
/^Backup manifest is not valid JSON\.$/u,
975+
`Backup archive verification failed: ${archivePath}. Backup manifest is not valid JSON.`,
937976
);
938977
await expect(backupVerifyCommand(runtime, { archive: archivePath })).rejects.not.toThrow(
939978
/position|Unexpected|Expected|SyntaxError/u,

‎src/commands/backup-verify.ts‎

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "../infra/backup-archive-path-policy.js";
1515
import { isTransientSqliteBackupPath } from "../infra/backup-volatile-filter.js";
1616
import { formatDiskSpaceBytes, tryReadDiskSpace } from "../infra/disk-space.js";
17+
import { formatErrorMessage, hasErrnoCode } from "../infra/errors.js";
1718
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
1819
import { assertSqliteIntegrity } from "../infra/sqlite-integrity.js";
1920
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
@@ -67,12 +68,18 @@ type SqliteSnapshotEntry = NormalizedArchiveEntry & {
6768

6869
type ExpectedSqliteRole = "agent" | "global";
6970

70-
async function listArchiveEntries(archivePath: string): Promise<ArchiveEntry[]> {
71+
async function listArchiveEntries(archivePath: string) {
7172
const entries: ArchiveEntry[] = [];
73+
let invalidReason: string | undefined;
7274
await tar.t({
7375
file: archivePath,
7476
gzip: true,
7577
maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO,
78+
onwarn: (code, message) => {
79+
if (code === "TAR_BAD_ARCHIVE" && invalidReason === undefined) {
80+
invalidReason = formatErrorMessage(message);
81+
}
82+
},
7683
onReadEntry: (entry) => {
7784
entries.push({
7885
path: entry.path,
@@ -82,7 +89,7 @@ async function listArchiveEntries(archivePath: string): Promise<ArchiveEntry[]>
8289
});
8390
},
8491
});
85-
return entries;
92+
return { entries, invalidReason };
8693
}
8794

8895
async function extractManifest(params: {
@@ -539,14 +546,40 @@ async function verifySqliteSnapshots(params: {
539546
}
540547
}
541548

542-
/** Verify a backup archive and return its normalized, integrity-checked inventory. */
543-
export async function verifyBackupArchive(archive: string): Promise<BackupVerifyResult> {
544-
const archivePath = resolveUserPath(archive);
545-
const rawEntries = await listArchiveEntries(archivePath);
546-
if (rawEntries.length === 0) {
547-
throw new Error("Backup archive is empty.");
549+
async function verifyResolvedBackupArchive(archivePath: string): Promise<BackupVerifyResult> {
550+
let archiveStat;
551+
try {
552+
archiveStat = await fs.stat(archivePath);
553+
} catch (error) {
554+
if (hasErrnoCode(error, "ENOENT")) {
555+
throw new Error(
556+
"Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.",
557+
{ cause: error },
558+
);
559+
}
560+
throw new Error(
561+
`Archive could not be inspected. ${formatErrorMessage(error)} Check the path and file permissions, then try again.`,
562+
{ cause: error },
563+
);
564+
}
565+
if (!archiveStat.isFile()) {
566+
throw new Error(
567+
"Archive must be a regular file. Choose a backup archive created by `openclaw backup create` and try again.",
568+
);
548569
}
549570

571+
const listing = await listArchiveEntries(archivePath).catch((error: unknown) => {
572+
throw new Error(
573+
`Archive could not be read or parsed. ${formatErrorMessage(error)} Check the file permissions and archive integrity, then try again.`,
574+
);
575+
});
576+
if (listing.invalidReason) {
577+
throw new Error(
578+
`Archive is not a valid OpenClaw backup. ${listing.invalidReason.replace(/[.!?]*$/u, ".")} Choose another archive or create a new one with \`openclaw backup create\`.`,
579+
);
580+
}
581+
const rawEntries = listing.entries;
582+
550583
const entries = rawEntries.map((entry) => ({
551584
raw: entry.path,
552585
normalized: normalizeArchivePath(entry.path, "Archive entry"),
@@ -613,6 +646,15 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
613646
return result;
614647
}
615648

649+
/** Verify a backup archive and return its normalized, integrity-checked inventory. */
650+
export async function verifyBackupArchive(archive: string): Promise<BackupVerifyResult> {
651+
const archivePath = resolveUserPath(archive);
652+
return await verifyResolvedBackupArchive(archivePath).catch((error: unknown) => {
653+
const detail = error instanceof Error ? error.message : formatErrorMessage(error);
654+
throw new Error(`Backup archive verification failed: ${archivePath}. ${detail}`);
655+
});
656+
}
657+
616658
/** Verify a backup archive, including snapshot shape and canonical SQLite integrity checks. */
617659
export async function backupVerifyCommand(
618660
runtime: RuntimeEnv,

‎src/snapshot/local-repository.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -597,9 +597,19 @@ class LocalSqliteSnapshotProvider implements SqliteSnapshotProvider {
597597
`SQLite snapshot must be an immediate child of repository ${this.#repositoryPath}: ${snapshotDir}`,
598598
);
599599
}
600-
const repositoryStat = await fs.lstat(this.#repositoryPath);
600+
const repositoryStat = await lstatIfExists(this.#repositoryPath);
601+
if (!repositoryStat) {
602+
throw new Error(
603+
`SQLite snapshot repository does not exist: ${this.#repositoryPath}. Check the snapshot path or create a snapshot with \`openclaw backup sqlite create\`.`,
604+
);
605+
}
601606
assertDirectory(repositoryStat, this.#repositoryPath, "SQLite snapshot repository");
602-
const snapshotStat = await fs.lstat(snapshotDir);
607+
const snapshotStat = await lstatIfExists(snapshotDir);
608+
if (!snapshotStat) {
609+
throw new Error(
610+
`SQLite snapshot does not exist: ${snapshotDir}. Run \`openclaw backup sqlite list --repository ${this.#repositoryPath}\` to inspect available snapshots.`,
611+
);
612+
}
603613
assertDirectory(snapshotStat, snapshotDir, "SQLite snapshot");
604614
if (await lstatIfExists(path.join(snapshotDir, SNAPSHOT_PENDING_FILENAME))) {
605615
const snapshotState = await classifySnapshotDirectory(snapshotDir);
@@ -667,7 +677,12 @@ async function verifySnapshotDatabaseFile(
667677
throw new Error(`Snapshot artifact changed before SQLite verification: ${artifactPath}`);
668678
}
669679

670-
const validationRootIdentity = await fs.lstat(validationRootPath);
680+
const validationRootIdentity = await lstatIfExists(validationRootPath);
681+
if (!validationRootIdentity) {
682+
throw new Error(
683+
`SQLite validation root does not exist: ${validationRootPath}. Create a private directory there or pass an existing directory with \`--scratch\`.`,
684+
);
685+
}
671686
assertDirectory(validationRootIdentity, validationRootPath, "SQLite validation root");
672687
await withPrivateSqliteStagingDirectory({
673688
rootPath: validationRootPath,

0 commit comments

Comments
 (0)