Skip to content

fix(cli): return JSON errors when devices commands refuse - #167294

Merged
obviyus merged 2 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-devices-json-errors-20261008
Oct 9, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-devices-json-errors-20261008

Conversation

@Leon-SK668

@Leon-SK668 Leon-SK668 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Closes #159488, reported by Masato Hoshino.

Devices commands can refuse with a nonzero exit but empty stdout in JSON mode, so scripts cannot read the reason. For example, openclaw devices clear --json should return the documented CLI error document when --yes is absent.

User Impact

Local refusals produce one {"ok":false,"error":{"type":"cli_error","message":"..."}} document on stdout and still exit nonzero. This covers explicit JSON commands and token commands whose existing default output is JSON. Recovery guidance remains sanitized; ordinary text errors, successful payloads, implicit-approval previews, and the existing list transport-error payload retain their behavior.

No new configuration, default, protocol, schema, storage, dependency, permission, or token-management policy. Confirmation, scope ceilings, authorization, and local-fallback decisions are unchanged.

Why This Change Was Made

Devices owns these local refusals; its direct stderr/exit calls bypass the root JSON renderer. A private helper sends JSON refusals to that existing renderer and retains the text path. Multi-line node-reapproval guidance is collected before propagation so it remains in the error message. Token validation follows the existing always-JSON command classification even without --json.

Existing-solutions preflight: the shared root failure renderer already supplies the required format. Reuse it; no new formatter, plugin, library, or service is needed. Masato Hoshino's earlier proposal #159489 is closed and unmerged; both the report and prior proposal are credited. The gap remains on current main. Active #167137 addresses the adjacent post-confirmation atomic-clear operation; its unchanged no-confirmation guard does not repair this output defect. The shared file could require conflict resolution if that work lands first.

Two files: production +24/-19 (net +5), tests +83/-18 (net +65). The small production growth consolidates the refusal producers without duplicating the JSON envelope or changing the RPC owner. No generated files, lockfiles, or proof assets.

Evidence

Baseline 7b41658157cf26d673d3cae847f857253b6d65ae; candidate f145baa8881a7fc99673af90e5d77cb4b608bf23, tree b0daff204d6e0e4d994c08449158cc1f2e4a1437. Linux, Node 24.16.0, compiled source version 2026.9.9. The whole relevant owner, callers/callees, root renderer, tests, docs, and contribution contracts remain unchanged on inspected current main ea7cc1066568fbbeece9151c497ecab15923bd2a.

The external harness launches the real built public node openclaw.mjs devices ... subprocess through registered Commander actions, the devices owner, and root failure renderer. Remote-result cases use the native Gateway client with an independent loopback WebSocket protocol fixture, with receiver-side request readback. This is CLI/client output proof, not production Gateway authorization or dispatch proof. Native network traces, child outputs/exits, configuration bytes, and persistent artifact readback are recorded independently.

Acceptance RED: 12 targeted JSON refusals exit1 with empty stdout; seven controls pass. The only target failure is the missing CLI output document. The same immutable harness is used on both checkouts: node devices-json-proof-20261008.mjs <built-checkout> <exact-head-sha> <run-label>, SHA-256 53f1c5988e588388cd059af5fee0cb9bc186105b74abbdad5bd02c6b8e93c28b. Baseline receipt SHA-256 2979e6812e34b685f316eaee748d1c5cdde8920741aa9328c83caec0bad1ba07, measured 67.09s.

Candidate GREEN: all 19 scenarios pass on the clean exact candidate and its matching compiled build, measured 55.85s. Each of the 12 repaired refusals emits one canonical JSON error document and exits1; all seven controls retain their contracts. Receiver-side method/parameter readback, raw output/network hashes, current fixture file bytes, continued database absence, source/tree and build metadata independently rechecked after the run. Candidate receipt SHA-256 44a53d38a001c9e3f149d0d61b467654e094325d581dbf2023343831d225d169.

Scenarios Baseline Candidate
Missing confirmation; blank remove/reject/rename arguments Empty JSON stdout, exit1 Canonical error document, exit1
Blank rotate/revoke targets, explicit and default JSON Empty JSON stdout, exit1 Canonical error document, exit1
Empty pending list, self-scope-upgrade refusal, unmatched request with node guidance Empty JSON stdout, exit1 Canonical error document with recovery guidance, exit1
Three ordinary text errors Existing stderr and exit1 Unchanged
Successful JSON list, implicit approval preview, list transport error, existing join-code error Existing command-specific behavior Unchanged

Redacted proof results are recorded here; raw artifacts and the external harness remain outside the product branch. Baseline compiled digests are archived in its immutable receipt; candidate compiled files were independently rehashed against the final receipt.

Validation:

  • node scripts/run-vitest.mjs src/cli/devices-cli.test.ts src/cli/devices-cli.lazy.test.ts src/cli/devices-cli.gateway.test.ts --maxWorkers=1 — 58/58 passed across three files, 111.77s. After replacing an intentional control-character regex with literal assertions, the final affected owner file reran: node scripts/run-vitest.mjs src/cli/devices-cli.test.ts --maxWorkers=1 — 50/50 passed, 8.21s. Production and Gateway/lazy sibling tests were unchanged by that assertion edit.
  • node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/cli/devices-cli.runtime.ts src/cli/devices-cli.test.ts — final scoped type-aware lint passed, 19.62s.
  • Scoped oxfmt --check and git diff --check — passed.
  • OPENCLAW_BUILD_PRIVATE_QA=1 node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime — owned exact-head source-runtime build passed, 146.85s; build-info commit matches the candidate and both native stamps record clean inputs. This is not installed-package qualification.

Not tested: successful pairing or token mutations, production Gateway authentication/authorization and dispatch, actual existing SQLite state or transaction rollback, provider/model calls, real channels, installed-package upgrades, other operating systems, and broad CI. No SQLite database existed or was created in the paired proof cases; configuration and non-SQLite persistent artifact bytes remained unchanged. Nine targeted pre-RPC refusals made zero INET/INET6 connection/send attempts; wire cases were restricted to the independently recorded loopback fixture. No real account or production credential was used.

Maintainer verification

Baseline main 5c81678cb280e6aa871522b08dceef5e706af03e reproduces devices clear --json: exit 1, empty stdout. Candidate 0f8198018b112b264bccde39fda056fc67ff1281 returns the documented JSON envelope with exit 1. An independent built Gateway reaches ready on isolated Linux/Node 26 state. Real CLI checks cover clear, blank remove/reject/rename/rotate/revoke targets and an empty approval queue. All return machine-readable refusals. Plain clear refusal is unchanged; devices list is byte-identical to baseline; confirmed clear succeeds.

The maintainer correction uses the existing ExpectedCliError so JSON refusals keep their original stderr guidance instead of replacing it with generic crash/doctor diagnostics. The regression assertions preserve both human and machine messages. pnpm build:docker, real pnpm tsgo, 50 focused devices tests (1.69s wrapper), and scoped formatting pass. Existing CLI documentation already defines this envelope. No overlap with Pash/Sarah changes. Credit remains with Leon-SK668 and the reporter of #159488.

Merge danger: two-way door; revert restores the prior output without migrating state. Blast radius is device-command refusal output consumed by CLI automation.

@clawsweeper

clawsweeper Bot commented Oct 8, 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 size: S labels Oct 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Device-command refusals return the standard JSON error document while preserving human-readable guidance and nonzero exits.

Example: Run openclaw devices clear --json without --yes

  • Before: The command exits 1 with empty stdout and prints the refusal on stderr.
  • After: The command exits 1 and returns {"ok":false,"error":{"type":"cli_error","message":"Refusing to clear pairing table without --yes"}} on stdout while retaining stderr guidance.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct repair with sufficient CLI proof and no remaining review findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded Linux CLI runs exercise the devices refusal owner through the built public entry point and shared renderer, showing JSON error documents with exit 1 and preserved text controls. Latest verification explicitly covers the reviewed head and an isolated real Gateway; earlier native-client loopback traces cover remote refusal guidance. No stored-data contract changes require migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Scripts receive no JSON explanation when a device command refuses, despite requesting machine-readable output.
Reason: The change restores an explicit CLI contract with a small repair at the refusal producers and preserves existing safety checks.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main still violates the documented JSON failure contract. The focused repair is correct, with sufficient CLI proof and no actionable findings.

Priority: P2
Reviewed head: 0f8198018b112b264bccde39fda056fc67ff1281

Before merge

None.

Findings

None.

Provenance

  • src/cli/devices-cli.runtime.ts: confirmation, blank-argument, and empty-pending refusals: original intent not found (unknown: Host history identifies the lazy-runtime relocation, but the scoped string-history search across current and earlier filenames failed on an unavailable promisor object; original introduction could not be established.)
Agent review details

How this fits together

The devices CLI manages pairing requests and device tokens through the Gateway. Its local refusal checks supply messages to the shared CLI failure renderer, which produces output for operators and scripts.

flowchart LR
 A[Device command and options] --> B[Device CLI]
 B --> C{Local refusal?}
 C -->|JSON mode| D[Shared CLI failure renderer]
 D --> E[JSON error and stderr guidance]
 C -->|Text mode| F[Stderr refusal]
 C -->|No| G[Existing Gateway operation]
 E --> H[Nonzero exit]
 F --> H
Loading

Technical review

Best possible solution:

Keep device refusal checks in their existing owner and use the shared failure renderer for the documented machine-readable output.

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

Yes. Current-main source shows the stderr-only clear refusal, and recorded baseline CLI runs demonstrate empty stdout with exit 1; this read-only review did not run the CLI.

Is this the best way to solve the issue?

Yes. Reusing ExpectedCliError repairs the refusal producers through the existing output owner and preserves recovery guidance without changing authorization or successful payloads.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • src/cli/devices-cli.runtime.ts: resolveRequiredDeviceRole keeps the original intent (ac44190: Deduplicate device and role validation for token operations, retaining rejection before token RPCs.)
  • src/cli/devices-cli.runtime.ts: approval recovery messages keeps the original intent (fix(cli): explain how to recover from device approve deadlock #98146: Explain remote self-upgrade refusal and missing requests with actionable guidance without weakening approval checks.)
  • src/cli/devices-cli.runtime.ts: pending node approval guidance keeps the original intent (fix: surface node approval guidance from devices CLI #98115: Direct wrong-layer device approval attempts to node approval while preserving approval semantics and omitting connection secrets.)
  • src/cli/devices-cli.test.ts: existing refusal assertions keeps the original intent (test(core,plugins): remove low-value tests (batch d125) #162544: Consolidate low-value tests while retaining meaningful authentication, routing, and lifecycle regressions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Dallin Romney: Raw commit 9003042 adds src/cli/devices-cli.runtime.ts:1117 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9003042c5fa0; files: src/cli/devices-cli.runtime.ts)

PR surface

Source +7, Tests +71. Total +78 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 26 19 +7
Tests 1 89 18 +71
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 115 37 +78

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #159488
Summary: This PR is the candidate repair for the documented device JSON refusal defect.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Missing refusal documents break device-command scripting, with limited impact because failures already exit nonzero.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-08T15:20:05.758Z sha f145baa :: needs maintainer review before merge. :: none

Reviewed October 8, 2026, 11:14 PM ET / October 9, 2026, 03:14 UTC (Revision 2).

@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

Maintainer override: the only red jobs are inherited and outside this diff.

@obviyus
obviyus merged commit 15305cc into openclaw:main Oct 9, 2026
102 of 107 checks passed
@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

Landed in 15305cc. Thanks @Leon-SK668! Verified with the real CLI against a built Gateway: devices refusals in --json mode now print the error envelope with the original message, and list/clear success output is unchanged.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…67294)

Print the documented JSON error envelope on stdout when an `openclaw devices` command is refused in --json mode (for example `devices clear --json`), instead of leaving stdout empty. The original stderr refusal and exit code are kept.

Fixes openclaw#159488.

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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

devices commands with --json print nothing on stdout when they refuse

2 participants