The agent that turns websites into APIs!
Feature/gh actions ci (#123)
Wojciech Kocemba01ec87ecd0fa
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..87c8be2--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,66 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++permissions:+ contents: read++# One run per branch/PR at a time; a newer push cancels the stale one.+concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++# Pin action revisions so upstream tag changes cannot alter CI code.+jobs:+ lint:+ name: ruff+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0+ with:+ enable-cache: true+ # No explicit python-version: uv picks up the interpreter from .python-version.+ - run: uv sync --all-extras --locked+ - run: uv run ruff check src tests++ # mypy reports ~170 pre-existing errors across src/. Until those are fixed the+ # job is informational only: it runs on every PR so regressions are visible+ # in the logs, but it never blocks a merge. Remove `continue-on-error` once+ # `uv run mypy src` is clean.+ typecheck:+ name: mypy (informational)+ runs-on: ubuntu-latest+ continue-on-error: true+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0+ with:+ enable-cache: true+ - run: uv sync --all-extras --locked+ - run: uv run mypy src++ test:+ name: pytest (py${{ matrix.python-version }}, ${{ matrix.os }})+ runs-on: ${{ matrix.os }}+ env:+ # Make the matrix interpreter explicit for every uv invocation.+ UV_PYTHON: ${{ matrix.python-version }}+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.11", "3.12", "3.13"]+ os: [ubuntu-latest, macos-latest, windows-latest]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0+ with:+ enable-cache: true+ python-version: ${{ matrix.python-version }}+ # --locked: fail loudly if uv.lock is stale instead of silently re-resolving.+ - run: uv sync --all-extras --locked+ - run: uv run pytest -qdiff --git a/README.md b/README.mdindex b93de15..f414caf 100644--- a/README.md+++ b/README.md@@ -4,6 +4,7 @@<a href="https://pypi.org/project/reverse-api-engineer/"><img src="https://img.shields.io/pypi/v/reverse-api-engineer?style=flat&color=e50d75&labelColor=1f1f1f" alt="PyPI"></a><a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.11+-e50d75?style=flat&labelColor=1f1f1f" alt="Python"></a><a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/license-MIT-e50d75?style=flat&labelColor=1f1f1f" alt="License"></a>+ <a href="https://github.com/kalil0321/reverse-api-engineer/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/kalil0321/reverse-api-engineer/ci.yml?branch=main&style=flat&labelColor=1f1f1f&label=CI" alt="CI"></a><br>[](https://www.greptile.com/?utm_source=oss_badge&utm_medium=readme&utm_campaign=greptile_for_open_source)diff --git a/src/reverse_api/auto_engineer.py b/src/reverse_api/auto_engineer.pyindex f03c758..2b17855 100644--- a/src/reverse_api/auto_engineer.py+++ b/src/reverse_api/auto_engineer.py@@ -1,7 +1,8 @@"""Auto mode engineers: LLM-controlled browsing with real-time reverse engineering.Providers **auto** and **chrome-mcp** attach a browser MCP server to the SDK. Provider-**agent-browser** shells the upstream Vercel ``agent-browser`` CLI (auto-install via npm when missing, validated with ``--help``) instead of attaching browser MCP here.+**agent-browser** shells the upstream Vercel ``agent-browser`` CLI (auto-install via npm+when missing, validated with ``--help``) instead of attaching browser MCP here."""import asynciodiff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex ce58059..cae77fc 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -501,7 +501,10 @@ def _build_dry_run_payload(checks.append({"name": "chrome-mcp:auto-connect","status": "warn",- "message": "chrome-mcp without --headless requires Chrome 146+ with auto-connect enabled at chrome://inspect/#remote-debugging — this is not auto-checkable",+ "message": (+ "chrome-mcp without --headless requires Chrome 146+ with auto-connect enabled "+ "at chrome://inspect/#remote-debugging — this is not auto-checkable"+ ),})# 7. agent-browser CLI: read-only validation (no npm install during dry-run).@@ -751,7 +754,7 @@ AGENT_TASK_SUGGESTIONS = []-def prompt_interactive_options(+def prompt_interactive_options( # noqa: C901 — long questionary flow; split when it is next touchedprompt: str | None = None,url: str | None = None,reverse_engineer: bool | None = None,@@ -964,7 +967,7 @@ def prompt_interactive_options(if url is None: # questionary returns None on Ctrl+Craise click.Abort()except KeyboardInterrupt:- raise click.Abort()+ raise click.Abort() from None# Use settings defaults for the restif reverse_engineer is None:@@ -1159,7 +1162,7 @@ def handle_settings(mode_color=THEME_PRIMARY):pass-def _handle_settings_action(mode_color=THEME_PRIMARY) -> bool:+def _handle_settings_action(mode_color=THEME_PRIMARY) -> bool: # noqa: C901 — one branch per settings menu entry; split when next touched"""Display and manage settings with improved layout and descriptions."""from rich.table import Table@@ -1709,12 +1712,18 @@ Exit codes:@click.option("--headless",is_flag=True,- help="Launch the MCP-controlled browser in headless mode (required on machines without an X server). For chrome-mcp this drops --autoConnect since auto-connect requires a headed Chrome instance.",+ help=(+ "Launch the MCP-controlled browser in headless mode (required on machines without an X server). "+ "For chrome-mcp this drops --autoConnect since auto-connect requires a headed Chrome instance."+ ),)@click.option("--dry-run",is_flag=True,- help="Validate prompt/url/config/env without launching the browser. Emits a manifest of what would run + check results. Implies --json. Exits 0 if all checks pass, 1 if any error.",+ help=(+ "Validate prompt/url/config/env without launching the browser. Emits a manifest of what would run + check results. "+ "Implies --json. Exits 0 if all checks pass, 1 if any error."+ ),)def agent(prompt, url, model, output_dir, no_interactive, as_json, json_stream, headless, dry_run):"""Run autonomous agent browser session.diff --git a/src/reverse_api/collector_ui.py b/src/reverse_api/collector_ui.pyindex 76053ab..eb97c5d 100644--- a/src/reverse_api/collector_ui.py+++ b/src/reverse_api/collector_ui.py@@ -2,7 +2,7 @@from rich.console import Console-from .theme import MODE_COLORS, THEME_DIM+from .theme import MODE_COLORSfrom .tui import print_session_headerCOLLECTOR_COLOR = MODE_COLORS["collector"]@@ -100,7 +100,7 @@ class CollectorUI:cost = usage.get("estimated_cost_usd", 0)if input_tokens > 0 or output_tokens > 0:- self.console.print(f" [dim]usage:[/dim]")+ self.console.print(" [dim]usage:[/dim]")if input_tokens > 0:self.console.print(f" [dim] input: {input_tokens:,} tokens[/dim]")if output_tokens > 0:diff --git a/src/reverse_api/opencode_engineer.py b/src/reverse_api/opencode_engineer.pyindex e7f7525..de280b1 100644--- a/src/reverse_api/opencode_engineer.py+++ b/src/reverse_api/opencode_engineer.py@@ -70,7 +70,7 @@ def format_error(e: Exception) -> str:import jsonresponse_text = json.dumps(response_json, indent=2)[:1000] # Limit to 1000 chars- lines.append(f"\n[dim]Response Body:[/dim]")+ lines.append("\n[dim]Response Body:[/dim]")# Split into lines and indentfor line in response_text.split("\n"):lines.append(f" [dim]{line}[/dim]")@@ -78,23 +78,23 @@ def format_error(e: Exception) -> str:# Fall back to text if not JSONresponse_text = e.response.text[:500]if response_text:- lines.append(f"\n[dim]Response Body:[/dim]")+ lines.append("\n[dim]Response Body:[/dim]")lines.append(f" [dim]{response_text}[/dim]")except Exception:passelif isinstance(e, httpx.ConnectError):- lines.append(f"\n[dim]Unable to connect to OpenCode server[/dim]")+ lines.append("\n[dim]Unable to connect to OpenCode server[/dim]")if error_msg and "Connection refused" not in error_msg:lines.append(f" [dim]{error_msg}[/dim]")elif isinstance(e, httpx.ReadError):- lines.append(f"\n[dim]Connection was interrupted while reading response[/dim]")+ lines.append("\n[dim]Connection was interrupted while reading response[/dim]")if error_msg:lines.append(f" [dim]{error_msg}[/dim]")elif isinstance(e, httpx.TimeoutException):- lines.append(f"\n[dim]Request timed out[/dim]")+ lines.append("\n[dim]Request timed out[/dim]")if error_msg:lines.append(f" [dim]{error_msg}[/dim]")@@ -103,7 +103,7 @@ def format_error(e: Exception) -> str:import tracebacktb_str = "".join(traceback.format_exception(type(e), e, e.__traceback__))- lines.append(f"\n[dim]Traceback:[/dim]")+ lines.append("\n[dim]Traceback:[/dim]")for line in tb_str.split("\n"):lines.append(f" [dim]{line}[/dim]")@@ -320,7 +320,7 @@ class OpenCodeEngineer(BaseEngineer):self.message_store.save_error(error_msg)return None- async def _stream_events(self, client: httpx.AsyncClient):+ async def _stream_events(self, client: httpx.AsyncClient): # noqa: C901 — SSE event dispatch loop; split when next touched"""Stream events from OpenCode and update UI."""seen_parts: set = set() # Track part IDs to avoid duplicatesimport time@@ -664,7 +664,7 @@ class OpenCodeEngineer(BaseEngineer):# Only process parts for our sessionif part_session != self._session_id:- debug_log(f"Skipping part for other session")+ debug_log("Skipping part for other session")returnif part_type == "text":diff --git a/src/reverse_api/opencode_ui.py b/src/reverse_api/opencode_ui.pyindex 4b40d91..e0b7cab 100644--- a/src/reverse_api/opencode_ui.py+++ b/src/reverse_api/opencode_ui.py@@ -7,7 +7,7 @@ from rich.console import Consolefrom rich.live import Livefrom rich.text import Text-from .theme import MODE_COLORS, THEME_DIM, THEME_PRIMARY, THEME_SUCCESS+from .theme import THEME_DIM, THEME_PRIMARYfrom .tui import ERROR_CTA, print_session_headerdiff --git a/src/reverse_api/tui.py b/src/reverse_api/tui.pyindex a540226..e947892 100644--- a/src/reverse_api/tui.py+++ b/src/reverse_api/tui.py@@ -14,10 +14,8 @@ from .theme import (BRAND_WORDMARK,MODE_COLORS,THEME_DIM,- THEME_ERROR,THEME_PRIMARY,THEME_SECONDARY,- THEME_SUCCESS,)ERROR_CTA = "If an unexpected error occurred, please create an issue at https://github.com/kalil0321/reverse-api-engineer/issues/new"@@ -389,13 +387,16 @@ def print_session_header(def display_banner(console: Console, sdk: str | None = None, model: str | None = None):"""Display minimalist startup banner with * rae branding."""+ # Redirected Windows streams may use a legacy encoding such as cp1252.+ divider = "--" if console.options.ascii_only else "━━"+ separator = "|" if console.options.ascii_only else "·"console.print()print_cli_logo(console)- console.print(f" [bold {THEME_PRIMARY}]━━[/bold {THEME_PRIMARY}]")+ console.print(f" [bold {THEME_PRIMARY}]{divider}[/bold {THEME_PRIMARY}]")if sdk and model:console.print(f" [{THEME_DIM}]sdk[/{THEME_DIM}] [{THEME_SECONDARY}]{sdk}[/{THEME_SECONDARY}]"- f" [{THEME_DIM}]·[/{THEME_DIM}] [{THEME_DIM}]model[/{THEME_DIM}]"+ f" [{THEME_DIM}]{separator}[/{THEME_DIM}] [{THEME_DIM}]model[/{THEME_DIM}]"f" [{THEME_SECONDARY}]{model}[/{THEME_SECONDARY}]")console.print()diff --git a/tests/conftest.py b/tests/conftest.pyindex 9efe926..5eb1ec0 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,8 +1,6 @@"""Shared test fixtures."""import json-import tempfile-from pathlib import Pathimport pytestdiff --git a/tests/test_auto_engineer.py b/tests/test_auto_engineer.pyindex 5ed6628..f9a0059 100644--- a/tests/test_auto_engineer.py+++ b/tests/test_auto_engineer.py@@ -1,9 +1,8 @@"""Tests for auto_engineer.py - Auto mode engineers."""+import asynciofrom contextlib import contextmanagerfrom dataclasses import dataclass-from pathlib import Path-from typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchimport httpx2 as httpx@@ -1275,8 +1274,6 @@ class TestOpenCodeAutoEngineerAnalyze:mock_client.delete = AsyncMock()# Patch the second httpx.AsyncClient (for message fetch) to fail- original_async_client = httpx.AsyncClient-call_count = [0]with patch("reverse_api.auto_engineer.httpx.AsyncClient") as mock_async:diff --git a/tests/test_base_engineer.py b/tests/test_base_engineer.pyindex 648348c..99128e7 100644--- a/tests/test_base_engineer.py+++ b/tests/test_base_engineer.py@@ -1,6 +1,8 @@"""Tests for base_engineer.py - BaseEngineer abstract class."""+import osimport shlex+import sysfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import MagicMock, patch@@ -10,6 +12,17 @@ import pytestfrom reverse_api.base_engineer import REPORT_CLIENT_VERIFIED_INSTRUCTION, BaseEngineer+def _split_run_command(command):+ """Split generated commands without treating Windows backslashes as escapes.++ These commands contain plain arguments or double-quoted Windows paths;+ Windows filenames cannot contain literal double quotes.+ """+ if sys.platform == "win32":+ return [token.strip('"') for token in shlex.split(command, posix=False)]+ return shlex.split(command)++class ConcreteEngineer(BaseEngineer):"""Concrete implementation for testing."""@@ -121,7 +134,9 @@ class TestBaseEngineerInit:python_client.write_text("print('python')\n")typescript_client = scripts_dir / "api_client.ts"typescript_client.write_text("export {};\n")- typescript_client.touch()+ # Back-to-back writes may have identical timestamps on Windows.+ os.utime(python_client, (1_700_000_000, 1_700_000_000))+ os.utime(typescript_client, (1_700_000_010, 1_700_000_010))with patch("reverse_api.base_engineer.get_scripts_dir", return_value=scripts_dir):with patch("reverse_api.base_engineer.MessageStore"):@@ -260,8 +275,9 @@ class TestBaseEngineerHelpers:python/node/npx, Maven hard-fails with no upward search if invokedfrom a directory with no pom.xml."""eng = self._make_engineer(tmp_path, output_language="java")- expected_pom = shlex.quote(str(eng.scripts_dir.resolve() / "pom.xml"))- assert eng._get_run_command() == f"mvn -q -f {expected_pom} compile exec:exec"+ assert _split_run_command(eng._get_run_command()) == [+ "mvn", "-q", "-f", str(eng.scripts_dir.resolve() / "pom.xml"), "compile", "exec:exec",+ ]def test_get_run_command_java_quotes_metacharacters(self, tmp_path):"""A scripts_dir containing shell metacharacters must round-trip@@ -269,7 +285,7 @@ class TestBaseEngineerHelpers:expansion — what the naive f'"{path}"' approach got wrong."""eng = self._make_engineer(tmp_path, output_language="java")eng.scripts_dir = Path("/tmp/weird$(rm -rf ~) dir")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())assert tokens[:2] == ["mvn", "-q"]assert tokens[3] == str(eng.scripts_dir.resolve() / "pom.xml")@@ -281,7 +297,7 @@ class TestBaseEngineerHelpers:location."""eng = self._make_engineer(tmp_path, output_language="java")eng.scripts_dir = Path("relative_output/scripts/run123")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())pom_arg = tokens[3]assert Path(pom_arg).is_absolute()assert pom_arg == str(eng.scripts_dir.resolve() / "pom.xml")@@ -291,8 +307,9 @@ class TestBaseEngineerHelpers:scripts_dir.parent.parent (see analyze_and_generate), and dotnetonly looks for a project file in the current directory."""eng = self._make_engineer(tmp_path, output_language="csharp")- expected_csproj = shlex.quote(str(eng.scripts_dir.resolve() / "ApiClient.csproj"))- assert eng._get_run_command() == f"dotnet run --project {expected_csproj}"+ assert _split_run_command(eng._get_run_command()) == [+ "dotnet", "run", "--project", str(eng.scripts_dir.resolve() / "ApiClient.csproj"),+ ]def test_get_run_command_csharp_quotes_metacharacters(self, tmp_path):"""A scripts_dir containing shell metacharacters must round-trip@@ -300,7 +317,7 @@ class TestBaseEngineerHelpers:expansion — what the naive f'"{path}"' approach got wrong."""eng = self._make_engineer(tmp_path, output_language="csharp")eng.scripts_dir = Path("/tmp/weird$(rm -rf ~) dir")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())assert tokens[:2] == ["dotnet", "run"]assert tokens[3] == str(eng.scripts_dir.resolve() / "ApiClient.csproj")@@ -312,7 +329,7 @@ class TestBaseEngineerHelpers:location."""eng = self._make_engineer(tmp_path, output_language="csharp")eng.scripts_dir = Path("relative_output/scripts/run123")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())project_arg = tokens[3]assert Path(project_arg).is_absolute()assert project_arg == str(eng.scripts_dir.resolve() / "ApiClient.csproj")@@ -323,8 +340,9 @@ class TestBaseEngineerHelpers:script lives, and shlex.quote() (not manual double-quoting) is whatactually neutralizes shell metacharacters in an arbitrary output_dir."""eng = self._make_engineer(tmp_path, output_language="php")- expected_path = shlex.quote(str(eng.scripts_dir.resolve() / "api_client.php"))- assert eng._get_run_command() == f"php {expected_path}"+ assert _split_run_command(eng._get_run_command()) == [+ "php", str(eng.scripts_dir.resolve() / "api_client.php"),+ ]def test_get_run_command_php_quotes_metacharacters(self, tmp_path):"""A scripts_dir containing shell metacharacters must round-trip@@ -335,7 +353,7 @@ class TestBaseEngineerHelpers:eng = self._make_engineer(tmp_path, output_language="php")eng.scripts_dir = Path("/tmp/weird$(rm -rf ~) dir")command = eng._get_run_command()- tokens = shlex.split(command)+ tokens = _split_run_command(command)assert tokens[0] == "php"assert tokens[1] == str(eng.scripts_dir.resolve() / "api_client.php")@@ -347,7 +365,7 @@ class TestBaseEngineerHelpers:location."""eng = self._make_engineer(tmp_path, output_language="php")eng.scripts_dir = Path("relative_output/scripts/run123")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())script_arg = tokens[1]assert Path(script_arg).is_absolute()assert script_arg == str(eng.scripts_dir.resolve() / "api_client.php")@@ -357,8 +375,9 @@ class TestBaseEngineerHelpers:parent.parent (see analyze_and_generate), not scripts_dir where thescript lives."""eng = self._make_engineer(tmp_path, output_language="ruby")- expected_path = shlex.quote(str(eng.scripts_dir.resolve() / "api_client.rb"))- assert eng._get_run_command() == f"ruby {expected_path}"+ assert _split_run_command(eng._get_run_command()) == [+ "ruby", str(eng.scripts_dir.resolve() / "api_client.rb"),+ ]def test_get_run_command_ruby_quotes_metacharacters(self, tmp_path):"""A scripts_dir containing shell metacharacters must round-trip@@ -366,7 +385,7 @@ class TestBaseEngineerHelpers:expansion — what the naive f'"{path}"' approach got wrong."""eng = self._make_engineer(tmp_path, output_language="ruby")eng.scripts_dir = Path("/tmp/weird$(rm -rf ~) dir")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())assert tokens[0] == "ruby"assert tokens[1] == str(eng.scripts_dir.resolve() / "api_client.rb")@@ -378,7 +397,7 @@ class TestBaseEngineerHelpers:location."""eng = self._make_engineer(tmp_path, output_language="ruby")eng.scripts_dir = Path("relative_output/scripts/run123")- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())script_arg = tokens[1]assert Path(script_arg).is_absolute()assert script_arg == str(eng.scripts_dir.resolve() / "api_client.rb")@@ -390,11 +409,10 @@ class TestBaseEngineerHelpers:all actually live."""eng = self._make_engineer(tmp_path, output_language="c")resolved = eng.scripts_dir.resolve()- source = shlex.quote(str(resolved / "api_client.c"))- cjson = shlex.quote(str(resolved / "cJSON.c"))- binary = shlex.quote(str(resolved / "api_client"))- expected = f"cc {source} {cjson} -lcurl -o {binary} && {binary}"- assert eng._get_run_command() == expected+ assert _split_run_command(eng._get_run_command()) == [+ "cc", str(resolved / "api_client.c"), str(resolved / "cJSON.c"),+ "-lcurl", "-o", str(resolved / "api_client"), "&&", str(resolved / "api_client"),+ ]def test_get_run_command_c_quotes_metacharacters(self, tmp_path):"""A scripts_dir containing shell metacharacters must round-trip@@ -404,7 +422,7 @@ class TestBaseEngineerHelpers:eng = self._make_engineer(tmp_path, output_language="c")eng.scripts_dir = Path("/tmp/weird$(rm -rf ~) dir")resolved = eng.scripts_dir.resolve()- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())assert tokens[:2] == ["cc", str(resolved / "api_client.c")]assert tokens[2] == str(resolved / "cJSON.c")assert tokens[3:6] == ["-lcurl", "-o", str(resolved / "api_client")]@@ -421,7 +439,7 @@ class TestBaseEngineerHelpers:eng = self._make_engineer(tmp_path, output_language="c")eng.scripts_dir = Path("relative_output/scripts/run123")resolved = eng.scripts_dir.resolve()- tokens = shlex.split(eng._get_run_command())+ tokens = _split_run_command(eng._get_run_command())assert Path(tokens[1]).is_absolute()assert tokens[1] == str(resolved / "api_client.c")assert tokens[2] == str(resolved / "cJSON.c")@@ -446,6 +464,18 @@ class TestBaseEngineerHelpers:eng = self._make_engineer(tmp_path, output_language=language, output_mode="client")assert REPORT_CLIENT_VERIFIED_INSTRUCTION not in eng._get_codegen_instructions(), language+ @pytest.mark.parametrize("language", ["java", "csharp", "php", "ruby", "c"])+ def test_run_command_preserves_posix_shell_quoting(self, tmp_path, monkeypatch, language):+ """Token round-trips alone cannot detect unsafe double-quoted substitutions."""+ eng = self._make_engineer(tmp_path, output_language=language)+ eng.scripts_dir = tmp_path / "client $(printf injected) `printf injected`"+ monkeypatch.setattr("reverse_api.base_engineer.sys.platform", "linux")+ command = eng._get_run_command()+ paths = [token for token in shlex.split(command) if str(tmp_path) in token]+ assert paths+ for path in paths:+ assert shlex.quote(path) in command+def test_quote_path_posix(self, monkeypatch):"""POSIX platforms use shlex.quote (single quotes for spaces)."""from reverse_api import base_engineer as bediff --git a/tests/test_cli_agent_json.py b/tests/test_cli_agent_json.pyindex 3881e4f..6ccafe1 100644--- a/tests/test_cli_agent_json.py+++ b/tests/test_cli_agent_json.py@@ -16,7 +16,6 @@ from reverse_api.cli import ()from reverse_api.session import SessionManager-EXPECTED_PAYLOAD_KEYS = {"schema_version","status",diff --git a/tests/test_cli_followups.py b/tests/test_cli_followups.pyindex 2fd6ee5..632390d 100644--- a/tests/test_cli_followups.py+++ b/tests/test_cli_followups.py@@ -6,9 +6,11 @@ Covers:"""import json+import osimport subprocessfrom unittest.mock import patch+import pytestfrom click.testing import CliRunnerfrom reverse_api.cli import (@@ -39,13 +41,16 @@ EXPECTED_ENGINEER_KEYS = {class TestTtyDetectionAtReplEntry:"""Without a TTY and no subcommand, the REPL must NOT block on prompt_toolkit."""- def test_no_tty_no_subcommand_exits_2(self):- """End-to-end: invoke the installed binary with stdin redirected from /dev/null."""+ @pytest.mark.parametrize("encoding", ["utf-8", "cp1252"])+ def test_no_tty_no_subcommand_exits_2(self, encoding):+ """A pipe is non-interactive on all OSes; Windows NUL can report isatty()."""result = subprocess.run(["uv", "run", "reverse-api-engineer"],- stdin=subprocess.DEVNULL,+ input="",+ env={**os.environ, "PYTHONIOENCODING": encoding},capture_output=True,text=True,+ encoding=encoding,timeout=10,)assert result.returncode == 2@@ -418,20 +423,25 @@ class TestAgentDryRun:assert payload["error_kind"] == "misuse"assert any(c["name"] == "url" and c["status"] == "error" for c in payload["checks"])- def test_dry_run_unwritable_output_dir_is_config_invalid(self):+ def test_dry_run_unwritable_output_dir_is_config_invalid(self, tmp_path):"""Unwritable output_dir → error_kind=config_invalid, not misuse."""from reverse_api.cli import agent as agent_cmdrunner = CliRunner()- with patch("reverse_api.cli.config_manager") as cm:+ # /sys is not protected on Windows, and chmod is ineffective as root.+ # Simulate a denied write at the actual filesystem boundary instead.+ with patch("reverse_api.cli.config_manager") as cm, patch(+ "pathlib.Path.write_text", side_effect=PermissionError("Access denied")+ ) as write_probe:cm.get.side_effect = lambda key, default=None: {"agent_provider": "auto","sdk": "claude",- "output_dir": "/sys/forbidden",+ "output_dir": str(tmp_path),}.get(key, default)result = runner.invoke(- agent_cmd, ["--dry-run", "-p", "x", "--output-dir", "/sys/forbidden"]+ agent_cmd, ["--dry-run", "-p", "x", "--output-dir", str(tmp_path)])+ write_probe.assert_called_once()assert result.exit_code == 1payload = json.loads(result.stdout.strip())diff --git a/tests/test_cli_manual_missing_extra.py b/tests/test_cli_manual_missing_extra.pyindex 0383082..0161beb 100644--- a/tests/test_cli_manual_missing_extra.py+++ b/tests/test_cli_manual_missing_extra.py@@ -8,7 +8,7 @@ history that later "operate on the latest run" flows could target.import ioimport sys-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport clickimport pytestdiff --git a/tests/test_collector.py b/tests/test_collector.pyindex 0eb95e8..0a1b80a 100644--- a/tests/test_collector.py+++ b/tests/test_collector.py@@ -67,7 +67,7 @@ class TestCollectorRun:@pytest.mark.asyncioasync def test_run_success(self, tmp_path):"""Run executes agent loop and finalizes."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -144,7 +144,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_exception(self, tmp_path):"""Agent loop handles SDK exception."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -169,7 +169,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_result_error(self, tmp_path):"""Agent loop handles ResultMessage with error."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -208,7 +208,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_result_success(self, tmp_path):"""Agent loop handles ResultMessage with success."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -246,7 +246,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_assistant_message_with_tools(self, tmp_path):"""Agent loop processes AssistantMessage with ToolUseBlock, ToolResultBlock, TextBlock."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -311,7 +311,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_write_items_tracking(self, tmp_path):"""Agent loop tracks Write to items.jsonl."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -362,7 +362,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_usage_tracking(self, tmp_path):"""Agent loop accumulates usage metadata."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -412,7 +412,7 @@ class TestCollectorAgentLoop:@pytest.mark.asyncioasync def test_agent_loop_no_result_returns_success(self, tmp_path):"""Agent loop returns success when no ResultMessage (line 186)."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -594,7 +594,7 @@ class TestCollectorFinalizeCollection:def test_finalize_no_items(self, tmp_path):"""Finalize with no items returns error."""with patch("reverse_api.collector.MessageStore"):- with patch("reverse_api.collector.CollectorUI") as mock_ui:+ with patch("reverse_api.collector.CollectorUI"):collector = Collector(run_id="test123",prompt="test",@@ -623,7 +623,7 @@ class TestCollectorFinalizeCollection:def test_finalize_with_items(self, tmp_path):"""Finalize with items creates all output files."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -653,7 +653,7 @@ class TestCollectorFinalizeCollection:def test_finalize_with_usage(self, tmp_path):"""Finalize calculates cost from usage."""- with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.MessageStore"):with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:mock_ui = MagicMock()mock_ui_cls.return_value = mock_ui@@ -673,7 +673,7 @@ class TestCollectorFinalizeCollection:with open(tmp_path / "items.jsonl", "w") as f:f.write(json.dumps({"name": "test"}) + "\n")- result = collector._finalize_collection()+ collector._finalize_collection()assert "estimated_cost_usd" in collector.usage_metadatadef test_finalize_with_cache_usage(self, tmp_path):@@ -699,7 +699,7 @@ class TestCollectorFinalizeCollection:with open(tmp_path / "items.jsonl", "w") as f:f.write(json.dumps({"name": "test"}) + "\n")- result = collector._finalize_collection()+ collector._finalize_collection()assert collector.usage_metadata["estimated_cost_usd"] > 0def test_finalize_skips_invalid_json_lines(self, tmp_path):diff --git a/tests/test_collector_ui.py b/tests/test_collector_ui.pyindex 6c0a4e3..43cf39b 100644--- a/tests/test_collector_ui.py+++ b/tests/test_collector_ui.py@@ -4,7 +4,7 @@ from io import StringIOfrom rich.console import Console-from reverse_api.collector_ui import COLLECTOR_COLOR, CollectorUI+from reverse_api.collector_ui import CollectorUIclass TestCollectorUI:diff --git a/tests/test_config.py b/tests/test_config.pyindex bc27654..c18257a 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -1,9 +1,6 @@"""Tests for config.py - ConfigManager."""import json-from pathlib import Path--import pytestfrom reverse_api.config import DEFAULT_CONFIG, ConfigManagerdiff --git a/tests/test_engineer.py b/tests/test_engineer.pyindex b3759b2..791d509 100644--- a/tests/test_engineer.py+++ b/tests/test_engineer.py@@ -1,6 +1,5 @@"""Tests for engineer.py - run_reverse_engineering dispatch."""-from pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -32,7 +31,7 @@ class TestRunReverseEngineering:mock_instance.stop_sync = MagicMock()with patch("reverse_api.engineer.asyncio.run", return_value={"test": True}):- result = run_reverse_engineering(+ run_reverse_engineering(run_id="test123",har_path=har_path,prompt="test prompt",@@ -52,7 +51,7 @@ class TestRunReverseEngineering:mock_instance.stop_sync = MagicMock()with patch("reverse_api.engineer.asyncio.run", return_value={"test": True}):- result = run_reverse_engineering(+ run_reverse_engineering(run_id="test123",har_path=har_path,prompt="test prompt",@@ -93,7 +92,7 @@ class TestRunReverseEngineering:mock_instance.stop_sync = MagicMock()with patch("reverse_api.engineer.asyncio.run", side_effect=Exception("fail")):- with pytest.raises(Exception):+ with pytest.raises(Exception, match="fail"):run_reverse_engineering(run_id="test123",har_path=har_path,diff --git a/tests/test_init.py b/tests/test_init.pyindex de9f411..0e2760c 100644--- a/tests/test_init.py+++ b/tests/test_init.py@@ -1,7 +1,6 @@"""Tests for __init__.py - Package initialization."""from importlib.metadata import PackageNotFoundError-from unittest.mock import patchfrom reverse_api import __version__diff --git a/tests/test_messages.py b/tests/test_messages.pyindex ea434da..540c0c8 100644--- a/tests/test_messages.py+++ b/tests/test_messages.py@@ -3,8 +3,6 @@import jsonfrom unittest.mock import patch-import pytest-from reverse_api.messages import MessageStorediff --git a/tests/test_opencode_engineer.py b/tests/test_opencode_engineer.pyindex 5a4a48e..05681ee 100644--- a/tests/test_opencode_engineer.py+++ b/tests/test_opencode_engineer.py@@ -9,7 +9,6 @@ import httpx2 as httpximport pytestfrom reverse_api.opencode_engineer import (- DEBUG,OpenCodeEngineer,debug_log,format_error,@@ -748,7 +747,8 @@ class TestOpenCodeEngineerStreamEvents:eng = self._make_engineer(tmp_path)lines = [- 'data: {"type":"session.error","properties":{"sessionID":"session_abc","error":{"name":"ProviderAuthError","data":{"providerID":"anthropic","message":"Invalid API key"}}}}',+ 'data: {"type":"session.error","properties":{"sessionID":"session_abc",'+ '"error":{"name":"ProviderAuthError","data":{"providerID":"anthropic","message":"Invalid API key"}}}}',]mock_response = AsyncMock()@@ -777,7 +777,8 @@ class TestOpenCodeEngineerStreamEvents:eng = self._make_engineer(tmp_path)lines = [- 'data: {"type":"session.error","properties":{"sessionID":"session_abc","error":{"name":"APIError","data":{"message":"Rate limited","statusCode":429}}}}',+ 'data: {"type":"session.error","properties":{"sessionID":"session_abc",'+ '"error":{"name":"APIError","data":{"message":"Rate limited","statusCode":429}}}}',]mock_response = AsyncMock()@@ -1004,8 +1005,6 @@ class TestOpenCodeEngineerStreamEvents:eng = self._make_engineer(tmp_path)# Patch json.loads to raise JSONDecodeError with buffer size in message- original_loads = json.loads-def mock_loads(s, *args, **kwargs):raise json.JSONDecodeError("exceeded maximum buffer size 1048576", s, 0)diff --git a/tests/test_pricing.py b/tests/test_pricing.pyindex 7eef9e0..97a83d0 100644--- a/tests/test_pricing.py+++ b/tests/test_pricing.py@@ -2,11 +2,9 @@from unittest.mock import MagicMock, patch-import pytest-from reverse_api.pricing import (- MODEL_PRICING,_LITELLM_MODEL_MAP,+ MODEL_PRICING,_get_pricing_from_litellm,calculate_cost,get_model_pricing,@@ -184,7 +182,7 @@ class TestLitellmModelMap:def test_map_values_are_lists(self):"""Each map entry is a list of alternative names."""- for key, value in _LITELLM_MODEL_MAP.items():+ for value in _LITELLM_MODEL_MAP.values():assert isinstance(value, list)assert len(value) >= 1diff --git a/tests/test_run_command.py b/tests/test_run_command.pyindex c0981fe..1b38f29 100644--- a/tests/test_run_command.py+++ b/tests/test_run_command.py@@ -1,7 +1,5 @@"""Tests for the `run` command and its supporting functions (resolve_run, discover_scripts)."""-import json-import subprocessfrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -12,7 +10,6 @@ from click.testing import CliRunnerfrom reverse_api.session import SessionManagerfrom reverse_api.utils import discover_scripts, resolve_run-# ---------------------------------------------------------------------------# Fixtures# ---------------------------------------------------------------------------@@ -420,7 +417,7 @@ class TestRunCommandLs:def test_ls_does_not_execute(self, cli_runner, mock_cli_env):from reverse_api.cli import mainwith patch("subprocess.run") as mock_sub:- result = cli_runner.invoke(main, ["run", "abc123def456", "--ls"])+ cli_runner.invoke(main, ["run", "abc123def456", "--ls"])mock_sub.assert_not_called()@@ -430,7 +427,7 @@ class TestRunCommandFileFlag:def test_file_flag_selects_script(self, cli_runner, mock_cli_env):from reverse_api.cli import mainwith patch("subprocess.run", return_value=MagicMock(returncode=0, stdout="", stderr="")) as mock_sub:- result = cli_runner.invoke(main, ["run", "abc123def456", "--file", "example_usage.py"])+ cli_runner.invoke(main, ["run", "abc123def456", "--file", "example_usage.py"])assert mock_sub.calledcall_args = mock_sub.call_args[0][0]assert "example_usage.py" in str(call_args[1])@@ -455,7 +452,7 @@ class TestRunCommandExecution:def test_single_script_auto_selected(self, cli_runner, mock_cli_env):from reverse_api.cli import mainwith patch("subprocess.run", return_value=MagicMock(returncode=0, stdout="", stderr="")) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012"])+ cli_runner.invoke(main, ["run", "def789ghi012"])assert mock_sub.calledcall_args = mock_sub.call_args[0][0]assert "api_client.py" in str(call_args[1])@@ -463,7 +460,7 @@ class TestRunCommandExecution:def test_args_passthrough(self, cli_runner, mock_cli_env):from reverse_api.cli import mainwith patch("subprocess.run", return_value=MagicMock(returncode=0, stdout="", stderr="")) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012", "--", "--org", "acme", "--limit", "10"])+ cli_runner.invoke(main, ["run", "def789ghi012", "--", "--org", "acme", "--limit", "10"])call_args = mock_sub.call_args[0][0]assert "--org" in call_argsassert "acme" in call_args@@ -490,7 +487,7 @@ class TestRunCommandExecution:with patch("questionary.select") as mock_select:mock_select.return_value.ask.return_value = script_pathwith patch("subprocess.run", return_value=MagicMock(returncode=0, stdout="", stderr="")):- result = cli_runner.invoke(main, ["run", "abc123def456"])+ cli_runner.invoke(main, ["run", "abc123def456"])mock_select.assert_called_once()def test_multiple_scripts_user_cancels_picker(self, cli_runner, mock_cli_env):@@ -530,7 +527,7 @@ class TestRunCommandSharedVenv:from reverse_api.cli import mainok = MagicMock(returncode=0, stdout="", stderr="")with patch("subprocess.run", return_value=ok) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012"])+ cli_runner.invoke(main, ["run", "def789ghi012"])# Should have: venv create, pip install requests, script run = 3 callsassert mock_sub.call_count == 3@@ -554,7 +551,7 @@ class TestRunCommandSharedVenv:ok = MagicMock(returncode=0, stdout="", stderr="")with patch("subprocess.run", return_value=ok) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012"])+ cli_runner.invoke(main, ["run", "def789ghi012"])# Only the script execution call — no venv create, no pip installassert mock_sub.call_count == 1@@ -574,7 +571,7 @@ class TestRunCommandSharedVenv:ok = MagicMock(returncode=0, stdout="", stderr="")with patch("subprocess.run", return_value=ok) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012"])+ cli_runner.invoke(main, ["run", "def789ghi012"])# pip install -r requirements.txt + script run = 2 callsassert mock_sub.call_count == 2@@ -593,7 +590,7 @@ class TestRunCommandSharedVenv:ok = MagicMock(returncode=0, stdout="", stderr="")with patch("subprocess.run", return_value=ok) as mock_sub:- result = cli_runner.invoke(main, ["run", "def789ghi012"])+ cli_runner.invoke(main, ["run", "def789ghi012"])script_call = mock_sub.call_args_list[-1][0][0]assert ".venv" in str(script_call[0])@@ -665,7 +662,11 @@ class TestRunCommandOutputMessages:with patch("subprocess.run", return_value=MagicMock(returncode=0, stdout="", stderr="")):result = cli_runner.invoke(main, ["run", "def789ghi012"])- assert "scripts/def789ghi012" in result.output+ # Rich soft-wraps at 80 columns when stdout is not a TTY, so a long tmp_path+ # (CI runners, some usernames) gets split across lines; join before matching.+ # str(Path) also keeps the assertion valid with Windows separators.+ expected = str(tmp_path / "scripts" / "def789ghi012")+ assert expected in result.output.replace("\n", "")def test_shows_run_id_in_output(self, cli_runner, mock_cli_env):from reverse_api.cli import maindiff --git a/tests/test_session.py b/tests/test_session.pyindex 0f04a27..3963c9d 100644--- a/tests/test_session.py+++ b/tests/test_session.py@@ -2,8 +2,6 @@import json-import pytest-from reverse_api.session import SessionManagerdiff --git a/tests/test_sync.py b/tests/test_sync.pyindex c1c02a8..35e6984 100644--- a/tests/test_sync.py+++ b/tests/test_sync.py@@ -1,12 +1,8 @@"""Tests for sync.py - File synchronization."""-import shutilimport time-from pathlib import Pathfrom unittest.mock import MagicMock, patch-import pytest-from reverse_api.sync import (FileSyncWatcher,SyncHandler,diff --git a/tests/test_tui.py b/tests/test_tui.pyindex 8b40aea..54d3f70 100644--- a/tests/test_tui.py+++ b/tests/test_tui.py@@ -1,14 +1,11 @@"""Tests for tui.py, collector_ui.py, opencode_ui.py - UI modules."""-from io import StringIO-from unittest.mock import patch+from io import BytesIO, StringIO, TextIOWrapperimport pytestfrom rich.console import Consolefrom reverse_api.tui import (- THEME_DIM,- THEME_PRIMARY,TOOL_COLORS,TOOL_ICONS,ClaudeUI,@@ -356,6 +353,19 @@ class TestDisplayBanner:assert "rae" in outputassert "Turn websites into APIs" in output+ @pytest.mark.parametrize("encoding", ["ascii", "cp1252", "utf-8"])+ def test_banner_with_encoded_output(self, encoding):+ """Redirected output must render even with Windows' legacy encoding."""+ buffer = BytesIO()+ with TextIOWrapper(buffer, encoding=encoding) as stream:+ console = Console(file=stream, no_color=True)+ display_banner(console, sdk="claude", model="claude-sonnet-4-6")+ stream.flush()+ output = buffer.getvalue().decode(encoding)+ assert "rae" in output+ assert "claude-sonnet-4-6" in output+ assert ("━━" if encoding == "utf-8" else "--") in output+def test_banner_with_sdk_and_model(self):"""Banner with SDK and model info."""console = Console(file=StringIO(), no_color=True)diff --git a/tests/test_utils.py b/tests/test_utils.pyindex d819fad..32bf821 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -407,14 +407,14 @@ class TestGenerateFolderName:def test_opencode_calls_opencode_async(self):"""OpenCode SDK calls _generate_folder_name_opencode_async."""with patch("reverse_api.utils.asyncio.get_running_loop", side_effect=RuntimeError):- with patch("reverse_api.utils.asyncio.run", return_value="opencode_result") as mock_run:+ with patch("reverse_api.utils.asyncio.run", return_value="opencode_result"):result = generate_folder_name("test prompt", sdk="opencode")assert result == "opencode_result"def test_claude_calls_claude_async(self):"""Claude SDK calls _generate_folder_name_async."""with patch("reverse_api.utils.asyncio.get_running_loop", side_effect=RuntimeError):- with patch("reverse_api.utils.asyncio.run", return_value="claude_result") as mock_run:+ with patch("reverse_api.utils.asyncio.run", return_value="claude_result"):result = generate_folder_name("test prompt", sdk="claude")assert result == "claude_result"@@ -428,7 +428,7 @@ class TestGenerateFolderName:def test_with_session_id(self):"""OpenCode with session_id passes it through."""with patch("reverse_api.utils.asyncio.get_running_loop", side_effect=RuntimeError):- with patch("reverse_api.utils.asyncio.run", return_value="test_result") as mock_run:+ with patch("reverse_api.utils.asyncio.run", return_value="test_result"):result = generate_folder_name("test prompt", sdk="opencode", session_id="sess123")assert result == "test_result"@@ -439,9 +439,10 @@ class TestGenerateFolderNameAsync:@pytest.mark.asyncioasync def test_async_with_sdk_response(self):"""Async function returns cleaned folder name from SDK."""- from reverse_api.utils import _generate_folder_name_asyncfrom claude_agent_sdk import AssistantMessage, TextBlock+ from reverse_api.utils import _generate_folder_name_async+mock_text = MagicMock(spec=TextBlock)mock_text.text = " Apple_Jobs_API "@@ -487,9 +488,10 @@ class TestGenerateFolderNameAsync:@pytest.mark.asyncioasync def test_async_cleans_special_chars(self):"""Async function cleans special characters from response."""- from reverse_api.utils import _generate_folder_name_asyncfrom claude_agent_sdk import AssistantMessage, TextBlock+ from reverse_api.utils import _generate_folder_name_async+mock_text = MagicMock(spec=TextBlock)mock_text.text = "my-cool/api (v2)"@@ -537,13 +539,10 @@ class TestGenerateFolderNameOpencodeAsync:"""Creates a new session when session_id is None."""from reverse_api.utils import _generate_folder_name_opencode_async- mock_health = AsyncMock()mock_session_create = MagicMock()mock_session_create.raise_for_status = MagicMock()mock_session_create.json.return_value = {"id": "new_sess_123"}- mock_message_post = AsyncMock()-mock_messages_response = MagicMock()mock_messages_response.status_code = 200mock_messages_response.json.return_value = [@@ -553,8 +552,6 @@ class TestGenerateFolderNameOpencodeAsync:}]- call_idx = [0]-async def mock_get(path, **kwargs):if path == "/global/health":return _opencode_health_response()