Skip to content

fix(cli): keep backup remote guard remedies in --json error output - #199900

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/backup-remote-key-guards-json-remedy-431
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/backup-remote-key-guards-json-remedy-431

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw backup verify bogus-key --from archive --json exits 1 with a stderr that only says the command failed, even though the guard that rejected the key already carries the exact next step: "Expected a backup key from openclaw backup list --from <location> or latest." The same happens for the storage-location probe failure, the empty-location listing, and the missing-key guard in the remote backup flow, and for the upload size-confirmation guard on backup create --to. This converts those five operator-facing guards to the canonical expected-CLI-error owner so the remedy survives the --json lane, with identical message text.

  • Problem: src/commands/backup-remote.ts throws plain Error for five operator-facing guards. In the --json lane runCommandWithRuntime rethrows plain errors to the root renderer, which generalizes them to a two-line banner; the remedy text that the guard already wrote is lost to scripts and automation reading stderr.
  • Solution: replace each of the five throw new Error(...) sites with throwExpectedCliError(...) from src/cli/expected-cli-error.ts, keeping every message byte-identical. ExpectedCliError carries humanOutput/machineOutput, so the JSON failure envelope keeps the same message and stderr keeps the remedy.
  • What changed: src/commands/backup-remote.ts (one import plus five guard conversions: location probe, stored-size confirmation, backup-key shape, empty listing, missing key) and src/cli/program/register.backup.offsite.test.ts (a class assertion folded into the existing offsite integration case, net 0 test lines).
  • What did NOT change: guard message texts, JSON failure envelope shape and content, exit codes, text-lane output, the internal rethrow in openBackupLocation, and adjacent owners (resolveBackupNamespace in src/infra/backup-retention.ts, src/commands/backup-namespace.ts, the registration-layer --namespace requires --from guard).

Why This Change Was Made

Best fix: reuse the repository's canonical ExpectedCliError owner instead of formatting JSON stderr per site; this is the same conversion already merged for the sibling backup guards (#199763 backup create --to, #199850 backup git scope, #199760 sqlite snapshot sources, #199573 record guards, #199562 shared path guards), so the remote flow joins the family behavior instead of inventing a new policy. Alternative considered: converting the neighboring resolveBackupNamespace guard too — rejected because it lives in a different owner file and belongs to its own change; the matrix keeps it as an untouched plain-error control. Risk: the stored-size confirmation guard cannot be triggered naturally without a storage backend that misreports object sizes, so its runtime cell is not claimed (see What was not tested); its conversion is message-identical and symmetric with the four exercised guards.

User Impact

Operators and scripts driving openclaw backup verify/restore --from <location> (and backup create --to) with --json now get the actionable remedy on stderr when a guard rejects the request — which key format to use, which openclaw storage test/storage init step to run, or that the location/namespace holds no such backup — instead of a generic failure banner. Text-lane users, JSON envelopes, and exit codes see no change.

Evidence

Case Before (base 6d6b7b7) After (this head b3f948f)
backup verify bogus-key --from probe-loc --json stderr generalized banner The CLI command failed. remedy Expected a backup key from \openclaw backup list --from ` or latest.`
backup verify latest --from archive --namespace probe-ns --json (empty location) stderr generalized banner No backups in archive/probe-ns.
backup verify <missing-key> --from archive --namespace probe-ns --json stderr generalized banner Backup <missing-key> was not found in archive/probe-ns.
JSON failure envelope (stdout, every guard) {ok:false,error:{type:"cli_error",message:<remedy>}} byte-identical (cmp)
text-lane stderr (every guard) remedy present remedy present, byte-identical (cmp)
success listing backup list --from archive --namespace probe-ns (control) exit 0, key listed exit 0, byte-identical (cmp)
adjacent-owner namespace guard --namespace "bad ns" (control) text real message / json banner byte-identical both lanes (cmp)

End-to-end shipped proof (dual-arm built launcher)

Both arms were built from source with node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup (per-package node_modules symlinked first; build exit 0 on both). The base arm is frozen at origin/main commit 6d6b7b7; the head arm is commit b3f948f. Each cell runs the real built launcher node openclaw.mjs <command> under env -i with a fresh chmod 700 scratch HOME / XDG_RUNTIME_DIR / OPENCLAW_STATE_DIR, no credentials and no mocks. The storage location is a real filesystem provider initialized with openclaw storage init archive and a synthetic passphrase; the success-path object is provisioned by a real openclaw backup create --to archive --namespace probe-ns --only-config run (618 plaintext bytes, 762 stored), and its bytes are preserved across arms so the listing is deterministic. --version self-reports each arm's commit:

$ node openclaw.mjs --version
OpenClaw 2026.11.3 (6d6b7b7)   # base arm
OpenClaw 2026.11.3 (b3f948f)   # head arm

Guard cells, base vs head --json stderr (the discriminating stream). A deterministic log-append notice (log file append failed; records dropped; ... file=openclaw-2026-11-16.log) appears identically on both arms in every stderr and is part of the cmp invariants; it is an isolated-HOME environment artifact, not a behavior change.

$ node openclaw.mjs backup verify bogus-key --from probe-loc --json   # exit 1
# BASE stderr:
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.
# HEAD stderr:
Expected a backup key from `openclaw backup list --from <location>` or latest.
$ node openclaw.mjs backup verify latest --from archive --namespace probe-ns --json   # empty location, exit 1
# BASE stderr:
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.
# HEAD stderr:
No backups in archive/probe-ns.
$ node openclaw.mjs backup verify 20260102T000000Z-22222222.tar.gz --from archive --namespace probe-ns --json   # exit 1
# BASE stderr:
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.
# HEAD stderr:
Backup 20260102T000000Z-22222222.tar.gz was not found in archive/probe-ns.

The JSON failure envelope on stdout already carried the remedy on the base arm and is unchanged by the fix (byte-identical across arms for every guard):

{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "Expected a backup key from `openclaw backup list --from <location>` or latest."
  }
}

The text lane already showed the remedy on both arms (byte-identical):

$ node openclaw.mjs backup verify bogus-key --from probe-loc   # exit 1, stderr both arms
Expected a backup key from `openclaw backup list --from <location>` or latest.

Success-path control — the provisioned encrypted object lists identically on both arms (exit 0, cmp stdout identical):

$ node openclaw.mjs backup list --from archive --namespace probe-ns
20261116T022411Z-528ae870.tar.gz  618 bytes (762 stored)

Cross-arm invariants (cmp)

A 26-assertion compare script ran over both arms' captured stdout/stderr/exit for every cell: FAILED=0. It asserts, per converted guard, exit 1 both arms/lanes, empty text stdout, remedy present in text stderr both arms, remedy present in head json stderr, remedy absent + generalized banner in base json stderr, and byte-identical json stdout envelope and text stdout. Controls (c1 already-Expected registration guard, g2 storage-layer absent-directory error, c3 adjacent-owner namespace guard, c2 success listing) assert all four streams + exit byte-identical across arms, and that g2/c3 keep the real text message + generalized json banner on BOTH arms (over-conversion check).

Built-bundle self-attestation

The shipped bundles prove the executed form. Base dist/backup-remote-DvIBe8s3.mjs has 0 throwExpectedCliError; head dist/backup-remote-Dp8-Qwbd.mjs has 6 (5 guards + 1 import). All five converted sites, message text unchanged:

key-shape (:258)   BASE: )===void 0)throw new Error("Expected a backup key from `openclaw backup list --from
                   HEAD: id 0)throwExpectedCliError("Expected a backup key from `openclaw backup list --from
empty-list (:268)  BASE: !e)throw new Error(`No backups in ${t.from}/${r}.`);con
                   HEAD: owExpectedCliError(`No backups in ${t.from}/${r}.`);con
not-found (:272)   BASE: ;if(!o)throw new Error(`Backup ${e} was not found
                   HEAD: )throwExpectedCliError(`Backup ${e} was not found
probe (:58)        BASE: Error(r.message??`Storage location ${e}: ${r.state}. Run \`openclaw storage t
                   HEAD: wExpectedCliError(r.message??`Storage location ${e}: ${r.state}. Run \`openclaw storage t
stored-size (:151) BASE: ytes)throw new Error(`Stored backup size could not be confirmed for ${e.to
                   HEAD: toredBytes)throwExpectedCliError(`Stored backup size could not be confirmed for ${e.to

Base-arm OPENCLAW_DEBUG=1 stack confirms a plain Error reaching the root renderer (absolute paths sanitized to neutral placeholders):

[openclaw] The CLI command failed.
[openclaw] Reason: Expected a backup key from `openclaw backup list --from <location>` or latest.
[openclaw] Error: Expected a backup key from `openclaw backup list --from <location>` or latest.
[openclaw]     at withDownloadedBackup (file:///<base>/dist/backup-remote-DvIBe8s3.mjs:7:248)
[openclaw]     at backupRemoteVerifyCommand (file:///<base>/dist/backup-remote-DvIBe8s3.mjs:7:962)
[openclaw]     at async runCommandWithRuntime (file:///<base>/dist/cli-utils-Cz2q-7HD.mjs:3:233)

Regression test (red on base, green with the fix)

A class assertion was folded into the existing offsite integration case (net 0 test lines): await expect(backupRemoteVerifyCommand(defaultRuntime, { from: "archive", archive: "x" })).rejects.toSatisfy(isExpectedCliError). Message assertions cannot discriminate the class because the harness renders both classes with the same text, so the assertion targets the error class directly.

# BASE (source at 6d6b7b7, test kept): 1 failed | 3 passed
FAIL  src/cli/program/register.backup.offsite.test.ts > ... refuses uninitialized storage, then uploads, lists, verifies and stages an encrypted archive
Error: expect(received).toSatisfy()
Expected value to satisfy: [Function isExpectedCliError]
Received: [Error: Expected a backup key from `openclaw backup list --from <location>` or latest.]

# HEAD (b3f948f): 4 passed (4)
Test Files  1 passed (1)
     Tests  4 passed (4)

Open PR collision check

Searched the submission-day open-PR snapshot by changed file (src/commands/backup-remote.ts) and by anchor/anti-pattern keywords across three lanes (per-PR changed-file intersection, stem search, recent-created search); zero open PRs touch this file or convert these guards. The sibling backup-guard conversions already merged (#199763, #199850, #199760, #199573, #199562) cover other owner files, not backup-remote.ts.

What was not tested

  • The stored-size confirmation guard (:151) cannot be triggered naturally without a storage backend that misreports object sizes; no runtime cell is claimed for it. Its conversion is message-identical and symmetric with the exercised guards, and the bundle snippet above proves the executed form.
  • The location-probe guard (:58) fires only when openStorageLocation succeeds but the subsequent probe() returns non-ok — a TOCTOU race for the filesystem provider, not deterministically reachable in an isolated single-process run. The absent-directory cell (g2) is thrown earlier by the storage-layer owner (StorageLocationError, a plain Error) and is kept as an untouched adjacent-owner control; :58's conversion is proven by the bundle snippet.
  • Only the filesystem storage provider was exercised (the sole built-in provider); no network object store was used.
  • The deterministic log-append notice in every stderr is an isolated-HOME artifact present identically on both arms; it is not addressed by this change.

@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 cli CLI command changes commands Command implementations size: XS labels Nov 16, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. 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 remote-backup guard messages on stderr when commands run with --json.

Example: Run openclaw backup verify bogus-key --from archive --json.

  • Before: Stderr shows a generic command-failed banner and Doctor hint.
  • After: Stderr says: Expected a backup key from openclaw backup list --from &lt;location> or latest.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused repair with shipped CLI comparisons, a reported red/green regression, and no actionable findings; workflow approval remains separate from patch quality.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Pinned base/head built CLI traces exercise invalid, empty, and missing remote keys against isolated filesystem storage and show the corrected stderr with unchanged JSON stdout, text output, and exit codes; probe and size-mismatch execution are explicitly unclaimed, and their message-identical conversions use the same renderer contract.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Operators reading stderr in JSON mode lose the remote-backup guard's existing explanation and recovery instructions.
Reason: The change preserves established behavior and applies the same narrow diagnostic repair already merged for sibling backup guards.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR fixes a current CLI diagnostic bug through the existing error owner, with no introduced correctness or security defects found.

Priority: P3
Reviewed head: b3f948fd95b486f7f414d55250aad64f8efd60dc

Before merge

  • Await maintainer action - Review and approve the action_required GitHub Actions runs for this head so required validation can execute.

Findings

None.

Agent review details

How this fits together

Backup CLI commands pass storage and archive options to the remote-backup owner, whose errors reach the shared CLI renderer for stderr diagnostics and JSON failure output.

flowchart TD
  A[Backup CLI command] --> B[Remote backup owner]
  B --> C[Storage location]
  B --> D[Expected CLI error]
  D --> E[Root failure renderer]
  E --> F[Stderr remedy]
  E --> G[JSON stdout envelope]
Loading

Technical review

Best possible solution:

Use the existing ExpectedCliError owner at these five guards while preserving their messages, validation, and cleanup.

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

Current-main source shows plain errors reaching the generic JSON-mode stderr renderer, and the contributor records the matching failure through a pinned base CLI build; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch restores the existing expected-error rendering contract at the guard producer without adding formatting, state, options, or a parallel owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Remote-backup validation and storage failure guards keeps the original intent (37ffe3c: The storage-location feature introduced encrypted offsite backups with explicit rejection of unavailable storage, unconfirmed uploads, and invalid or absent backup keys.)
  • Existing offsite integration coverage keeps the original intent (test(core,plugins): remove low-value tests (batch d436) #180365: Test consolidation retained owner-boundary behavioral assertions while removing redundant replay coverage; this patch retains those assertions and folds in one discriminating error-contract check.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 37ffe3c adds src/commands/backup-remote.ts:215 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 37ffe3ce94e2; files: src/commands/backup-remote.ts)

PR surface

Source +1, Tests 0. Total +1 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 5 +1
Tests 1 12 12 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 18 17 +1

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 for an advanced backup CLI workflow; rejection behavior, JSON stdout, and exit codes already work.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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:58 PM ET / November 16, 2026, 02:58 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

cli CLI command changes commands Command implementations P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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