Skip to content

fix(cli): surface migrate blank agent remedy in JSON - #199448

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/migrate-context-agent-blank-json-remedy-421
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/migrate-context-agent-blank-json-remedy-421

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw migrate plan hermes --agent " " --json prints the correct --agent must not be blank message inside its JSON envelope, but its stderr collapses to the generic [openclaw] The CLI command failed. plus a doctor hint, so anyone reading stderr (or any wrapper that surfaces stderr only) loses the actionable remedy. openclaw migrate apply ... --json behaves the same way. The guard now throws through the existing expected-CLI-error path, so JSON failures keep the concrete message.

  • Problem: resolveMigrationTargetAgentId() threw a plain Error for an explicitly blank --agent. In JSON mode the runtime treats an unrecognized error as an unexpected failure and replaces the stderr hint with the generic failure line, even though the user-facing message already existed.
  • Solution: throw the existing text through throwExpectedCliError, the canonical expected-CLI-error owner already used by the sandbox explain and sessions compact blank-agent guards.
  • What changed: src/commands/migrate/context.ts imports throwExpectedCliError and converts the single blank-value guard; src/commands/migrate/context.test.ts folds the error-name assertion into the existing migration-target test and drops the now-redundant standalone case.
  • What did NOT change: text-mode output, JSON stdout envelopes, exit codes, invalid-agent and unknown-agent errors, and the configured-default fallback.

Why This Change Was Made

resolveMigrationTargetAgentId() is the single owner shared by migrate plan and migrate apply, so one conversion covers both entry points without duplicating a guard per subcommand.

  • Best fix: convert the existing guard in the shared owner. The message was already correct; only the error type was wrong, so the change introduces no new user-facing text and keeps a single source of truth for migration target validation.
  • Alternative(s): adding a per-command guard in register.migrate.ts would duplicate ownership in two call sites; changing the global JSON failure formatter would alter behavior for unrelated commands. Both were rejected.
  • Risk: the conversion only affects the explicitly blank --agent path. Invalid ids such as research/../main and unknown ids such as missing keep their existing plain Error path, which the control case below verifies. Full-repository type checking was left to CI.

User Impact

A JSON consumer that reads stderr now receives --agent must not be blank instead of a generic failure line, matching the message that was already available on stdout. Text mode, stdout bytes and exit codes are unchanged, so existing scripts that parse either stream keep working.

Evidence

Both arms are real built CLIs: the frozen origin/main base and the candidate were each built with build-all.mts cliStartup, and every cell below is a full node openclaw.mjs ... invocation under a minimal environment (only PATH, HOME, XDG_RUNTIME_DIR, state dir and config), with 0700 scratch directories, an empty config, no credentials and no mocks. --version self-reports each arm.

Case Before (pre-fix, base c8caba2) After (post-fix, this head 1ee8a90)
migrate plan hermes --agent " " --json stderr generic The CLI command failed. plus doctor hint --agent must not be blank
migrate apply hermes --yes --agent " " --json stderr generic The CLI command failed. plus doctor hint --agent must not be blank
migrate plan hermes --agent " " --json stdout 104-byte cli_error envelope carrying the blank-agent message identical 104 bytes
text mode migrate plan hermes --agent " " blank-agent message on stderr, exit 1 identical bytes, exit 1
unknown agent control --agent missing --json unknown-agent envelope and generic stderr, exit 1 identical bytes, exit 1

Arm identity:

# frozen base
$ node openclaw.mjs --version
OpenClaw 2026.11.3 (c8caba2)

# candidate
$ node openclaw.mjs --version
OpenClaw 2026.11.3 (1ee8a90)

Bug case on the launched CLI:

$ node openclaw.mjs migrate plan hermes --agent " " --json

# stdout, byte-identical on both arms
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "--agent must not be blank"
  }
}

# stderr on frozen base
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.

# stderr on candidate
--agent must not be blank
$ node openclaw.mjs migrate apply hermes --yes --agent " " --json

# stdout, byte-identical on both arms
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "--agent must not be blank"
  }
}

# stderr on frozen base
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.

# stderr on candidate
--agent must not be blank

Control case, unknown agent:

$ node openclaw.mjs migrate plan hermes --agent missing --json

# stdout and stderr byte-identical on both arms, exit 1
{
  "ok": false,
  "error": {
    "type": "cli_error",
    "message": "Unknown agent id \"missing\". Run openclaw agents list to see configured agents."
  }
}

Full matrix as emitted by the comparison harness (cmp per stream, 1 = byte-identical):

plan-text       exit=1/1   stdout_cmp=1   stderr_cmp=1
plan-json       exit=1/1   stdout_cmp=1   stderr_cmp=0
apply-text      exit=1/1   stdout_cmp=1   stderr_cmp=1
apply-json      exit=1/1   stdout_cmp=1   stderr_cmp=0
unknown-json    exit=1/1   stdout_cmp=1   stderr_cmp=1

Built bundle, proving which form actually shipped:

# frozen base dist/context-*.mjs
throw new Error(`--agent must not be blank`)

# candidate dist/context-*.mjs
throwExpectedCliError(`--agent must not be blank`)

Regression test, same assertion on both arms:

# candidate
$ npx vitest run src/commands/migrate/context.test.ts
Test Files  1 passed (1)
     Tests  4 passed (4)

# frozen base with the same assertion
Test Files  1 failed (1)
     Tests  1 failed | 3 passed (4)

What was not tested

  • Full-repository type checking was not run locally; targeted oxlint (0 warnings, 0 errors), oxfmt and the focused suite passed, so type checking is left to CI.
  • No migration was allowed to run past argument validation, so no real import path was exercised in this proof.
  • Both arms emit the same Node security-patch warning and the same log-append warning in the isolated scratch HOME; they are identical across arms and unrelated to this change.

Open PR collision check

Searched the changed-file lists of the latest 300 open PRs plus title and body searches for migrate, blank agent and expected-cli-error: no open PR touches src/commands/migrate/context.ts or src/commands/migrate/context.test.ts. The same-day merged #199386 converts the equivalent guard in sessions compact only, leaving the migrate owner untouched, so this is not a duplicate.

Ref: BUG-421-migrate-context-agent-blank-json-remedy-hidden (local finding)
@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.

@SunnyShu0925
SunnyShu0925 marked this pull request as ready for review November 15, 2026 04:37
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: XS labels Nov 15, 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: 🦞 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: blocked before merge.

What this changes

The PR preserves the blank-agent validation message on stderr when migration commands use JSON output.

Example: Run openclaw migrate plan hermes --agent " " --json.

  • Before: Stderr reports a generic CLI failure and Doctor hint.
  • After: Stderr reports --agent must not be blank; JSON stdout and exit status remain unchanged.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal, source-supported diagnostic repair with supplied shipped-entry-point proof and no open findings; required CI awaits workflow approval.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR supplies built-CLI terminal output at the pinned candidate showing blank-agent plan and apply JSON failures now print the remedy on stderr, with unchanged stdout, exit status, text-mode behavior, and unknown-agent controls.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Wrappers displaying only stderr lose the existing blank-agent remedy when migration commands use JSON output.
Reason: The patch restores actionable validation output through an established mechanism without changing accepted input, defaults, or migration behavior.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR: it fixes a current diagnostic bug with a minimal change, supplied CLI proof, and no identified correctness defects.

Priority: P3
Reviewed head: 1ee8a9073a14fc8bf9be8431865c4195e9fd9ef3

Before merge

  • Await maintainer action - Approve the required GitHub Actions workflows for this head so CI can run.

Findings

None.

Agent review details

How this fits together

Migration plan and apply commands build a shared migration context, whose argument errors reach the root CLI renderer for JSON stdout and human-readable stderr.

flowchart TD
  A[Migration CLI arguments] --> B[Plan or apply command]
  B --> C[Shared migration context]
  C --> D[Expected CLI error]
  D --> E[Root failure renderer]
  E --> F[JSON stdout and actionable stderr]
Loading

Technical review

Best possible solution:

Retain this focused conversion in the shared migration context and land it after the required CI workflows pass.

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

Current-main source shows the plain Error reaching generic failure rendering, and the contributor supplies before/after built CLI traces for both affected commands; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete fix: preserve blank-agent rejection while using the existing error-classification owner shared by CLI diagnostics.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Explicit blank migration target rejection keeps the original intent (46dcc57: Reject explicitly blank selectors so an empty shell variable cannot silently select the default agent.)
  • Migration target regression coverage keeps the original intent (46dcc57: Protect explicit blank-agent rejection alongside configured-agent validation; the patch retains that assertion and adds the expected-error classification contract.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 46dcc57 adds src/commands/migrate/context.ts:43 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 46dcc57c5498; files: src/commands/migrate/context.ts)
  • Jacob Tomlinson: Raw commit 20ac22f adds src/commands/migrate/context.ts:43 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 20ac22f647a4; files: src/commands/migrate/context.ts)

PR surface

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

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 3 4 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 5 5 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This improves stderr diagnostics for an invalid argument in an advanced CLI workflow; JSON stdout already contains the remedy.
  • 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 14, 2026, 11:54 PM ET / November 15, 2026, 04:54 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: 🦞 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