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.

feat(agents): wire OpenCode as a fifth agent target (#1459)

Raghav Chamadiya73c82764c855
diff --git a/README.md b/README.md
index 550d4c145..d7e23e9d1 100644
--- a/README.md
+++ b/README.md
@@ -368,7 +368,7 @@ Set Up This Repository**. Guide: **[docs/agent/VSCODE.md →](docs/agent/VSCODE.
## Supported agents
-**Four agents wired end to end · two at the Full tier · every other MCP host one
+**Five agents wired end to end · two at the Full tier · every other MCP host one
paste away.**
<p>
@@ -380,6 +380,7 @@ paste away.**
<strong>Good tier &nbsp;</strong>
<img src="https://img.shields.io/badge/VS_Code-007ACC?style=flat-square&logo=visualstudiocode&logoColor=white" alt="VS Code" />
<img src="https://img.shields.io/badge/Cursor-000000?style=flat-square&logo=cursor&logoColor=white" alt="Cursor" />
+ <img src="https://img.shields.io/badge/OpenCode-000000?style=flat-square&logo=opencode&logoColor=white" alt="OpenCode" />
</p>
**Full** is every surface repowise has: MCP tools, skills, slash commands, a managed
diff --git a/docs/agent/CODEX.md b/docs/agent/CODEX.md
index b1c8a7b7e..f8a5fd07d 100644
--- a/docs/agent/CODEX.md
+++ b/docs/agent/CODEX.md
@@ -128,6 +128,8 @@ Note this is the mirror image of Claude Code, where the commands come from the p
`repowise init --codex` generates a managed `AGENTS.md` by default. `repowise update` refreshes it when `editor_files.agents_md` is enabled, or when `--agents` is passed. The Repowise section is bounded by managed markers and user content outside the markers is preserved.
+`AGENTS.md` is a host-neutral convention rather than a Codex-only file: [OpenCode](OPENCODE.md) reads the same path and manages the same section. Both writing it is safe, because the section is idempotent. Removing one of the two agents while the other is still wired leaves the section in place and reports that it did, so the agent still using it does not silently lose its instructions.
+
Controls:
```bash
diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.md
index 2a3ada540..7fcf67be1 100644
--- a/docs/agent/INTEGRATIONS.md
+++ b/docs/agent/INTEGRATIONS.md
@@ -29,12 +29,13 @@ for that agent.
| [Codex CLI](https://developers.openai.com/codex/cli) | Full | Yes | Yes | Plugin | Yes | Yes | Yes |
| [VS Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) | Good | Yes | No | No | No | No | No |
| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | No | No | No | Yes | No |
+| [OpenCode](https://opencode.ai/docs/mcp-servers/) | Good | Yes | No | No | No | Yes | No |
-Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`.
+Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`, `opencode`.
### What Good tier does not include
-VS Code and Cursor sit at Good, and the honest version of that is worth stating
+VS Code, Cursor and OpenCode sit at Good, and the honest version of that is worth stating
plainly. These agents get the MCP tools and the config repowise writes.
They do **not** get hook-level interception: repowise never sees a tool
call before it runs, never rewrites a noisy command, and never annotates
@@ -57,12 +58,13 @@ repowise agents print-config claude-code # prints, writes nothing
Ask for the target id whose host is closest to yours rather than editing a
snippet by hand. The shapes genuinely differ, and not only in their wrapper:
hosts disagree about the top-level key, about whether each entry carries a
-`type` field, and about the file format itself, so `codex` prints TOML where
-the others print JSON. `claude-code` is the plain `mcpServers` JSON most hosts
-read and is the right default when yours is not listed below. Hosts people ask
-about most, none of which repowise writes config for today:
+`type` field, about whether the invocation is one array or a command plus a
+separate argument list, and about the file format itself, so `codex` prints
+TOML where the others print JSON. `claude-code` is the plain `mcpServers` JSON
+most hosts read and is the right default when yours is not listed below.
+Hosts people ask about most, none of which repowise writes config for today:
-Cline, Windsurf, Zed, Continue, Gemini CLI, OpenCode, JetBrains AI Assistant, Amp.
+Cline, Windsurf, Zed, Continue, Gemini CLI, JetBrains AI Assistant, Amp.
`print-config` takes one of the target ids above; there is no descriptor to
name for a host at this tier, which is the point of the tier.
diff --git a/docs/agent/OPENCODE.md b/docs/agent/OPENCODE.md
index 22ae3aa06..13774ca80 100644
--- a/docs/agent/OPENCODE.md
+++ b/docs/agent/OPENCODE.md
@@ -1,9 +1,45 @@
# OpenCode Integration
-Repowise supports OpenCode via the `opencode` LLM provider, which runs
-documentation generation through your local OpenCode CLI installation.
-No API keys are managed by repowise — OpenCode handles all authentication
-and model selection through its own provider system.
+Repowise and OpenCode connect in **two independent directions**, and it is worth
+knowing which one you want before reading further. They share nothing but a name.
+
+| Direction | What it is | Where to read |
+|---|---|---|
+| Repowise calls OpenCode | The `opencode` **LLM provider**. Repowise runs your local OpenCode CLI to generate wiki pages, instead of using an API key. | [`opencode` Provider](#opencode-provider) below |
+| OpenCode calls Repowise | The `opencode` **agent target**. OpenCode gets the repowise MCP tools, so you can ask it about your codebase. | [OpenCode as an MCP host](#opencode-as-an-mcp-host) below |
+
+You can use either, both, or neither. Enabling one does not enable the other.
+
+## OpenCode as an MCP host
+
+```bash
+repowise agents add --target=opencode
+```
+
+This registers the repowise MCP server under the `mcp` key of your
+`opencode.jsonc` (or an existing `opencode.json`) and adds a managed section to
+`AGENTS.md`. By default it writes both the repo-local pair at the repo root and
+the per-machine pair under `$XDG_CONFIG_HOME/opencode`, falling back to
+`~/.config/opencode`; pass `--scope=project` or `--scope=user` for one of them.
+That config path is the same on Windows, where OpenCode does not read
+`%APPDATA%`.
+
+OpenCode is at the **Good** tier: it gets the MCP tools and the config to reach
+them, but no hook-level interception and no transcript mining. See the
+[support matrix](INTEGRATIONS.md) for what that means in full.
+
+Two things worth knowing:
+
+- **Comments in the config are safe.** OpenCode accepts JSONC, and repowise does
+ not rewrite a config it cannot parse as strict JSON. If yours has comments,
+ `repowise agents add` leaves it alone and tells you to run
+ `repowise agents print-config opencode` and paste the entry yourself.
+- **`AGENTS.md` is shared with Codex.** Both agents read the same file, and both
+ manage the same marker-delimited section of it. Removing one of them leaves the
+ section in place while the other is still wired, and says so.
+
+Remove it with `repowise agents remove --target=opencode`, and check it with
+`repowise agents` or `repowise doctor`.
## Prerequisites
@@ -106,7 +142,7 @@ The provider enforces several safety measures:
| Reasoning modes | Not passed (OpenCode manages it) | `model_reasoning_effort` mapping |
| Sandbox | OpenCode manages its own | `--sandbox read-only` |
| Model discovery | `opencode models` | `codex debug models --bundled` |
-| Editor integration | None | `.codex/config.toml`, hooks, plugin |
+| MCP host integration | `opencode.jsonc`, `AGENTS.md` (Good tier) | `.codex/config.toml`, hooks, plugin, prompts (Full tier) |
| API keys stored | No | No |
## Official OpenCode Docs
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index 335c88115..125a5989d 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -136,6 +136,26 @@ Cursor does not read `.vscode/mcp.json`, so this is separate from the VS Code
setup below. See [Agent integrations](../agent/INTEGRATIONS.md).
</details>
+<details><summary><b>OpenCode</b></summary>
+
+```bash
+repowise agents add --target=opencode # this repo and this machine
+repowise agents add --target=opencode --scope=project # this repo only
+```
+
+Writes `opencode.jsonc` (or an existing `opencode.json`) and a managed section in
+`AGENTS.md`, in both scopes by default. The repo-local pair sits at the repo root;
+the per-machine pair goes to `$XDG_CONFIG_HOME/opencode`, falling back to
+`~/.config/opencode`. That path is the same on Windows: OpenCode does not read
+`%APPDATA%`. The repo-local entry names its repo outright, while the per-machine one
+resolves whichever repo OpenCode was launched in.
+
+OpenCode accepts comments in its config. Repowise does not rewrite a file it cannot
+parse as strict JSON, so if yours has comments it prints the entry to paste instead:
+`repowise agents print-config opencode`. See
+[Agent integrations](../agent/INTEGRATIONS.md).
+</details>
+
<details><summary><b>Cline, Windsurf, and other MCP clients</b></summary>
Print the server entry and paste it into whatever config the host reads:
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
index 994ffc7f4..de7e45c3b 100644
--- a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py
@@ -84,12 +84,22 @@ def is_damaged(config_path: Path) -> bool:
False for a file that is absent or that cannot be opened at all: neither is
damage we can claim to have seen.
+
+ A file that is not UTF-8 counts as damage. It is present, it was opened,
+ and it is not readable JSON, which is exactly what this answers. It used to
+ escape instead: ``UnicodeDecodeError`` is a ``ValueError``, so neither
+ handler below caught it, and both callers run this inside ``doctor()``. The
+ result was not a crash -- ``repo_checks`` catches a raising ``doctor()`` --
+ but something quieter and worse: a cp1252 ``settings.json`` or
+ ``hooks.json``, an ordinary thing to meet on Windows, rendered as a
+ **passing** "Could not check" row, so the one file state this check exists
+ to report was the one state it could not report.
"""
if not config_path.exists():
return False
try:
json.loads(config_path.read_text(encoding="utf-8"))
- except json.JSONDecodeError:
+ except (json.JSONDecodeError, UnicodeDecodeError):
return True
except OSError:
return False
diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/server_entry.py b/packages/cli/src/repowise/cli/agent_targets/formats/server_entry.py
new file mode 100644
index 000000000..ce4bb0449
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/formats/server_entry.py
@@ -0,0 +1,52 @@
+"""Whether a stored MCP server entry is one repowise can safely repoint.
+
+One rule, shared, because getting it wrong has now produced the same bug in
+three different config files. Every host that writes MCP servers as JSON
+supports a local transport (a command repowise launches) and a remote one (a
+URL someone else hosts), and repowise only ever writes the local kind.
+
+The trap is that the merge helper is *careful*. It lets generated keys win and
+keeps every other key the user added, which is right for ``command`` and
+``args`` and for an ``env`` block carrying provider keys. Against a hand-wired
+remote server it is exactly wrong: it forces ``type`` back to the local value
+while faithfully preserving the ``url`` beside it, producing an entry that is
+neither a valid local server nor a valid remote one. **The preservation rule is
+what makes the result broken rather than merely overwritten**, and a
+schema-validated config can reject the whole file over the stray key rather
+than just the one entry.
+
+So a remote entry is left alone and said so. It is a deliberate choice repowise
+did not make, and converting it in place is not a conversion.
+"""
+
+from __future__ import annotations
+
+
+class RemoteServerEntryError(ValueError):
+ """The stored entry names a transport repowise did not write.
+
+ A ``ValueError`` so it lands in the same handler as an unparseable file, and
+ a distinct type so the caller can say which of the two happened. Both mean
+ "left alone"; only one of them is a broken file.
+ """
+
+
+def is_remote_entry(entry: dict, *, local_type: str) -> bool:
+ """Whether *entry* describes a transport repowise did not write.
+
+ *local_type* is the host's spelling of "a command we launch", because the
+ hosts disagree: VS Code and Cursor say ``stdio``, OpenCode says ``local``.
+ Passing it in rather than accepting any of them keeps a config that names
+ another host's word for it from being silently treated as ours.
+
+ **The entry's own declared type decides.** A bare ``url`` counts only when
+ there is no ``command`` beside it: reading ``"url" in entry`` first, ahead
+ of the declared type, calls ``{"type": "stdio", "command": ..., "url": ...}``
+ remote in contradiction of what the entry says about itself. That shape is
+ the ordinary stale state ``agents add`` exists to repoint, and treating it
+ as remote wedges it shut against every command that could have fixed it.
+ """
+ declared = entry.get("type")
+ if declared is not None:
+ return declared != local_type
+ return "url" in entry and "command" not in entry
diff --git a/packages/cli/src/repowise/cli/agent_targets/registry.py b/packages/cli/src/repowise/cli/agent_targets/registry.py
index d83175988..6dc85b869 100644
--- a/packages/cli/src/repowise/cli/agent_targets/registry.py
+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py
@@ -18,9 +18,12 @@ ids *are* the registry keys, so there is nothing to synchronise.
from __future__ import annotations
import importlib
+from collections.abc import Iterable
+from contextlib import contextmanager
+from contextvars import ContextVar
from pathlib import Path
-from .types import AgentTarget, InstallMethod, Registration, Tier, derive_tier
+from .types import AgentTarget, InstallMethod, Registration, Scope, Tier, derive_tier
#: Every known target, by id. Values are ``module:attribute`` so registration
#: costs no import.
@@ -29,6 +32,7 @@ _TARGET_MODULES: dict[str, str] = {
"codex": "repowise.cli.agent_targets.targets.codex:TARGET",
"vscode": "repowise.cli.agent_targets.targets.vscode:TARGET",
"cursor": "repowise.cli.agent_targets.targets.cursor:TARGET",
+ "opencode": "repowise.cli.agent_targets.targets.opencode:TARGET",
}
#: Resolved when :meth:`resolve_target_flag` is asked for ``auto`` and nothing
@@ -179,6 +183,100 @@ def select_install_method(
return writable[0] if writable else None
+#: Ids being removed by the command currently running, so a shared file is not
+#: kept on behalf of an agent the same invocation is also removing.
+#:
+#: A context variable rather than a parameter on
+#: :meth:`~.types.AgentTarget.uninstall` because the fact belongs to the *run*,
+#: not to the target: a descriptor is asked to remove itself and has no business
+#: knowing what else the user asked for. Adding it to the Protocol would put a
+#: batch concern into the contract every future target has to implement.
+_REMOVING: ContextVar[frozenset[str]] = ContextVar("_REMOVING", default=frozenset())
+
+
+@contextmanager
+def removing(target_ids: Iterable[str]):
+ """Declare which targets the current command is removing.
+
+ Set by ``agents remove`` and ``doctor --repair`` around the whole batch.
+ Without it, ``agents remove --target=all`` deadlocks on any file two agents
+ share: each target's uninstall sees the other still wired -- it has not been
+ processed yet, or its own config is not what detection keys on -- and keeps
+ the shared block on its behalf, so both keep it and the user is told twice
+ to remove an agent they just removed.
+ """
+ token = _REMOVING.set(frozenset(target_ids))
+ try:
+ yield
+ finally:
+ _REMOVING.reset(token)
+
+
+def other_managers_of(
+ config_path: Path,
+ *,
+ exclude: str,
+ scope: Scope,
+ repo_path: Path | None = None,
+) -> list[str]:
+ """Display names of other **wired** targets that also manage *config_path*.
+
+ Some files are a host-neutral convention rather than one agent's private
+ config. ``AGENTS.md`` is the case that forced this: Codex reads it, OpenCode
+ reads it, and both descriptors legitimately manage the same path in the same
+ repo. Install is unaffected, because the managed block is marker-delimited
+ and idempotent, so the second writer reports ``unchanged``. **Uninstall is
+ not.** Removing one of the two agents stripped the block out from under the
+ other, which stayed wired and silently lost its instructions, and nothing in
+ the output said so.
+
+ So a target about to remove a shared file asks who else is still using it.
+ Only *wired* targets count: a descriptor that merely knows about the path is
+ not a reason to leave a block behind, and every target claims paths it has
+ never written. Targets the current command is itself removing do not count
+ either -- see :func:`removing`.
+
+ Deliberately built out of :meth:`~.types.AgentTarget.detect` and
+ :meth:`~.types.AgentTarget.describe_paths`, both of which already exist and
+ already mean exactly this. An ``owns_path`` method on the Protocol would be
+ a third thing to keep in agreement with the two that already answer the
+ question.
+
+ Paths are compared resolved, so ``AGENTS.md`` reached through a symlinked
+ or differently-cased repo root still matches. Best-effort per target, by the
+ same contract detection has everywhere else: a descriptor whose probe raises
+ is treated as not using the file rather than taking an uninstall down.
+ """
+ try:
+ wanted = config_path.resolve()
+ except OSError:
+ wanted = config_path
+
+ ignored = _REMOVING.get() | {exclude}
+ owners: list[str] = []
+ for target_id in _TARGET_MODULES:
+ if target_id in ignored:
+ continue
+ target = get_target(target_id)
+ if target is None:
+ continue
+ try:
+ if not any(r.scope is scope for r in target.detect(repo_path)):
+ continue
+ claimed = target.describe_paths(scope, repo_path=repo_path)
+ except Exception:
+ continue
+ for raw in claimed:
+ try:
+ candidate = Path(raw).resolve()
+ except OSError:
+ candidate = Path(raw)
+ if candidate == wanted:
+ owners.append(target.display_name)
+ break
+ return owners
+
+
def resolve_target_flag(value: str, repo_path: Path | None = None) -> list[AgentTarget]:
"""Resolve a ``--target=`` value to targets.
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index 38fcf3e4f..fa2ae3bbf 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -578,6 +578,31 @@ class CodexTarget:
if repo_path is None:
raise ValueError("project-scope uninstall needs a repo_path")
instructions = instructions_path(repo_path)
+
+ from ..formats.marker_block import BlockState, inspect
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+ from ..registry import other_managers_of
+
+ # ``AGENTS.md`` is a host-neutral convention, not this target's private
+ # file: OpenCode reads the same path in the same repo and manages the
+ # same marker block. Stripping it while that agent is still wired leaves
+ # it configured and silently without its instructions, so the block
+ # stays and the caller is told which agent is still reading it.
+ #
+ # This guard arrived with OpenCode and belongs here just as much. A
+ # shared-ownership fix applied only to the agent added most recently
+ # leaves the identical bug in its sibling, which is how this class of
+ # defect has kept surviving a review round on this track.
+ owners = other_managers_of(instructions, exclude=ID, scope=scope, repo_path=repo_path)
+ block_state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ if owners and block_state is BlockState.PRESENT:
+ result.record(instructions, FileAction.KEPT)
+ result.note(
+ f"{instructions} kept: {' and '.join(owners)} still reads the same "
+ "managed block. Remove that agent too if you want the block gone."
+ )
+ return result
+
if remove_agents_md_distill_section(repo_path):
result.record(instructions, FileAction.REMOVED)
return result
@@ -586,10 +611,9 @@ class CodexTarget:
# them all as not-found says "there was nothing of ours here" about a
# file we deliberately declined to touch. Same distinction the Cursor
# rules file draws, and it matters more here: AGENTS.md is a file users
- # write in, so "left alone" is the common answer.
- from ..formats.marker_block import BlockState, inspect
- from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
-
+ # write in, so "left alone" is the common answer. Re-inspected rather
+ # than reusing ``block_state``: the removal above runs in between and
+ # the whole question here is what the file looks like after it.
state = inspect(instructions, DISTILL_MARKER_START, DISTILL_MARKER_END).state
result.record(
instructions,
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
new file mode 100644
index 000000000..130578800
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
@@ -0,0 +1,775 @@
+"""OpenCode as an agent target.
+
+Good tier, structurally: it names neither a hook adapter nor a transcript
+adapter, so :func:`derive_tier` cannot place it at Full however many files it
+writes. OpenCode exposes no hook protocol repowise can intercept tool calls
+through, and no transcript format to mine.
+
+**This is not the ``opencode`` LLM provider.** repowise has shipped one of those
+since well before this target: ``core.providers.llm.opencode`` shells out to the
+same binary to *generate* wiki pages. That is repowise calling OpenCode. This
+module is the opposite direction, OpenCode calling repowise, and the two share
+nothing but a name. ``docs/agent/OPENCODE.md`` covers both and says which is
+which.
+
+Three host facts this target is built on, each checked against OpenCode's own
+documentation on 2026-08-12 rather than inherited from any prior reading:
+
+* **The config key is ``mcp``, not ``mcpServers``**, and the per-server value is
+ ``{"type": "local", "command": [...]}`` where ``command`` is a *single array*
+ combining the binary and its arguments. Every other JSON host repowise writes
+ for splits those into ``command`` and ``args``, so the shape here is the one
+ most likely to be "made consistent" with its neighbours and thereby broken.
+* **The user config directory is XDG on every platform, Windows included**:
+ ``XDG_CONFIG_HOME`` when it is set and not blank, otherwise ``~/.config``,
+ then ``opencode``. Never ``%APPDATA%``. Confirmed on this machine, which is
+ the strongest form of the check available: OpenCode 1.18.15 created
+ ``C:\\Users\\<user>\\.config\\opencode\\opencode.jsonc`` on Windows with
+ ``XDG_CONFIG_HOME`` unset.
+* **``AGENTS.md`` is its instructions file**, at the repo root and at
+ ``<config dir>/AGENTS.md``. That is the same file Codex reads, which is a
+ design problem rather than a coincidence. See :func:`_remove_instructions`.
+
+**The config file may legitimately contain comments and repowise declines to
+rewrite one that does.** OpenCode accepts JSONC, and repowise ships no
+comment-preserving JSON parser. Adding a dependency to this codebase to write
+one host's config file is not a trade worth making, and the alternative that
+needs no dependency is worse than declining: parsing a commented file with
+comments stripped and re-serialising it deletes every comment the user wrote.
+So an unparseable file is left exactly as it is, and the note names
+``print-config`` so the user can paste the entry in themselves. This matches
+what ``vscode.py`` and ``cursor.py`` already do for the same reason.
+
+**New files are created as ``opencode.jsonc``**, matching what OpenCode itself
+creates on first run, with an existing ``.jsonc`` preferred over an existing
+``.json``. The extension is not what decides whether repowise can read a file --
+a ``.jsonc`` holding plain JSON parses fine and is the common case -- so
+choosing ``.json`` to advertise our own limitation would buy nothing and risks
+the genuinely bad outcome, which is two config files in one directory where the
+host reads whichever it prefers and repowise writes the other.
+
+Both spellings are swept by detection and removal, and writes follow whichever
+one already holds the entry (:func:`write_target_path`). Those three have to
+agree. When they did not, an install that had landed in ``opencode.json``
+stayed detected there once a ``.jsonc`` appeared beside it, and ``refresh``
+wrote a second entry into the other file rather than skipping a scope it had
+been told was already wired.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from ..formats.server_entry import RemoteServerEntryError
+from ..types import (
+ Capability,
+ DoctorReport,
+ DoctorStatus,
+ FileAction,
+ FileWrite,
+ InstallMethod,
+ Registration,
+ Scope,
+ WriteResult,
+)
+
+ID = "opencode"
+DISPLAY_NAME = "OpenCode"
+DOCS_URL = "https://opencode.ai/docs/mcp-servers/"
+
+#: Config key gating this agent's managed instruction file. Deliberately the
+#: same id Codex uses, because it is the same file: one ``AGENTS.md`` per repo,
+#: so one switch that turns it on and off rather than two that disagree.
+PROJECT_FILE_ID = "agents_md"
+
+#: Name of the server entry inside the ``mcp`` table.
+SERVER_NAME = "repowise"
+
+#: Both spellings OpenCode reads, in the order :func:`config_path` prefers them.
+#: Uninstall and detection sweep the whole tuple rather than the one file
+#: :func:`config_path` picks today, because which one that is depends on what
+#: exists at the moment of the call. An entry written into ``opencode.json``
+#: before an ``opencode.jsonc`` appeared beside it would otherwise be invisible
+#: to every command that could remove it.
+CONFIG_NAMES = ("opencode.jsonc", "opencode.json")
+
+METHODS = (
+ InstallMethod(
+ id="direct",
+ provides=frozenset({Capability.MCP, Capability.INSTRUCTIONS}),
+ managed_by="repowise",
+ preferred=True,
+ ),
+)
+
+
+def user_config_dir() -> Path:
+ """OpenCode's user config directory, XDG on every platform.
+
+ ``XDG_CONFIG_HOME`` wins when it is set to something that is not blank,
+ otherwise ``~/.config``. The blank check is the part that matters and the
+ part a plain truthiness test misses: an exported-but-empty
+ ``XDG_CONFIG_HOME`` is common in trimmed CI images and in shell profiles
+ that build the value conditionally, and treating ``""`` as a real prefix
+ resolves the config directory to ``/opencode`` at the filesystem root.
+ Whitespace-only gets the same treatment for the same reason.
+
+ The **stripped** value is what gets joined. Surrounding whitespace on this
+ variable comes from the same sloppy profile line that produces the blank
+ value above, and leaving it in is worse than blank rather than merely
+ untidy: ``Path(" /home/u/.config")`` is a *relative* path, so the config
+ would be written into a directory named ``" "`` inside whatever repo the
+ user happened to be standing in, and read back from somewhere else on the
+ next call from a different working directory.
+
+ There is deliberately **no Windows branch**. The absence is the feature:
+ ``%APPDATA%\\opencode`` is where this would land if it followed the platform
+ convention, OpenCode has never read that location, and an entry written
+ there is invisible rather than broken, which is the harder bug to see.
+ """
+ configured = (os.environ.get("XDG_CONFIG_HOME") or "").strip()
+ if configured:
+ return Path(configured) / "opencode"
+ return Path.home() / ".config" / "opencode"
+
+
+def config_dir(scope: Scope, repo_path: Path | None = None) -> Path:
+ """Where this scope's ``opencode.json{,c}`` and ``AGENTS.md`` live."""
+ if scope is Scope.USER:
+ return user_config_dir()
+ if repo_path is None:
+ raise ValueError("project scope needs a repo_path")
+ return repo_path
+
+
+def config_path(scope: Scope, repo_path: Path | None = None) -> Path:
+ """The config file to read and write for *scope*.
+
+ An existing ``.jsonc`` wins, then an existing ``.json``, then ``.jsonc`` for
+ a file that does not exist yet. Pure existence, in that order: there is no
+ merge across the two, because OpenCode's own precedence between them is not
+ something repowise should be guessing at, and writing to the one the host
+ does not read is the failure this ordering exists to avoid.
+
+ **This answers "where should a write go", and only that.** Removal and
+ detection use :func:`config_paths` instead, because the answer here depends
+ on what exists at the moment of the call and that can change between an
+ install and the uninstall that undoes it.
+ """
+ directory = config_dir(scope, repo_path)
+ for name in CONFIG_NAMES:
+ candidate = directory / name
+ if candidate.exists():
+ return candidate
+ return directory / CONFIG_NAMES[0]
+
+
+def config_paths(scope: Scope, repo_path: Path | None = None) -> list[Path]:
+ """Every file this target may have written an entry into, preferred first.
+
+ Removal and detection sweep all of them rather than trusting
+ :func:`config_path`. The failure that forces this is ordinary: install into
+ a repo that has only ``opencode.json`` writes there, OpenCode later creates
+ an ``opencode.jsonc`` beside it, and from then on ``config_path`` answers
+ ``.jsonc``. Uninstall would report success against the empty new file while
+ the real registration sat in the old one, invisible to ``detect`` and so
+ unreachable by every command that could have removed it.
+ """
+ directory = config_dir(scope, repo_path)
+ return [directory / name for name in CONFIG_NAMES]
+
+
+def write_target_path(scope: Scope, repo_path: Path | None = None) -> Path:
+ """Where an install should write: the file already holding our entry, else the preferred one.
+
+ Detection sweeps both spellings and writing did not, which is worse than
+ either rule on its own. An install that had landed in ``opencode.json``
+ stayed *detected* there after an ``opencode.jsonc`` appeared beside it, so
+ ``agents refresh`` no longer skipped the scope as unwired -- and then wrote
+ a **second** repowise entry into the other file. ``doctor --repair`` routes
+ through the same refresh, so it did it too, and the result renders as
+ "configured x2" under a warning that an agent wired twice loads repowise
+ twice. Refresh is contracted to add nothing, so creating a registration is
+ the one thing it must not do.
+
+ Following the entry also makes re-running idempotent whichever file holds
+ it, which is what an install should be.
+ """
+ for candidate in config_paths(scope, repo_path):
+ if candidate.exists() and _reads_repowise(candidate):
+ return candidate
+ return config_path(scope, repo_path)
+
+
+def instructions_path(scope: Scope, repo_path: Path | None = None) -> Path:
+ """``AGENTS.md`` for *scope*. Shared with Codex at project scope."""
+ return config_dir(scope, repo_path) / "AGENTS.md"
+
+
+def server_entry(scope: Scope, repo_path: Path | None = None) -> dict:
+ """The ``mcp.repowise`` entry, in OpenCode's shape.
+
+ Two differences from every other JSON host, both load-bearing:
+
+ * ``command`` is one array. The shared generator returns a binary and an
+ argument list, so they are concatenated here rather than passed through.
+ * The generator's ``description`` is dropped. OpenCode's config is
+ ``$schema``-validated and its MCP entry documents ``type``, ``command``,
+ ``enabled`` and ``environment``; a key outside that set buys nothing and
+ is the sort of thing a strict validator rejects.
+
+ Scope decides the invocation, following the rule the whole codebase uses. A
+ project ``opencode.json`` is committed, so it carries the bare ``repowise``
+ command and names its repo by absolute path. The user file is per machine
+ and serves every workspace, so it pins the absolute binary of the install
+ that wrote it -- a PATH shadow cannot hijack it -- and passes **no** repo
+ path, letting the server resolve the repo it was launched in. That bare
+ ``repowise mcp`` form is not novel: it is what ``.mcp.json``, the README and
+ both plugins have always emitted.
+ """
+ from repowise.cli.mcp_config import generate_mcp_config, resolve_repowise_command
+
+ if scope is Scope.USER:
+ binary = resolve_repowise_command()
+ return {"type": "local", "command": [binary, "mcp", "--transport", "stdio"]}
+
+ if repo_path is None:
+ raise ValueError("project scope needs a repo_path")
+ generated = generate_mcp_config(repo_path)["mcpServers"]["repowise"]
+ return {
+ "type": "local",
+ "command": [generated["command"], *generated["args"]],
+ }
+
+
+#: OpenCode's spelling of "a command we launch". Its remote servers are
+#: ``type: "remote"`` and carry a ``url`` instead.
+LOCAL_TYPE = "local"
+
+
+def _merge_entry(stored: object, generated: dict) -> dict:
+ """Overlay *generated* onto whatever the user already had.
+
+ Same rule as ``merge_server_entries``: generated keys win so a moved install
+ or a renamed repo takes effect, and every other key the user added -- an
+ ``environment`` block carrying provider keys, most importantly -- survives.
+
+ ``enabled`` is the one exception and it runs the other way. It is not a
+ field repowise computes, it is a switch the user flips, and ``false`` is the
+ documented way to park a server without deleting it. Forcing it back to
+ ``true`` would mean ``agents refresh`` and ``doctor --repair`` silently
+ re-enable something that was turned off on purpose, which is the same
+ class of bug as overwriting ``env``. So it is seeded as ``true`` on an entry
+ repowise is creating and left strictly alone on one that already has it.
+ """
+ if not isinstance(stored, dict):
+ return {**generated, "enabled": True}
+ merged = dict(stored)
+ merged.update(generated)
+ if "enabled" not in merged:
+ merged["enabled"] = True
+ return merged
+
+
+def write_mcp_config(scope: Scope, repo_path: Path | None = None) -> FileWrite:
+ """Merge the repowise server into ``opencode.json{,c}``.
+
+ Raises ``ValueError`` when the file is not strict JSON so the caller can
+ skip it. See the module docstring for why declining beats every available
+ alternative here.
+ """
+ from ..formats.json_merge import (
+ load_json_object_or_value_error,
+ write_json_config,
+ )
+ from ..formats.server_entry import is_remote_entry
+
+ path = write_target_path(scope, repo_path)
+ generated = server_entry(scope, repo_path)
+
+ if path.exists():
+ existing = load_json_object_or_value_error(path, path.name)
+ servers = existing.get("mcp", {})
+ if not isinstance(servers, dict):
+ raise ValueError(f"{path.name} 'mcp' must be a JSON object")
+ servers = dict(servers)
+ stored = servers.get(SERVER_NAME)
+ if isinstance(stored, dict) and is_remote_entry(stored, local_type=LOCAL_TYPE):
+ # See ``formats.server_entry``. This config is ``$schema``-validated,
+ # so the stray key a half-conversion leaves behind can cost the whole
+ # file rather than the one entry.
+ raise RemoteServerEntryError(f"{path.name} 'repowise' is wired to a remote server")
+ servers[SERVER_NAME] = _merge_entry(stored, generated)
+ existing["mcp"] = servers
+ merged = existing
+ else:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ # No ``$schema`` seeded here, deliberately. It would be a nice courtesy
+ # and it costs more than it gives: OpenCode's own first-run file is
+ # exactly ``{"$schema": "..."}`` and nothing else, so a file holding
+ # only that is far more likely to be the host's than ours. Writing one
+ # leaves uninstall no way to tell "a stub we created" from "the config
+ # the user already had", and the safe reading of that ambiguity is the
+ # one that never deletes. Without it, a file repowise created holds only
+ # ``mcp`` and empties to nothing, which is unambiguous.
+ merged = {"mcp": {SERVER_NAME: {**generated, "enabled": True}}}
+
+ return FileWrite(path=path, action=write_json_config(path, merged))
+
+
+def write_instructions(scope: Scope, repo_path: Path | None = None) -> FileWrite:
+ """Upsert the managed block into ``AGENTS.md``.
+
+ The body comes from :mod:`..instructions`, which is the one home for it.
+ Unlike Cursor's rules file this is a document the user owns and may already
+ have written in, so there is no ``new_file_prefix`` and no ``delete_if_only``
+ -- an ``AGENTS.md`` repowise created still belongs to the repo afterwards,
+ and Codex, which has managed this same file since long before this target,
+ does not delete it either.
+ """
+ from ..formats import marker_block
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START, DISTILL_SECTION
+
+ path = instructions_path(scope, repo_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ action = marker_block.upsert(
+ path,
+ f"\n{DISTILL_SECTION}\n",
+ DISTILL_MARKER_START,
+ DISTILL_MARKER_END,
+ )
+ return FileWrite(path=path, action=action)
+
+
+def _remove_server_entry(path: Path) -> tuple[Path, FileAction]:
+ """Drop ``mcp.repowise``, preserving sibling servers.
+
+ Rounds the install trip back to nothing: the ``mcp`` wrapper goes once it is
+ empty, and the file goes once *it* is empty, so a file repowise created
+ leaves no stub behind.
+
+ "Empty" means empty, not "holds nothing we recognise". An earlier version
+ also deleted a file holding just ``{"$schema": "..."}`` on the grounds that
+ it was a stub of ours, which is false in the most ordinary case there is:
+ that is exactly the file OpenCode itself writes on first run. Not seeding a
+ ``$schema`` on create is what makes this test unambiguous.
+ """
+ from ..formats.json_merge import load_json_object_or_value_error, write_json_config
+
+ if not path.exists():
+ return path, FileAction.NOT_FOUND
+ try:
+ existing = load_json_object_or_value_error(path, path.name)
+ except (OSError, ValueError):
+ # Same reason install declines: rewriting a file we could not parse
+ # destroys whatever we failed to read.
+ return path, FileAction.KEPT
+
+ servers = existing.get("mcp")
+ if not isinstance(servers, dict) or SERVER_NAME not in servers:
+ return path, FileAction.NOT_FOUND
+ servers.pop(SERVER_NAME)
+
+ if not servers:
+ existing.pop("mcp", None)
+ if not existing:
+ try:
+ path.unlink()
+ except OSError:
+ # Never report REMOVED over a file that still holds our entry. A
+ # read-only bit is enough to cause this, and swallowing it turns a
+ # loud failure into a silent false success on the destructive verb.
+ # Falling through to the rewrite keeps the failure loud, from the
+ # same ``os.replace`` the write path uses.
+ write_json_config(path, existing)
+ return path, FileAction.REMOVED
+
+ write_json_config(path, existing)
+ return path, FileAction.REMOVED
+
+
+def _remove_instructions(
+ scope: Scope, repo_path: Path | None = None
+) -> tuple[Path, FileAction, list[str]]:
+ """Strip the managed block from ``AGENTS.md``, unless another agent needs it.
+
+ **The shared-file case, and it is the whole reason this function is not two
+ lines.** ``AGENTS.md`` is a host-neutral convention, not this target's
+ private config: Codex has managed the same path in the same repo since long
+ before OpenCode was wired, and both descriptors are right to claim it.
+
+ Install is unaffected -- the block is marker-delimited and idempotent, so
+ whichever agent writes second reports ``unchanged``. Uninstall is where the
+ sharing bites. Removing OpenCode from a repo that still has Codex wired
+ would strip the block out from under Codex, which stays configured, stops
+ getting its instructions, and says nothing about it. So the file is left
+ alone while another wired agent is still reading it, and the note names
+ which one, because a silent ``kept`` is the state that reads as a bug.
+
+ The same guard is in ``codex.py``. It has to be: a fix that only runs on the
+ agent added most recently leaves the identical bug sitting in its sibling,
+ which is exactly how it went unnoticed for four phases.
+
+ Returns the owners that caused a ``KEPT``, empty when something else did.
+ The caller needs that distinction rather than re-deriving it: ``KEPT`` also
+ means "the markers are malformed" and "the file could not be read", and a
+ note blaming shared ownership for one of those sends the user to remove an
+ agent that will not help.
+ """
+ from ..formats import marker_block
+ from ..formats.marker_block import BlockState
+ from ..instructions import DISTILL_MARKER_END, DISTILL_MARKER_START
+ from ..registry import other_managers_of
+
+ path = instructions_path(scope, repo_path)
+
+ state = marker_block.inspect(path, DISTILL_MARKER_START, DISTILL_MARKER_END).state
+ if state is BlockState.PRESENT:
+ owners = other_managers_of(path, exclude=ID, scope=scope, repo_path=repo_path)
+ if owners:
+ return path, FileAction.KEPT, owners
+
+ if marker_block.remove(path, DISTILL_MARKER_START, DISTILL_MARKER_END):
+ return path, FileAction.REMOVED, []
+
+ # ``remove`` returns False for several distinct reasons and they do not mean
+ # the same thing to a reader. "There was nothing of ours here" is not-found;
+ # "there is a file we deliberately did not touch" is kept. Asking
+ # ``exists()`` conflates them, and AGENTS.md is a file users write in, so
+ # "left alone" is a common and honest answer.
+ if state in (BlockState.ABSENT_FILE, BlockState.ABSENT):
+ return path, FileAction.NOT_FOUND, []
+ return path, FileAction.KEPT, []
+
+
+def _prune_user_dir() -> None:
+ """Remove ``<config>/opencode`` when a user-scope uninstall emptied it.
+
+ **Only when uninstall actually removed a file**, and only via ``rmdir``,
+ which refuses a directory holding anything. So the host's own config
+ directory survives: OpenCode keeps state in there, and a directory that
+ still has any of it in it cannot be removed by this.
+
+ An earlier round deleted this function outright, over-correcting past the
+ defect it was reacting to. That defect was the ``$schema`` file deletion,
+ and it is fixed where it lived. Removing the prune as well cost something
+ real and non-obvious: :meth:`OpenCodeTarget.is_present` reads this directory
+ as evidence the user has OpenCode, and ``install`` creates it. So an
+ ``agents add`` followed by an ``agents remove`` left an empty directory that
+ kept OpenCode pre-ticked in every later checklist and listing, on a machine
+ that had never had it. Our own residue became the reason we kept offering.
+
+ The symlink guard is the other half, and it is not theoretical. ``rmdir``
+ does refuse a non-empty *directory*, and a Windows junction is not one: it
+ is a reparse point, so ``rmdir`` unlinks it however full its target is. The
+ target survives and the link does not.
+ """
+ import contextlib
+
+ candidate = user_config_dir()
+ if candidate.is_symlink():
+ return
+ with contextlib.suppress(OSError):
+ candidate.rmdir()
+
+
+def _parses_as_strict_json(path: Path) -> bool:
+ """Whether *path* can be read as strict JSON at all.
+
+ Separate from :func:`_reads_repowise` because "we could not read it" and
+ "we read it and repowise is not in it" lead a health check to say different
+ things, and both make :func:`_reads_repowise` answer False.
+
+ Not :func:`json_merge.is_damaged`, for two reasons. It exists to answer "is
+ this file damaged", which for a host that accepts JSONC is the wrong
+ question. And it lets ``UnicodeDecodeError`` escape: that is a ``ValueError``
+ rather than an ``OSError`` or a ``JSONDecodeError``, so neither of its
+ handlers catches it.
+ """
+ try:
+ json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ return True
+
+
+def _reads_repowise(path: Path) -> bool:
+ """Whether *path* is a config naming the repowise MCP server."""
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, ValueError):
+ # ``UnicodeDecodeError`` is a ``ValueError`` and not an ``OSError``, and
+ # a file we cannot decode tells us nothing either way.
+ return False
+
+ try:
+ data = json.loads(text)
+ except ValueError:
+ # The JSONC case, and answering "no" here was wrong in a way that was
+ # not obvious. This probe is what ``detect`` is built on, and
+ # ``registry.other_managers_of`` asks ``detect`` who is still using a
+ # shared file. So a user whose ``opencode.jsonc`` carries a comment --
+ # the exact user this module goes out of its way to support -- was
+ # reported as not wired, and removing *Codex* then stripped the managed
+ # AGENTS.md block out from under a fully working OpenCode, silently and
+ # with no note. That is the failure the ownership guard exists to
+ # prevent, reached through the front door.
+ #
+ # So a commented file gets a text probe rather than a verdict of "no".
+ # It is the same shape ``codex.py`` uses on its TOML, and the error
+ # asymmetry is what justifies it: a false positive costs an
+ # ``agents add`` that declines and prints the entry to paste, while a
+ # false negative deletes instructions from an agent that is working.
+ return f'"{SERVER_NAME}"' in text and '"mcp"' in text
+
+ servers = data.get("mcp") if isinstance(data, dict) else None
+ return isinstance(servers, dict) and SERVER_NAME in servers
+
+
+def detect(repo_path: Path | None = None) -> list[Registration]:
+ """Every place OpenCode is currently wired to repowise.
+
+ Both scopes, matching what this target writes, and both config spellings
+ within each scope: an entry written into ``opencode.json`` stays findable
+ after an ``opencode.jsonc`` appears beside it, which is what makes it
+ removable. Contracted never to raise.
+ """
+ found: list[Registration] = []
+
+ scopes: list[tuple[Scope, Path | None]] = [(Scope.USER, None)]
+ if repo_path is not None:
+ scopes.append((Scope.PROJECT, repo_path))
+
+ for scope, repo in scopes:
+ for candidate in config_paths(scope, repo):
+ if candidate.exists() and _reads_repowise(candidate):
+ found.append(Registration(method="direct", scope=scope, config_path=candidate))
+
+ return found
+
+
+class OpenCodeTarget:
+ """Descriptor for OpenCode. See the module docstring."""
+
+ id = ID
+ display_name = DISPLAY_NAME
+ docs_url = DOCS_URL
+ hook_adapter = None
+ session_adapter = None
+ methods = METHODS
+ project_file_id = PROJECT_FILE_ID
+
+ def supports_scope(self, scope: Scope) -> bool:
+ """Both. The user config serves every workspace, the project one is committed."""
+ return True
+
+ def is_present(self, repo_path: Path | None = None) -> bool:
+ """The ``opencode`` binary on PATH, or a user config directory.
+
+ No repo-local limb, unlike Cursor and VS Code. OpenCode keeps nothing
+ repo-local of its own: its project config is a bare ``opencode.json`` at
+ the root, which this target may well have written itself, so reading it
+ as evidence the user has OpenCode would make our own output the reason
+ the agent keeps being offered.
+ """
+ import shutil
+
+ if shutil.which("opencode") is not None:
+ return True
+ return user_config_dir().is_dir()
+
+ def detect(self, repo_path: Path | None = None) -> list[Registration]:
+ return detect(repo_path)
+
+ def install(
+ self,
+ scope: Scope,
+ options: object = None,
+ *,
+ repo_path: Path | None = None,
+ ) -> WriteResult:
+ result = WriteResult()
+ if scope is Scope.PROJECT and repo_path is None:
+ raise ValueError("project-scope install needs a repo_path")
+
+ # Both writes are guarded, and neither guard is theoretical. Nothing
+ # wraps ``install`` -- ``agents add``, ``agents refresh`` and
+ # ``doctor --repair`` all call it bare -- so anything escaping here
+ # aborts the run after other agents' configs have already been written
+ # and prints a traceback in place of the summary naming them.
+ #
+ # ``OSError`` sits alongside ``ValueError`` because the read, the parent
+ # ``mkdir`` and the command resolution all live inside the guarded call.
+ # ``UnicodeDecodeError`` is a ``ValueError``, not an ``OSError``, and is
+ # the ordinary way a cp1252 config on Windows reaches this.
+ try:
+ written = write_mcp_config(scope, repo_path)
+ result.record(written.path, written.action)
+ except RemoteServerEntryError:
+ path = write_target_path(scope, repo_path)
+ result.record(path, FileAction.KEPT)
+ result.note(
+ f'{path.name} left unchanged: its "repowise" entry names a remote server, '
+ "and converting it in place would leave an entry that is neither. Run "
+ "'repowise agents remove --target=opencode' first if you want the local "
+ "server instead."
+ )
+ except (ValueError, OSError) as exc:
+ # ``write_target_path`` rather than ``config_path``: the note has to
+ # name the file the write actually aimed at, which is the one
+ # already holding our entry when there is one.
+ path = write_target_path(scope, repo_path)
+ result.record(path, FileAction.KEPT)
+ # The reason is carried rather than asserted: this guard is wide
+ # enough to catch things that are not a bad config file at all, and
+ # a note that flatly said "not valid JSON" would send the user to
+ # inspect a file that is fine. The JSONC case is the common one, so
+ # it is named alongside the command that unblocks it.
+ result.note(
+ f"{path.name} left unchanged ({exc}). OpenCode accepts comments in this "
+ "file and repowise does not rewrite one it cannot parse as strict JSON. "
+ "Run 'repowise agents print-config opencode' and paste the entry under "
+ '"mcp".'
+ )
+
+ try:
+ written = write_instructions(scope, repo_path)
+ result.record(written.path, written.action)
+ if written.action is FileAction.KEPT:
+ # The helper refuses an orphaned or duplicated marker pair
+ # rather than guessing at a repair that could swallow the
+ # user's own text, so name the file to unpick instead of
+ # reporting a write that did not happen.
+ result.note(
+ f"{instructions_path(scope, repo_path)} left unchanged: its Repowise "
+ "markers are unpaired or duplicated, or the file could not be read. "
+ "Fix it by hand and re-run."
+ )
+ except (OSError, ValueError) as exc:
+ result.record(instructions_path(scope, repo_path), FileAction.KEPT)
+ result.note(f"AGENTS.md could not be written ({exc}).")
+
+ return result
+
+ def uninstall(self, scope: Scope, *, repo_path: Path | None = None) -> WriteResult:
+ """Remove the server entry and the managed block, because install writes both."""
+ result = WriteResult()
+ if scope is Scope.PROJECT and repo_path is None:
+ raise ValueError("project-scope uninstall needs a repo_path")
+
+ # Both spellings, not just the one ``config_path`` prefers right now.
+ # A file that never held our entry costs a stat and reports nothing,
+ # except for the preferred one, which reports not-found so that removing
+ # from a repo that was never wired still names a file.
+ #
+ # ``preferred`` is resolved once, before the loop. Reading it inside
+ # would consult the filesystem after a candidate had already been
+ # deleted, so the answer could change halfway through and decide whether
+ # the *next* iteration reports anything.
+ preferred = config_path(scope, repo_path)
+ for candidate in config_paths(scope, repo_path):
+ path, action = _remove_server_entry(candidate)
+ if action is not FileAction.NOT_FOUND or path == preferred:
+ result.record(path, action)
+
+ instructions, action, owners = _remove_instructions(scope, repo_path)
+ result.record(instructions, action)
+ if owners:
+ result.note(
+ f"{instructions} kept: {' and '.join(owners)} still reads the same "
+ "managed block. Remove that agent too if you want the block gone."
+ )
+
+ if scope is Scope.USER and any(
+ written.action is FileAction.REMOVED for written in result.files
+ ):
+ _prune_user_dir()
+ return result
+
+ def print_config(self, scope: Scope, *, repo_path: Path | None = None) -> str:
+ """The entry to paste, in the shape OpenCode reads.
+
+ Project scope resolves ``repo_path`` to the cwd the same way its
+ neighbours do, so the printed absolute path is the repo the user is
+ standing in rather than a placeholder they have to notice and edit.
+ """
+ if scope is Scope.USER:
+ entry = server_entry(Scope.USER)
+ else:
+ entry = server_entry(Scope.PROJECT, repo_path or Path.cwd())
+ return json.dumps({"mcp": {SERVER_NAME: {**entry, "enabled": True}}}, indent=2)
+
+ def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
+ # ``repo_path`` is resolved for both scopes and ignored by the user one,
+ # so the fallback is unconditional rather than a branch that has to stay
+ # in step with ``config_dir``.
+ repo = repo_path or Path.cwd()
+ return [
+ str(config_path(scope, repo)),
+ str(instructions_path(scope, repo)),
+ ]
+
+ def doctor(self) -> DoctorReport:
+ """User-scope health, which is the only half a bare call can see.
+
+ ``doctor()`` takes no repo path, so the project config is out of reach
+ and reporting ``OK`` on its behalf would be a claim nothing checked.
+ Unlike Cursor and VS Code there *is* something user-level to look at, so
+ a wired user config is reported as wired and the repo-scoped half is
+ named as the part still unchecked.
+
+ **An unparseable config is never reported as BROKEN here**, which is
+ where this differs from every other target. ``BROKEN`` fails the whole
+ ``doctor`` run, and for a host that accepts JSONC by design a file
+ ``json.loads`` rejects is far more likely to be a legal config with a
+ comment in it than a damaged one. Calling that broken would fail
+ ``doctor`` -- and any CI running it -- for someone who has simply
+ installed OpenCode and never touched repowise, and then hand them a fix
+ command that declines for the same reason. It is reported as unknown
+ rather than as damage, which is what it is.
+ """
+ # Both spellings, like detection and removal. Reading only the file
+ # ``config_path`` prefers made this contradict ``repowise agents``: an
+ # entry in ``opencode.json`` with a ``.jsonc`` beside it showed as wired
+ # in the listing and not-installed here, and the fix command printed
+ # here then wrote a second entry into the other file.
+ candidates = config_paths(Scope.USER)
+ if any(path.exists() and _reads_repowise(path) for path in candidates):
+ return DoctorReport(target_id=ID, status=DoctorStatus.OK)
+
+ unreadable = [
+ path for path in candidates if path.exists() and not _parses_as_strict_json(path)
+ ]
+ if unreadable:
+ user_config = unreadable[0]
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.NOT_INSTALLED,
+ issues=(
+ f"{user_config} could not be read as strict JSON, so whether repowise "
+ "is registered in it is unknown. Comments are legal in this file; if "
+ "yours has them, add the entry with "
+ "'repowise agents print-config opencode'.",
+ ),
+ # No ``repairable=False`` here, deliberately: ``repo_checks``
+ # returns before reading it for a ``not-installed`` row, so
+ # setting it would read as load-bearing while doing nothing.
+ # The advice that matters is in the issue text above, which is
+ # what that row actually prints.
+ fix_command="repowise agents print-config opencode",
+ )
+
+ return DoctorReport(
+ target_id=ID,
+ status=DoctorStatus.NOT_INSTALLED,
+ issues=(
+ "OpenCode is not wired at user scope; workspace wiring is repo-local, "
+ "so run this from a repo to check that half.",
+ ),
+ fix_command="repowise agents add --target=opencode",
+ )
+
+
+TARGET = OpenCodeTarget()
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
index f346d2137..3d02a23ea 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from ..formats.server_entry import RemoteServerEntryError
from ..types import (
Capability,
DoctorReport,
@@ -87,6 +88,7 @@ def write_mcp_config(repo_path: Path) -> FileWrite:
merge_server_entries,
write_json_config,
)
+ from ..formats.server_entry import is_remote_entry
config_path = mcp_config_path(repo_path)
new_entry = {"repowise": server_entry(repo_path)}
@@ -97,6 +99,14 @@ def write_mcp_config(repo_path: Path) -> FileWrite:
if not isinstance(servers, dict):
raise ValueError("mcp.json 'servers' must be a JSON object")
servers = dict(servers)
+ stored = servers.get("repowise")
+ if isinstance(stored, dict) and is_remote_entry(stored, local_type="stdio"):
+ # VS Code documents ``"type": "http"`` in this file, so a hand-wired
+ # remote repowise server is a shape that really turns up. See
+ # ``formats.server_entry``: the merge would force ``type`` back to
+ # ``stdio`` and keep the ``url`` beside it, leaving an entry that is
+ # neither.
+ raise RemoteServerEntryError("mcp.json 'repowise' is wired to a remote server")
merge_server_entries(servers, new_entry)
existing["servers"] = servers
merged = existing
@@ -257,6 +267,17 @@ class VSCodeTarget:
try:
written = write_mcp_config(repo_path)
result.record(written.path, written.action)
+ except RemoteServerEntryError:
+ # Before the broader handler below, which it would otherwise reach
+ # as a ``ValueError`` and be described as an unreadable file. It is
+ # a perfectly readable file holding a deliberate choice.
+ result.record(mcp_config_path(repo_path), FileAction.KEPT)
+ result.note(
+ '.vscode/mcp.json left unchanged: its "repowise" entry names a remote '
+ "server, and converting it in place would leave an entry that is "
+ "neither. Run 'repowise agents remove --target=vscode' first if you "
+ "want the local server instead."
+ )
except (ValueError, OSError):
result.record(mcp_config_path(repo_path), FileAction.KEPT)
result.note(
diff --git a/packages/cli/src/repowise/cli/commands/agents_cmd.py b/packages/cli/src/repowise/cli/commands/agents_cmd.py
index 37aa85b67..51cb96cf9 100644
--- a/packages/cli/src/repowise/cli/commands/agents_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/agents_cmd.py
@@ -24,6 +24,7 @@ test that checks the projection by itself.
from __future__ import annotations
+import contextlib
import sys
from pathlib import Path
from typing import Any
@@ -126,12 +127,54 @@ def _write_payload(
written, or ``doctor --repair`` buys a global config write with a local
detection.
"""
- from repowise.cli.agent_targets.registry import select_install_method
- from repowise.cli.agent_targets.types import Scope
+ from repowise.cli.agent_targets.registry import removing
from repowise.cli.editor_setup import is_editor_setup_disabled
user_scope_disabled = is_editor_setup_disabled()
+ # Declared for the whole batch, before the first uninstall runs. A file two
+ # agents share is kept on behalf of an agent that is staying, never on
+ # behalf of one this same command is also removing -- which otherwise
+ # deadlocks `--target=all` on AGENTS.md and tells the user to remove an
+ # agent they just removed.
+ with removing(t.id for t in targets) if remove else contextlib.nullcontext():
+ agents = _run_writes(
+ targets,
+ repo_path,
+ scope,
+ remove=remove,
+ refresh_only=refresh_only,
+ user_scope_disabled=user_scope_disabled,
+ )
+
+ changed = any(
+ f["action"] in ("created", "updated", "removed")
+ for agent in agents
+ for write in agent["writes"].values()
+ for f in write["files"]
+ )
+ return {
+ "action": action,
+ "repo": str(repo_path),
+ "scope": scope,
+ "changed": changed,
+ "agents": agents,
+ }
+
+
+def _run_writes(
+ targets: list[Any],
+ repo_path: Path,
+ scope: str,
+ *,
+ remove: bool,
+ refresh_only: bool,
+ user_scope_disabled: bool,
+) -> list[dict]:
+ """The per-target loop of :func:`_write_payload`. See its docstring."""
+ from repowise.cli.agent_targets.registry import select_install_method
+ from repowise.cli.agent_targets.types import Scope
+
agents: list[dict] = []
for target in targets:
registrations = list(target.detect(repo_path))
@@ -187,19 +230,7 @@ def _write_payload(
entry["writes"][target_scope.value] = result.as_dict()
agents.append(entry)
- changed = any(
- f["action"] in ("created", "updated", "removed")
- for agent in agents
- for write in agent["writes"].values()
- for f in write["files"]
- )
- return {
- "action": action,
- "repo": str(repo_path),
- "scope": scope,
- "changed": changed,
- "agents": agents,
- }
+ return agents
# ---------------------------------------------------------------------------
diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.py
index 2a292ecf9..cb8b62067 100644
--- a/scripts/gen_agent_matrix.py
+++ b/scripts/gen_agent_matrix.py
@@ -60,7 +60,6 @@ PASTE_CONFIG_HOSTS: tuple[str, ...] = (
"Zed",
"Continue",
"Gemini CLI",
- "OpenCode",
"JetBrains AI Assistant",
"Amp",
)
@@ -352,10 +351,11 @@ def render() -> str:
"Ask for the target id whose host is closest to yours rather than editing a",
"snippet by hand. The shapes genuinely differ, and not only in their wrapper:",
"hosts disagree about the top-level key, about whether each entry carries a",
- "`type` field, and about the file format itself, so `codex` prints TOML where",
- "the others print JSON. `claude-code` is the plain `mcpServers` JSON most hosts",
- "read and is the right default when yours is not listed below. Hosts people ask",
- "about most, none of which repowise writes config for today:",
+ "`type` field, about whether the invocation is one array or a command plus a",
+ "separate argument list, and about the file format itself, so `codex` prints",
+ "TOML where the others print JSON. `claude-code` is the plain `mcpServers` JSON",
+ "most hosts read and is the right default when yours is not listed below.",
+ "Hosts people ask about most, none of which repowise writes config for today:",
"",
", ".join(PASTE_CONFIG_HOSTS) + ".",
"",
diff --git a/tests/unit/cli/conftest.py b/tests/unit/cli/conftest.py
index cc4e82925..10601808b 100644
--- a/tests/unit/cli/conftest.py
+++ b/tests/unit/cli/conftest.py
@@ -9,6 +9,14 @@ every subsequent Claude Code session until repaired. The autouse fixture
below points "home" at a per-test temp directory so no CLI test can ever
touch real user-level config; tests that build their own fake home simply
patch over it.
+
+``XDG_CONFIG_HOME`` is cleared for the same reason, and it is not covered by
+redirecting home: it is an *absolute* path that wins over ``~`` outright. The
+OpenCode target resolves its user config through it on every platform, so on a
+machine that exports one, an unset ``XDG_CONFIG_HOME`` is the difference
+between a test writing to a temp directory and a test writing to the
+developer's real ``opencode.jsonc``. A test that wants the variable set sets it
+itself.
"""
from __future__ import annotations
@@ -23,5 +31,6 @@ def _isolated_home(tmp_path_factory, monkeypatch):
fake_home = tmp_path_factory.mktemp("home")
monkeypatch.setenv("HOME", str(fake_home))
monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
monkeypatch.setattr(Path, "home", lambda: fake_home)
return fake_home
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index 6bdfeaa4a..3b2953882 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -47,7 +47,7 @@ def test_registry_exposes_the_shipped_targets() -> None:
Order is load-bearing: it is the order agents appear in prompts, in
``--target=all`` and in listings, and new ids append rather than sort in.
"""
- assert ALL_IDS == ["claude-code", "codex", "vscode", "cursor"]
+ assert ALL_IDS == ["claude-code", "codex", "vscode", "cursor", "opencode"]
@pytest.mark.parametrize("target_id", ALL_IDS)
@@ -124,6 +124,7 @@ def test_tiers_are_derived_from_the_adapters_a_target_names() -> None:
assert tier_of("codex") is Tier.FULL
assert tier_of("vscode") is Tier.GOOD
assert tier_of("cursor") is Tier.GOOD
+ assert tier_of("opencode") is Tier.GOOD
def test_a_target_cannot_reach_full_without_a_session_adapter() -> None:
@@ -743,6 +744,800 @@ def test_plugin_detection_degrades_to_absent_on_a_broken_manifest(
assert target_mod._plugin_installs() == []
+# ---------------------------------------------------------------------------
+# OpenCode
+# ---------------------------------------------------------------------------
+
+
+def _opencode():
+ from repowise.cli.agent_targets.targets import opencode as opencode_target
+
+ return opencode_target
+
+
+def test_opencode_resolves_its_user_dir_through_xdg_on_every_platform(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """XDG on Windows too, and a blank value is not a value.
+
+ The absence of a Windows branch is the point: ``%APPDATA%/opencode`` is
+ where a platform-conventional implementation would land, and OpenCode has
+ never read it, so an entry written there is invisible rather than broken.
+
+ The blank guard is the other half. An exported-but-empty ``XDG_CONFIG_HOME``
+ is ordinary in trimmed CI images, and a plain truthiness test on it resolves
+ the config directory to ``/opencode`` at the filesystem root.
+ """
+ opencode = _opencode()
+
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ assert opencode.user_config_dir() == tmp_path / "xdg" / "opencode"
+
+ for blank in ("", " ", "\t"):
+ monkeypatch.setenv("XDG_CONFIG_HOME", blank)
+ assert opencode.user_config_dir() == Path.home() / ".config" / "opencode"
+
+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
+ assert opencode.user_config_dir() == Path.home() / ".config" / "opencode"
+
+ # Surrounding whitespace is stripped before the join, not merely tested for.
+ # Leaving it in makes the path *relative*, so the config would be written
+ # into a directory named " " inside whatever repo the user was standing in.
+ # The blank cases above all pass without this, so they do not pin it.
+ monkeypatch.setenv("XDG_CONFIG_HOME", f" {tmp_path / 'xdg'} ")
+ resolved = opencode.user_config_dir()
+ assert resolved.is_absolute()
+ assert resolved == tmp_path / "xdg" / "opencode"
+
+ # Not %APPDATA%, whatever the platform and whatever APPDATA says.
+ monkeypatch.setenv("APPDATA", str(tmp_path / "roaming"))
+ assert (tmp_path / "roaming") not in opencode.user_config_dir().parents
+
+
+def test_opencode_writes_opencodes_config_shape_not_its_neighbours(tmp_path: Path) -> None:
+ """``mcp``, ``type: local``, and one combined ``command`` array.
+
+ Every other JSON host repowise writes for keys on ``mcpServers`` and splits
+ the invocation into ``command`` plus ``args``. This one does neither, which
+ makes it the shape most likely to be quietly made consistent with its
+ neighbours, so all three halves are pinned.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ written = json.loads(opencode.TARGET.print_config(Scope.PROJECT, repo_path=repo))
+
+ assert set(written) == {"mcp"}
+ entry = written["mcp"]["repowise"]
+ assert entry["type"] == "local"
+ assert isinstance(entry["command"], list)
+ assert "args" not in entry
+ # Binary first, then its arguments, in one array.
+ assert entry["command"][0] == "repowise"
+ assert entry["command"][1] == "mcp"
+ assert str(repo.resolve()).replace("\\", "/") in entry["command"]
+
+
+def test_opencode_user_scope_names_no_repo(tmp_path: Path) -> None:
+ """One global entry serves every workspace, so it cannot name one repo.
+
+ The user entry pins the absolute binary of the install that wrote it, so a
+ PATH shadow cannot hijack it, and passes no repo path so the server resolves
+ whichever repo it was launched in. The project entry does the opposite on
+ both counts, and swapping either would be silent.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ user = opencode.server_entry(Scope.USER)
+ project = opencode.server_entry(Scope.PROJECT, repo)
+
+ assert str(repo.resolve()).replace("\\", "/") not in user["command"]
+ assert str(repo.resolve()).replace("\\", "/") in project["command"]
+
+ # Repo-shared file keeps the bare command, because one contributor's
+ # absolute path breaks everyone else's checkout. The per-user one pins the
+ # install that wrote it so a PATH shadow cannot hijack the server. Both
+ # halves are asserted: checking only the project one leaves the user limb
+ # free to be "simplified" to the bare name with nothing going red.
+ from repowise.cli.mcp_config import resolve_repowise_command
+
+ assert project["command"][0] == "repowise"
+ assert user["command"][0] == resolve_repowise_command()
+
+
+def test_opencode_round_trips_to_nothing(tmp_path: Path) -> None:
+ """Install then uninstall leaves no file and no wrapper key behind.
+
+ A file repowise created holds only ``mcp``, so removing the entry empties
+ it and it goes. Nothing is left that still reads as repowise having been
+ here.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ config = opencode.config_path(Scope.PROJECT, repo)
+ assert config.name == "opencode.jsonc"
+ assert "repowise" in json.loads(config.read_text(encoding="utf-8"))["mcp"]
+
+ opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert not config.exists()
+ assert not (repo / "opencode.json").exists()
+ assert not (repo / "AGENTS.md").exists()
+
+
+def test_opencode_reinstall_reports_unchanged(tmp_path: Path) -> None:
+ """``agents refresh`` on a settled repo reports no movement on either file."""
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ first = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert first.changed
+
+ second = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert not second.changed
+ assert {f.action for f in second.files} == {FileAction.UNCHANGED}
+
+
+def test_opencode_prefers_an_existing_json_over_creating_a_jsonc(tmp_path: Path) -> None:
+ """Writing the file the host does not read is the failure this ordering avoids.
+
+ ``.jsonc`` wins when it exists, ``.json`` when only it does, and a brand-new
+ file is ``.jsonc`` to match what OpenCode itself creates. What must never
+ happen is a second config file appearing beside the one already there.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "opencode.json").write_text("{}\n", encoding="utf-8")
+
+ assert opencode.config_path(Scope.PROJECT, repo).name == "opencode.json"
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert not (repo / "opencode.jsonc").exists()
+ assert "repowise" in json.loads((repo / "opencode.json").read_text(encoding="utf-8"))["mcp"]
+
+ (repo / "opencode.jsonc").write_text("{}\n", encoding="utf-8")
+ assert opencode.config_path(Scope.PROJECT, repo).name == "opencode.jsonc"
+
+
+def test_opencode_declines_a_commented_config_rather_than_stripping_it(tmp_path: Path) -> None:
+ """A JSONC file is legal here, and repowise ships no parser that preserves it.
+
+ Declining leaves a working config untouched and prints what to add.
+ Re-serialising it through a strict parser with comments stripped would
+ delete every one of them, which is unrecoverable and silent.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = repo / "opencode.jsonc"
+ commented = '{\n // my provider settings\n "mcp": {}\n}\n'
+ config.write_text(commented, encoding="utf-8")
+
+ result = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert config.read_text(encoding="utf-8") == commented
+ assert any(f.action is FileAction.KEPT for f in result.files)
+ assert any("print-config opencode" in note for note in result.notes)
+
+
+def test_opencode_keeps_a_sibling_server_and_a_user_environment_block(tmp_path: Path) -> None:
+ """The merge is per server, and per key inside ours."""
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = repo / "opencode.jsonc"
+ config.write_text(
+ json.dumps(
+ {
+ "mcp": {
+ "other": {"type": "local", "command": ["other-server"]},
+ "repowise": {
+ "type": "local",
+ "command": ["stale"],
+ "environment": {"RUST_LOG": "debug"},
+ },
+ }
+ },
+ indent=2,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ servers = json.loads(config.read_text(encoding="utf-8"))["mcp"]
+ assert servers["other"] == {"type": "local", "command": ["other-server"]}
+ assert servers["repowise"]["environment"] == {"RUST_LOG": "debug"}
+ assert servers["repowise"]["command"] != ["stale"]
+
+
+def test_opencode_does_not_re_enable_a_server_the_user_disabled(tmp_path: Path) -> None:
+ """``enabled`` is a switch the user flips, not a field repowise computes.
+
+ ``false`` is the documented way to park a server without deleting it, and
+ ``agents refresh`` and ``doctor --repair`` both call ``install``. Forcing it
+ back to ``true`` there would silently undo a deliberate choice, which is the
+ same class of bug as overwriting a user's ``env`` block.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = repo / "opencode.jsonc"
+ config.write_text(
+ json.dumps({"mcp": {"repowise": {"type": "local", "command": ["x"], "enabled": False}}})
+ + "\n",
+ encoding="utf-8",
+ )
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ entry = json.loads(config.read_text(encoding="utf-8"))["mcp"]["repowise"]
+ assert entry["enabled"] is False
+ # The rest of the entry is still repointed.
+ assert entry["command"] != ["x"]
+
+ # A fresh entry gets it seeded on, so a first install is usable.
+ fresh = tmp_path / "fresh"
+ fresh.mkdir()
+ opencode.TARGET.install(Scope.PROJECT, repo_path=fresh)
+ written = json.loads((fresh / "opencode.jsonc").read_text(encoding="utf-8"))
+ assert written["mcp"]["repowise"]["enabled"] is True
+
+
+def test_opencode_keeps_a_config_holding_anything_of_the_users(tmp_path: Path) -> None:
+ """The file is deleted only when nothing of the user's is in it."""
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = repo / "opencode.jsonc"
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ data = json.loads(config.read_text(encoding="utf-8"))
+ data["theme"] = "tokyonight"
+ config.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+
+ opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert config.exists()
+ remaining = json.loads(config.read_text(encoding="utf-8"))
+ assert remaining["theme"] == "tokyonight"
+ assert "mcp" not in remaining
+
+
+def test_is_damaged_calls_a_non_utf8_config_damaged_rather_than_raising(tmp_path: Path) -> None:
+ """It is present, it was opened, and it is not readable JSON. That is the question.
+
+ ``UnicodeDecodeError`` is a ``ValueError``, so neither of this helper's
+ handlers caught it and it escaped. Both callers run it inside ``doctor()``,
+ so a cp1252 ``settings.json`` or ``hooks.json`` -- ordinary on Windows --
+ tracebacked out of ``repowise doctor`` instead of being reported by it.
+ Fixed in the shared helper rather than at the two call sites.
+ """
+ config = tmp_path / "settings.json"
+ config.write_bytes(b'{"mcpServers": {}} \xff\xfe caf\xe9')
+
+ assert json_merge.is_damaged(config) is True
+
+
+def test_every_target_doctor_survives_a_non_utf8_config(tmp_path: Path, monkeypatch) -> None:
+ """``doctor`` runs every registered target, so one raising takes the command down.
+
+ The user-level config each target reads is seeded with undecodable bytes
+ first. Calling ``doctor()`` against an empty home would pass without the
+ fix, which is the shape of test that let this survive in the first place.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ garbage = b'{"a": 1} \xff\xfe caf\xe9'
+
+ home = Path.home()
+ for relative in (
+ Path(".claude") / "settings.json",
+ Path(".codex") / "hooks.json",
+ Path(".config") / "opencode" / "opencode.jsonc",
+ ):
+ target_file = home / relative
+ target_file.parent.mkdir(parents=True, exist_ok=True)
+ target_file.write_bytes(garbage)
+ xdg_config = tmp_path / "xdg" / "opencode" / "opencode.jsonc"
+ xdg_config.parent.mkdir(parents=True, exist_ok=True)
+ xdg_config.write_bytes(garbage)
+
+ for target_id in ALL_IDS:
+ target = get_target(target_id)
+ assert target is not None
+ target.doctor()
+
+
+def test_opencode_never_deletes_the_config_file_opencode_itself_created(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """A bare ``{"$schema": ...}`` file is the host's first-run config, not our stub.
+
+ Uninstall used to delete a file holding only that, on the invariant that
+ repowise had seeded it. False in the most ordinary case there is: OpenCode
+ writes exactly that file on first run. Not seeding a ``$schema`` on create
+ is what makes "is this file empty" an unambiguous test.
+
+ The config directory is not pruned either. It is the host's, and "we
+ emptied it, so it was ours" is the same false claim one level up.
+ """
+ opencode = _opencode()
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ config_dir = tmp_path / "xdg" / "opencode"
+ config_dir.mkdir(parents=True)
+ host_file = config_dir / "opencode.jsonc"
+ host_file.write_text('{\n "$schema": "https://opencode.ai/config.json"\n}\n', encoding="utf-8")
+
+ opencode.TARGET.install(Scope.USER)
+ opencode.TARGET.uninstall(Scope.USER)
+
+ assert host_file.exists(), "deleted the host's own config file"
+ assert config_dir.is_dir(), "deleted the host's own config directory"
+ assert "mcp" not in json.loads(host_file.read_text(encoding="utf-8"))
+
+
+def test_opencode_creates_no_schema_key_of_its_own(tmp_path: Path) -> None:
+ """A file repowise creates holds only ``mcp``, so it empties to nothing."""
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ written = json.loads((repo / "opencode.jsonc").read_text(encoding="utf-8"))
+
+ assert set(written) == {"mcp"}
+
+
+def test_opencode_removes_an_entry_from_whichever_file_holds_it(tmp_path: Path) -> None:
+ """Uninstall and detection sweep both spellings, not the one preferred today.
+
+ Install into a repo holding only ``opencode.json`` writes there. When an
+ ``opencode.jsonc`` later appears beside it -- the host creates one, or the
+ user does -- ``config_path`` flips to the new file. Uninstall then reported
+ success against the empty one while the real registration sat in the old,
+ invisible to ``detect`` and so unreachable by every command that could have
+ removed it.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "opencode.json").write_text("{}\n", encoding="utf-8")
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert "repowise" in json.loads((repo / "opencode.json").read_text(encoding="utf-8"))["mcp"]
+
+ (repo / "opencode.jsonc").write_text("{}\n", encoding="utf-8")
+ assert opencode.config_path(Scope.PROJECT, repo).name == "opencode.jsonc"
+
+ # Still found, so still removable.
+ assert [r.config_path.name for r in opencode.TARGET.detect(repo)] == ["opencode.json"]
+
+ opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert opencode.TARGET.detect(repo) == []
+ assert not (repo / "opencode.json").exists()
+
+
+def test_opencode_refresh_does_not_create_a_second_registration(tmp_path: Path) -> None:
+ """Writes follow the file already holding the entry, or detection and install disagree.
+
+ Teaching ``detect`` to sweep both spellings without teaching writes the same
+ thing was worse than either rule alone: an install that had landed in
+ ``opencode.json`` stayed detected there once an ``opencode.jsonc`` appeared
+ beside it, so ``agents refresh`` no longer skipped the scope as unwired and
+ wrote a **second** entry into the other file. ``doctor --repair`` routes
+ through the same refresh. Refresh is contracted to add nothing.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "opencode.json").write_text("{}\n", encoding="utf-8")
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ (repo / "opencode.jsonc").write_text("{}\n", encoding="utf-8")
+
+ second = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert [r.config_path.name for r in opencode.TARGET.detect(repo)] == ["opencode.json"]
+ assert "mcp" not in json.loads((repo / "opencode.jsonc").read_text(encoding="utf-8"))
+ assert {f.action for f in second.files} == {FileAction.UNCHANGED}
+
+
+def test_opencode_doctor_agrees_with_detection_about_which_file_counts(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """``doctor`` reads both spellings, like ``detect`` and ``uninstall``.
+
+ Reading only the preferred one made it contradict ``repowise agents``: wired
+ in the listing, not-installed here, and the fix command printed here then
+ wrote a second entry into the other file.
+ """
+ from repowise.cli.agent_targets.types import DoctorStatus
+
+ opencode = _opencode()
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ config_dir = tmp_path / "xdg" / "opencode"
+ config_dir.mkdir(parents=True)
+
+ opencode.TARGET.install(Scope.USER)
+ # The host's first-run file turns up beside ours and takes preference.
+ (config_dir / "opencode.jsonc").rename(config_dir / "opencode.json")
+ (config_dir / "opencode.jsonc").write_text(
+ '{"$schema": "https://opencode.ai/config.json"}\n', encoding="utf-8"
+ )
+
+ assert opencode.TARGET.detect() != []
+ assert opencode.TARGET.doctor().status is DoctorStatus.OK
+
+
+def test_opencode_uninstall_leaves_no_directory_of_ours_behind(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """An empty leftover directory keeps the agent pre-ticked forever.
+
+ ``is_present`` reads the config directory as evidence the user has OpenCode
+ and ``install`` creates it, so leaving it made our own residue the reason
+ the agent kept being offered on a machine that never had it.
+ """
+ import shutil
+
+ opencode = _opencode()
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+
+ assert opencode.TARGET.is_present() is False
+
+ opencode.TARGET.install(Scope.USER)
+ opencode.TARGET.uninstall(Scope.USER)
+
+ assert opencode.TARGET.is_present() is False
+
+
+def test_opencode_detects_a_commented_config_that_names_repowise(tmp_path: Path) -> None:
+ """A JSONC config is the shape this target blesses, so it must not read as unwired.
+
+ ``other_managers_of`` asks ``detect`` who is still using a shared file, so
+ answering "no" for a commented config meant removing Codex stripped the
+ managed AGENTS.md block out from under a fully working OpenCode, silently.
+ """
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ # OpenCode writes the managed block; Codex's own install does not touch
+ # AGENTS.md, which the generation path owns.
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ # Now the user adds a comment to the config OpenCode reads. Nothing about
+ # their setup has changed except that repowise can no longer parse it.
+ (repo / "opencode.jsonc").write_text(
+ '{\n // my own note\n "mcp": {\n "repowise": {"type": "local", '
+ '"command": ["repowise", "mcp"]}\n }\n}\n',
+ encoding="utf-8",
+ )
+
+ assert opencode.TARGET.detect(repo) != []
+
+ result = codex_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert DISTILL_MARKER_START in (repo / "AGENTS.md").read_text(encoding="utf-8")
+ assert any("OpenCode" in note for note in result.notes)
+
+
+def test_vscode_declines_a_hand_wired_remote_server(tmp_path: Path) -> None:
+ """The same guard, in the sibling that also had the bug.
+
+ VS Code documents ``"type": "http"`` in ``.vscode/mcp.json``, so a remote
+ repowise entry is a shape that turns up. The merge would force ``type`` back
+ to ``stdio`` while preserving the ``url``, leaving an entry that is neither.
+ Ported when the guard was written for OpenCode rather than left for the next
+ review to find here.
+ """
+ from repowise.cli.agent_targets.targets import vscode as vscode_target
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = vscode_target.mcp_config_path(repo)
+ config.parent.mkdir(parents=True)
+ remote = {"servers": {"repowise": {"type": "http", "url": "https://mcp.repowise.dev/mcp"}}}
+ config.write_text(json.dumps(remote, indent=2) + "\n", encoding="utf-8")
+
+ result = vscode_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert json.loads(config.read_text(encoding="utf-8"))["servers"]["repowise"] == (
+ remote["servers"]["repowise"]
+ )
+ assert any("remote server" in note for note in result.notes)
+
+
+def test_opencode_declines_a_hand_wired_remote_server(tmp_path: Path) -> None:
+ """Half-converting a remote entry leaves one that is neither.
+
+ The merge lets generated keys win and keeps the rest, which forces ``type``
+ back to ``local`` while faithfully preserving the ``url`` beside it. The
+ preservation rule is what makes the result broken rather than merely
+ overwritten, and this config is ``$schema``-validated, so a stray key can
+ cost the whole file rather than the one entry.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ config = repo / "opencode.jsonc"
+ remote = {
+ "mcp": {"repowise": {"type": "remote", "url": "https://mcp.repowise.dev/sse", "enabled": True}}
+ }
+ config.write_text(json.dumps(remote, indent=2) + "\n", encoding="utf-8")
+
+ result = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert json.loads(config.read_text(encoding="utf-8")) == remote
+ assert any(f.action is FileAction.KEPT for f in result.files)
+ assert any("remote server" in note for note in result.notes)
+
+
+def test_opencode_doctor_does_not_call_a_legal_jsonc_config_broken(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """``BROKEN`` fails the whole doctor run, and a commented config is not damage.
+
+ OpenCode accepts JSONC by design, so a file ``json.loads`` rejects is far
+ more likely to be a legal config with a comment in it. Reporting that as
+ broken failed ``repowise doctor`` -- and any CI running it -- for someone
+ who had installed OpenCode and never touched repowise, then handed them a
+ fix command that declines for the same reason.
+ """
+ from repowise.cli.agent_targets.types import DoctorStatus
+
+ opencode = _opencode()
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ config_dir = tmp_path / "xdg" / "opencode"
+ config_dir.mkdir(parents=True)
+ (config_dir / "opencode.jsonc").write_text(
+ '{\n // my theme\n "theme": "tokyonight"\n}\n', encoding="utf-8"
+ )
+
+ report = opencode.TARGET.doctor()
+
+ assert report.status is not DoctorStatus.BROKEN
+ assert any("Comments are legal" in issue for issue in report.issues)
+
+
+def test_opencode_uninstall_note_names_the_real_reason_it_kept_the_file(tmp_path: Path) -> None:
+ """A malformed marker pair is not shared ownership, and the advice differs.
+
+ ``KEPT`` covers three unrelated causes. Blaming the shared block for an
+ orphaned marker sends the user to remove an agent, after which the block
+ still will not go and nothing has said why.
+ """
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ # Break the pair by hand, leaving the start marker orphaned.
+ agents_md = repo / "AGENTS.md"
+ text = agents_md.read_text(encoding="utf-8")
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_END
+
+ agents_md.write_text(text.replace(DISTILL_MARKER_END, ""), encoding="utf-8")
+
+ result = opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert DISTILL_MARKER_START in agents_md.read_text(encoding="utf-8")
+ assert not any("still reads the same managed block" in note for note in result.notes)
+
+
+def test_opencode_detect_survives_a_config_that_is_not_utf8(tmp_path: Path) -> None:
+ """``detect`` is contracted never to raise, and cp1252 files are ordinary.
+
+ ``UnicodeDecodeError`` is a ``ValueError``, not an ``OSError``, so a handler
+ naming only ``OSError`` and ``JSONDecodeError`` lets it escape a probe that
+ runs on paths which do not catch.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "opencode.jsonc").write_bytes(b'{"mcp": {"repowise": {}}} \xff\xfe caf\xe9')
+
+ assert opencode.TARGET.detect(repo) == []
+
+
+def test_opencode_install_survives_a_config_path_that_is_a_directory(tmp_path: Path) -> None:
+ """Nothing wraps ``install``, so an escape aborts a multi-agent run.
+
+ ``agents add``, ``agents refresh`` and ``doctor --repair`` all call it bare,
+ and a traceback here replaces the summary naming the agents already written.
+ """
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "opencode.jsonc").mkdir()
+
+ result = opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert any(f.action is FileAction.KEPT for f in result.files)
+ assert result.notes
+
+
+def test_opencode_is_present_checks_each_limb_on_its_own(tmp_path: Path, monkeypatch) -> None:
+ """Neither limb may be carried by the other, or the test proves nothing.
+
+ A single assertion over the real machine passes for whichever reason
+ happens to hold there, which is how a probe with a dead limb ships green.
+ """
+ opencode = _opencode()
+ import shutil
+
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ assert opencode.TARGET.is_present() is False
+
+ # Limb one: the config directory, with nothing on PATH.
+ (tmp_path / "xdg" / "opencode").mkdir(parents=True)
+ assert opencode.TARGET.is_present() is True
+
+ # Limb two: the binary, with no config directory.
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "empty"))
+ assert opencode.TARGET.is_present() is False
+ monkeypatch.setattr(shutil, "which", lambda name: "/usr/bin/opencode" if name == "opencode" else None)
+ assert opencode.TARGET.is_present() is True
+
+
+def test_opencode_does_not_read_its_own_output_as_evidence_of_the_agent(tmp_path: Path, monkeypatch) -> None:
+ """A repo-local limb would make our own install the reason we keep offering.
+
+ OpenCode keeps nothing repo-local of its own: the project config is a bare
+ ``opencode.json`` at the root, which this target may well have written
+ itself. Cursor and VS Code can read a repo-local directory as evidence
+ because those directories are the editor's, not ours.
+ """
+ opencode = _opencode()
+ import shutil
+
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ assert opencode.TARGET.is_present(repo) is False
+
+
+# ---------------------------------------------------------------------------
+# AGENTS.md is shared between targets
+# ---------------------------------------------------------------------------
+
+
+def test_agents_md_survives_removing_one_of_two_agents_that_read_it(tmp_path: Path) -> None:
+ """The shared-file case, in both directions.
+
+ ``AGENTS.md`` is a host-neutral convention rather than one agent's private
+ config: Codex and OpenCode both manage the same path in the same repo, and
+ both are right to. Install is safe because the block is marker-delimited and
+ idempotent. Uninstall is not: removing either agent stripped the block out
+ from under the other, which stayed wired and silently lost its instructions.
+
+ Asserted for Codex as well as OpenCode on purpose. A guard added only to the
+ agent that arrived most recently leaves the identical bug in its sibling.
+ """
+ from repowise.cli.agent_targets.instructions import (
+ DISTILL_MARKER_START,
+ )
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ agents_md = repo / "AGENTS.md"
+
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert DISTILL_MARKER_START in agents_md.read_text(encoding="utf-8")
+
+ # Removing OpenCode leaves Codex's block alone, and says why.
+ result = opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+ assert DISTILL_MARKER_START in agents_md.read_text(encoding="utf-8")
+ assert any(f.path == agents_md and f.action is FileAction.KEPT for f in result.files)
+ assert any("Codex" in note for note in result.notes)
+
+ # And the mirror: with only Codex left, removing Codex does strip it. The
+ # file held nothing but our block, so it goes with it.
+ codex_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+ assert not agents_md.exists()
+
+
+def test_agents_md_is_kept_by_codex_while_opencode_still_reads_it(tmp_path: Path) -> None:
+ """The same guard, driven from the other side."""
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ agents_md = repo / "AGENTS.md"
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+
+ result = codex_target.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert DISTILL_MARKER_START in agents_md.read_text(encoding="utf-8")
+ assert any(f.path == agents_md and f.action is FileAction.KEPT for f in result.files)
+ assert any("OpenCode" in note for note in result.notes)
+
+
+def test_removing_both_agents_at_once_does_not_deadlock_on_the_shared_file(
+ tmp_path: Path,
+) -> None:
+ """``agents remove --target=all`` must not keep the block for an agent it is removing.
+
+ Each target's uninstall asks who else is still wired, and during a batch
+ removal the answer is "the one that has not been processed yet" -- or worse,
+ one whose detection is latched on by a file its own uninstall does not
+ delete. Both then keep the block on the other's behalf, and each tells the
+ user to remove an agent they removed in the same command.
+
+ Asserted in **both orders**, because the failure is order-dependent and the
+ order that works proves nothing about the one that does not.
+ """
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+ from repowise.cli.agent_targets.registry import removing
+ from repowise.cli.agent_targets.targets import codex as codex_target
+
+ opencode = _opencode()
+ for order in ([codex_target.TARGET, opencode.TARGET], [opencode.TARGET, codex_target.TARGET]):
+ repo = tmp_path / f"repo-{order[0].id}"
+ repo.mkdir()
+ agents_md = repo / "AGENTS.md"
+
+ codex_target.TARGET.install(Scope.PROJECT, repo_path=repo)
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert DISTILL_MARKER_START in agents_md.read_text(encoding="utf-8")
+
+ with removing(t.id for t in order):
+ for target in order:
+ target.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert not agents_md.exists(), f"block survived removal in order {[t.id for t in order]}"
+
+
+def test_a_target_that_is_not_wired_does_not_hold_the_shared_file(tmp_path: Path) -> None:
+ """Only *wired* agents count, or nothing could ever be removed.
+
+ Every descriptor claims paths it has never written, so ``describe_paths``
+ alone would make ``AGENTS.md`` permanently unremovable by anyone.
+ """
+ from repowise.cli.agent_targets.instructions import DISTILL_MARKER_START
+
+ opencode = _opencode()
+ repo = tmp_path / "repo"
+ repo.mkdir()
+
+ opencode.TARGET.install(Scope.PROJECT, repo_path=repo)
+ assert DISTILL_MARKER_START in (repo / "AGENTS.md").read_text(encoding="utf-8")
+
+ # Codex knows the path but has never been wired here.
+ opencode.TARGET.uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert not (repo / "AGENTS.md").exists()
+
+
# ---------------------------------------------------------------------------
# WriteResult
# ---------------------------------------------------------------------------
diff --git a/tests/unit/cli/test_agents_cmd.py b/tests/unit/cli/test_agents_cmd.py
index df41d7095..1bdd5700c 100644
--- a/tests/unit/cli/test_agents_cmd.py
+++ b/tests/unit/cli/test_agents_cmd.py
@@ -75,6 +75,7 @@ def test_bare_agents_lists_every_registered_target_as_json(repo: Path) -> None:
"codex",
"vscode",
"cursor",
+ "opencode",
]
for row in payload["agents"]:
# The keys the table renders, so a dropped one is a broken table.
@@ -353,6 +354,7 @@ def test_doctor_reports_one_row_per_agent_from_its_own_descriptor(repo: Path) ->
"Agent: codex",
"Agent: vscode",
"Agent: cursor",
+ "Agent: opencode",
]
# Nothing is wired on a clean machine, and an agent you do not use is not a
# problem with your setup.
@@ -480,3 +482,27 @@ def test_a_tty_that_cannot_answer_falls_through_to_the_defaults(repo: Path, monk
assert result.exit_code == 0
assert (repo / ".vscode" / "mcp.json").exists()
+
+
+def test_removing_every_agent_clears_the_shared_agents_md(repo: Path) -> None:
+ """``agents remove --target=all`` must not keep AGENTS.md for an agent it removes.
+
+ Codex and OpenCode both manage the repo's ``AGENTS.md``, and each target's
+ uninstall asks who else is still using it. During a batch removal the answer
+ used to be "the one not processed yet", so both kept the block on the
+ other's behalf and each told the user to remove an agent they had removed in
+ the same command.
+
+ Driven through ``CliRunner`` on purpose. The registry helper that fixes this
+ is entered in exactly one place in production, and a test that calls it by
+ hand passes with the entire CLI half of the fix deleted.
+ """
+ _run(["agents", "add", str(repo), "--target", "codex,opencode", "--scope", "project", "-y"])
+ agents_md = repo / "AGENTS.md"
+ assert agents_md.exists()
+
+ payload = _json(["agents", "remove", str(repo), "--target", "all", "--scope", "project"])
+
+ assert not agents_md.exists(), "shared AGENTS.md survived removing every agent"
+ notes = [note for agent in payload["agents"] for w in agent["writes"].values() for note in w["notes"]]
+ assert not any("still reads the same managed block" in note for note in notes)