Skip to content

fix(cli): keep backup archive verification remedies in --json error output - #199891

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/backup-verify-error-remedy-430
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/backup-verify-error-remedy-430

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw backup verify <missing-archive> --json prints the full operator remedy to stdout's JSON envelope but only a generic two-line fallback (The CLI command failed. / For help, run openclaw doctor.) to stderr, so an operator reading the terminal in JSON mode has no actionable next step. Converting the archive-verification summary error to ExpectedCliError keeps the same remedy text on stderr in JSON mode without changing the stdout envelope or exit code.

  • Problem: prepareBackupArchive() wraps every archive-verification failure in a plain Error. In JSON mode runCommandWithRuntime rethrows plain Errors, and the root renderer only emits a generic failure line to stderr; the structured message survives only in the stdout envelope.
  • Solution: Replace throw new Error(...) in prepareBackupArchive() with throwExpectedCliError(...). ExpectedCliError carries humanOutput and machineOutput, so formatCliFailureLines/formatCliJsonFailure render the same remedy to stderr in both text and JSON modes.
  • What changed: src/commands/backup-verify.ts imports throwExpectedCliError and uses it at the single prepareBackupArchive summary wrapper. A single-use intermediate Set is inlined at its one call site so the file stays within the repository line-cap ratchet after the new import. src/commands/backup-verify.test.ts folds the two existing failure cases (missing/directory and invalid header) to assert the rethrown ExpectedCliError shape directly instead of runtime.error/runtime.exit. test/cli-json-stdout.e2e.test.ts adds a stderr-remedy assertion to the existing JSON-failure case.
  • What did NOT change: guard conditions, message text, exit codes, the JSON stdout envelope, the parser, renderers, or any production export. Text-mode stderr output is byte-for-byte unchanged.

Why This Change Was Made

prepareBackupArchive is the canonical owner introduced to wrap every archive-verification failure so that direct verify, backup restore, and backup create --verify share one diagnostic boundary. Converting the wrapper's throw preserves that design and covers manifest, path-header, and SQLite snapshot failures in one change instead of per-guard edits.

  • Best fix: Yes. The wrapper is the single point where all archive-verification errors are already summarized with a user-facing prefix; this is the narrowest change that fixes every failure mode for every shared caller.
  • Alternative(s): Converting only the three preflight guards (missing/directory/invalid) would leave manifest and path-header failures on the generic path and would require an extra branch to preserve any existing ExpectedCliError. Editing the CLI renderer instead would change behavior for every plain Error in the codebase. Both are wider or less complete.
  • Risk: ExpectedCliError extends Error, so shared callers that propagate or format the rejected error see the same message. Internal callers (create --verify, remote, doctor schema guard, update worker) already handle failures through generic formatErrorMessage/diagnostics, so the subtype change is additive. The only observable change is JSON-mode stderr now carries the remedy that was already in the stdout envelope.

User Impact

Operators running backup verify (or backup restore / backup create --verify) against a bad archive in --json mode now see the same actionable remedy on stderr that text mode already showed, instead of a generic doctor hint. The JSON stdout envelope and exit code are unchanged, so machine consumers are unaffected.

Evidence

Before/after comparison

Case Before (base, origin/main) After (candidate)
backup verify <missing> --json stderr [openclaw] The CLI command failed. + doctor hint Backup archive verification failed: <missing>. Archive does not exist. Check the path and run \openclaw backup verify ` again.`
backup verify <directory> --json stderr generic two-line fallback ... Archive must be a regular file. Choose a backup archive created by \openclaw backup create` and try again.`
backup verify <invalid.tar.gz> --json stderr progress logs + generic two-line fallback progress logs + ... Archive is not a valid OpenClaw backup. ... Choose another archive or create a new one with \openclaw backup create`.`
backup verify <missing> (text, control) full remedy on stderr full remedy on stderr (unchanged)
backup restore <missing> --target <dir> --json stderr generic two-line fallback full remedy on stderr (shared wrapper)
JSON stdout envelope, all failure cases { ok: false, error: { type: "cli_error", message: "<full remedy>" } }, exit 1 identical envelope, exit 1 (byte-for-byte)

End-to-end shipped proof

Both arms built independently from the same parent commit with node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup; each launcher self-reports the identical commit via node openclaw.mjs --version. Isolated scratch HOME/state/config, no credentials or mocks.

Built-bundle self-proof:

# base bundle (backup-verify chunk)
throw new Error(`Backup archive verification failed: ${r}. ${t}`)

# candidate bundle (backup-verify chunk)
throwExpectedCliError(`Backup archive verification failed: ${r}. ${t}`)

Real command runs. Two symmetric harness-noise lines are omitted because they appear identically on both arms and are unrelated to the fix: the Node 24.19.0 security warning, and [openclaw] log file append failed; records dropped ... file=openclaw-2026-11-16.log (the scratch HOME has no writable log path):

$ node openclaw.mjs backup verify <scratch>/missing.tar.gz --json
[base stderr]
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.

[candidate stderr]
Backup archive verification failed: <scratch>/missing.tar.gz. Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.

[both stdout, byte-for-byte identical]
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "Backup archive verification failed: <scratch>/missing.tar.gz. Archive does not exist. Check the path and run `openclaw backup verify <archive>` again."
  }
}
exit 1

Text-mode control (unchanged between arms):

$ node openclaw.mjs backup verify <scratch>/missing.tar.gz
Backup archive verification failed: <scratch>/missing.tar.gz. Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.
exit 1

Shared backup restore channel confirms the wrapper fix reaches all callers:

$ node openclaw.mjs backup restore <scratch>/missing.tar.gz --target <scratch>/target --json
[base stderr]      [openclaw] The CLI command failed. ... doctor hint
[candidate stderr] Backup archive verification failed: <scratch>/missing.tar.gz. Archive does not exist. ... (same remedy)
[both stdout]      identical { ok: false, error: { type: "cli_error", message: "..." } }, exit 1

Invariants verified with cmp: JSON stdout envelopes identical across arms for missing/directory/invalid/restore; text-mode stderr identical; exit codes identical (all 1).

Regression tests

  • src/commands/backup-verify.test.ts: the two existing failure cases now assert name: "ExpectedCliError" plus message/humanOutput/machineOutput. Base arm (production reverted) fails these assertions with name: "Error"; candidate arm passes. Full file: 40 passed, 1 skipped.
  • backup-verify-completeness, backup-verify.utf8, backup-legacy-hardlinks, backup-restore: 72 passed.
  • doctor-update-schema-guard, database-migration-capture: 35 passed (shared verifyBackupArchive callers).
  • test/cli-json-stdout.e2e.test.ts: existing JSON-failure case now also asserts stderr contains the remedy; passes on candidate.

Open PR collision check

Searched all open pull requests by changed-file list (full snapshot, not only title/body keywords). No open PR modifies the prepareBackupArchive wrapper or the error-classification path in src/commands/backup-verify.ts. Two open PRs (#194566, #192698) touch the same file but only the hardlink-target resolution block (around lines 541-610), disjoint from this change at the verification-summary wrapper.

Related: #199869 converts nine restore-input guards in src/commands/backup-restore.ts and deliberately leaves the shared archive-verification path generic; its file set is disjoint from this PR, so either merge order needs no rebase. After both land, backup restore with a bad archive also keeps the remedy on stderr, which extends that PR's missing-archive control cell by design.

What was not tested

  • backup create --verify and backup remote were not exercised end-to-end with a built CLI in this run; they share the same verifyBackupArchive/prepareBackupArchive wrapper and are covered by unit tests.
  • Windows path handling was not exercised on a Windows host.

…utput

prepareBackupArchive wrapped every archive-verification failure in a plain
Error, so in JSON mode stderr fell back to the generic doctor banner while
the structured remedy survived only in the stdout envelope. Convert the
shared wrapper to throwExpectedCliError so verify, restore, and
create --verify keep the operator remedy on stderr, with messages, exit
codes, the JSON envelope, and text-mode output unchanged.
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: XS labels Nov 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR preserves archive-verification recovery instructions on stderr when backup commands use --json.

Example: Run openclaw backup verify /tmp/missing.tar.gz --json.

  • Before: Stderr shows a generic command-failed message and Doctor hint; the specific recovery instruction appears only in stdout JSON.
  • After: Stderr explains that the archive does not exist and asks the operator to check the path; stdout JSON and exit code 1 remain unchanged.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with direct CLI evidence and no actionable findings; required hosted validation awaits workflow approval.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied terminal output exercises independently built base and candidate launchers in isolated homes, showing archive-verification and restore remedies on stderr while JSON stdout, text controls, and failure exits remain unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Operators watching stderr during JSON-mode backup failures lose the existing archive-specific recovery instruction.
Reason: It restores actionable diagnostics through established error ownership without adding options or changing archive acceptance.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: it fixes a current diagnostic defect through the existing shared owner, supplied CLI proof demonstrates the result, and no actionable patch defect was found.

Priority: P3
Reviewed head: 327c12e66ab33e1940a09631a90e74b815e7a566

Before merge

  • Await maintainer action - Approve the gated GitHub Actions runs for head 327c12e so required CI can execute.

Findings

None.

Agent review details

How this fits together

Backup verification validates archive inputs for verify, restore, creation, and recovery callers; its shared error reaches the CLI renderer, which produces human diagnostics and machine-readable failures.

flowchart TD
  A[Backup CLI commands] --> B[Shared archive preparation]
  B --> C[Archive and snapshot validation]
  C --> D[Expected CLI error]
  D --> E[Root failure renderer]
  E --> F[Recovery instructions on stderr]
  E --> G[JSON failure on stdout]
Loading

Technical review

Best possible solution:

Use the existing expected-error classification at the shared archive summary boundary while preserving validation, recovery wording, and machine output.

Do we have a high-confidence way to reproduce the issue?

Current-main source deterministically routes the plain archive error to generic stderr in JSON mode, consistent with the contributor's supplied before/after CLI traces; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is the smallest complete repair: classify the existing shared summary through ExpectedCliError rather than changing global rendering or duplicating fixes across archive guards and callers.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d0e09e419d7e.

Provenance checked

  • Shared archive-verification diagnostic wrapper keeps the original intent (b990160: Centralize path-qualified, actionable archive failures across verify, restore, and create --verify.)
  • Normalized archive-entry membership keeps the original intent (d4973a9: Use the normalized entry index for manifest membership and hardlink resolution; constructing its single-use Set at the consumer preserves the same entries.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b990160 adds src/commands/backup-verify.ts:556 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b9901605e83d; files: src/commands/backup-verify.ts)
  • Vincent Koc: Raw commit 3fed2ee adds src/commands/backup-verify.ts:701 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3fed2eed50c3; files: src/commands/backup-verify.ts)
  • shichangs: Raw commit 0ecfd37 adds src/commands/backup-verify.ts:280 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0ecfd37b4465; files: src/commands/backup-verify.ts)

PR surface

Source 0, Tests -2. Total -2 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 3 3 0
Tests 2 13 15 -2
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 16 18 -2

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This improves diagnostics in an operator CLI workflow; failures already return the specific remedy in JSON stdout.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 15, 2026, 9:22 PM ET / November 16, 2026, 02:22 UTC.

@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the work here. We're closing this one along with the other open per-command --json error fixes. These PRs all fix the same root cause one command at a time: runCommandWithRuntime rethrows plain errors in JSON mode, so the root renderer prints the generic failure instead of the existing message. We're fixing that once in the shared wrapper instead, which covers this command too. Please don't open more per-command variants of this fix; if you find a case the shared fix doesn't cover, open an issue with a reproduction.

@obviyus obviyus closed this Nov 16, 2026
obviyus added a commit that referenced this pull request Nov 16, 2026
fix(cli): show the existing failure message for plain errors in --json mode

`runCommandWithRuntime` rethrew every plain error in JSON mode, so the root renderer printed only the generic "The CLI command failed." plus the Doctor hint on stderr, while text mode printed the error's own (redacted) message. Contributors had been patching this one command at a time by converting individual throws to expected errors. JSON mode now shows the same redacted message text mode already shows, once in the shared wrapper; the JSON stdout envelope, exit codes and text-mode output are unchanged. Commands that fail outside the wrapper (for example `models auth login` conflicts and `attach` target resolution) are not covered. No new text.

Evidence: host, isolated state. 76 CLI runs across eight command flows (including `backup verify`, `backup remote`, `skills list/check/info` and `migrate plan/apply`), twice per side: base prints the generic failure in --json mode, this change prints the existing message; text failure output, JSON stdout and exit codes are identical across 150 comparisons. 156 unit and 124 consumer tests pass; full build and installed packed smoke pass. CI reds are inherited from main (receipt: #199970 (comment)).

Supersedes the closed per-command PRs #199891, #199900, #199910 and #199448.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
fix(cli): show the existing failure message for plain errors in --json mode

`runCommandWithRuntime` rethrew every plain error in JSON mode, so the root renderer printed only the generic "The CLI command failed." plus the Doctor hint on stderr, while text mode printed the error's own (redacted) message. Contributors had been patching this one command at a time by converting individual throws to expected errors. JSON mode now shows the same redacted message text mode already shows, once in the shared wrapper; the JSON stdout envelope, exit codes and text-mode output are unchanged. Commands that fail outside the wrapper (for example `models auth login` conflicts and `attach` target resolution) are not covered. No new text.

Evidence: host, isolated state. 76 CLI runs across eight command flows (including `backup verify`, `backup remote`, `skills list/check/info` and `migrate plan/apply`), twice per side: base prints the generic failure in --json mode, this change prints the existing message; text failure output, JSON stdout and exit codes are identical across 150 comparisons. 156 unit and 124 consumer tests pass; full build and installed packed smoke pass. CI reds are inherited from main (receipt: openclaw#199970 (comment)).

Supersedes the closed per-command PRs openclaw#199891, openclaw#199900, openclaw#199910 and openclaw#199448.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants