Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(learn): include stdout in CLI failure messages, not just stderr (#3080)

gglucassc5563d3a7dd8
diff --git a/headroom/learn/analyzer.py b/headroom/learn/analyzer.py
index b939f7cf7..670b5c2b6 100644
--- a/headroom/learn/analyzer.py
+++ b/headroom/learn/analyzer.py
@@ -539,6 +539,40 @@ def _strip_fenced_json(raw: str) -> dict:
return result
+def _failure_detail(
+ stderr: str | None, stdout: str | None, *, result_text: str | None = None
+) -> str:
+ """Build the operator-facing reason for a non-zero CLI exit.
+
+ stderr alone is not enough. `claude -p --output-format stream-json` writes
+ *nothing* to stderr and reports API failures only in its final ``result``
+ event on stdout, so a stderr-only message renders as a bare
+ ``failed (exit 1):`` with no reason at all -- the user (and we) cannot tell a
+ usage limit from an unreachable proxy from an expired login.
+
+ Both streams are included when both have content, and stdout is tailed rather
+ than headed because CLI backends emit the error last (a streaming backend's
+ whole event log precedes it).
+
+ Args:
+ stderr: Captured stderr, if any.
+ stdout: Captured stdout, if any.
+ result_text: Pre-extracted reason (claude-cli's final ``result`` field),
+ used in place of the raw stdout tail when available.
+
+ Returns:
+ A non-empty snippet, or ``"(no output captured)"`` when both streams were
+ empty, so the message is never a dangling colon.
+ """
+ parts: list[str] = []
+ if stderr and stderr.strip():
+ parts.append(stderr.strip()[:_MAX_SNIPPET_LEN])
+ tail = result_text if result_text and result_text.strip() else stdout
+ if tail and tail.strip():
+ parts.append(tail.strip()[-_MAX_SNIPPET_LEN:])
+ return "\n".join(parts) if parts else "(no output captured)"
+
+
def _call_cli_llm(digest: str, model: str) -> dict:
"""Call a locally installed CLI tool as the LLM backend.
@@ -611,10 +645,8 @@ def _call_cli_llm(digest: str, model: str) -> dict:
) from None
if result.returncode != 0:
- stderr_snippet = (result.stderr or "")[:_MAX_SNIPPET_LEN]
- raise RuntimeError(
- f"`{' '.join(cmd)}` failed (exit {result.returncode}):\n{stderr_snippet}"
- )
+ detail = _failure_detail(result.stderr, result.stdout)
+ raise RuntimeError(f"`{' '.join(cmd)}` failed (exit {result.returncode}):\n{detail}")
# Log stderr warnings even on success (auth refreshes, deprecation notices).
if result.stderr and result.stderr.strip():
@@ -757,8 +789,14 @@ def _call_claude_cli_streaming(
proc.wait()
if proc.returncode != 0:
- stderr_blob = "".join(stderr_lines)[:_MAX_SNIPPET_LEN]
- raise RuntimeError(f"`{' '.join(cmd)}` failed (exit {proc.returncode}):\n{stderr_blob}")
+ # `final_result` is preferred over the raw stdout tail: claude emits a
+ # final `result` event even when the run fails, and its `result` field is
+ # the human-readable reason ("API Error: ...", "Not logged in", usage
+ # limits).
+ detail = _failure_detail(
+ "".join(stderr_lines), "".join(stdout_lines), result_text=final_result
+ )
+ raise RuntimeError(f"`{' '.join(cmd)}` failed (exit {proc.returncode}):\n{detail}")
stderr_blob = "".join(stderr_lines)
if stderr_blob.strip():
diff --git a/tests/test_learn/test_analyzer.py b/tests/test_learn/test_analyzer.py
index 2d711227f..e271d2226 100644
--- a/tests/test_learn/test_analyzer.py
+++ b/tests/test_learn/test_analyzer.py
@@ -796,6 +796,51 @@ class TestCallCliLlm:
with pytest.raises(RuntimeError, match="failed.*exit 1"):
_call_cli_llm("test digest", "claude-cli")
+ def test_claude_cli_nonzero_exit_includes_api_error_from_stdout(self):
+ # Regression: `claude -p --output-format stream-json` writes NOTHING to
+ # stderr on an API failure. It still emits a final `result` event whose
+ # `result` field carries the reason, so a stderr-only message rendered as
+ # a bare "failed (exit 1):" with no cause for the user or the logs.
+ api_error = "API Error: Connection refused — a firewall or proxy may be blocking it"
+ stdout = [
+ _stream_event("system", subtype="init"),
+ _stream_event(
+ "result",
+ subtype="success",
+ is_error=False,
+ terminal_reason="api_error",
+ result=api_error,
+ ),
+ ]
+ popen = _fake_claude_popen(stdout_lines=stdout, stderr_lines=[], returncode=1)
+ with patch("headroom.learn.analyzer.subprocess.Popen", popen):
+ with pytest.raises(RuntimeError) as exc_info:
+ _call_cli_llm("test digest", "claude-cli")
+ message = str(exc_info.value)
+ assert "failed (exit 1)" in message
+ assert api_error in message
+
+ def test_claude_cli_nonzero_exit_with_no_output_says_so(self):
+ popen = _fake_claude_popen(stdout_lines=[], stderr_lines=[], returncode=1)
+ with patch("headroom.learn.analyzer.subprocess.Popen", popen):
+ with pytest.raises(RuntimeError) as exc_info:
+ _call_cli_llm("test digest", "claude-cli")
+ # Never a dangling colon: the message states that nothing was captured.
+ assert "(no output captured)" in str(exc_info.value)
+
+ def test_claude_cli_nonzero_exit_keeps_stderr_when_present(self):
+ popen = _fake_claude_popen(
+ stdout_lines=[_result_event("partial")],
+ stderr_lines=["Error: auth required\n"],
+ returncode=1,
+ )
+ with patch("headroom.learn.analyzer.subprocess.Popen", popen):
+ with pytest.raises(RuntimeError) as exc_info:
+ _call_cli_llm("test digest", "claude-cli")
+ message = str(exc_info.value)
+ assert "auth required" in message
+ assert "partial" in message
+
def test_claude_cli_unparseable_result_raises_with_context(self):
stdout = [_result_event("This is not JSON at all")]
with patch(
@@ -843,6 +888,17 @@ class TestCallCliLlm:
with pytest.raises(RuntimeError, match="failed.*exit 1"):
_call_cli_llm("test digest", "codex-cli")
+ @patch("headroom.learn.analyzer.subprocess.run")
+ def test_codex_nonzero_exit_includes_stdout_when_stderr_empty(self, mock_run: MagicMock):
+ mock_run.return_value = MagicMock(
+ returncode=1,
+ stdout="stream error: rate limit exceeded",
+ stderr="",
+ )
+ with pytest.raises(RuntimeError) as exc_info:
+ _call_cli_llm("test digest", "codex-cli")
+ assert "rate limit exceeded" in str(exc_info.value)
+
@patch("headroom.learn.analyzer.subprocess.run")
def test_codex_stderr_truncated_in_error(self, mock_run: MagicMock):
long_stderr = "x" * 5000