The agent that turns websites into APIs!
fix(cli): address review feedback on agent --json contract
Kalil Bouziguesc91d1fad76fe
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex 0038ba3..4850246 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -97,16 +97,21 @@ def _build_agent_payload(*,prompt: str | None,url: str | None,+ output_dir: str | None = None,error: str | None = None,) -> dict:- """Normalize an agent capture result into a stable JSON shape."""+ """Normalize an agent capture result into a stable JSON shape.++ `output_dir` must match the value passed to the underlying capture so the+ HAR path is resolved against the user's chosen run root, not the default.+ """result = result or {}run_id = result.get("run_id")inner_error = result.get("error")final_error = error or inner_error or (None if run_id else "agent capture produced no run")har_path = Noneif run_id:- candidate = get_har_dir(run_id, None) / "recording.har"+ candidate = get_har_dir(run_id, output_dir) / "recording.har"har_path = str(candidate) if candidate.exists() else Nonereturn {"schema_version": AGENT_JSON_SCHEMA_VERSION,@@ -1368,11 +1373,14 @@ def agent(prompt, url, reverse_engineer, model, output_dir, no_interactive, as_jif no_interactive and not (prompt and prompt.strip()):if as_json:- click.echo(json.dumps({- "schema_version": AGENT_JSON_SCHEMA_VERSION,- "status": "error",- "error": "--prompt is required in non-interactive/--json mode",- }))+ misuse = _build_agent_payload(+ {},+ prompt=prompt,+ url=url,+ output_dir=output_dir,+ error="--prompt is required in non-interactive/--json mode",+ )+ click.echo(json.dumps(misuse))else:click.echo("error: --prompt is required when --no-interactive is set", err=True)sys.exit(2)@@ -1391,11 +1399,15 @@ def agent(prompt, url, reverse_engineer, model, output_dir, no_interactive, as_jmodel=model,output_dir=output_dir,)- payload = _build_agent_payload(result, prompt=prompt, url=url)+ payload = _build_agent_payload(result, prompt=prompt, url=url, output_dir=output_dir)except KeyboardInterrupt:- payload = _build_agent_payload({}, prompt=prompt, url=url, error="interrupted")+ payload = _build_agent_payload(+ {}, prompt=prompt, url=url, output_dir=output_dir, error="interrupted"+ )except Exception as e:- payload = _build_agent_payload({}, prompt=prompt, url=url, error=str(e))+ payload = _build_agent_payload(+ {}, prompt=prompt, url=url, output_dir=output_dir, error=str(e)+ )real_stdout.write(json.dumps(payload) + "\n")real_stdout.flush()@@ -1757,10 +1769,12 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_p# Start sync before analysisengineer.start_sync()+ interrupted = Falsetry:result = asyncio.run(engineer.analyze_and_generate())except KeyboardInterrupt:result = None+ interrupted = Truefinally:# Always stop sync when doneengineer.stop_sync()@@ -1778,6 +1792,7 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_p"mode": mode_label,"script_path": (result or {}).get("script_path"),"usage": (result or {}).get("usage", {}),+ **({"error": "interrupted"} if interrupted else {}),}except Exception as e:diff --git a/tests/test_cli_agent_json.py b/tests/test_cli_agent_json.pyindex 72672d0..f15d27d 100644--- a/tests/test_cli_agent_json.py+++ b/tests/test_cli_agent_json.py@@ -17,6 +17,20 @@ from reverse_api.cli import (from reverse_api.session import SessionManager+EXPECTED_PAYLOAD_KEYS = {+ "schema_version",+ "status",+ "run_id",+ "prompt",+ "url",+ "mode",+ "har_path",+ "script_path",+ "usage",+ "error",+}++class TestBuildAgentPayload:"""Stable shape for the `agent --json` payload."""@@ -68,6 +82,28 @@ class TestBuildAgentPayload:assert payload["status"] == "error"assert payload["error"] == "inner"+ def test_har_path_resolves_against_provided_output_dir(self, tmp_path):+ """har_path must use the user's --output-dir, not the default config root.++ Regression for cubic-dev-ai PR #61 review (P2).+ """+ run_id = "deadbeef0001"+ run_har_dir = tmp_path / "har" / run_id+ run_har_dir.mkdir(parents=True)+ (run_har_dir / "recording.har").write_text("{}")++ with patch("reverse_api.cli.get_har_dir") as gethar:+ gethar.side_effect = lambda rid, odir: tmp_path / "har" / rid+ payload = _build_agent_payload(+ {"run_id": run_id, "mode": "auto"},+ prompt="x",+ url=None,+ output_dir=str(tmp_path),+ )++ gethar.assert_called_with(run_id, str(tmp_path))+ assert payload["har_path"] == str(run_har_dir / "recording.har")+class TestAgentCommandJson:"""`agent` click command's --json / --no-interactive behavior."""@@ -80,6 +116,16 @@ class TestAgentCommandJson:assert payload["status"] == "error"assert "prompt" in payload["error"].lower()+ def test_json_without_prompt_emits_full_schema(self):+ """Misuse JSON must contain every documented field (nulled), not a 3-key shortcut.++ Regression for cubic-dev-ai PR #61 review (P2).+ """+ runner = CliRunner()+ result = runner.invoke(agent, ["--json"])+ payload = json.loads(result.stdout.strip())+ assert set(payload.keys()) == EXPECTED_PAYLOAD_KEYS+def test_no_interactive_without_prompt_exits_2(self):runner = CliRunner()result = runner.invoke(agent, ["--no-interactive"])@@ -280,6 +326,29 @@ class TestAgentJsonInterruption:assert payload["status"] == "error"assert payload["error"] == "interrupted"+ def test_inner_keyboard_interrupt_does_not_silently_succeed(self):+ """When run_agent_capture returns a dict with `error: "interrupted"` (the+ scenario where KeyboardInterrupt is caught inside run_auto_capture rather+ than propagating up), the agent payload must report status=error.++ Regression for cubic-dev-ai PR #61 review (P1).+ """+ runner = CliRunner()+ captured = {+ "run_id": "abc12345",+ "mode": "auto",+ "script_path": None,+ "usage": {},+ "error": "interrupted",+ }+ with patch("reverse_api.cli.run_agent_capture", return_value=captured):+ result = runner.invoke(agent, ["--json", "-p", "x"])+ assert result.exit_code == 1+ payload = json.loads(result.stdout.strip().splitlines()[-1])+ assert payload["status"] == "error"+ assert payload["error"] == "interrupted"+ assert payload["run_id"] == "abc12345"+class TestAgentJsonStdoutPurity:"""Stdout should contain exactly one JSON line; Rich noise must go to stderr."""