Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(claude_cli): parse the verbose event array from claude -p (#3170)

inchang-ing9e877e452f90
diff --git a/packages/core/src/repowise/core/providers/llm/claude_cli.py b/packages/core/src/repowise/core/providers/llm/claude_cli.py
index f98a61bad..56dbb59d2 100644
--- a/packages/core/src/repowise/core/providers/llm/claude_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/claude_cli.py
@@ -97,11 +97,21 @@ def _payload_failure(payload: dict[str, Any]) -> tuple[str, int | None]:
return f"claude -p reported failure ({detail}).", status_code
+def _last_result_event(events: list[Any]) -> dict[str, Any] | None:
+ """Return the final ``"type": "result"`` object from a verbose event array."""
+ for event in reversed(events):
+ if isinstance(event, dict) and event.get("type") == "result":
+ return event
+ return None
+
+
def _parse_result(stdout: str) -> dict[str, Any]:
"""Parse ``--output-format json`` output, tolerating leading noise.
- The CLI emits a single JSON object, but warnings can precede it on stdout,
- so fall back to a line scan before giving up.
+ The CLI emits a single JSON object, but with ``--verbose`` it instead
+ emits an array of stream events (``system``/``assistant``/``result``...);
+ warnings can also precede either shape on stdout, so fall back to a line
+ scan before giving up.
"""
text = stdout.strip()
if not text:
@@ -111,6 +121,10 @@ def _parse_result(stdout: str) -> dict[str, Any]:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
+ if isinstance(parsed, list):
+ result = _last_result_event(parsed)
+ if result is not None:
+ return result
for raw_line in reversed(text.splitlines()):
line = raw_line.strip()
diff --git a/tests/unit/test_providers/test_claude_cli_provider.py b/tests/unit/test_providers/test_claude_cli_provider.py
index 43bf1b38a..52b2ffdf2 100644
--- a/tests/unit/test_providers/test_claude_cli_provider.py
+++ b/tests/unit/test_providers/test_claude_cli_provider.py
@@ -393,6 +393,58 @@ def test_parse_result_rejects_empty_output():
_parse_result(" ")
+def test_parse_result_reads_result_event_from_verbose_array():
+ """With --verbose the CLI emits an event array, not a single object (#3161)."""
+ events = json.dumps(
+ [
+ {"type": "system", "subtype": "init", "session_id": "abc"},
+ {"type": "assistant", "message": {"content": [{"type": "text", "text": "hi"}]}},
+ {"type": "result", "subtype": "success", "is_error": False, "result": "hi"},
+ ]
+ )
+ assert _parse_result(events)["result"] == "hi"
+
+
+def test_parse_result_rejects_array_without_result_event():
+ """An event array with no result event must keep the existing failure."""
+ events = json.dumps(
+ [
+ {"type": "system", "subtype": "init"},
+ {"type": "assistant", "message": {"content": [{"type": "text", "text": "hi"}]}},
+ ]
+ )
+ with pytest.raises(ProviderError, match="could not parse"):
+ _parse_result(events)
+
+
+async def test_verbose_array_nonzero_exit_surfaces_error_and_http_status(claude_on_path, monkeypatch):
+ """A verbose run still reports the API failure carried by its result event."""
+
+ async def fake_exec(*_args, **_kwargs):
+ return FakeProcess(
+ returncode=1,
+ stdout=json.dumps(
+ [
+ {"type": "system", "subtype": "init"},
+ {
+ "type": "result",
+ "subtype": "error_during_execution",
+ "is_error": True,
+ "api_error_status": 404,
+ "result": "There's an issue with the selected model.",
+ },
+ ]
+ ),
+ )
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="selected model") as caught:
+ await ClaudeCliProvider().generate("sys", "user")
+
+ assert caught.value.status_code == 404
+
+
async def test_missing_usage_is_flagged_estimated(claude_on_path, monkeypatch):
async def fake_exec(*_args, **_kwargs):
return FakeProcess(stdout=json.dumps({"subtype": "success", "result": "hi"}) + "\n")