Skip to content

fix(cli): surface backup restore guard remedies in --json failures - #199869

Merged
obviyus merged 2 commits into
openclaw:mainfrom
SunnyShu0925:fix/backup-restore-guards-json-remedy-429
Nov 16, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
SunnyShu0925:fix/backup-restore-guards-json-remedy-429

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw backup restore backup.tar.gz --target ./restored --postgres-connection-env "not a name" --json exits 1, but stderr prints only [openclaw] The CLI command failed. and For help, run openclaw doctor. — the actionable remedy (--postgres-connection-env requires an environment variable name.) survives only inside the stdout JSON envelope, so an operator watching stderr loses the next step. Eight more restore guards behave the same way: state/agent directory containment, file target, non-empty target, disk capacity, unset connection env, --local-companion profile mismatch, and a plain archive without PostgreSQL stores. This PR routes those nine operator-input guards through the existing throwExpectedCliError owner so --json failures keep their remedy on stderr, with messages, exit codes, and the stdout envelope unchanged.

  • Problem: nine operator-facing guards in backupRestoreCommand throw plain Error; the JSON failure path replaces their remedy text with the generic two-line banner on stderr.
  • Solution: classify the nine guards through the existing throwExpectedCliError owner, retaining their exact messages.
  • Production: +10/-9. Tests: +46/-47, net -1; existing cases folded without dropping a distinct boundary.
  • Unchanged: guard ordering, restore/extraction behavior, text output, exit codes, JSON stdout, internal runtime-error classification and dependencies.

Evidence

Repeated before/after CLI receipts and focused checks, baseline a237e95ceb3f, candidate 69e5e72fa8a7:

  • One real config-only archive, seven refusal conditions, twice per side in both text and JSON modes. All 28 refusals per side exited 1. Candidate JSON stderr reports the existing diagnostic; text streams and JSON stdout remain byte-identical.
  • Normal restore succeeds identically; complete reports and every restored-file hash match. Refused targets remain untouched.
  • 66 focused tests pass; the same assertions on baseline produce eight expected-error classification failures and 58 passes. Matching test typecheck leaf and targeted formatting pass.
  • Full declaration build and clean packed-install CLI smoke pass. Source, tests and packaging ran on the host through ocx; the diff touches no install/lifecycle-sensitive paths.
  • File/non-empty errors pass unchanged through the existing non-ENOENT catch. Env diagnostics expose variable names, never values. Capacity and agent-directory containment are regression-test boundaries, not fault-injected CLI claims.

Merge danger: reversible error-classification/test change. Blast radius: JSON stderr presentation of existing backup-restore refusals; no stored-data or public-contract 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 commands Command implementations size: S labels Nov 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug 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: needs maintainer review before merge.

What this changes

Classifies nine existing backup restore refusals as expected CLI errors so their remedies appear on stderr in JSON mode.

Example: Run openclaw backup restore backup.tar.gz --target ./restored --postgres-connection-env "not a name" --json.

  • Before: Stderr shows a generic failure and Doctor hint; the specific remedy appears only in JSON stdout.
  • After: Stderr shows "--postgres-connection-env requires an environment variable name." while JSON stdout and exit code 1 remain unchanged.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused repair with real CLI before/after evidence, reported red/green regressions, preserved safety contracts, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact-head CLI receipts exercise seven restore refusals against a real archive in isolated state, showing specific JSON-mode stderr diagnostics with unchanged stdout, text output, exit codes, and refused targets; a successful restore preserves reports and file hashes.
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 watching stderr lose the specific next step when a backup restore guard rejects a JSON-mode command.
Reason: The narrow classification repair restores useful diagnostics through an existing mechanism without introducing options, policy, or storage changes.

Merge readiness

✅ Ready for maintainer review

This PR fixes a diagnostic defect still present on current main, with convincing CLI evidence and no actionable findings.

Priority: P3
Reviewed head: 69e5e72fa8a7c83bc81b9cad25454ee64da316ba

Before merge

None.

Findings

None.

Agent review details

How this fits together

The backup CLI passes restore options to the archive restore command; guard failures flow through the shared CLI error renderer to JSON stdout and human-readable stderr.

flowchart TD
  A[Backup restore CLI] --> B[Restore command guards]
  B --> C[Expected CLI error]
  C --> D[Shared failure renderer]
  D --> E[JSON stdout]
  D --> F[Actionable stderr]
  B --> G[Verified staging restore]
Loading

Technical review

Best possible solution:

Use the existing expected-error owner for these operator refusals while preserving restore safety checks and unexpected-error handling.

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

Current-main guards throw plain Error, and the shared renderer suppresses their specific stderr diagnostics in JSON mode; supplied before/after CLI receipts confirm this path without requiring reviewer execution.

Is this the best way to solve the issue?

The patch is the smallest complete production fix: classify the existing refusals at their producer through the established error owner, preserving all predicates and messages.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Fresh-target and live-state containment refusals keeps the original intent (e69a973: Whole-archive restore intentionally verifies first, restores only into fresh staging, excludes live state, and leaves activation explicit.)
  • Configured agent-directory containment keeps the original intent (2f17d11: Backup ownership includes configured external agent roots, which restore must also protect.)
  • Target capacity refusal keeps the original intent (dd64b3b: Refuse extraction when available space cannot hold archive data plus the existing reserve.)
  • PostgreSQL override refusals keeps the original intent (96c685b: The approved environment-only destination override requires a valid populated variable and an archive containing PostgreSQL stores while preserving archived configuration.)
  • Local-companion profile refusal keeps the original intent (4fb684e: Explicit local-companion restore must refuse ordinary archives before extraction.)
  • Existing restore regression coverage keeps the original intent (05c3308: Earlier test consolidation retained distinct ownership, safety, and recovery contracts; this patch retains those boundaries while strengthening error classification assertions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Dallin Romney: Raw commit dd64b3b adds src/commands/backup-restore.ts:90 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: dd64b3b24f17; files: src/commands/backup-restore.ts)

PR surface

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

View PR surface stats
Area Files Added Removed Net
Source 1 10 9 +1
Tests 2 46 47 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 56 56 0

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.

Review metrics

Metric Value Why it matters
Production versus test LOC Production +10/-9; tests +46/-47. One existing helper import accounts for production growth; test consolidation retains the distinct refusal and cleanup boundaries without net test growth.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P3: This improves diagnostics in an advanced backup CLI workflow; refusal behavior already works and the remedy remains available in JSON stdout.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-16T01:10:55.748Z sha 47b24be :: needs maintainer review before merge. :: none

Reviewed November 15, 2026, 8:56 PM ET / November 16, 2026, 01:56 UTC (Revision 2).

@obviyus

obviyus commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Head: 69e5e72fa8a7c83bc81b9cad25454ee64da316ba.

Validated restore-guard error forwarding against main baseline a237e95ceb3f. The contributor production fix is retained; restore selection, validation order and extraction behavior are unchanged.

Real archive, repeated CLI proof

Tier: source, host through ocx src, pinned Bun fork. One real 636-byte config-only archive was made by backup create --only-config; SHA-256 2f4ea68bd2682586cafeed72d797b42ee03aaa0b70b9d7720e42e7e18bce3b0f. Both sides restored that exact immutable archive. HOME/profile/state and all targets were task-owned; no Gateway was started and nothing was activated.

Each refusal below was run twice on main and twice on candidate, in both JSON and text modes:

Input condition Existing diagnostic restored on JSON stderr
--postgres-connection-env 'not a name' Requires an environment variable name
Unset OC_BUGLOOP_199869_UNSET name That variable is not set; nothing was restored
Non-empty target Restore target directory must be empty
File target Restore target must be a directory
Target under the isolated state directory Target must be outside the live OpenClaw state directory
--local-companion on the ordinary archive Requires a local-companion checkpoint; no PostgreSQL data was imported
Set variable, but no PostgreSQL stores in the archive Requires an archive with PostgreSQL stores; nothing was restored

Main JSON stderr contained only:

[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw --profile p199869proof doctor`.

Candidate JSON stderr contained the specific existing diagnostic, including the unchanged target path or variable name where applicable. All 28 refused CLI invocations per side exited 1. JSON stdout was byte-identical before/after; text-mode stdout/stderr were byte-identical. The existing file/non-empty contents stayed intact, and the other refused targets remained absent.

A normal restore into an empty target succeeded on both sides with exit 0. The complete restore reports were identical (ok:true, one asset, two entries, verified SQLite inventory), and hashes of every restored file matched across sides.

Selected identical JSON stdout SHA-256:

  • Invalid variable name: e0e5f067738287d2681354a857c339ca8cce88553afd51ae4125a04ab0980247.
  • File target: 01419f7a9479298f2a5b66c7d867ce0b3a3c2b79e43bb25541b6c3684a71be68.
  • Non-companion archive: 1fec5c409f4a87987f7d2174dcc664c528834c11842574fed4f60aab84822afb.

Catch and privacy checks

prepareRestoreTarget catches only to handle ENOENT. ExpectedCliError has no code field; file/non-empty errors therefore enter the existing non-ENOENT branch and are rethrown as the same error object, without wrapping. The real CLI file/non-empty runs and expected-error assertions confirm that classification survives to the failure owner.

The env guards interpolate only the variable name, never process.env[name]. The no-PostgreSQL source runs used a nonempty, non-connection-string sentinel value and verified that its value appeared in neither stream. No connection string was used or published.

Tests and trim audit

  • vitest-source, host: candidate 66 passed across backup-restore.test.ts and backup-verify-completeness.test.ts; baseline with the new guard assertions had 8 failures / 58 passes, all expected-error classifications.
  • Matching commands typecheck leaf and targeted Oxfmt passed. Candidate check sequence took 87.11 s; its two Vitest shards took 61.72 s.
  • Confirmed no case was dropped: empty success/non-empty refusal and marker preservation remain; all three env refusals became table rows; capacity refusal/exact-capacity hardlink control remain; external-agent containment remains with an added state-containment row; both incomplete-target cleanup checks and aggregate-error checks remain; ordinary-versus-companion refusal/success remains.
  • Restored the complete pre-existing no-PostgreSQL message check in the folded table while replacing its unused connection-shaped fixture with a harmless nonempty value. No production behavior was added.

Agent-directory containment and capacity are regression-test boundaries; no disk-space fault or artificial capacity restriction was injected into the CLI runs.

Packaging and isolation

  • full, host through ocx build --dts: passed in 141 s, including declarations. The build emitted existing Control UI size-budget warnings; this PR changes no UI files.
  • Packed tarball integrity, clean task-local npm install, installed --version and backup restore --help: passed. The installed CLI reported OpenClaw 2026.11.3 (69e5e72).
  • Host-ocx eligibility: the complete merge-base diff touches only src/commands/backup-restore.ts and the two named test files. No package, lockfile, workspace, npmrc, patches, scripts, git-hook or lifecycle path changed.
  • Production +10/-9; tests +46/-47, net -1, with no allocation file. No new runtime wording, exports or dependencies. Simplification retains the existing error owner and removes no distinct test case.

Representative commands (all with isolated task-owned HOME/state/config, and no Gateway):

ocx test src/commands/backup-restore.test.ts src/commands/backup-verify-completeness.test.ts
ocx src -- --profile p199869proof backup create --only-config --output <archive>
ocx src -- --profile p199869proof backup restore <archive> --target <target> --postgres-connection-env 'not a name' --json
ocx src -- --profile p199869proof backup restore <archive> --target <target> --local-companion --json
ocx build --dts

Exact-head gates and timings

  • CI run: green, 68 jobs, no failed or cancelled jobs. openclaw/ci-gate: success on 69e5e72fa8a7.
  • Fresh ClawSweeper review: 5/6, machine state ready, zero findings, exact head 69e5e72fa8a7.
  • The 28 refused source invocations totaled 20.456 s on baseline (range 0.629–1.387 s) and 36.436 s on candidate (0.952–7.298 s). These are execution receipts under shared host load, not a performance claim.
  • Candidate focused Vitest: 61.72 s; combined test/typecheck/format sequence: 87.11 s; full build: 141 s; packed tarball validation: 39 s, packed install: 20 s.
  • Normal, contributor-preserving push; after-push.sh passed with three changed files. Task-local packed installation and ocx baseline scratch were removed; no Docker resources or Gateway were started. Worktree/branch remain available for maintainer landing.

Merge danger: reversible error-classification/test change. Blast radius: JSON stderr presentation of the existing restore guard refusals.

@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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
@obviyus
obviyus merged commit a97d3d4 into openclaw:main Nov 16, 2026
138 of 139 checks passed
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Landed in a97d3d4. Thanks @SunnyShu0925.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…penclaw#199869)

fix(cli): report backup restore preflight errors through the expected-error path

`openclaw backup restore <archive> --target ... --json` threw plain errors for its preflight checks (an invalid or unset `--postgres-connection-env` variable, a target inside the live state or agent directory, a target that is a file or a non-empty directory, not enough free disk space, `--local-companion` on an archive that is not a local-companion checkpoint, and `--postgres-connection-env` on an archive with no PostgreSQL stores), so `--json` stderr showed the generic failure plus the Doctor hint instead of the existing message. These checks now use the expected-error path with the same messages; messages name the variable but never its value. Restore behavior is unchanged. No new text.

Evidence: host, isolated state, no Gateway. A small archive made with `backup create`, then `backup restore <archive> --target <tmp>` for seven refusals, twice per side, with --json and in text mode (28 calls per side). Base prints the generic failure and Doctor hint, this change prints the existing message; text output, JSON stdout, exit codes and targets are unchanged, and a normal restore into an empty target gives matching reports and file hashes on both. Vitest-source: eight cases fail on base, 66 pass here; full build and packed smoke pass. Receipts: openclaw#199869 (comment).

Thanks @SunnyShu0925.

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: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants