Skip to content

fix(backup): surface record guard remedies in --json failures - #199573

Merged
obviyus merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/backup-record-guards-remedy
Nov 15, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/backup-record-guards-remedy

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw backup record --status bogus --target label --json exits 1 with only [openclaw] The CLI command failed. and the doctor hint on stderr, so machine callers that read stderr never see the --status must be ok or failed. remediation that the text lane already prints.

  • Problem: the three backup record argument guards (--status enum, blank --target label, non-numeric/negative --bytes) throw a plain Error. The text lane renders its message, but the JSON lane classifies it as an unexpected failure and replaces it with the generic failure banner, leaving the remediation only inside the stdout envelope.
  • Solution: throw ExpectedCliError from the same guards, so the JSON lane renders the same remediation the text lane prints while keeping the envelope untouched.
  • What changed: src/commands/backup-record.ts routes the three guards through throwExpectedCliError (one new import, three throw call sites, identical message text). src/commands/backup-outcome.test.ts folds regression assertions into the existing malformed-argument test (name: "ExpectedCliError" plus the unchanged messages).
  • What did NOT change: exit codes, the stdout JSON envelope shape and message, the happy-path record write/output, and every other backup subcommand.

Why This Change Was Made

ExpectedCliError is the shipped owner for argument-level CLI failures (src/cli/expected-cli-error.ts), so the fix reuses the existing failure classifier instead of adding a new rendering path.

  • Best fix: convert the guard throws in place; the message text, exit code, and machine envelope stay byte-identical, and only the stderr classification changes.
  • Alternative: special-case the JSON renderer to print error.message for plain Error too. Rejected: that would leak stack-y unexpected failures into the "expected" lane and change every other command at once.
  • Risk: the only observable delta is which stderr lines appear in JSON mode for these three invalid inputs; valid records and the stdout envelope were verified byte-identical in the shipped-build comparison below.

User Impact

Operators and CI jobs that run backup record with --json now get the actionable remediation (--status must be ok or failed., Missing required --target label., --bytes must be a nonnegative integer.) on stderr, matching the text lane, instead of a generic failure banner. Scripts that parse the stdout envelope see no change.

Evidence

Both arms were built with the shipped CLI pipeline (node --import ./scripts/tsx.mjs scripts/build-all.mts cliStartup) and exercised through the real launcher (node openclaw.mjs <cmd>) with a fresh scratch HOME / OPENCLAW_STATE_DIR / config per cell. --version self-reports both arm identities: base OpenClaw 2026.11.3 (69c3aca), this head OpenClaw 2026.11.3 (43eb3ee).

Case (backup record ...) Before (origin/main 69c3aca) After (this head 43eb3ee)
--status bogus --target label --json exit 1; stderr only [openclaw] The CLI command failed. + For help, run \openclaw doctor`.`; remedy confined to stdout envelope exit 1; stderr --status must be ok or failed.; stdout envelope byte-identical (109 B)
--status ok --target " " --json exit 1; same generic stderr pair; remedy only in envelope exit 1; stderr Missing required --target label.; stdout envelope byte-identical (111 B)
--status ok --target label --bytes nope --json exit 1; same generic stderr pair; remedy only in envelope exit 1; stderr --bytes must be a nonnegative integer.; stdout envelope byte-identical (117 B)
text lane, all three invalid inputs (no --json) exit 1; stderr carries the remedy exit 1; stderr byte-identical to before (cmp reports no difference)
control: --status ok --target label --bytes 42 --json exit 0; 105 B record envelope on stdout exit 0; stdout and stderr byte-identical to before (cmp reports no difference)

Pre-fix JSON lane (base build):

$ node openclaw.mjs backup record --status ok --target label --bytes nope --json
# exit=1
# stderr:
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.
# stdout:
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "--bytes must be a nonnegative integer."
  }
}

Post-fix JSON lane (this head build, identical command):

$ node openclaw.mjs backup record --status ok --target label --bytes nope --json
# exit=1
# stderr:
--bytes must be a nonnegative integer.
# stdout:
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "--bytes must be a nonnegative integer."
  }
}

Invariants across the two builds (cmp on captured files):

status-json, target-blank-json, bytes-json stdout : byte-identical
control-json stdout                              : byte-identical
control-json stderr                              : byte-identical
all three text-lane cells (stdout and stderr)    : byte-identical
stderr delta on JSON cells                       : the two generic lines are replaced by the single guard message

Serialized shipped bundle of the changed owner (this head, dist/backup-record-*.mjs) proves the guard now throws the expected-error type:

import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";
async function backupRecordCommand(e,t){if(t.status!==`ok`&&t.status!==`failed`)throwExpectedCliError(`--status must be ok or failed.`);const n=t.target?.trim();if(!n)throwExpectedCliError(`Missing required --target label.`);...

Regression test is red on the pre-fix owner and green after (test kept, production file reverted with git stash push -- src/commands/backup-record.ts):

# pre-fix owner, folded assertions kept
$ npx vitest run src/commands/backup-outcome.test.ts -t "rejects malformed record arguments"
 FAIL  src/commands/backup-outcome.test.ts > rejects malformed record arguments as expected CLI errors instead of coercing
 AssertionError: expected Error: --bytes must be a nonnegative inte… to match object { name: 'ExpectedCliError', …(1) }
 Tests  1 failed | 6 skipped (7)

# this head
$ npx vitest run src/commands/backup-outcome.test.ts
 Test Files  1 passed (1)
 Tests  7 passed (7)

What was not tested: no Windows run; the --target missing-value path that commander rejects before the owner is not exercised (only the blank-string path). Both arms emit the same Node security-patch warning on stderr; it was filtered out of the quoted output and is unrelated to this change.

Open PR collision check: searched open PRs by changed-file list for src/commands/backup-record.ts, src/commands/backup-outcome.test.ts, and src/cli/program/register.backup.ts on the day of writing; no open PR touched them. Same-family merges this week are per-site siblings (#199369 sandbox explain, #198975/#198965/#198861 selector guards), none covering backup record.

`backup record` validated --status/--target/--bytes with plain Error, so
--json runs printed only the generic CLI failure plus the doctor hint and
lost the remediation text on stderr. Route the three argument guards
through throwExpectedCliError so the JSON lane keeps the same message the
text lane already prints.
@clawsweeper

clawsweeper Bot commented Nov 15, 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 15, 2026
@SunnyShu0925
SunnyShu0925 marked this pull request as ready for review November 15, 2026 11:11
@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: 🦞 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes invalid backup record arguments print their existing remedies on stderr in JSON mode.

Example: Run openclaw backup record --status bogus --target label --json.

  • Before: Stderr prints a generic failure and Doctor hint; the specific remedy appears only in stdout JSON.
  • After: Stderr prints --status must be ok or failed.; the JSON envelope and exit code remain unchanged.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused, correct repair with shipped-entry-point proof, useful regression coverage, and no open findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Built-launcher output exercises all three changed guards in JSON and text modes, with unchanged envelopes and exit codes; collaborator verification adds valid-record persistence controls and exact-head packed-CLI confirmation.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: JSON-mode backup record failures send stderr readers a generic failure instead of the actionable argument remedy.
Reason: A narrow classification repair restores the existing expected-error contract without adding options or changing valid records.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current CLI diagnostic bug with a focused change; no actionable defects were found, and current-head CI remains pending.

Priority: P3
Reviewed head: 0c7e070d774d23458e95ff725a1e4ef6c6b79d7c

Before merge

None.

Findings

None.

Agent review details

How this fits together

The backup command validates external-job outcome arguments before recording them; the shared CLI failure renderer converts rejected arguments into stderr diagnostics and a JSON failure envelope.

flowchart TD
  A[Backup record CLI] --> B[Argument guards]
  B --> C[Expected CLI error]
  C --> D[Shared failure renderer]
  D --> E[Stderr remedy]
  D --> F[JSON failure envelope]
  B --> G[Valid outcome recording]
Loading

Technical review

Best possible solution:

Use the existing expected-error helper at these three argument guards, as this PR does.

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

Current-main guards and the shared renderer establish the failure path, supported by supplied before/after shipped-CLI output; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is the smallest complete fix: classify argument failures at their producer while retaining the existing renderer, validation rules, and recording owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Backup record argument guards keeps the original intent (37ffe3c: External backup jobs gained outcome recording with status, target, and byte validation; this PR preserves those validations and changes their diagnostic classification.)
  • Strict decimal byte validation and regression keeps the original intent (2450ae0: Reject radix and exponent forms before recording; the consolidated table retains the original invalid inputs and verifies expected-error classification.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 37ffe3c adds src/commands/backup-record.ts:17 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-record.ts)
  • YangManBOBO: Raw commit 2450ae0 adds src/commands/backup-record.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2450ae0b6aa7; files: src/commands/backup-record.ts)
  • Ayaan Zaidi: Raw commit 2d2b465 adds src/commands/backup-record.ts:2 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2d2b4658943d; files: src/commands/backup-record.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 4 3 +1
Tests 1 7 7 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 11 10 +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 CLI workflow; the command already rejects invalid input and includes the remedy in stdout JSON.
  • 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 (2 earlier review cycles)
  • reviewed 2026-11-15T11:26:59.730Z sha 43eb3ee :: blocked before merge. :: none
  • reviewed 2026-11-15T12:27:35.952Z sha 45b8928 :: needs maintainer review before merge. :: none

Reviewed November 15, 2026, 9:47 AM ET / 14:47 UTC (Revision 3).

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Independent before/after proof against base 69c3aca, using the unchanged production fix from contributor commit 43eb3ee.

Host isolation check: only src/commands/backup-record.ts and its existing test file differ; no package, lockfile, workspace, lifecycle, hook or scripts changes. Product commands ran through ocx with task-owned HOME and profile p199573; no Gateway was started. CLI state resolved under the task-owned HOME/.openclaw-p199573/state/openclaw.sqlite. Worktrunk and commit hooks were skipped; normal ocx install lifecycle ran.

Source tier (Node + tsx): ran each command once on base and candidate, with --json and without it:

openclaw backup record --status done --target label
openclaw backup record --status ok --target "  "
openclaw backup record --status ok --target label --bytes 0x10

Base JSON stderr prints generic failure plus the Doctor hint. Candidate JSON stderr prints the existing messages:

--status must be ok or failed.
Missing required --target label.
--bytes must be a nonnegative integer.

All six corresponding stdout captures and exit codes compare identically; invalid cases exit 1. Text-mode product stderr is identical as well (excluding ocx's own diagnostics). The patch changes error classification only, not message text. The guards at backup-record.ts:20-29 execute before constructing the outcome and before recordBackupOutcomeBestEffort at line 39.

Valid control: initialized each isolated profile database with the existing state owner, then ran backup record --status ok --target label --bytes 10 --json. Both exit successfully, emit identical JSON, and record exactly one external outcome with status ok, target/archivePath label and bytes 10. Persisted rows compare identically after removing only generated ID and creation time. An initial fixture setup targeted the default profile instead of p199573 and therefore recorded nothing; the corrected profile-specific fixture produced the results above. No Gateway or live state was involved.

Vitest-source: the strengthened backup-outcome regression has nine malformed-input cases, including all original nondecimal byte forms and the status/target guards. On base these nine fail on the Error-vs-ExpectedCliError contract while six existing controls pass; candidate's full file passes all fifteen. Every malformed-input case verifies that no outcome was recorded in its initialized database. The consolidation removes repeated assertions and the incidental runtime.error spy assertion rather than adding a separate suite.

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Final head: 45b8928. Production +4/-3, tests +7/-7 (net zero), no allocation file. The contributor commit remains intact; only the existing regression was consolidated. No production message changed. Simplification keeps the existing expected-error owner, with no new catches or state machinery.

Final local checks: backup-outcome.test.ts 15/15 passes (108.63s total wrapper wall time on this loaded host); targeted formatting passes. Full tier on the host: ocx build --dts passes; the supported self-contained package builder and tarball-integrity check pass through ocx. The extracted packed CLI reports OpenClaw 2026.11.3 (45b8928). Its invalid-status JSON command exits 1, preserves the source JSON stdout byte-for-byte, and prints --status must be ok or failed. on stderr. Bundled workspace dependencies came from the tarball; external dependencies were linked from the ocx-installed checkout. Host isolation check remains only the two src/commands files.

Credit retained: SunnyShu [email protected], human author/committer of the production fix. The test-only maintenance commit uses Ayaan Zaidi [email protected]; no agent trailers. Worktrunk and Git hooks were skipped; the normal ocx install lifecycle ran. after-push.sh requested a fresh exact-head review. Source and persistence receipts: #199573 (comment) .

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. labels Nov 15, 2026
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Repaired our regression-table typing on final head 0c7e070: the outer table and mapped rows now retain their tuple types. Production is unchanged; tests remain +7/-7, net zero. The prior check-test-types-core-4 failure was caused by our test consolidation, not inherited.

Verified through ocx on the host: node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.commands.json --incremental succeeds; formatting succeeds; backup-outcome.test.ts passes all 15 tests. ocx build --dts succeeds on this exact head. Supported self-contained packaging with --skip-build reuses that verified build; tarball integrity and extracted packed-CLI smoke pass, with unchanged JSON and the expected invalid-status stderr message. Host load was 82.9 during diagnosis; tarball checking required its supported timeout override after the default five-minute cap expired during extraction. No assertion or product timeout was changed.

Both pushes were normal fast-forwards after checking the current contributor ref was an ancestor. after-push.sh requested a new exact-head review. The same two-file host-isolation check passes; no production, dependency, lifecycle or message-text changes were added by the repairs. Prior source and persistence proof remains applicable because all later changes are test-only: #199573 (comment) .

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 15, 2026
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Final head 0c7e070 is ready: exact-head ClawSweeper review is 5/6 and ready (#199573 (comment)); CI and ci-gate are green (https://github.com/openclaw/openclaw/actions/runs/43725968078 and https://github.com/openclaw/openclaw/actions/runs/43728484007). No failed or cancelled checks remain. Proof and the resolved test-type regression are recorded above. No merge performed.

@obviyus
obviyus merged commit 3e1c0cd into openclaw:main Nov 15, 2026
113 checks passed
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Landed in 3e1c0cd. Thanks @SunnyShu0925.

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

fix(cli): report backup record input errors through the expected-error path

`openclaw backup record --json` threw plain errors for a bad `--status`, a blank `--target` and a bad `--bytes`, so `--json` stderr showed the generic failure plus the Doctor hint instead of the existing message. The three checks now use throwExpectedCliError with the same messages. All three run before anything is recorded; no new text.

Evidence: host, isolated state. Source CLI: each bad value with `--json` and in text mode, on base and on this change: base prints the generic failure and Doctor hint, this change prints the existing message; text mode, JSON stdout and exit codes are identical, and a valid `--status ok --target label --bytes 10 --json` records exactly one matching outcome on both. Vitest-source: base 9 failures, 15 pass here. Targeted typecheck, full build and packed smoke pass. Receipts: openclaw#199573 (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: XS 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