YeonGyu-Kim 8247d7d2eb fix: #179 — JSON mode now fully suppresses argparse stderr + preserves real error message
Dogfood discovered #178 had two residual gaps:

1. Stderr pollution: argparse usage + error text still leaked to stderr even in
   JSON mode (envelope was correct on stdout, but stderr noise broke the
   'machine-first protocol' contract — claws capturing both streams got dual output)

2. Generic error message: envelope carried 'invalid command or argument (argparse
   rejection)' instead of argparse's actual text like 'the following arguments
   are required: session_id' or 'invalid choice: typo (choose from ...)'

Before #179:
  $ claw load-session --output-format json
  [stdout] {"error": {"message": "invalid command or argument (argparse rejection)"}}
  [stderr] usage: main.py load-session [-h] ...
           main.py load-session: error: the following arguments are required: session_id
  [exit 1]

After #179:
  $ claw load-session --output-format json
  [stdout] {"error": {"message": "the following arguments are required: session_id"}}
  [stderr] (empty)
  [exit 1]

Implementation:
- New _ArgparseError exception class captures argparse's real message
- main() monkey-patches parser.error (+ all subparser.error) in JSON mode to raise
  _ArgparseError instead of print-to-stderr + sys.exit(2)
- _emit_parse_error_envelope() now receives the real message verbatim
- Text mode path unchanged: still uses original argparse print+exit behavior

Contract:
- JSON mode: stdout carries envelope with argparse's actual error; stderr silent
- Text mode: unchanged — argparse usage to stderr, exit 2
- Parse errors still error.kind='parse', retryable=false

Test additions (5 new, 14 total in test_parse_error_envelope.py):
- TestParseErrorStderrHygiene (5):
  - test_json_mode_stderr_is_silent_on_unknown_command
  - test_json_mode_stderr_is_silent_on_missing_arg
  - test_json_mode_envelope_carries_real_argparse_message
  - test_json_mode_envelope_carries_invalid_choice_details (verifies valid-choices list)
  - test_text_mode_stderr_preserved_on_unknown_command (backward compat)

Operational impact:
Claws capturing both stdout and stderr no longer get garbled output. The envelope
message now carries discoverability info (valid command list, missing-arg name)
that claws can use for retry/recovery without probing the CLI a second time.

Test results: 201 → 206 passing, 3 skipped unchanged, zero regression.

Pinpoint discovered via dogfood at 2026-04-22 20:30 KST (cycle #20).
2026-04-22 20:32:28 +09:00
..