Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(opencode): drop --dir for OpenCode CLI v2 compatibility (#3572)
hirawat-ll4dc6c205f5ea
diff --git a/docs/agent/OPENCODE.md b/docs/agent/OPENCODE.mdindex 0d912d92e..76ee57974 100644--- a/docs/agent/OPENCODE.md+++ b/docs/agent/OPENCODE.md@@ -82,10 +82,11 @@ You can also persist it:REPOWISE_PROVIDER=opencode repowise update```-The provider runs:+The provider runs `opencode run --format json` with the repository as the+subprocess working directory:```bash-opencode run --format json --dangerously-skip-permissions --dir /absolute/path/to/repo+cd /absolute/path/to/repo && opencode run --format json```Repowise sends the combined system + user prompt on **stdin**, parses@@ -129,8 +130,8 @@ The provider enforces several safety measures:- Model names are validated against a safe character set(`[a-zA-Z0-9][a-zA-Z0-9._/\-]*`), rejecting shell metacharactersbefore anything reaches the subprocess.-- All paths are resolved with `Path.resolve()` before being passed to- `--dir`.+- All paths are resolved with `Path.resolve()` before the repo is used as+ the subprocess working directory.- Subprocess execution is serialized via `asyncio.Semaphore(1)`.- A 600-second hard timeout with process kill prevents runaway calls.diff --git a/docs/architecture/agent-platform.md b/docs/architecture/agent-platform.mdindex 10ba29e62..dc0d41f70 100644--- a/docs/architecture/agent-platform.md+++ b/docs/architecture/agent-platform.md@@ -146,7 +146,8 @@ takes a reasoning flag. The defaults offer one option, the configured model,with reasoning `auto`.`self._repo_path` holds the repo the CLI should read. Pass it with the CLI's-directory flag (opencode uses `--dir`, codex `--cd`) if the CLI has one.+directory flag (`codex` uses `--cd`) or, when the CLI has none, as the+subprocess working directory (`opencode`); `claude_cli` ignores it.### Step 2: the `ProviderSpec`diff --git a/packages/core/src/repowise/core/providers/llm/agent_cli.py b/packages/core/src/repowise/core/providers/llm/agent_cli.pyindex cd14cfea9..580660b2c 100644--- a/packages/core/src/repowise/core/providers/llm/agent_cli.py+++ b/packages/core/src/repowise/core/providers/llm/agent_cli.py@@ -173,7 +173,8 @@ class AgentCliProvider(BaseProvider):self._model = normalize_model(model, self.provider_name, self.default_model)if self._model is not None and self.validates_model_name:validate_model_name(self.provider_name, self._model)- # Where the CLI is pointed (``--cd`` / ``--dir``); claude_cli ignores it.+ # Where the CLI is pointed (``--cd`` for codex, the subprocess cwd for+ # opencode); claude_cli ignores it.self._repo_path = (Path(repo_path).resolve() if repo_path is not None else Path.cwd().resolve())diff --git a/packages/core/src/repowise/core/providers/llm/opencode.py b/packages/core/src/repowise/core/providers/llm/opencode.pyindex 384f62941..96ee28ab2 100644--- a/packages/core/src/repowise/core/providers/llm/opencode.py+++ b/packages/core/src/repowise/core/providers/llm/opencode.py@@ -12,11 +12,13 @@ subprocess, and enforces a read-only permission profile via ``OPENCODE_CONFIG_COfrom __future__ import annotations+import contextlibimport jsonimport osimport reimport subprocessimport uuid+from collections.abc import Iteratorfrom functools import lru_cache, partialfrom typing import Any@@ -222,7 +224,7 @@ class OpenCodeProvider(AgentCliProvider):model: Optional model identifier in ``provider/model`` format(e.g. ``deepseek/deepseek-v4-pro``). If omitted or``opencode/default``, opencode uses its configured default.- repo_path: Working directory passed to opencode via ``--dir``.+ repo_path: Working directory the CLI runs in (the subprocess cwd).rate_limiter: Accepted for interface consistency; the provider alsobounds its own subprocess fan-out."""@@ -239,14 +241,19 @@ class OpenCodeProvider(AgentCliProvider):def available_model_options(self) -> tuple[ProviderModelOption, ...]:return _opencode_model_options(self._executable)+ @contextlib.contextmanager+ def working_dir(self) -> Iterator[str]:+ # The repo is the subprocess cwd. OpenCode CLI v2 removed ``--dir``+ # (it fails the run with "Unrecognized flag"), and both v1 and v2+ # resolve the project from the working directory.+ yield str(self._repo_path)+def build_command(self, system_prompt: str, reasoning: ReasoningMode) -> list[str]:cmd = [self._executable,"run","--format","json",- "--dir",- str(self._repo_path),"--title",f"repowise_auto_{uuid.uuid4().hex}",]diff --git a/tests/unit/test_providers/test_agent_cli_contract.py b/tests/unit/test_providers/test_agent_cli_contract.pyindex cf538a84a..40ea7587d 100644--- a/tests/unit/test_providers/test_agent_cli_contract.py+++ b/tests/unit/test_providers/test_agent_cli_contract.py@@ -32,9 +32,12 @@ class Backend:success_stdout: Callable[[str], str]tokens: tuple[int, int, int] # parsed (input, output, cached)books_cost: bool- # Flag that points the CLI at the repo; None means a per-call scratch cwd.+ # Flag that points the CLI at the repo; None means no flag is passed.repo_flag: str | Noneenv: dict[str, str] | None # entries the subprocess env must carry+ # True when the repo is passed as the subprocess cwd (opencode, after the+ # OpenCode CLI v2 removed ``--dir``); False means a per-call scratch cwd.+ repo_cwd: bool = Falsedef _jsonl(*events: dict[str, Any]) -> str:@@ -97,8 +100,9 @@ BACKENDS = [_opencode_stdout,tokens=(80, 10, 20),books_cost=False,- repo_flag="--dir",+ repo_flag=None,env={"OPENCODE_DISABLE_PROJECT_CONFIG": "true"},+ repo_cwd=True,),]@@ -209,13 +213,16 @@ async def test_runs_against_the_repo_or_a_scratch_dir(backend, monkeypatch, tmp_await _make(backend, tmp_path).generate("sys", "user")args, cwd = calls[0]["args"], calls[0]["kwargs"]["cwd"]- if backend.repo_flag is None:+ if backend.repo_flag is not None:+ assert args[args.index(backend.repo_flag) + 1] == str(tmp_path.resolve())+ assert cwd is None+ elif backend.repo_cwd:+ # No flag: the repo travels as the subprocess cwd.+ assert cwd == str(tmp_path.resolve())+ else:# A neutral per-call directory, removed afterwards.assert cwd is not None and Path(cwd) != tmp_path.resolve()assert not Path(cwd).exists()- else:- assert args[args.index(backend.repo_flag) + 1] == str(tmp_path.resolve())- assert cwd is Noneasync def test_subprocess_env(backend, monkeypatch, tmp_path):diff --git a/tests/unit/test_providers/test_opencode_provider.py b/tests/unit/test_providers/test_opencode_provider.pyindex b3a7a79d3..dab467f90 100644--- a/tests/unit/test_providers/test_opencode_provider.py+++ b/tests/unit/test_providers/test_opencode_provider.py@@ -212,9 +212,11 @@ async def test_generate_invokes_opencode_with_stdin(monkeypatch, tmp_path):assert "system rules" in promptassert "user context" in promptargs = list(captured["args"])- assert args[:5] == [opencode_cmd, "run", "--format", "json", "--dir"]+ assert args[:4] == [opencode_cmd, "run", "--format", "json"]+ # OpenCode CLI v2 removed --dir; the repo is the subprocess cwd instead.+ assert "--dir" not in argsassert "--dangerously-skip-permissions" not in args- assert args[args.index("--dir") + 1] == str(tmp_path.resolve())+ assert captured["kwargs"]["cwd"] == str(tmp_path.resolve())assert args[args.index("--model") + 1] == "deepseek/deepseek-v4-pro"assert re.fullmatch(r"repowise_auto_[0-9a-f]{32}", args[args.index("--title") + 1])assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE@@ -242,6 +244,34 @@ async def test_generate_default_model_omits_model_flag(monkeypatch, tmp_path):assert "--model" not in args+def test_build_command_omits_dir_flag(monkeypatch, tmp_path):+ """OpenCode CLI v2 rejects ``--dir`` with "Unrecognized flag" (issue #3571)."""+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")++ cmd = OpenCodeProvider(+ model="opencode/deepseek/deepseek-v4-pro", repo_path=tmp_path+ ).build_command("sys", "auto")++ assert "--dir" not in cmd+ assert cmd[1:3] == ["run", "--format"]+++async def test_generate_runs_in_repo_path_as_cwd(monkeypatch, tmp_path):+ """The repo is passed as the subprocess cwd, since ``--dir`` is gone."""+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")+ captured: dict[str, Any] = {}++ async def fake_exec(*_args: str, **kwargs: Any) -> FakeProcess:+ captured["kwargs"] = kwargs+ return FakeProcess(stdout=_success_jsonl("OK"))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")++ assert captured["kwargs"]["cwd"] == str(tmp_path.resolve())++async def test_generate_parses_jsonl_tokens(monkeypatch, tmp_path):monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")diff --git a/website/opencode.md b/website/opencode.mdindex 72120fb36..194ff3d53 100644--- a/website/opencode.md+++ b/website/opencode.md@@ -40,10 +40,11 @@ OpenCode is detected automatically when it's on `PATH`. No API keys to store.repowise init --provider opencode --yes```-It runs:+It runs `opencode run --format json` with the repository as the working+directory:```bash-opencode run --format json --dangerously-skip-permissions --dir <repo>+cd <repo> && opencode run --format json```Repowise sends the prompt on **stdin**, parses OpenCode's **JSONL** output, and treats `opencode/*` cost as `$0.00`.